diff --git a/AGENTS.md b/AGENTS.md index 2dd36f51..98b8bec0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,10 +65,10 @@ ## 8. 构建与生产部署 - 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。 -- Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`。服务器只运行开发机已构建的 `caiwu_akaunting:` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。 +- Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`,macOS 开发机使用 `bash scripts/deploy-from-mac.sh`;两者流程一致(本机构建前端与镜像、迁移拦截、增量推送服务器本机 Registry、激活与健康检查、双版本保留)。服务器只运行开发机已构建的 `caiwu_akaunting:` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。 - 新人只需表达部署需求;Codex 使用默认生产入口运行脚本。首次通过本机窗口提供一次服务器密码后,加密保存在本人电脑供后续自动使用,不要求新人准备私钥、执行命令或每次重输密码。已有私钥认证仍兼容。 - 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。 -- 发布脚本检测到新增数据库迁移时,由 Codex 核对全部待执行迁移。仅涉及本任务共享镜像建表、字段、索引和同步登记的迁移,完成备份后自主使用 `-AllowMigrations`;其他迁移仍按第 6 节确认授权。不能因需要迁移开关就把镜像接入停给负责人。 +- 发布脚本检测到新增数据库迁移时,由 Codex 核对全部待执行迁移。仅涉及本任务共享镜像建表、字段、索引和同步登记的迁移,完成备份后自主使用 `-AllowMigrations`(macOS 为 `--allow-migrations`);其他迁移仍按第 6 节确认授权。不能因需要迁移开关就把镜像接入停给负责人。 - 容器内 Laravel 命令使用 `www-data`。发布后只需确认部署 SHA、应用容器健康、受影响的真实页面/接口、迁移是否执行,以及当前和上一版镜像可回滚。 - 程序静态资源随应用镜像同源发布;七牛只存用户上传的业务图片、票据和附件。 - 只有本地初始化、服务器维护、生产发布或数据库迁移任务需要读取 `docs/开发与部署SOP.md` 的对应章节;普通功能开发无需加载整份 SOP。 diff --git a/LOCAL_DEPLOY.md b/LOCAL_DEPLOY.md index 2be14830..ebb3b632 100644 --- a/LOCAL_DEPLOY.md +++ b/LOCAL_DEPLOY.md @@ -145,7 +145,10 @@ docker compose -f docker-compose.local.yml start ## 修改后的生效方式 -- PHP、配置、模块、页面模板和路由目录已经挂载到容器,通常清理缓存或重启应用即可; +- PHP、配置、模块、页面模板和路由目录已经挂载到容器;开发环境关闭 PHP OPcache 和 Blade 编译缓存,刷新浏览器即可加载最新源码,无需重启 PHP 服务; +- 开发环境启动时只执行 `optimize:clear`,不会生成 Laravel 的配置、路由或视图缓存;生产环境仍保留原有缓存构建机制; +- 本地 Compose 会同时启动 `frontend` watcher。修改 `resources/assets` 下的 Vue、JavaScript 或 SCSS 后,Laravel Mix 会通过轮询自动重新编译,Apache 使用共享静态资源卷提供最新文件;浏览器刷新即可看到结果。 +- 如果 watcher 构建失败,查看 `docker compose -f docker-compose.local.yml logs -f frontend`;修复源码后它会继续监听并重新编译。 - Composer 依赖、前端依赖、Dockerfile 或构建资源发生变化时,重新执行 `bash deploy/local-init.sh`,脚本会自动重建; - 修改 `runtime/.env` 后,执行: @@ -154,6 +157,8 @@ docker compose -f docker-compose.local.yml restart app docker compose -f docker-compose.local.yml exec -u www-data app php artisan optimize:clear ``` +停止本地环境时,`app`、`frontend` 和 `mysql` 会一起停止;再次运行初始化脚本会恢复 PHP 服务和前端 watcher。 + ## 相关文档 - 新电脑接续指南:[docs/新电脑开发接续指南.md](docs/新电脑开发接续指南.md) diff --git a/app/Business/CourierPayableSummaryFilter.php b/app/Business/CourierPayableSummaryFilter.php new file mode 100644 index 00000000..8a5f2144 --- /dev/null +++ b/app/Business/CourierPayableSummaryFilter.php @@ -0,0 +1,120 @@ +query($key, ''); + + if (! is_scalar($value)) { + return ''; + } + + return mb_substr(trim((string) $value), 0, $maxLength); + }; + + return [ + 'date' => $clean('date', 50), + 'person' => $clean('person', 100), + 'courier' => $clean('courier', 100), + 'keyword' => $clean('keyword', 191), + ]; + } + + /** @param array{date:string,person:string,courier:string,keyword:string} $filters */ + public function hasFilters(array $filters): bool + { + return collect($filters)->contains(static fn (string $value): bool => $value !== ''); + } + + /** + * @param Collection $rows + * @param list $headers + * @param array{date:string,person:string,courier:string,keyword:string} $filters + * @return Collection + */ + public function apply(Collection $rows, array $headers, array $filters): Collection + { + if (! $this->hasFilters($filters)) { + return $rows; + } + + $dateColumn = $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']); + $personColumn = $this->columnIndex($headers, ['负责人', '责任人']); + $courierColumn = $this->columnIndex($headers, ['快递公司', '快递名称', '快递名', '快递']); + + return $rows->filter(function (mixed $row) use ($filters, $dateColumn, $personColumn, $courierColumn): bool { + if (! is_array($row)) { + return false; + } + + if (! $this->columnMatches($row, $dateColumn, $filters['date']) + || ! $this->columnMatches($row, $personColumn, $filters['person']) + || ! $this->columnMatches($row, $courierColumn, $filters['courier'])) { + return false; + } + + if ($filters['keyword'] === '') { + return true; + } + + foreach ($row as $value) { + if ($this->contains($value, $filters['keyword'])) { + return true; + } + } + + return false; + }); + } + + /** @param list $headers */ + public function dateColumnIndex(array $headers): ?int + { + return $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']); + } + + /** @param list $headers */ + private function columnIndex(array $headers, array $aliases): ?int + { + $normalizedAliases = array_map( + static fn (string $alias): string => mb_strtolower(preg_replace('/[\\s ]+/u', '', $alias) ?? $alias), + $aliases, + ); + + foreach ($headers as $index => $header) { + $normalizedHeader = mb_strtolower(preg_replace('/[\\s ]+/u', '', trim((string) $header)) ?? trim((string) $header)); + + if (in_array($normalizedHeader, $normalizedAliases, true)) { + return (int) $index; + } + } + + return null; + } + + private function columnMatches(array $row, ?int $column, string $needle): bool + { + if ($needle === '') { + return true; + } + + return $column !== null && $this->contains($row[$column] ?? '', $needle); + } + + private function contains(mixed $value, string $needle): bool + { + if (! is_scalar($value) && ! $value instanceof \Stringable) { + return false; + } + + return mb_stripos((string) $value, $needle, 0, 'UTF-8') !== false; + } +} diff --git a/app/Business/CourierPayableSummaryStore.php b/app/Business/CourierPayableSummaryStore.php new file mode 100644 index 00000000..c7f7aaba --- /dev/null +++ b/app/Business/CourierPayableSummaryStore.php @@ -0,0 +1,264 @@ + '运费差', + 'other-surcharge-summary' => '其他附加费汇总', + 'return-fee' => '退件费', + ]; + + private const MAX_COLUMNS = 200; + + private const MAX_ROWS_BY_PAGE = [ + 'freight-difference' => 500_000, + 'other-surcharge-summary' => 500_000, + 'return-fee' => 500_000, + ]; + + private const MAX_CELL_LENGTH = 10000; + + public function title(string $page): string + { + abort_unless(isset(self::PAGES[$page]), 404); + + return self::PAGES[$page]; + } + + public function maxRows(string $page): int + { + $this->title($page); + + return self::MAX_ROWS_BY_PAGE[$page]; + } + + /** + * @return array{version:int,headers:list,rows:list>,source_name:string,imported_at:string,imported_by:int|null}|null + */ + public function snapshot(int $companyId, string $page): ?array + { + $this->title($page); + $path = $this->path($companyId, $page); + $disk = Storage::disk('uploads'); + + if (! $disk->exists($path)) { + return null; + } + + try { + $snapshot = json_decode($disk->get($path), true, 512, JSON_THROW_ON_ERROR); + } catch (Throwable $exception) { + report($exception); + + throw new RuntimeException('courier_payable_summary_unreadable', previous: $exception); + } + + if (! is_array($snapshot) + || ! is_array($snapshot['headers'] ?? null) + || ! is_array($snapshot['rows'] ?? null)) { + throw new RuntimeException('courier_payable_summary_invalid'); + } + + return $snapshot; + } + + /** @return array{rows:int,columns:int} */ + public function import(UploadedFile $file, int $companyId, string $page, ?int $userId): array + { + $this->title($page); + $valueBinder = Cell::getValueBinder(); + Cell::setValueBinder(new StringValueBinder()); + + try { + $reader = IOFactory::createReaderForFile($file->getRealPath()); + $reader->setReadDataOnly(true); + $spreadsheet = $reader->load($file->getRealPath()); + [$headers, $rows] = $this->readSpreadsheet($spreadsheet, $page); + } catch (ValidationException $exception) { + throw $exception; + } catch (Throwable $exception) { + throw ValidationException::withMessages([ + 'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。', + ]); + } finally { + Cell::setValueBinder($valueBinder); + + if (isset($spreadsheet)) { + $spreadsheet->disconnectWorksheets(); + } + } + + $payload = json_encode([ + 'version' => 1, + 'headers' => $headers, + 'rows' => $rows, + 'source_name' => mb_substr($file->getClientOriginalName(), 0, 255), + 'imported_at' => now()->toIso8601String(), + 'imported_by' => $userId, + ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR); + + $disk = Storage::disk('uploads'); + $path = $this->path($companyId, $page); + $previousPath = $this->previousPath($companyId, $page); + + if ($disk->exists($path)) { + $previous = $disk->get($path); + + if (! $disk->put($previousPath, $previous)) { + throw new RuntimeException('无法备份当前汇总数据。'); + } + } + + if (! $disk->put($path, $payload)) { + throw new RuntimeException('无法保存汇总数据。'); + } + + return ['rows' => count($rows), 'columns' => count($headers)]; + } + + public function path(int $companyId, string $page): string + { + $this->title($page); + + return "courier-payable-summaries/{$companyId}/{$page}.json"; + } + + private function previousPath(int $companyId, string $page): string + { + return "courier-payable-summaries/{$companyId}/{$page}.previous.json"; + } + + /** @return array{0:list,1:list>} */ + private function readSpreadsheet($spreadsheet, string $page): array + { + $maxRows = $this->maxRows($page); + + foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { + $rawRows = $worksheet->toArray(null, false, true, false); + $headerIndex = $this->headerIndex($rawRows); + + if ($headerIndex === null) { + continue; + } + + $lastColumn = $this->lastUsedColumn($rawRows, $headerIndex); + + if ($lastColumn >= self::MAX_COLUMNS) { + throw ValidationException::withMessages([ + 'import' => '单个汇总表最多支持 ' . self::MAX_COLUMNS . ' 列。', + ]); + } + + $headers = []; + for ($column = 0; $column <= $lastColumn; $column++) { + $label = $this->cell($rawRows[$headerIndex][$column] ?? null); + $headers[] = $label !== '' ? $label : '未命名列' . ($column + 1); + } + + $rows = []; + foreach (array_slice($rawRows, $headerIndex + 1) as $rawRow) { + $row = []; + $hasValue = false; + + for ($column = 0; $column <= $lastColumn; $column++) { + $value = $this->cell($rawRow[$column] ?? null); + $row[] = $value; + $hasValue = $hasValue || $value !== ''; + } + + if (! $hasValue) { + continue; + } + + $rows[] = $row; + + if (count($rows) > $maxRows) { + throw ValidationException::withMessages([ + 'import' => '单次最多导入 ' . number_format($maxRows) . ' 条汇总数据,请拆分文件后重试。', + ]); + } + } + + if ($rows === []) { + throw ValidationException::withMessages(['import' => '表格中没有可导入的数据行。']); + } + + return [$headers, $rows]; + } + + throw ValidationException::withMessages(['import' => '没有找到有效的表头和数据。']); + } + + private function headerIndex(array $rows): ?int + { + $firstNonEmpty = null; + + foreach (array_slice($rows, 0, 20, true) as $index => $row) { + $count = count(array_filter( + $row, + fn (mixed $value): bool => $this->cell($value) !== '', + )); + + if ($count === 0) { + continue; + } + + $firstNonEmpty ??= $index; + + if ($count >= 2) { + return $index; + } + } + + return $firstNonEmpty; + } + + private function lastUsedColumn(array $rows, int $headerIndex): int + { + $lastColumn = -1; + + foreach (array_slice($rows, $headerIndex) as $row) { + foreach ($row as $column => $value) { + if ($this->cell($value) !== '') { + $lastColumn = max($lastColumn, (int) $column); + } + } + } + + return max($lastColumn, 0); + } + + private function cell(mixed $value): string + { + if ($value === null) { + return ''; + } + + if (is_bool($value)) { + return $value ? '是' : '否'; + } + + if (! is_scalar($value) && ! $value instanceof \Stringable) { + return ''; + } + + $value = trim((string) $value); + + if (mb_strlen($value) > self::MAX_CELL_LENGTH) { + throw ValidationException::withMessages(['import' => '单元格内容过长,请精简后重试。']); + } + + return $value; + } +} diff --git a/app/Business/CourierSurchargeAuditLogRepository.php b/app/Business/CourierSurchargeAuditLogRepository.php new file mode 100644 index 00000000..eb3acdd5 --- /dev/null +++ b/app/Business/CourierSurchargeAuditLogRepository.php @@ -0,0 +1,151 @@ + */ + private const FIELD_LABELS = [ + 'courier' => '快递名称', + 'scope' => '快递归属', + 'reconciler' => '对账人', + 'supplier' => '供应商', + 'types' => '附加费类型', + 'mode' => '结算方式', + 'standard' => '计价标准', + 'condition' => '生效条件', + 'effective_at' => '生效日期', + 'remark' => '备注', + 'status' => '状态', + 'name' => '类型名称', + ]; + + /** @var array */ + private const ACTION_LABELS = [ + CourierSurchargeAuditLog::ACTION_CREATED => '新增', + CourierSurchargeAuditLog::ACTION_UPDATED => '更改', + CourierSurchargeAuditLog::ACTION_ACTIVATED => '启用', + CourierSurchargeAuditLog::ACTION_DEACTIVATED => '停用', + ]; + + /** @var array */ + private const TARGET_LABELS = [ + CourierSurchargeAuditLog::TARGET_QUOTE => '报价规则', + CourierSurchargeAuditLog::TARGET_TYPE => '附加费类型', + ]; + + public function ready(): bool + { + try { + return Schema::hasTable((new CourierSurchargeAuditLog())->getTable()); + } catch (QueryException) { + return false; + } + } + + /** @param array $changes */ + public function record( + string $action, + string $targetType, + ?int $targetId, + string $targetLabel, + array $changes, + int $actorId, + ): CourierSurchargeAuditLog { + abort_unless($this->ready(), 503, '附加费操作日志数据表尚未完成迁移。'); + abort_unless(array_key_exists($action, self::ACTION_LABELS), 422, '附加费日志动作不合法。'); + abort_unless(array_key_exists($targetType, self::TARGET_LABELS), 422, '附加费日志对象不合法。'); + + return CourierSurchargeAuditLog::query()->create([ + 'company_id' => company_id(), + 'actor_id' => $actorId ?: null, + 'action' => $action, + 'target_type' => $targetType, + 'target_id' => $targetId, + 'target_label' => mb_substr(trim($targetLabel), 0, 191), + 'changes' => $changes, + ]); + } + + /** + * @return Collection> + */ + public function recent(int $limit = 50): Collection + { + if (! $this->ready()) { + return collect(); + } + + try { + return CourierSurchargeAuditLog::query() + ->with('actor') + ->orderByDesc('id') + ->limit(max(1, min($limit, 200))) + ->get() + ->map(fn (CourierSurchargeAuditLog $log): array => [ + 'id' => $log->id, + 'occurred_at' => optional($log->created_at)->format('Y-m-d H:i:s') ?: '', + 'actor_name' => $log->actor?->name ?: '系统', + 'action' => $log->action, + 'action_label' => self::ACTION_LABELS[$log->action] ?? $log->action, + 'target_type' => $log->target_type, + 'target_id' => $log->target_id, + 'target_type_label' => self::TARGET_LABELS[$log->target_type] ?? $log->target_type, + 'target_label' => $log->target_label, + 'changes_label' => $this->changesLabel($log), + ]) + ->values(); + } catch (QueryException) { + return collect(); + } + } + + private function changesLabel(CourierSurchargeAuditLog $log): string + { + $changes = (array) $log->changes; + if ($log->action === CourierSurchargeAuditLog::ACTION_CREATED) { + return '新增记录'; + } + + if (in_array($log->action, [CourierSurchargeAuditLog::ACTION_ACTIVATED, CourierSurchargeAuditLog::ACTION_DEACTIVATED], true)) { + $before = data_get($changes, 'before.status'); + $after = data_get($changes, 'after.status'); + return sprintf('状态:%s → %s', $before ?: '—', $after ?: '—'); + } + + $before = (array) ($changes['before'] ?? []); + $after = (array) ($changes['after'] ?? []); + $parts = []; + foreach (array_unique(array_merge(array_keys($before), array_keys($after))) as $field) { + $old = $this->valueLabel($before[$field] ?? null); + $new = $this->valueLabel($after[$field] ?? null); + if ($old !== $new) { + $parts[] = sprintf('%s:%s → %s', self::FIELD_LABELS[$field] ?? $field, $old, $new); + } + } + + return $parts === [] ? '未改变字段' : implode(';', $parts); + } + + private function valueLabel(mixed $value): string + { + if (is_array($value)) { + return implode('、', array_map(static fn (mixed $item): string => (string) $item, $value)); + } + + $value = trim((string) $value); + + return $value === '' ? '—' : $value; + } +} diff --git a/app/Business/CourierSurchargeQuoteRepository.php b/app/Business/CourierSurchargeQuoteRepository.php index 8cc35a10..bd084c20 100644 --- a/app/Business/CourierSurchargeQuoteRepository.php +++ b/app/Business/CourierSurchargeQuoteRepository.php @@ -2,10 +2,12 @@ namespace App\Business; +use App\Models\Business\CourierSurchargeAuditLog; use App\Models\Business\CourierSurchargeQuote; use App\Models\Business\CourierSurchargeType; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; /** @@ -28,14 +30,21 @@ class CourierSurchargeQuoteRepository public const SCOPES = ['自有快递', '代发仓']; - public function __construct(private readonly CourierSurchargeTypeRepository $types) + public function __construct( + private readonly CourierSurchargeTypeRepository $types, + private readonly CourierSurchargeAuditLogRepository $audits, + ) { } public function ready(): bool { try { - return Schema::hasTable((new CourierSurchargeQuote())->getTable()) && $this->types->ready(); + $table = (new CourierSurchargeQuote())->getTable(); + + return Schema::hasTable($table) + && Schema::hasColumn($table, 'supplier') + && $this->types->ready(); } catch (QueryException) { return false; } @@ -58,8 +67,7 @@ class CourierSurchargeQuoteRepository try { $all = CourierSurchargeQuote::query() - ->orderByDesc('effective_at') - ->orderByDesc('id') + ->orderBy('id') ->get(); } catch (QueryException) { return [ @@ -71,7 +79,7 @@ class CourierSurchargeQuoteRepository } $filtered = $all->filter(function (CourierSurchargeQuote $quote) use ($filters): bool { - foreach (['courier', 'scope', 'reconciler', 'mode'] as $key) { + foreach (['courier', 'scope', 'reconciler', 'supplier', 'mode'] as $key) { if (($filters[$key] ?? '') !== '' && (string) $quote->{$key} !== $filters[$key]) { return false; } @@ -91,6 +99,7 @@ class CourierSurchargeQuoteRepository $quote->courier, $quote->scope, $quote->reconciler, + (string) $quote->supplier, $quote->typeLabel(), $quote->mode, $quote->standard, @@ -134,6 +143,7 @@ class CourierSurchargeQuoteRepository 'modes' => collect(self::MODES), 'scopes' => self::SCOPES, 'reconcilers' => $all->pluck('reconciler')->filter()->unique()->sort()->values(), + 'suppliers' => $all->pluck('supplier')->filter()->unique()->sort()->values(), 'statuses' => ['已启用', '已停用'], ], ]; @@ -151,30 +161,147 @@ class CourierSurchargeQuoteRepository return $this->types->activeNames(); } + /** @param array $data */ + public function findImportDuplicate(array $data, bool $lockForUpdate = false): ?CourierSurchargeQuote + { + $query = CourierSurchargeQuote::query() + ->where('company_id', company_id()) + ->where('courier', trim((string) $data['courier'])) + ->where('scope', trim((string) $data['scope'])) + ->where('reconciler', trim((string) $data['reconciler'])) + ->where('mode', trim((string) $data['mode'])) + ->where('condition', trim((string) $data['condition'])) + ->whereDate('effective_at', (string) $data['effective_at']); + + $supplier = trim((string) ($data['supplier'] ?? '')); + $supplier === '' ? $query->whereNull('supplier') : $query->where('supplier', $supplier); + + if ($lockForUpdate) { + $query->lockForUpdate(); + } + + $types = $this->normalizedTypes((array) $data['types']); + + return $query->get()->first( + fn (CourierSurchargeQuote $quote): bool => $this->normalizedTypes((array) $quote->types) === $types, + ); + } + + /** @param array $data */ + public function importIdentity(array $data): string + { + return hash('sha256', json_encode([ + trim((string) ($data['courier'] ?? '')), + trim((string) ($data['scope'] ?? '')), + trim((string) ($data['reconciler'] ?? '')), + trim((string) ($data['supplier'] ?? '')), + $this->normalizedTypes((array) ($data['types'] ?? [])), + trim((string) ($data['mode'] ?? '')), + trim((string) ($data['effective_at'] ?? '')), + trim((string) ($data['condition'] ?? '')), + ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); + } + /** @param array $data */ public function create(array $data, int $userId): CourierSurchargeQuote { - return CourierSurchargeQuote::query()->create($this->attributes($data, $userId) + [ - 'status' => CourierSurchargeQuote::STATUS_ACTIVE, - 'created_by' => $userId, - ]); + return DB::transaction(function () use ($data, $userId): CourierSurchargeQuote { + $quote = CourierSurchargeQuote::query()->create($this->attributes($data, $userId) + [ + 'status' => CourierSurchargeQuote::STATUS_ACTIVE, + 'created_by' => $userId, + ]); + + $this->audits->record( + CourierSurchargeAuditLog::ACTION_CREATED, + CourierSurchargeAuditLog::TARGET_QUOTE, + (int) $quote->id, + $this->targetLabel($quote), + ['after' => $this->snapshot($quote)], + $userId, + ); + + return $quote; + }); } /** @param array $data */ public function update(CourierSurchargeQuote $quote, array $data, int $userId): CourierSurchargeQuote { - $quote->update($this->attributes($data, $userId)); + return DB::transaction(function () use ($quote, $data, $userId): CourierSurchargeQuote { + $before = $this->snapshot($quote); + $quote->update($this->attributes($data, $userId)); + $fresh = $quote->fresh(); - return $quote->fresh(); + $this->audits->record( + CourierSurchargeAuditLog::ACTION_UPDATED, + CourierSurchargeAuditLog::TARGET_QUOTE, + (int) $fresh->id, + $this->targetLabel($fresh), + ['before' => $before, 'after' => $this->snapshot($fresh)], + $userId, + ); + + return $fresh; + }); } public function setStatus(CourierSurchargeQuote $quote, string $status, int $userId): CourierSurchargeQuote { abort_unless(in_array($status, [CourierSurchargeQuote::STATUS_ACTIVE, CourierSurchargeQuote::STATUS_INACTIVE], true), 422, '报价规则状态不合法。'); - $quote->forceFill(['status' => $status, 'updated_by' => $userId])->save(); + return DB::transaction(function () use ($quote, $status, $userId): CourierSurchargeQuote { + $oldStatus = $quote->status; + $quote->forceFill(['status' => $status, 'updated_by' => $userId])->save(); + $fresh = $quote->fresh(); - return $quote->fresh(); + if ($oldStatus !== $status) { + $this->audits->record( + $status === CourierSurchargeQuote::STATUS_ACTIVE + ? CourierSurchargeAuditLog::ACTION_ACTIVATED + : CourierSurchargeAuditLog::ACTION_DEACTIVATED, + CourierSurchargeAuditLog::TARGET_QUOTE, + (int) $fresh->id, + $this->targetLabel($fresh), + [ + 'before' => ['status' => $this->statusLabel($oldStatus)], + 'after' => ['status' => $this->statusLabel($status)], + ], + $userId, + ); + } + + return $fresh; + }); + } + + private function targetLabel(CourierSurchargeQuote $quote): string + { + $type = $quote->typeLabel(); + + return trim(sprintf('%s%s', $quote->courier, $type === '' ? '' : ' · ' . $type)); + } + + /** @return array */ + private function snapshot(CourierSurchargeQuote $quote): array + { + return [ + 'courier' => $quote->courier, + 'scope' => $quote->scope, + 'reconciler' => $quote->reconciler, + 'supplier' => $quote->supplier, + 'types' => array_values((array) $quote->types), + 'mode' => $quote->mode, + 'standard' => $quote->standard, + 'condition' => $quote->condition, + 'effective_at' => optional($quote->effective_at)->format('Y-m-d'), + 'status' => $this->statusLabel($quote->status), + 'remark' => $quote->remark, + ]; + } + + private function statusLabel(?string $status): string + { + return $status === CourierSurchargeQuote::STATUS_ACTIVE ? '已启用' : '已停用'; } /** @param array $data */ @@ -185,6 +312,7 @@ class CourierSurchargeQuoteRepository 'courier' => trim((string) $data['courier']), 'scope' => trim((string) $data['scope']), 'reconciler' => trim((string) $data['reconciler']), + 'supplier' => trim((string) ($data['supplier'] ?? '')) ?: null, 'types' => array_values(array_unique(array_map('strval', $data['types']))), 'mode' => trim((string) $data['mode']), 'standard' => trim((string) $data['standard']), @@ -195,6 +323,18 @@ class CourierSurchargeQuoteRepository ]; } + /** @param array $types @return list */ + private function normalizedTypes(array $types): array + { + $types = array_values(array_unique(array_filter(array_map( + static fn (mixed $type): string => trim((string) $type), + $types, + )))); + sort($types, SORT_STRING); + + return $types; + } + /** @return array */ private function present(CourierSurchargeQuote $quote): array { @@ -204,6 +344,7 @@ class CourierSurchargeQuoteRepository 'courier' => $quote->courier, 'scope' => $quote->scope, 'reconciler' => $quote->reconciler, + 'supplier' => $quote->supplier, 'types' => array_values((array) $quote->types), 'type' => $quote->typeLabel(), 'mode' => $quote->mode, @@ -227,6 +368,7 @@ class CourierSurchargeQuoteRepository 'modes' => collect(self::MODES), 'scopes' => self::SCOPES, 'reconcilers' => collect(), + 'suppliers' => collect(), 'statuses' => ['已启用', '已停用'], ]; } diff --git a/app/Business/CourierSurchargeQuoteWorkbookImporter.php b/app/Business/CourierSurchargeQuoteWorkbookImporter.php new file mode 100644 index 00000000..a630cc1f --- /dev/null +++ b/app/Business/CourierSurchargeQuoteWorkbookImporter.php @@ -0,0 +1,386 @@ +quotes->activeTypeNames(); + + return response()->streamDownload(function () use ($types): void { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('附加费报价'); + $sheet->fromArray(self::HEADERS, null, 'A1'); + + $lastColumn = Coordinate::stringFromColumnIndex(count(self::HEADERS)); + $headerRange = 'A1:' . $lastColumn . '1'; + $sheet->getStyle($headerRange)->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER], + 'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'D8D2C7']]], + ]); + $sheet->getRowDimension(1)->setRowHeight(24); + $sheet->freezePane('A2'); + $sheet->setAutoFilter($headerRange); + + $widths = [18, 14, 14, 20, 24, 18, 30, 32, 14, 12, 30]; + foreach ($widths as $index => $width) { + $column = Coordinate::stringFromColumnIndex($index + 1); + $sheet->getColumnDimension($column)->setWidth($width); + $sheet->getStyle($column . '2:' . $column . (self::MAX_ROWS + 1)) + ->getNumberFormat() + ->setFormatCode('@'); + } + + $instructions = $spreadsheet->createSheet(); + $instructions->setTitle('填写说明'); + $instructions->fromArray([ + ['项目', '填写要求'], + ['必填字段', '快递名称、快递归属、对账人、附加费类型、结算方式、计价标准、生效条件、生效日期、状态。'], + ['供应商', '选填;没有供应商时保持空白。'], + ['附加费类型', '多种类型使用“、”分隔;只能填写当前已启用类型。当前可选:' . implode('、', $types)], + ['快递归属', '自有快递 或 代发仓。'], + ['结算方式', implode('、', CourierSurchargeQuoteRepository::MODES)], + ['生效日期', '使用 YYYY-MM-DD,例如 2026-09-22。'], + ['状态', '已启用 或 已停用;也可填写 active 或 inactive。'], + ['重复规则', '预览后必须明确选择跳过已有规则或更新已有规则,系统不会静默覆盖。'], + ['单次上限', '最多 ' . self::MAX_ROWS . ' 条非空数据。'], + ], null, 'A1'); + $instructions->getStyle('A1:B1')->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + ]); + $instructions->getColumnDimension('A')->setWidth(18); + $instructions->getColumnDimension('B')->setWidth(90); + $instructions->getStyle('A1:B10')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER)->setWrapText(true); + foreach (range(1, 10) as $row) { + $instructions->getRowDimension($row)->setRowHeight($row === 1 ? 24 : 34); + } + + $spreadsheet->setActiveSheetIndex(0); + (new Xlsx($spreadsheet))->save('php://output'); + $spreadsheet->disconnectWorksheets(); + }, '附加费报价导入模板_' . now()->format('Ymd') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * @return array{ + * rows:list,display:array,errors:list,result:string,result_label:string,existing_id:?int}>, + * summary:array{total:int,valid:int,new:int,duplicate:int,invalid:int} + * } + */ + public function preview(UploadedFile $file): array + { + $extension = mb_strtolower($file->getClientOriginalExtension()); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages(['import' => '仅支持 xlsx、xls 或 csv 文件。']); + } + + try { + $reader = IOFactory::createReader(match ($extension) { + 'xlsx' => 'Xlsx', + 'xls' => 'Xls', + 'csv' => 'Csv', + }); + $reader->setReadDataOnly(true); + $spreadsheet = $reader->load($file->getRealPath()); + $rows = $spreadsheet->getActiveSheet()->toArray(null, false, false, false); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。', + ]); + } finally { + if (isset($spreadsheet)) { + $spreadsheet->disconnectWorksheets(); + } + } + + $headers = array_map(fn (mixed $value): string => $this->text($value), $rows[0] ?? []); + while ($headers !== [] && end($headers) === '') { + array_pop($headers); + } + if ($headers !== self::HEADERS) { + throw ValidationException::withMessages([ + 'import' => '表头不正确。请下载最新模板,并保持 11 个字段名称及顺序不变。', + ]); + } + + $dataRows = []; + foreach (array_slice($rows, 1, null, true) as $index => $row) { + $row = array_slice(array_pad($row, count(self::HEADERS), null), 0, count(self::HEADERS)); + if (collect($row)->every(fn (mixed $value): bool => $this->text($value) === '')) { + continue; + } + $dataRows[] = ['line' => $index + 1, 'values' => $row]; + if (count($dataRows) > self::MAX_ROWS) { + throw ValidationException::withMessages([ + 'import' => '单次最多导入 ' . self::MAX_ROWS . ' 条非空数据,请拆分文件后重试。', + ]); + } + } + + if ($dataRows === []) { + throw ValidationException::withMessages(['import' => '表格中没有可预览的数据行。']); + } + + $previewRows = array_map(fn (array $row): array => $this->normalizeRow($row['values'], $row['line']), $dataRows); + $signatures = []; + foreach ($previewRows as $index => $row) { + if ($row['errors'] === []) { + $signatures[$this->quotes->importIdentity($row['data'])][] = $index; + } + } + foreach ($signatures as $indexes) { + if (count($indexes) < 2) { + continue; + } + $lines = implode('、', array_map(fn (int $index): int => $previewRows[$index]['line'], $indexes)); + foreach ($indexes as $index) { + $previewRows[$index]['errors'][] = '文件内规则重复(行号:' . $lines . ')。'; + } + } + + foreach ($previewRows as &$row) { + if ($row['errors'] !== []) { + $row['result'] = 'invalid'; + $row['result_label'] = '校验失败'; + continue; + } + $existing = $this->quotes->findImportDuplicate($row['data']); + $row['existing_id'] = $existing?->id; + $row['result'] = $existing ? 'duplicate' : 'new'; + $row['result_label'] = $existing ? '已有规则' : '可新增'; + } + unset($row); + + $collection = collect($previewRows); + + return [ + 'rows' => $previewRows, + 'summary' => [ + 'total' => $collection->count(), + 'valid' => $collection->where('result', '!=', 'invalid')->count(), + 'new' => $collection->where('result', 'new')->count(), + 'duplicate' => $collection->where('result', 'duplicate')->count(), + 'invalid' => $collection->where('result', 'invalid')->count(), + ], + ]; + } + + /** + * @param list,errors:list}> $rows + * @return array{created:int,updated:int,skipped:int,total:int} + */ + public function commit(array $rows, string $duplicatePolicy, int $userId): array + { + if (! in_array($duplicatePolicy, [self::DUPLICATE_SKIP, self::DUPLICATE_UPDATE], true)) { + throw ValidationException::withMessages(['duplicate_policy' => '请选择已有规则的处理方式。']); + } + if ($rows === [] || count($rows) > self::MAX_ROWS || collect($rows)->contains(fn (array $row): bool => ($row['errors'] ?? []) !== [])) { + throw ValidationException::withMessages(['import' => '预览数据无效或包含错误,请重新上传文件。']); + } + + $activeTypes = $this->quotes->activeTypeNames(); + foreach ($rows as $row) { + $inactive = array_values(array_diff((array) ($row['data']['types'] ?? []), $activeTypes)); + if ($inactive !== []) { + throw ValidationException::withMessages([ + 'import' => '附加费类型“' . implode('、', $inactive) . '”已停用或不存在,请重新预览。', + ]); + } + } + + $counts = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'total' => count($rows)]; + DB::transaction(function () use ($rows, $duplicatePolicy, $userId, &$counts): void { + foreach ($rows as $row) { + $data = $row['data']; + $status = $data['status']; + unset($data['status']); + + $existing = $this->quotes->findImportDuplicate($data, true); + if ($existing && $duplicatePolicy === self::DUPLICATE_SKIP) { + $counts['skipped']++; + continue; + } + + if ($existing) { + $quote = $this->quotes->update($existing, $data, $userId); + $counts['updated']++; + } else { + $quote = $this->quotes->create($data, $userId); + $counts['created']++; + } + + if ($quote->status !== $status) { + $this->quotes->setStatus($quote, $status, $userId); + } + } + }); + + return $counts; + } + + /** @return array{line:int,data:array,display:array,errors:list,result:string,result_label:string,existing_id:?int} */ + private function normalizeRow(array $values, int $line): array + { + $raw = array_combine(self::HEADERS, $values); + $display = []; + foreach ($raw as $header => $value) { + $display[$header] = $this->text($value); + } + + $errors = []; + foreach (['快递名称', '快递归属', '对账人', '附加费类型', '结算方式', '计价标准', '生效条件', '生效日期', '状态'] as $header) { + if ($display[$header] === '') { + $errors[] = $header . '不能为空。'; + } + } + + $this->checkLength($display, '快递名称', 191, $errors); + $this->checkLength($display, '对账人', 100, $errors); + $this->checkLength($display, '供应商', 191, $errors); + $this->checkLength($display, '计价标准', 2000, $errors); + $this->checkLength($display, '生效条件', 2000, $errors); + $this->checkLength($display, '备注', 2000, $errors); + + $types = array_values(array_unique(array_filter(array_map( + 'trim', + preg_split('/[、,,;;]+/u', $display['附加费类型']) ?: [], + )))); + if (count($types) > 50) { + $errors[] = '附加费类型最多 50 项。'; + } + $validTypes = $this->quotes->validTypeNames(); + $activeTypes = $this->quotes->activeTypeNames(); + $unknownTypes = array_values(array_diff($types, $validTypes)); + $inactiveTypes = array_values(array_diff(array_intersect($types, $validTypes), $activeTypes)); + if ($unknownTypes !== []) { + $errors[] = '附加费类型不存在:' . implode('、', $unknownTypes) . '。'; + } + if ($inactiveTypes !== []) { + $errors[] = '附加费类型已停用:' . implode('、', $inactiveTypes) . '。'; + } + if ($display['快递归属'] !== '' && ! in_array($display['快递归属'], CourierSurchargeQuoteRepository::SCOPES, true)) { + $errors[] = '快递归属只能填写“自有快递”或“代发仓”。'; + } + if ($display['结算方式'] !== '' && ! in_array($display['结算方式'], CourierSurchargeQuoteRepository::MODES, true)) { + $errors[] = '结算方式不在允许范围内。'; + } + + $effectiveAt = $this->date($raw['生效日期']); + if ($display['生效日期'] !== '' && $effectiveAt === null) { + $errors[] = '生效日期必须是有效的 YYYY-MM-DD 日期。'; + } + + $status = match (mb_strtolower($display['状态'])) { + '已启用', CourierSurchargeQuote::STATUS_ACTIVE => CourierSurchargeQuote::STATUS_ACTIVE, + '已停用', CourierSurchargeQuote::STATUS_INACTIVE => CourierSurchargeQuote::STATUS_INACTIVE, + default => null, + }; + if ($display['状态'] !== '' && $status === null) { + $errors[] = '状态只能填写“已启用/active”或“已停用/inactive”。'; + } + + if ($effectiveAt !== null) { + $display['生效日期'] = $effectiveAt; + } + + return [ + 'line' => $line, + 'data' => [ + 'courier' => $display['快递名称'], + 'scope' => $display['快递归属'], + 'reconciler' => $display['对账人'], + 'supplier' => $display['供应商'] !== '' ? $display['供应商'] : null, + 'types' => $types, + 'mode' => $display['结算方式'], + 'standard' => $display['计价标准'], + 'condition' => $display['生效条件'], + 'effective_at' => $effectiveAt, + 'status' => $status, + 'remark' => $display['备注'], + ], + 'display' => $display, + 'errors' => array_values(array_unique($errors)), + 'result' => 'invalid', + 'result_label' => '校验失败', + 'existing_id' => null, + ]; + } + + /** @param array $values @param list $errors */ + private function checkLength(array $values, string $field, int $max, array &$errors): void + { + if (mb_strlen($values[$field]) > $max) { + $errors[] = $field . '不能超过 ' . $max . ' 个字符。'; + } + } + + private function date(mixed $value): ?string + { + if (is_numeric($value) && (float) $value > 0) { + try { + return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d'); + } catch (Throwable) { + return null; + } + } + + $value = $this->text($value); + if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value, $matches)) { + return null; + } + + return checkdate((int) $matches[2], (int) $matches[3], (int) $matches[1]) ? $value : null; + } + + private function text(mixed $value): string + { + return trim(str_replace("\xEF\xBB\xBF", '', (string) ($value ?? ''))); + } +} diff --git a/app/Business/CourierSurchargeTypeRepository.php b/app/Business/CourierSurchargeTypeRepository.php index 674cdee2..66791f73 100644 --- a/app/Business/CourierSurchargeTypeRepository.php +++ b/app/Business/CourierSurchargeTypeRepository.php @@ -2,10 +2,12 @@ namespace App\Business; +use App\Models\Business\CourierSurchargeAuditLog; use App\Models\Business\CourierSurchargeQuote; use App\Models\Business\CourierSurchargeType; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; @@ -17,6 +19,10 @@ use Illuminate\Validation\ValidationException; */ class CourierSurchargeTypeRepository { + public function __construct(private readonly CourierSurchargeAuditLogRepository $audits) + { + } + /** @var list */ public const DEFAULT_NAMES = [ '退回费', '拦截费', '改地址', '异形件', '超长费', @@ -89,14 +95,27 @@ class CourierSurchargeTypeRepository $sortOrder = ((int) CourierSurchargeType::query()->max('sort_order')) + 1; - return CourierSurchargeType::query()->create([ - 'company_id' => company_id(), - 'name' => $name, - 'status' => CourierSurchargeType::STATUS_ACTIVE, - 'sort_order' => $sortOrder, - 'created_by' => $userId, - 'updated_by' => $userId, - ]); + return DB::transaction(function () use ($name, $sortOrder, $userId): CourierSurchargeType { + $type = CourierSurchargeType::query()->create([ + 'company_id' => company_id(), + 'name' => $name, + 'status' => CourierSurchargeType::STATUS_ACTIVE, + 'sort_order' => $sortOrder, + 'created_by' => $userId, + 'updated_by' => $userId, + ]); + + $this->audits->record( + CourierSurchargeAuditLog::ACTION_CREATED, + CourierSurchargeAuditLog::TARGET_TYPE, + (int) $type->id, + $type->name, + ['after' => ['name' => $type->name, 'status' => '已启用']], + $userId, + ); + + return $type; + }); } catch (QueryException $exception) { if ((int) $exception->getCode() === 23000) { throw ValidationException::withMessages(['name' => '当前公司已有同名附加费类型。']); @@ -110,12 +129,37 @@ class CourierSurchargeTypeRepository { abort_unless(in_array($status, [CourierSurchargeType::STATUS_ACTIVE, CourierSurchargeType::STATUS_INACTIVE], true), 422, '附加费类型状态不合法。'); - $type->forceFill([ - 'status' => $status, - 'updated_by' => $userId, - ])->save(); + return DB::transaction(function () use ($type, $status, $userId): CourierSurchargeType { + $oldStatus = $type->status; + $type->forceFill([ + 'status' => $status, + 'updated_by' => $userId, + ])->save(); + $fresh = $type->fresh(); - return $type->fresh(); + if ($oldStatus !== $status) { + $this->audits->record( + $status === CourierSurchargeType::STATUS_ACTIVE + ? CourierSurchargeAuditLog::ACTION_ACTIVATED + : CourierSurchargeAuditLog::ACTION_DEACTIVATED, + CourierSurchargeAuditLog::TARGET_TYPE, + (int) $fresh->id, + $fresh->name, + [ + 'before' => ['status' => $this->statusLabel($oldStatus)], + 'after' => ['status' => $this->statusLabel($status)], + ], + $userId, + ); + } + + return $fresh; + }); + } + + private function statusLabel(?string $status): string + { + return $status === CourierSurchargeType::STATUS_ACTIVE ? '已启用' : '已停用'; } private function ensureDefaults(int $companyId): void diff --git a/app/Business/InventoryWarehouseNameMappingWorkbookImporter.php b/app/Business/InventoryWarehouseNameMappingWorkbookImporter.php new file mode 100644 index 00000000..48f00077 --- /dev/null +++ b/app/Business/InventoryWarehouseNameMappingWorkbookImporter.php @@ -0,0 +1,213 @@ +,sheet:string,headers:list,summary:array} */ + public function preview(UploadedFile $file): array + { + $spreadsheet = IOFactory::load($file->getRealPath()); + $worksheet = $this->findWorksheet($spreadsheet); + + if ($worksheet === null) { + throw ValidationException::withMessages([ + 'import' => '未找到包含“仓储方、仓库、仓库简称”三列的工作表。Sheet2 仅是辅助仓库清单,不能直接导入。', + ]); + } + + $rows = $worksheet->toArray(null, true, false, false); + $parsed = []; + $seen = []; + $created = 0; + $same = 0; + $conflicts = 0; + $invalid = 0; + + foreach (array_slice($rows, 1) as $offset => $row) { + $rowNumber = $offset + 2; + $provider = trim((string) ($row[0] ?? '')); + $warehouse = trim((string) ($row[1] ?? '')); + $shortName = trim((string) ($row[2] ?? '')); + if ($provider === '' && $warehouse === '' && $shortName === '') { + continue; + } + + $key = $this->key($provider, $warehouse); + $item = [ + 'row_number' => $rowNumber, + 'warehouse_provider' => $provider, + 'warehouse' => $warehouse, + 'warehouse_short_name' => $shortName, + 'status' => 'new', + 'message' => '待新增', + ]; + + if ($provider === '' || $warehouse === '' || $shortName === '') { + $item['status'] = 'invalid'; + $item['message'] = '仓储方、仓库、仓库简称均为必填字段'; + $invalid++; + } elseif (isset($seen[$key])) { + $item['status'] = $seen[$key]['warehouse_short_name'] === $shortName ? 'same' : 'conflict'; + $item['message'] = $item['status'] === 'same' + ? '与文件内前一行重复,将跳过' + : '与文件内前一行的仓库简称冲突'; + $item['status'] === 'same' ? $same++ : $conflicts++; + } else { + $existing = InventoryWarehouseNameMapping::query() + ->where('warehouse_provider', $provider) + ->where('warehouse', $warehouse) + ->first(); + + if ($existing) { + $item['status'] = $existing->warehouse_short_name === $shortName ? 'same' : 'conflict'; + $item['message'] = $item['status'] === 'same' + ? '数据库已有相同映射,将跳过' + : '数据库已有不同简称,禁止静默覆盖'; + $item['status'] === 'same' ? $same++ : $conflicts++; + } else { + $created++; + } + } + + $parsed[] = $item; + if ($provider !== '' && $warehouse !== '' && $shortName !== '' && ! isset($seen[$key])) { + $seen[$key] = $item; + } + } + + return [ + 'rows' => $parsed, + 'sheet' => $worksheet->getTitle(), + 'headers' => self::HEADERS, + 'summary' => compact('created', 'same', 'conflicts', 'invalid'), + ]; + } + + /** @param array{rows:list} $preview */ + public function commit(array $preview): array + { + $rows = $preview['rows'] ?? []; + $invalid = collect($rows)->first(fn (array $row): bool => in_array($row['status'] ?? '', ['invalid', 'conflict'], true)); + if ($invalid !== null) { + throw ValidationException::withMessages([ + 'import' => '导入预览存在必填字段错误或简称冲突,请先处理标记为失败的行。', + ]); + } + + $created = 0; + $skipped = 0; + DB::transaction(function () use ($rows, &$created, &$skipped): void { + foreach ($rows as $row) { + if (($row['status'] ?? '') === 'same') { + $skipped++; + continue; + } + + $query = InventoryWarehouseNameMapping::query() + ->where('warehouse_provider', $row['warehouse_provider']) + ->where('warehouse', $row['warehouse']); + if ($query->exists()) { + throw ValidationException::withMessages([ + 'import' => "第 {$row['row_number']} 行在确认时已被其他操作占用,请重新预览。", + ]); + } + + InventoryWarehouseNameMapping::create([ + 'company_id' => company_id() ?: 1, + 'warehouse_provider' => $row['warehouse_provider'], + 'warehouse' => $row['warehouse'], + 'warehouse_short_name' => $row['warehouse_short_name'], + 'created_by' => auth()->id(), + 'updated_by' => auth()->id(), + ]); + $created++; + } + }); + + return compact('created', 'skipped'); + } + + public static function suggestion(string $provider, string $warehouse): string + { + $provider = trim($provider); + $warehouse = trim($warehouse); + $haystack = $provider . ' ' . $warehouse; + + if (str_starts_with($provider, '奇门-')) { + return '不看'; + } + + foreach ([ + '配件单仓' => '配件单仓-不看', + 'POP仓' => '京东入仓-不看', + '自动发货仓' => '虚拟仓-不看', + '京东云仓' => '京东云仓-不看', + '京东京造' => '京东京造-不看', + '苏州福利品仓' => '苏州福利品仓-不看', + '信誉订单仓' => '信誉订单仓-不看', + '代发仓' => '代发仓', + '销退仓' => '销退仓-不看', + '客退' => '客退仓-不看', + '次品仓' => '退货报废-不看', + '数量校验仓' => '数量校验仓-不看', + ] as $needle => $result) { + if (str_contains($haystack, $needle)) { + return $result; + } + } + + foreach ([ + '运营C崔桥工厂仓' => '崔桥工厂仓', + '运营C横林二仓' => '横林二仓', + '运营C睢宁' => '睢宁仓', + '运营C新苏北' => '新苏北仓', + '江西仓送货' => '南昌樵舍仓', + ] as $needle => $result) { + if (str_contains($haystack, $needle)) { + return $result; + } + } + + $short = preg_replace('/(主仓|进货仓)$/u', '', $warehouse) ?: $warehouse; + $short = preg_replace('/^(简尚-|京仓-|三方-|奇门-)/u', '', $short) ?: $short; + $providerBase = preg_replace('/^(简尚-|京仓-|三方-|奇门-)/u', '', $provider) ?: $provider; + if ($short === $providerBase || str_starts_with($short, $providerBase)) { + $short = $providerBase; + } + + return $short !== '' ? $short : $warehouse; + } + + private function findWorksheet($spreadsheet): ?object + { + foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { + $row = $worksheet->toArray(null, true, false, false)[0] ?? []; + $headers = array_map(fn ($value): string => $this->normalize((string) $value), $row); + $expected = array_map(fn ($value): string => $this->normalize($value), self::HEADERS); + if (count(array_intersect($expected, $headers)) === count($expected)) { + return $worksheet; + } + } + + return null; + } + + private function normalize(string $value): string + { + return mb_strtolower(preg_replace('/[\s\x{FEFF}_\-()()]+/u', '', trim($value))); + } + + private function key(string $provider, string $warehouse): string + { + return $provider . "\0" . $warehouse; + } +} diff --git a/app/Business/InventoryWarehouseShortNames.php b/app/Business/InventoryWarehouseShortNames.php new file mode 100644 index 00000000..12a8025a --- /dev/null +++ b/app/Business/InventoryWarehouseShortNames.php @@ -0,0 +1,35 @@ + */ + public function forCompany(int $companyId): array + { + return InventoryWarehouseNameMapping::allCompanies() + ->companyId($companyId) + ->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']) + ->mapWithKeys(static fn (InventoryWarehouseNameMapping $mapping): array => [ + self::key($mapping->warehouse_provider, $mapping->warehouse) => $mapping->warehouse_short_name, + ])->all(); + } + + /** @param array $names */ + public function fill(object $row, array $names): object + { + $row->warehouse_short_name = $names[self::key( + (string) ($row->warehouse_provider ?? ''), + (string) ($row->warehouse ?? ''), + )] ?? ''; + + return $row; + } + + private static function key(string $provider, string $warehouse): string + { + return $provider . "\0" . $warehouse; + } +} diff --git a/app/Business/JstOrderLabelImporter.php b/app/Business/JstOrderLabelImporter.php new file mode 100644 index 00000000..7f4f5381 --- /dev/null +++ b/app/Business/JstOrderLabelImporter.php @@ -0,0 +1,158 @@ +normalizeDate($from, '起始日期'); + $to = $this->normalizeDate($to, '结束日期'); + if ($from > $to) { + throw new InvalidArgumentException('起始日期不能晚于结束日期。'); + } + + $start = $from . ' 00:00:00'; + $end = date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00'; + + $mirror = $this->databases->connection(config('upstream_mirrors.connection', 'business_mirror')); + if (! $mirror->getSchemaBuilder()->hasTable('ops_jst_orders')) { + throw new RuntimeException('聚水潭订单镜像尚未建立(ops_jst_orders)。'); + } + + $target = $this->databases->connection(); + $startedAt = microtime(true); + + if ($replace) { + $target->table('jst_order_labels') + ->where('company_id', $companyId) + ->where('ordered_at', '>=', $start) + ->where('ordered_at', '<', $end) + ->delete(); + } + + $now = now(); + $orders = 0; + $rows = 0; + $noLabelOrders = 0; + $buffer = []; + + $flush = function () use (&$buffer, &$rows, $target): void { + foreach (array_chunk($buffer, self::INSERT_CHUNK) as $chunk) { + $target->table('jst_order_labels')->insert($chunk); + $rows += count($chunk); + } + $buffer = []; + }; + + $mirror->table('ops_jst_orders') + ->where('order_date', '>=', $start) + ->where('order_date', '<', $end) + ->orderBy('Id') + ->chunkById(self::READ_CHUNK, function ($records) use (&$buffer, &$orders, &$noLabelOrders, $flush, $companyId, $source, $now): void { + foreach ($records as $record) { + $orders++; + $orderedAt = $record->order_date === null ? null : substr((string) $record->order_date, 0, 19); + if ($orderedAt === null || $orderedAt === '') { + continue; + } + + $labels = $this->splitLabels((string) ($record->labels ?? '')); + if ($labels === []) { + $labels = [self::NO_LABEL]; + $noLabelOrders++; + } + + foreach ($labels as $label) { + $buffer[] = [ + 'company_id' => $companyId, + 'order_no' => mb_substr((string) $record->so_id, 0, 100), + 'shop_name' => mb_substr((string) ($record->shop_name ?? ''), 0, 191), + 'ordered_at' => $orderedAt, + 'label' => $label, + 'created_from' => $source, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + if (count($buffer) >= self::INSERT_CHUNK * 2) { + $flush(); + } + } + }, 'Id'); + + $flush(); + + $labels = $target->table('jst_order_labels') + ->where('company_id', $companyId) + ->where('ordered_at', '>=', $start) + ->where('ordered_at', '<', $end) + ->distinct() + ->count('label'); + + // 导入会改变筛选选项,重新预热缓存,避免页面下次打开时做几秒的 distinct 扫描。 + app(JstOrderLabelOptions::class)->forget($companyId); + app(JstOrderLabelOptions::class)->warm($companyId); + + return [ + 'from' => $from, + 'to' => $to, + 'orders' => $orders, + 'rows' => $rows, + 'no_label_orders' => $noLabelOrders, + 'labels' => (int) $labels, + 'seconds' => round(microtime(true) - $startedAt, 1), + ]; + } + + /** @return list */ + private function splitLabels(string $labels): array + { + $out = []; + foreach (explode(',', $labels) as $label) { + $label = trim($label); + if ($label !== '') { + $out[] = mb_substr($label, 0, 191); + } + } + + return array_values(array_unique($out)); + } + + private function normalizeDate(string $value, string $label): string + { + $value = trim($value); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + throw new InvalidArgumentException($label . '必须是 YYYY-MM-DD。'); + } + + [$year, $month, $day] = array_map('intval', explode('-', $value)); + if (! checkdate($month, $day, $year)) { + throw new InvalidArgumentException($label . '不是有效日期。'); + } + + return $value; + } +} diff --git a/app/Business/JstOrderLabelOptions.php b/app/Business/JstOrderLabelOptions.php new file mode 100644 index 00000000..57e2a7dc --- /dev/null +++ b/app/Business/JstOrderLabelOptions.php @@ -0,0 +1,96 @@ + */ + public function labels(int $companyId): array + { + return $this->remember($companyId, 'label'); + } + + /** @return list */ + public function shops(int $companyId): array + { + return $this->remember($companyId, 'shop_name'); + } + + public function warm(int $companyId): void + { + $this->labels($companyId); + $this->shops($companyId); + $this->total($companyId); + } + + public function forget(int $companyId): void + { + Cache::forget($this->key($companyId, 'label')); + Cache::forget($this->key($companyId, 'shop_name')); + Cache::forget($this->totalKey($companyId)); + } + + /** 无筛选时的总行数:233 万行上 COUNT(*) 要 2 秒,缓存后翻页不再重复统计。 */ + public function total(int $companyId): int + { + $key = $this->totalKey($companyId); + $cached = Cache::get($key); + if (is_numeric($cached)) { + return (int) $cached; + } + + $count = (int) JstOrderLabel::query()->where('company_id', $companyId)->count(); + Cache::put($key, $count, now()->addMinutes(self::TOTAL_TTL_MINUTES)); + + return $count; + } + + /** @return list */ + private function remember(int $companyId, string $column): array + { + $key = $this->key($companyId, $column); + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + $values = JstOrderLabel::query() + ->where('company_id', $companyId) + ->whereNotNull($column) + ->where($column, '<>', '') + ->distinct() + ->orderBy($column) + ->limit(self::LIMIT) + ->pluck($column) + ->all(); + + Cache::put($key, $values, now()->addHours(self::TTL_HOURS)); + + return $values; + } + + private function key(int $companyId, string $column): string + { + return "jst-order-labels:options:v1:{$companyId}:{$column}"; + } + + private function totalKey(int $companyId): string + { + return "jst-order-labels:total:v1:{$companyId}"; + } +} diff --git a/app/Business/PlantingDetailImporter.php b/app/Business/PlantingDetailImporter.php new file mode 100644 index 00000000..06d4f2a6 --- /dev/null +++ b/app/Business/PlantingDetailImporter.php @@ -0,0 +1,299 @@ + 'bill_date', + '订单编号' => 'order_no', + '财务售价' => 'finance_selling_price', + '财务运费' => 'finance_freight', + '财务佣金' => 'finance_commission', + '京喜差价' => 'jingxi_price_diff', + '扣款' => 'deduction', + '财务空包费' => 'finance_empty_package_fee', + '财务打款金额' => 'finance_payment_amount', + '笔数' => 'pieces', + '备注' => 'remark', + '正确店铺' => 'store', + '负责人' => 'owner', + '账户' => 'account', + '类型' => 'type', + '创建人' => 'creator', + '标签' => 'tag', + '所属利润中心' => 'profit_center', + '负责平台' => 'responsible_platform', + 'ID' => 'external_id', + ]; + + private const MONEY_COLUMNS = [ + 'finance_selling_price', 'finance_freight', 'finance_commission', + 'jingxi_price_diff', 'deduction', 'finance_empty_package_fee', 'finance_payment_amount', + ]; + + private const CHUNK = 1000; + + /** + * @return array{rows:int,inserted:int,skipped:int,selling_price:string,payment_amount:string,date_min:?string,date_max:?string} + */ + public function import(string $path, int $companyId = 1, bool $replace = false, ?int $userId = null, string $source = 'planting-detail-import'): array + { + if (! is_file($path)) { + throw new InvalidArgumentException('找不到要导入的文件:' . $path); + } + + $grid = $this->read($path); + if ($grid === []) { + throw new InvalidArgumentException('文件里没有可读的数据行。'); + } + + $headerIndex = $this->locateHeader($grid); + if ($headerIndex === null) { + throw new InvalidArgumentException('没找到表头:至少要有「日期」「订单编号」「财务打款金额」。'); + } + + $map = $this->mapHeader($grid[$headerIndex]); + if (! isset($map['bill_date'], $map['order_no'], $map['finance_payment_amount'])) { + throw new InvalidArgumentException('表头缺少「日期」或「订单编号」或「财务打款金额」。'); + } + + $now = now(); + $rows = []; + $skipped = 0; + $sellingPrice = 0.0; + $paymentAmount = 0.0; + $dateMin = null; + $dateMax = null; + $inserted = 0; + + $connection = DB::connection(); + if ($replace) { + PlantingDetail::query()->where('company_id', $companyId)->forceDelete(); + } + + $flush = function () use (&$rows, &$inserted, $connection): void { + if ($rows !== []) { + foreach (array_chunk($rows, self::CHUNK) as $chunk) { + $connection->table('planting_details')->insert($chunk); + $inserted += count($chunk); + } + $rows = []; + } + }; + + foreach (array_slice($grid, $headerIndex + 1) as $gridRow) { + if (! $this->hasContent($gridRow)) { + continue; + } + + $date = $this->toDate($this->cell($gridRow, $map, 'bill_date')); + $orderNo = $this->toText($this->cell($gridRow, $map, 'order_no')); + if ($date === null || $orderNo === null) { + $skipped++; + + continue; + } + + $record = [ + 'company_id' => $companyId, + 'bill_date' => $date, + 'order_no' => mb_substr($orderNo, 0, 100), + 'pieces' => (int) ($this->toNumber($this->cell($gridRow, $map, 'pieces')) ?? 0), + 'remark' => $this->toText($this->cell($gridRow, $map, 'remark')), + 'store' => $this->toText($this->cell($gridRow, $map, 'store')), + 'owner' => $this->toText($this->cell($gridRow, $map, 'owner')), + 'account' => $this->toText($this->cell($gridRow, $map, 'account')), + 'type' => $this->toText($this->cell($gridRow, $map, 'type')), + 'creator' => $this->toText($this->cell($gridRow, $map, 'creator')), + 'tag' => $this->toText($this->cell($gridRow, $map, 'tag')), + 'profit_center' => $this->toText($this->cell($gridRow, $map, 'profit_center')), + 'responsible_platform' => $this->toText($this->cell($gridRow, $map, 'responsible_platform')), + // 源表存在一个单元格放多个 ID(换行分隔)的情况,这里保留到 500 字符。 + 'external_id' => $this->toText($this->cell($gridRow, $map, 'external_id'), 500), + 'created_from' => $source, + 'created_by' => $userId, + 'created_at' => $now, + 'updated_at' => $now, + ]; + + foreach (self::MONEY_COLUMNS as $column) { + $value = $this->toNumber($this->cell($gridRow, $map, $column)) ?? 0.0; + $record[$column] = number_format($value, 4, '.', ''); + } + $sellingPrice += (float) $record['finance_selling_price']; + $paymentAmount += (float) $record['finance_payment_amount']; + + $dateMin = $dateMin === null || $date < $dateMin ? $date : $dateMin; + $dateMax = $dateMax === null || $date > $dateMax ? $date : $dateMax; + + $rows[] = $record; + if (count($rows) >= self::CHUNK * 4) { + $flush(); + } + } + + $flush(); + + return [ + 'rows' => $inserted + $skipped, + 'inserted' => $inserted, + 'skipped' => $skipped, + 'selling_price' => number_format($sellingPrice, 4, '.', ''), + 'payment_amount' => number_format($paymentAmount, 4, '.', ''), + 'date_min' => $dateMin, + 'date_max' => $dateMax, + ]; + } + + /** @return array> */ + private function read(string $path): array + { + $extension = mb_strtolower(pathinfo($path, PATHINFO_EXTENSION)); + + if ($extension === 'csv') { + $handle = fopen($path, 'rb'); + if ($handle === false) { + throw new RuntimeException('无法读取文件。'); + } + $grid = []; + $first = true; + while (($cells = fgetcsv($handle)) !== false) { + if ($first && isset($cells[0])) { + $cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $cells[0]); + $first = false; + } + $grid[] = $cells; + } + fclose($handle); + + return $grid; + } + + if (! in_array($extension, ['xlsx', 'xls'], true)) { + throw new InvalidArgumentException('只支持 xlsx、xls、csv。'); + } + + try { + $reader = IOFactory::createReader($extension === 'xlsx' ? 'Xlsx' : 'Xls'); + $reader->setReadDataOnly(true); + $spreadsheet = $reader->load($path); + } catch (Throwable $exception) { + throw new InvalidArgumentException('读不出这个表格:' . $exception->getMessage()); + } + + try { + return $spreadsheet->getSheet(0)->toArray(null, true, false, false); + } finally { + $spreadsheet->disconnectWorksheets(); + } + } + + /** @param array> $grid */ + private function locateHeader(array $grid): ?int + { + foreach ($grid as $index => $row) { + $map = $this->mapHeader($row); + if (isset($map['bill_date'], $map['order_no'], $map['finance_payment_amount'])) { + return $index; + } + } + + return null; + } + + /** @param array $row @return array */ + private function mapHeader(array $row): array + { + $map = []; + foreach ($row as $index => $value) { + $label = trim((string) (is_scalar($value) ? $value : '')); + if ($label === '') { + continue; + } + $column = self::COLUMNS[$label] ?? null; + if ($column !== null && ! isset($map[$column])) { + $map[$column] = (int) $index; + } + } + + return $map; + } + + /** @param array $row @param array $map */ + private function cell(array $row, array $map, string $column): mixed + { + return isset($map[$column]) ? ($row[$map[$column]] ?? null) : null; + } + + private function hasContent(array $row): bool + { + foreach ($row as $value) { + if ($value !== null && trim((string) (is_scalar($value) ? $value : '')) !== '') { + return true; + } + } + + return false; + } + + private function toDate(mixed $value): ?string + { + if ($value === null || $value === '') { + return null; + } + + if (is_numeric($value) && (float) $value > 20000 && (float) $value < 60000) { + try { + return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d'); + } catch (Throwable) { + return null; + } + } + + $text = trim((string) $value); + $timestamp = strtotime($text); + + return $timestamp === false ? null : date('Y-m-d', $timestamp); + } + + private function toText(mixed $value, int $limit = 191): ?string + { + if ($value === null) { + return null; + } + + $text = trim((string) (is_scalar($value) ? $value : '')); + + return $text === '' ? null : mb_substr($text, 0, $limit); + } + + private function toNumber(mixed $value): ?float + { + if ($value === null || $value === '') { + return null; + } + if (is_numeric($value)) { + return (float) $value; + } + + $text = str_replace([',', ' ', '¥', '¥'], '', (string) $value); + + return is_numeric($text) ? (float) $text : null; + } +} diff --git a/app/Business/StoreViolationMapper.php b/app/Business/StoreViolationMapper.php new file mode 100644 index 00000000..bbd41379 --- /dev/null +++ b/app/Business/StoreViolationMapper.php @@ -0,0 +1,148 @@ + $platform) { + if ($normalized === $slug) { + return $slug; + } + + foreach ($platform['source_values'] ?? [] as $sourceValue) { + if ($normalized === mb_strtolower(trim((string) $sourceValue))) { + return $slug; + } + } + } + + return null; + } + + public function categoryForContent(?string $content): string + { + $content = trim((string) $content); + if ($content === '') { + return (string) config('store_violations.default_category', '其他'); + } + + foreach ((array) config('store_violations.category_rules', []) as $category => $keywords) { + foreach ((array) $keywords as $keyword) { + if ($keyword !== '' && mb_stripos($content, (string) $keyword) !== false) { + return (string) $category; + } + } + } + + return (string) config('store_violations.default_category', '其他'); + } + + /** + * 上游抓取行(rpt.crawl_shop_violation)→ 统一字段。 + * + * @param array $row + * @return array|null 平台无法识别时返回 null + */ + public function mapCrawlRow(array $row): ?array + { + $platform = $this->platformForSourceValue($row['platform'] ?? null); + if ($platform === null) { + return null; + } + + $content = trim((string) ($row['violation_content'] ?? '')); + + return [ + 'platform' => $platform, + 'shop_name' => mb_substr(trim((string) ($row['shop_name'] ?? '')), 0, 191), + 'violation_type' => $content === '' ? null : mb_substr($content, 0, 500), + 'violation_category' => $this->categoryForContent($content), + 'violation_no' => mb_substr(trim((string) ($row['violation_no'] ?? '')), 0, 100), + 'violation_date' => $this->normalizeDate($row['violation_date'] ?? null), + 'status' => $this->normalizeLabel($row['status'] ?? null, 64), + 'appeal_deadline' => $this->normalizeDate($row['deadline'] ?? null), + 'window_name' => $this->normalizeLabel($row['window_name'] ?? null, 191), + 'crawl_date' => $this->normalizeDate($row['crawl_date'] ?? null), + 'source' => 'crawl', + ]; + } + + public function normalizeDate(mixed $value): ?string + { + if ($value === null || $value === '') { + return null; + } + + if ($value instanceof DateTimeInterface) { + return $value->format('Y-m-d'); + } + + if (is_numeric($value)) { + $number = (float) $value; + if ($number >= 20000 && $number <= 80000) { + return ExcelDate::excelToDateTimeObject($number)->format('Y-m-d'); + } + } + + $text = trim((string) $value); + if ($text === '' || in_array($text, ['-', '—', '无'], true)) { + return null; + } + + $text = str_replace(['年', '月'], '-', str_replace('日', '', $text)); + $text = str_replace(['/', '.'], '-', $text); + $text = trim(preg_replace('/\s+/', ' ', $text) ?? $text); + + try { + return (new DateTimeImmutable($text))->format('Y-m-d'); + } catch (\Throwable) { + throw new InvalidArgumentException('无法识别的日期:' . $value); + } + } + + public function normalizePoints(mixed $value): ?float + { + if ($value === null || $value === '') { + return null; + } + + if (is_numeric($value)) { + return (float) $value; + } + + $text = trim((string) $value); + if ($text === '' || in_array($text, ['-', '—', '无', '不扣分'], true)) { + return null; + } + + $text = preg_replace('/(分|点|个?扣|扣除)/u', '', $text) ?? $text; + $text = trim($text); + if ($text === '' || ! is_numeric($text)) { + throw new InvalidArgumentException('无法识别的扣分:' . $value); + } + + return (float) $text; + } + + private function normalizeLabel(mixed $value, int $limit): ?string + { + $text = trim((string) $value); + + return $text === '' ? null : mb_substr($text, 0, $limit); + } +} diff --git a/app/Business/StoreViolationWorkbookImporter.php b/app/Business/StoreViolationWorkbookImporter.php new file mode 100644 index 00000000..43750e12 --- /dev/null +++ b/app/Business/StoreViolationWorkbookImporter.php @@ -0,0 +1,479 @@ +,unknown_headers:list,rows:list,summary:array,existing_checked:bool} + */ + public function preview(UploadedFile $file, string $platform): array + { + $platforms = (array) config('store_violations.platforms', []); + if (! array_key_exists($platform, $platforms)) { + throw ValidationException::withMessages(['import' => '未知平台,请刷新页面后重试。']); + } + + if (! $this->repository->available()) { + throw ValidationException::withMessages(['import' => '导入功能尚未就绪:统一表尚未建立,请联系管理员完成迁移。']); + } + + try { + $spreadsheet = IOFactory::load($file->getRealPath()); + } catch (Throwable $exception) { + report($exception); + + throw ValidationException::withMessages(['import' => '无法读取该文件,请上传 xlsx / xls / csv 格式的表格。']); + } + + $worksheet = $spreadsheet->getActiveSheet(); + $matrix = $worksheet->toArray(null, true, true, false); + + [$headerIndex, $columnMap, $unknownHeaders] = $this->detectHeaders($matrix); + if ($headerIndex === null) { + throw ValidationException::withMessages([ + 'import' => '未找到可识别的表头行,请使用统一表头或下载导入模板。', + ]); + } + + $missing = []; + foreach (['shop_name', 'violation_no'] as $required) { + if (! in_array($required, $columnMap, true)) { + $missing[] = $this->labelFor($required); + } + } + if ($missing !== []) { + throw ValidationException::withMessages([ + 'import' => '缺少必填列:' . implode('、', $missing) . '。请使用统一表头或下载导入模板。', + ]); + } + + $maxRows = (int) config('store_violations.import.max_rows', 20000); + $dataRows = array_slice($matrix, $headerIndex + 1); + if (count($dataRows) > $maxRows) { + throw ValidationException::withMessages([ + 'import' => '单次最多导入 ' . number_format($maxRows) . ' 行,请拆分文件后重试。', + ]); + } + + $rows = []; + $seen = []; + $invalid = 0; + + foreach ($dataRows as $offset => $row) { + $rowNumber = $headerIndex + 2 + $offset; + $raw = $this->rowToFields($row, $columnMap); + if ($this->isEmptyRow($raw)) { + continue; + } + + $item = $this->normalizeRow($raw, $platform, $rowNumber, $columnMap); + + if ($item['status'] === 'valid') { + $key = $platform . '|' . $item['data']['violation_no']; + if (isset($seen[$key])) { + $item = $seen[$key]['data'] === $item['data'] + ? $this->markRow($item, 'same', '与文件内前一行重复,将跳过') + : $this->markRow($item, 'invalid', '与文件内前一行的数据冲突,请先合并'); + } else { + $seen[$key] = $item; + } + } + + if ($item['status'] === 'invalid') { + $invalid++; + } + + $rows[] = $item; + } + + $summary = ['new' => 0, 'update' => 0, 'same' => 0, 'invalid' => $invalid]; + $this->compareWithExisting($rows, $platform, $summary); + + return [ + 'platform' => $platform, + 'sheet' => $worksheet->getTitle(), + 'columns' => collect((array) config('store_violations.columns', [])) + ->map(fn (array $column): array => ['key' => $column['key'], 'label' => $column['label']]) + ->all(), + 'unknown_headers' => $unknownHeaders, + 'provided_columns' => array_values($columnMap), + 'rows' => $rows, + 'summary' => $summary, + ]; + } + + /** @param array{rows:list} $preview */ + public function commit(array $preview): array + { + $platform = (string) ($preview['platform'] ?? ''); + $rows = $preview['rows'] ?? []; + $provided = array_values(array_unique((array) ($preview['provided_columns'] ?? []))); + $now = now(); + + $unifiedColumns = array_map( + static fn (array $column): string => (string) $column['key'], + (array) config('store_violations.columns', []), + ); + $updateColumns = array_values(array_intersect($unifiedColumns, $provided)); + if (! in_array('violation_category', $updateColumns, true) && in_array('violation_type', $provided, true)) { + $updateColumns[] = 'violation_category'; + } + $updateColumns[] = 'source'; + $updateColumns[] = 'updated_at'; + + $payload = []; + $created = 0; + $updated = 0; + + foreach ($rows as $row) { + $status = $row['status'] ?? ''; + if (! in_array($status, ['new', 'update'], true)) { + continue; + } + + $data = $row['data'] ?? []; + if (($data['platform'] ?? null) !== $platform || ($data['violation_no'] ?? '') === '') { + continue; + } + + foreach (array_values(array_diff($updateColumns, ['source', 'updated_at'])) as $column) { + if (! array_key_exists($column, $data)) { + $data[$column] = null; + } + } + + $payload[] = $data + [ + 'source' => 'import', + 'created_at' => $now, + 'updated_at' => $now, + ]; + + $status === 'new' ? $created++ : $updated++; + } + + $affected = $this->repository->upsertRows($payload, $updateColumns); + + return ['created' => $created, 'updated' => $updated, 'affected' => $affected]; + } + + /** + * @param list> $matrix + * @return array{0:?int,1:list,2:list} + */ + private function detectHeaders(array $matrix): array + { + $bestIndex = null; + $bestMap = []; + $bestUnknown = []; + $bestScore = 0; + + foreach ($matrix as $index => $row) { + $map = []; + $unknown = []; + foreach ($row as $cell) { + $label = trim((string) $cell); + if ($label === '') { + continue; + } + $key = $this->matchHeader($label); + if ($key === null) { + $unknown[] = $label; + continue; + } + if (! in_array($key, $map, true)) { + $map[] = $key; + } + } + + if (count($map) > $bestScore) { + $bestIndex = $index; + $bestMap = $map; + $bestUnknown = $unknown; + $bestScore = count($map); + } + + // 命中 6 列以上视为表头,避免把数据行误判为表头 + if ($bestScore >= 6) { + break; + } + } + + if ($bestIndex === null || $bestScore < 2) { + return [null, [], []]; + } + + return [$bestIndex, $bestMap, array_values(array_unique($bestUnknown))]; + } + + private function matchHeader(string $label): ?string + { + $normalized = mb_strtolower(preg_replace('/[\s"* ]/u', '', $label) ?? $label); + + foreach ((array) config('store_violations.header_aliases', []) as $key => $aliases) { + foreach ((array) $aliases as $alias) { + $alias = mb_strtolower(preg_replace('/[\s"* ]/u', '', (string) $alias) ?? (string) $alias); + if ($alias !== '' && $normalized === $alias) { + return (string) $key; + } + } + } + + return null; + } + + /** + * @param list $row + * @param list $columnMap + * @return array + */ + private function rowToFields(array $row, array $columnMap): array + { + $fields = []; + foreach ($row as $index => $cell) { + $key = $columnMap[$index] ?? null; + if ($key !== null) { + $fields[$key] = $cell; + } + } + + return $fields; + } + + /** @param array $fields */ + private function isEmptyRow(array $fields): bool + { + foreach ($fields as $value) { + if (trim((string) $value) !== '') { + return false; + } + } + + return true; + } + + /** + * @param array $raw + * @return array{row_number:int,status:string,message:string,data:array} + */ + private function normalizeRow(array $raw, string $platform, int $rowNumber, array $provided): array + { + $errors = []; + $data = ['platform' => $platform]; + $has = static fn (string $key): bool => in_array($key, $provided, true); + + if ($has('shop_name')) { + $shopName = trim((string) ($raw['shop_name'] ?? '')); + if ($shopName === '') { + $errors[] = '店铺名不能为空'; + } elseif (mb_strlen($shopName) > 191) { + $errors[] = '店铺名超过 191 字'; + } + $data['shop_name'] = mb_substr($shopName, 0, 191); + } + + if ($has('violation_no')) { + $violationNo = trim((string) ($raw['violation_no'] ?? '')); + if ($violationNo === '') { + $errors[] = '违规单号不能为空'; + } elseif (mb_strlen($violationNo) > 100) { + $errors[] = '违规单号超过 100 字'; + } + $data['violation_no'] = mb_substr($violationNo, 0, 100); + } + + $type = $has('violation_type') ? trim((string) ($raw['violation_type'] ?? '')) : null; + if ($has('violation_type')) { + $data['violation_type'] = $type === '' ? null : mb_substr($type, 0, 500); + } + + if ($has('violation_category')) { + $category = trim((string) ($raw['violation_category'] ?? '')); + $data['violation_category'] = $category === '' + ? $this->mapper->categoryForContent($type) + : mb_substr($category, 0, 64); + } elseif ($has('violation_type')) { + $data['violation_category'] = $this->mapper->categoryForContent($type); + } + + if ($has('violation_date')) { + try { + $data['violation_date'] = $this->mapper->normalizeDate($raw['violation_date'] ?? null); + } catch (Throwable $exception) { + $errors[] = '违规日期:' . $exception->getMessage(); + $data['violation_date'] = null; + } + } + + if ($has('points_deducted')) { + try { + $data['points_deducted'] = $this->mapper->normalizePoints($raw['points_deducted'] ?? null); + } catch (Throwable $exception) { + $errors[] = '扣分:' . $exception->getMessage(); + $data['points_deducted'] = null; + } + } + + if ($has('status')) { + $status = trim((string) ($raw['status'] ?? '')); + $data['status'] = $status === '' ? null : mb_substr($status, 0, 64); + } + + if ($has('penalty_date')) { + try { + $data['penalty_date'] = $this->mapper->normalizeDate($raw['penalty_date'] ?? null); + } catch (Throwable $exception) { + $errors[] = '处罚日期:' . $exception->getMessage(); + $data['penalty_date'] = null; + } + } + + if ($has('appeal_deadline')) { + try { + $data['appeal_deadline'] = $this->mapper->normalizeDate($raw['appeal_deadline'] ?? null); + } catch (Throwable $exception) { + $errors[] = '申诉截止日期:' . $exception->getMessage(); + $data['appeal_deadline'] = null; + } + } + + if ($has('handling_status')) { + $handling = trim((string) ($raw['handling_status'] ?? '')); + $options = (array) config('store_violations.handling_statuses', []); + if ($handling === '') { + $data['handling_status'] = (string) config('store_violations.default_handling_status', '未处理'); + } elseif (! in_array($handling, $options, true)) { + $errors[] = '处理状态必须是:' . implode('、', $options); + $data['handling_status'] = $handling; + } else { + $data['handling_status'] = $handling; + } + } + + return [ + 'row_number' => $rowNumber, + 'status' => $errors === [] ? 'valid' : 'invalid', + 'message' => $errors === [] ? '待导入' : implode(';', $errors), + 'data' => $data, + ]; + } + + private function markRow(array $row, string $status, string $message): array + { + $row['status'] = $status; + $row['message'] = $message; + + return $row; + } + + /** + * 与库内已有记录比对:无 → new,字段完全一致 → same,否则 → update。 + * + * @param list $rows + */ + private function compareWithExisting(array &$rows, string $platform, array &$summary): void + { + $keys = collect($rows) + ->filter(fn (array $row): bool => $row['status'] === 'valid' && ($row['data']['violation_no'] ?? '') !== '') + ->pluck('data.violation_no') + ->unique() + ->values(); + + if ($keys->isEmpty()) { + return; + } + + $existing = collect(); + foreach ($keys->chunk(500) as $chunk) { + $existing = $existing->merge( + DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->table(StoreViolationRecordRepository::TABLE) + ->where('platform', $platform) + ->whereIn('violation_no', $chunk->all()) + ->get() + ->keyBy('violation_no'), + ); + } + + foreach ($rows as $index => $row) { + if ($row['status'] !== 'valid') { + continue; + } + + $record = $existing->get($row['data']['violation_no']); + if ($record === null) { + $summary['new']++; + $rows[$index] = $this->markRow($row, 'new', '新增记录'); + + continue; + } + + $rows[$index] = $this->sameAsExisting($row['data'], $record) + ? $this->markRow($row, 'same', '与库内记录一致,将跳过') + : $this->markRow($row, 'update', '库内已有该单号,将按文件内容更新'); + $rows[$index]['status'] === 'same' ? $summary['same']++ : $summary['update']++; + } + } + + private function sameAsExisting(array $data, object $record): bool + { + $normalizePoints = static function (mixed $value): string { + if ($value === null || $value === '') { + return ''; + } + + return number_format((float) $value, 2, '.', ''); + }; + + foreach ($data as $key => $value) { + if ($key === 'platform') { + continue; + } + + $current = $record->{$key} ?? null; + + if ($key === 'points_deducted') { + if ($normalizePoints($value) !== $normalizePoints($current)) { + return false; + } + + continue; + } + + if (trim((string) $value) !== trim((string) $current)) { + return false; + } + } + + return true; + } + + private function labelFor(string $key): string + { + foreach ((array) config('store_violations.columns', []) as $column) { + if (($column['key'] ?? null) === $key) { + return (string) $column['label']; + } + } + + return $key; + } +} diff --git a/app/Business/TaobaoAlipayBillSpreadsheetImporter.php b/app/Business/TaobaoAlipayBillSpreadsheetImporter.php index c6fad7a1..fb8af9e2 100644 --- a/app/Business/TaobaoAlipayBillSpreadsheetImporter.php +++ b/app/Business/TaobaoAlipayBillSpreadsheetImporter.php @@ -35,7 +35,7 @@ class TaobaoAlipayBillSpreadsheetImporter 'counterparty_account', 'account_order_no', 'business_serial_no', 'goods_name', ]; - public function import(string $path, int $companyId): array + public function import(string $path, int $companyId, bool $replace = false): array { if (! is_file($path) || ! is_readable($path)) { throw new InvalidArgumentException('导入文件不存在或不可读取。'); @@ -55,21 +55,27 @@ class TaobaoAlipayBillSpreadsheetImporter throw new InvalidArgumentException('表头与淘系支付宝账户模板不一致。'); } + $rows = []; + $skipped = 0; + for ($rowNumber = 2; $rowNumber <= $sheet->getHighestDataRow(); $rowNumber++) { + $values = $sheet->rangeToArray("A{$rowNumber}:Y{$rowNumber}", null, false, false)[0]; + if (collect($values)->every(fn ($value) => $value === null || trim((string) $value) === '')) { + $skipped++; + continue; + } + $rows[] = $this->normalizeRow(array_combine(self::FIELDS, $values), $rowNumber); + } + $inserted = 0; $updated = 0; - $skipped = 0; + $replaced = 0; - DB::transaction(function () use ($sheet, $companyId, &$inserted, &$updated, &$skipped) { - for ($rowNumber = 2; $rowNumber <= $sheet->getHighestDataRow(); $rowNumber++) { - $values = $sheet->rangeToArray("A{$rowNumber}:Y{$rowNumber}", null, false, false)[0]; + DB::transaction(function () use ($rows, $companyId, $replace, &$inserted, &$updated, &$replaced) { + if ($replace) { + $replaced = DB::table('ec_alipay_bills')->where('company_id', $companyId)->delete(); + } - if (collect($values)->every(fn ($value) => $value === null || trim((string) $value) === '')) { - $skipped++; - continue; - } - - $data = array_combine(self::FIELDS, $values); - $data = $this->normalizeRow($data, $rowNumber); + foreach ($rows as $data) { $record = AlipayBill::query() ->where('company_id', $companyId) ->where('record_code', $data['record_code']) @@ -93,7 +99,7 @@ class TaobaoAlipayBillSpreadsheetImporter $spreadsheet->disconnectWorksheets(); - return compact('inserted', 'updated', 'skipped'); + return compact('inserted', 'updated', 'skipped', 'replaced'); } private function normalizeRow(array $data, int $rowNumber): array diff --git a/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php b/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php index 73f8875b..b1fe3902 100644 --- a/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php +++ b/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php @@ -37,7 +37,7 @@ class ThirdPartyWarehouseStorageFeeCalculator } /** - * @return array{summary:array,daily:list>,per_sku:list>} + * @return array{summary:array,daily:list>,per_sku:list>,daily_sku:list>} */ public function calculate(int $warehouseId, string $warehouseName, string $period): array { @@ -63,6 +63,10 @@ class ThirdPartyWarehouseStorageFeeCalculator $daily = []; /** @var array> $skus */ $skus = []; + $dailySku = []; + $storagePerPiecePerDay = $days > 0 && $piecesPerPallet > 0 + ? $palletArea * $sqmRate / $piecesPerPallet / $days + : 0.0; foreach ($this->mirror->exportRows(['dimension' => 'month', 'period' => $period], 5000) as $row) { $date = trim((string) ($row['date'] ?? '')); @@ -90,6 +94,20 @@ class ThirdPartyWarehouseStorageFeeCalculator $daily[$date]['inbound_qty'] += $inboundQty; $daily[$date]['outbound_qty'] += $outboundQty; + $dailySku[] = [ + 'date' => $date, + 'owner' => (string) ($row['owner'] ?? ''), + 'sku_code' => $code, + 'product_name' => (string) ($row['product_name'] ?? ''), + 'supplier' => (string) ($row['supplier'] ?? ''), + 'category' => (string) ($row['category'] ?? ''), + 'unit' => (string) ($row['unit'] ?? ''), + 'opening' => round($opening, 2), + 'net_movement' => round($closing - $opening, 2), + 'closing' => round($closing, 2), + 'storage_fee' => round($closing * $storagePerPiecePerDay, 6), + ]; + if (! isset($skus[$code])) { $skus[$code] = [ 'owner' => (string) ($row['owner'] ?? ''), @@ -198,6 +216,7 @@ class ThirdPartyWarehouseStorageFeeCalculator ], 'daily' => $dailyRows, 'per_sku' => $perSku, + 'daily_sku' => $dailySku, ]; } } diff --git a/app/Business/UpstreamBusinessInformation.php b/app/Business/UpstreamBusinessInformation.php index 24039b72..3cdf2f74 100644 --- a/app/Business/UpstreamBusinessInformation.php +++ b/app/Business/UpstreamBusinessInformation.php @@ -88,10 +88,12 @@ class UpstreamBusinessInformation private function companyPage(int $page, int $perPage): array { + $filters = $this->pageFilters('company-management', 'basic-information'); return $this->page( 'company-information.read', $page, $perPage, + $filters, fn () => $this->snapshot('company-information.read', [ 'page' => $page, 'perPage' => $perPage, @@ -133,10 +135,12 @@ SQL); private function storePage(int $page, int $perPage): array { + $filters = $this->pageFilters('store-management', 'basic-information'); return $this->page( 'store-information.read', $page, $perPage, + $filters, fn () => $this->snapshot('store-information.read', [ 'page' => $page, 'perPage' => $perPage, @@ -157,7 +161,11 @@ SQL); private function storeAccountPage(int $page, int $perPage): array { try { - return ($this->storeAccounts ?? app(StoreAccountMirrorRepository::class))->paginate($page, $perPage); + return ($this->storeAccounts ?? app(StoreAccountMirrorRepository::class))->paginate( + $page, + $perPage, + $this->pageFilters('store-management', 'store-accounts'), + ); } catch (\RuntimeException $exception) { report($exception); throw new ServiceUnavailableHttpException(null, '店铺账号共享镜像尚未完成首次同步。'); @@ -189,16 +197,20 @@ SQL); */ private function storeMatchesFilters(array $row, array $filters): bool { - foreach (['erp_store_name', 'store_name', 'store_id', 'profit_center', 'store_manager', 'department_manager', 'company_type'] as $key) { + foreach (['erp_store_name', 'store_name', 'store_id', 'profit_center', 'store_manager', 'department_manager'] as $key) { $expected = trim((string) ($filters[$key] ?? '')); if ($expected === '') { continue; } $actual = trim((string) ($row[$key] ?? '')); - if ($actual !== $expected) { + if (! str_contains(mb_strtolower($actual), mb_strtolower($expected))) { return false; } } + $companyType = trim((string) ($filters['company_type'] ?? '')); + if ($companyType !== '' && trim((string) ($row['company_type'] ?? '')) !== $companyType) { + return false; + } $statusMap = ['0' => '正常', '3' => '关闭中', '6' => '已关闭']; $status = trim((string) ($filters['status'] ?? '')); @@ -244,7 +256,8 @@ SQL); private function subjectOperatingReportPage(int $page, int $perPage): array { - $rows = $this->storeReportRows(); + $filters = $this->pageFilters('company-management', 'subject-operating-report'); + $rows = $this->storeReportRows(array_intersect_key($filters, array_flip(['company_type']))); $entities = []; foreach ($rows as $row) { @@ -276,20 +289,108 @@ SQL); } $rows = array_values($entities); - usort($rows, static fn (array $left, array $right): int => strcmp($left['entity'], $right['entity'])); - $offset = ($page - 1) * $perPage; - - $pageRows = array_slice($rows, $offset, $perPage); - $details = $this->companyDetails(array_column($pageRows, 'entity')); - foreach ($pageRows as &$row) { + $details = $this->companyDetails(array_column($rows, 'entity')); + foreach ($rows as &$row) { $row['company_details'] = $details[$row['entity']] ?? []; $row['city'] = $this->cityFromDetails($row['company_details']); } unset($row); + // 所有主体该月收入均为空时,该月份列在页面上默认隐藏;「筛选字段」中仍保留勾选项,可手动选出来。 + request()->attributes->set( + 'subject-operating-report.default_hidden_columns', + $this->subjectReportColumnsWithoutData($rows), + ); + + $rows = array_values(array_filter($rows, fn (array $row): bool => $this->subjectMatchesFilters($row, $filters))); + $this->sortSubjectRows($rows, $filters); + $offset = ($page - 1) * $perPage; + $pageRows = array_slice($rows, $offset, $perPage); + return ['data' => $pageRows, 'total' => count($rows)]; } + /** + * 没有数据的月份列:全部主体该月收入都为空(null/空字符串)时才视为没有数据。 + * 金额为 0 的月份代表当月有账单,不隐藏。 + * + * @param array> $rows + * @return array + */ + private function subjectReportColumnsWithoutData(array $rows): array + { + $columns = []; + + for ($month = 1; $month <= 12; $month++) { + $key = sprintf('income_%02d', $month); + foreach ($rows as $row) { + $value = $row[$key] ?? null; + if ($value === null || $value === '') { + continue; + } + + continue 2; + } + + $columns[] = $key; + } + + return $columns; + } + + /** @param array $row @param array $filters */ + private function subjectMatchesFilters(array $row, array $filters): bool + { + if (($filters['company_type'] ?? '') !== '' && (string) ($row['company_type'] ?? '') !== (string) $filters['company_type']) { + return false; + } + + foreach (['city', 'entity', 'plan', 'new_entity'] as $key) { + $needle = trim((string) ($filters[$key] ?? '')); + if ($needle !== '' && mb_stripos((string) ($row[$key] ?? ''), $needle) === false) { + return false; + } + } + + foreach (['rolling_12m_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) { + $needle = str_replace(',', '', trim((string) ($filters[$key] ?? ''))); + if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null) + || abs((float) $row[$key] - (float) $needle) > 0.000001)) { + return false; + } + } + + $canChange = trim((string) ($filters['can_change_entity'] ?? '')); + return $canChange === '' || (string) ($row['can_change_entity'] ?? '') === $canChange; + } + + /** @param array> $rows @param array $filters */ + private function sortSubjectRows(array &$rows, array $filters): void + { + $key = (string) ($filters['_sort'] ?? 'entity'); + $allowed = [ + 'city', 'entity', 'company_type', 'rolling_12m_income', + ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12)), + 'can_change_entity', 'plan', 'new_entity', + ]; + if (! in_array($key, $allowed, true)) { + return; + } + + $direction = ($filters['_direction'] ?? 'asc') === 'desc' ? -1 : 1; + usort($rows, static function (array $left, array $right) use ($key, $direction): int { + $leftValue = $left[$key] ?? null; + $rightValue = $right[$key] ?? null; + if (is_numeric($leftValue) && is_numeric($rightValue)) { + $comparison = ((float) $leftValue <=> (float) $rightValue) * $direction; + } else { + $comparison = strcmp((string) ($leftValue ?? ''), (string) ($rightValue ?? '')) * $direction; + } + + return $comparison !== 0 ? $comparison : strcmp((string) ($left['entity'] ?? ''), (string) ($right['entity'] ?? '')); + }); + } + private function sumNullable(array &$row, string $key, mixed $value): void { if ($value === null || $value === '') { @@ -469,10 +570,12 @@ SQL); private function trademarkPage(int $page, int $perPage): array { + $filters = $this->pageFilters('trademark-management', 'information'); return $this->page( 'trademark-information.read', $page, $perPage, + $filters, fn () => $this->snapshot('trademark-information.read', [ 'page' => $page, 'perPage' => $perPage, @@ -509,10 +612,14 @@ SQL); ]; } - private function page(string $scope, int $page, int $perPage, callable $resolver): array + private function page(string $scope, int $page, int $perPage, array $filters, callable $resolver): array { if ($this->mirror->ready($scope)) { - return $this->normalize($scope, $this->mirror->paginate($scope, $page, $perPage)); + return $this->normalize($scope, $this->mirror->paginate($scope, $page, $perPage, $filters)); + } + + if ($filters !== []) { + throw new ServiceUnavailableHttpException(null, '当前数据源暂不支持所选条件查询,请检查共享业务镜像状态。'); } if ((app(\App\Utilities\SystemDatabaseConfiguration::class)->current()['mode'] ?? '') === 'bootstrap' @@ -527,6 +634,34 @@ SQL); }); } + /** @return array */ + private function pageFilters(string $section, string $page): array + { + $fields = collect(config('business_navigation')) + ->firstWhere('slug', $section)['pages'] ?? []; + $pageConfig = collect($fields)->flatMap(fn (array $item) => [$item, ...($item['children'] ?? [])])->firstWhere('slug', $page); + $allowed = collect($pageConfig['directory']['fields'] ?? []) + ->reject(fn (array $field) => ($field['kind'] ?? '') === 'secret' && ($field['name'] ?? '') !== 'withdrawal_account') + ->pluck('name')->all(); + if ($section === 'company-management' && $page === 'basic-information') { + $allowed = array_values(array_unique([...$allowed, 'company_type', 'related_people'])); + } + $filters = []; + foreach ($allowed as $name) { + foreach ([$name, $name . '_from', $name . '_to'] as $key) { + $value = trim((string) request($key, '')); + if ($value !== '') $filters[$key] = mb_substr($value, 0, 191); + } + } + $sort = trim((string) request('sort', '')); + if (in_array($sort, $allowed, true)) { + $filters['_sort'] = $sort; + $filters['_direction'] = request('direction') === 'desc' ? 'desc' : 'asc'; + } + + return $filters; + } + /** @param array{data: array>, total: int} $payload */ private function normalize(string $scope, array $payload): array { @@ -548,6 +683,7 @@ SQL); $row = $this->toUtf8($row); $row['establishment_date'] = $this->date($row['establishment_date'] ?? null); $row['subscribed_at'] = $this->date($row['subscribed_at'] ?? null); + $row['city'] = RegisteredAddressCity::parse($row['registered_address'] ?? null); $row['company_status'] = match ((string) ($row['company_status'] ?? '')) { '0' => '正常', '1' => '已注销', diff --git a/app/Business/WithdrawalManagementReport.php b/app/Business/WithdrawalManagementReport.php new file mode 100644 index 00000000..e9d1ae76 --- /dev/null +++ b/app/Business/WithdrawalManagementReport.php @@ -0,0 +1,277 @@ +,paths:list,storeEntities:list,rows:Collection, + * balances:array, + * reserveStandards:array,withdrawalAmounts:array,compliance:array, + * summary:array{source:int,matched:int,ambiguous:int,unmatched:int,not_ready:int}, + * balanceColumnLabel:string,balanceDate:string,sort:array{field:string,direction:string} + * } + */ + public function results(Request $request): array + { + $filters = $this->filters($request); + $sort = $this->sorting($request); + $platforms = $this->options('store_platform'); + $paths = $this->options('receiving_method'); + $storeEntities = $this->options('store_entity_name'); + $query = StoreReceivingAccount::query(); + + if ($filters['platform'] !== '') { + $query->where('store_platform', $filters['platform']); + } + if ($filters['withdrawalPath'] !== '') { + $query->where('receiving_method', $filters['withdrawalPath']); + } + if ($filters['storeEntity'] !== '') { + $query->where('store_entity_name', $filters['storeEntity']); + } + if ($filters['keyword'] !== '') { + $query->where('store_name', 'like', '%' . addcslashes($filters['keyword'], '%_\\') . '%'); + } + + $today = now()->startOfDay(); + $balanceDate = $today->copy()->subDay()->toDateString(); + $rows = $query->orderByDesc('id')->get(); + $balances = $this->shopBalances->matchesForStores($rows, $balanceDate); + $balanceCounts = collect($balances)->countBy( + static fn (array $match): string => $match['status'], + ); + + if ($filters['balanceStatus'] !== '') { + $rows = $rows->filter( + static fn (StoreReceivingAccount $row): bool => ($balances[(int) $row->id]['status'] ?? 'not_ready') === $filters['balanceStatus'], + ); + } + + $reserveStandards = $rows->mapWithKeys( + static fn (StoreReceivingAccount $row): array => [ + (int) $row->id => WithdrawalReserveStandard::amountFor( + $row->store_platform, + $row->erp_store_name, + ), + ], + )->all(); + $withdrawalAmounts = $rows->mapWithKeys( + fn (StoreReceivingAccount $row): array => [ + (int) $row->id => $this->withdrawalAmountFor($row, $balanceDate), + ], + )->all(); + $compliance = $rows->mapWithKeys( + fn (StoreReceivingAccount $row): array => [ + (int) $row->id => $this->complianceFor( + $balances[(int) $row->id] ?? ['status' => 'not_ready', 'balance' => null], + $reserveStandards[(int) $row->id] ?? null, + $withdrawalAmounts[(int) $row->id] ?? null, + ), + ], + )->all(); + $rows = $sort['field'] === '' + ? $this->sortByBalanceStatus($rows, $balances) + : $this->sortRows($rows, $sort, $balances, $reserveStandards, $withdrawalAmounts, $compliance); + + return [ + 'filters' => $filters, + 'platforms' => $platforms, + 'paths' => $paths, + 'storeEntities' => $storeEntities, + 'rows' => $rows, + 'balances' => $balances, + 'reserveStandards' => $reserveStandards, + 'withdrawalAmounts' => $withdrawalAmounts, + 'compliance' => $compliance, + 'summary' => [ + 'source' => $this->shopBalances->countForDate($balanceDate), + 'matched' => (int) $balanceCounts->get('matched', 0), + 'ambiguous' => (int) $balanceCounts->get('ambiguous', 0), + 'unmatched' => (int) $balanceCounts->get('unmatched', 0), + 'not_ready' => (int) $balanceCounts->get('not_ready', 0), + ], + 'balanceColumnLabel' => $today->format('n月j日') . '店铺余额', + 'balanceDate' => $balanceDate, + 'sort' => $sort, + ]; + } + + /** @return array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string} */ + public function filters(Request $request): array + { + $clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length); + $balanceStatus = $clean($request->query('balance_status')); + + if (! in_array($balanceStatus, ['matched', 'unmatched', 'ambiguous', 'not_ready'], true)) { + $balanceStatus = ''; + } + + return [ + 'platform' => $clean($request->query('platform')), + 'withdrawalPath' => $clean($request->query('withdrawal_path')), + 'storeEntity' => $clean($request->query('store_entity'), 191), + 'keyword' => $clean($request->query('keyword'), 191), + 'balanceStatus' => $balanceStatus, + ]; + } + + /** @return list */ + private function options(string $column): array + { + return StoreReceivingAccount::query() + ->whereNotNull($column) + ->where($column, '<>', '') + ->distinct() + ->orderBy($column) + ->pluck($column) + ->filter() + ->values() + ->all(); + } + + /** @return array{field:string,direction:string} */ + private function sorting(Request $request): array + { + $field = trim((string) $request->query('sort')); + $direction = strtolower(trim((string) $request->query('direction'))); + + return [ + 'field' => in_array($field, self::SORT_FIELDS, true) ? $field : '', + 'direction' => in_array($direction, ['asc', 'desc'], true) ? $direction : 'asc', + ]; + } + + /** + * @param Collection $rows + * @param array $balances + * @return Collection + */ + private function sortByBalanceStatus(Collection $rows, array $balances): Collection + { + $statusOrder = ['matched' => 0, 'ambiguous' => 1, 'unmatched' => 2, 'not_ready' => 3]; + + return $rows->sort( + static function (StoreReceivingAccount $left, StoreReceivingAccount $right) use ($balances, $statusOrder): int { + $leftStatus = $balances[(int) $left->id]['status'] ?? 'not_ready'; + $rightStatus = $balances[(int) $right->id]['status'] ?? 'not_ready'; + $statusComparison = ($statusOrder[$leftStatus] ?? 99) <=> ($statusOrder[$rightStatus] ?? 99); + + return $statusComparison !== 0 + ? $statusComparison + : ((int) $right->id <=> (int) $left->id); + }, + )->values(); + } + + /** + * @param Collection $rows + * @param array{field:string,direction:string} $sort + * @param array $balances + * @param array $reserveStandards + * @param array $withdrawalAmounts + * @param array $compliance + * @return Collection + */ + private function sortRows(Collection $rows, array $sort, array $balances, array $reserveStandards, array $withdrawalAmounts, array $compliance): Collection + { + return $rows->sort(function (StoreReceivingAccount $left, StoreReceivingAccount $right) use ($sort, $balances, $reserveStandards, $withdrawalAmounts, $compliance): int { + $leftValue = $this->sortValue($left, $sort['field'], $balances, $reserveStandards, $withdrawalAmounts, $compliance); + $rightValue = $this->sortValue($right, $sort['field'], $balances, $reserveStandards, $withdrawalAmounts, $compliance); + $comparison = $this->compareSortValues($leftValue, $rightValue, $sort['direction']); + + return $comparison !== 0 + ? $comparison + : ((int) $right->id <=> (int) $left->id); + })->values(); + } + + /** + * @param array $balances + * @param array $reserveStandards + * @param array $withdrawalAmounts + * @param array $compliance + */ + private function sortValue(StoreReceivingAccount $row, string $field, array $balances, array $reserveStandards, array $withdrawalAmounts, array $compliance): mixed + { + return match ($field) { + 'platform' => $row->store_platform, + 'erp_store_name' => $row->erp_store_name, + 'store_id' => $row->store_id, + 'store_entity' => $row->store_entity_name, + 'withdrawal_path' => $row->withdrawal_path, + 'withdrawal_account' => $row->withdrawal_account_name, + 'bank_card' => $row->bank_card_last_four, + 'balance' => ($balances[(int) $row->id]['status'] ?? null) === 'matched' + ? $balances[(int) $row->id]['balance'] + : null, + 'reserve_standard' => $reserveStandards[(int) $row->id] ?? null, + 'withdrawal_amount' => $withdrawalAmounts[(int) $row->id] ?? null, + 'compliance' => $compliance[(int) $row->id] ?? null, + default => null, + }; + } + + private function withdrawalAmountFor(StoreReceivingAccount $row, string $balanceDate): ?float + { + if ($row->withdrawal_balance_date !== $balanceDate || $row->withdrawal_amount === null) { + return null; + } + + return is_numeric($row->withdrawal_amount) ? (float) $row->withdrawal_amount : null; + } + + /** @param array{status:string,balance:?float} $balance */ + private function complianceFor(array $balance, ?int $reserve, ?float $withdrawalAmount): ?string + { + if (($balance['status'] ?? '') !== 'matched' || $balance['balance'] === null || $reserve === null || $withdrawalAmount === null) { + return null; + } + + $remainingCents = (int) round((float) $balance['balance'] * 100) + - (int) round($withdrawalAmount * 100); + + return $remainingCents <= $reserve * 100 ? 'yes' : 'no'; + } + + private function compareSortValues(mixed $left, mixed $right, string $direction): int + { + $leftEmpty = $left === null || $left === ''; + $rightEmpty = $right === null || $right === ''; + if ($leftEmpty || $rightEmpty) { + return $leftEmpty === $rightEmpty ? 0 : ($leftEmpty ? 1 : -1); + } + + $comparison = is_numeric($left) && is_numeric($right) + ? ((float) $left <=> (float) $right) + : strnatcasecmp((string) $left, (string) $right); + + return $direction === 'desc' ? -$comparison : $comparison; + } +} diff --git a/app/Business/WithdrawalManagementSpreadsheet.php b/app/Business/WithdrawalManagementSpreadsheet.php new file mode 100644 index 00000000..9aa2bc5f --- /dev/null +++ b/app/Business/WithdrawalManagementSpreadsheet.php @@ -0,0 +1,469 @@ +, + * balances:array, + * reserveStandards:array,withdrawalAmounts:array,compliance:array, + * balanceColumnLabel:string,balanceDate:string + * } $report + */ + public function export(array $report): StreamedResponse + { + $spreadsheet = $this->workbook($report); + + return $this->download( + $spreadsheet, + 'withdrawal_management_' . str_replace('-', '', $report['balanceDate']) . '_' . now()->format('His') . '.xlsx', + ); + } + + public function template(): StreamedResponse + { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('提现管理'); + $this->writeHeader($sheet, [...self::CONFIG_HEADERS, '提现金额']); + $this->sizeColumns($sheet, [14, 30, 20, 32, 16, 24, 22, 18]); + + $instructions = $spreadsheet->createSheet(); + $instructions->setTitle('填写说明'); + $instructions->fromArray([ + ['提现管理导入说明'], + ['1. 店铺平台、ERP店铺名称用于定位店铺;有平台店铺ID时优先按平台和ID匹配。'], + ['2. 店铺主体、提现路径、提现账户名称、银行卡号后四位和提现金额为可更新字段。'], + ['3. 可更新字段留空表示保持原值,填写“' . self::CLEAR_VALUE . '”表示清空原值。'], + ['4. 提现金额须为非负数,最多两位小数,只用于导入当天对应的余额数据日期;上传后先预览再确认。'], + ], null, 'A1'); + $instructions->getStyle('A1')->getFont()->setBold(true)->setSize(14); + $instructions->getColumnDimension('A')->setWidth(88); + $instructions->getStyle('A1:A5')->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP); + foreach (range(1, 5) as $row) { + $instructions->getRowDimension($row)->setRowHeight($row === 1 ? 26 : 34); + } + $spreadsheet->setActiveSheetIndex(0); + + return $this->download($spreadsheet, 'withdrawal_management_import_template.xlsx'); + } + + /** + * @return array{ + * total:int,changed:int,unchanged:int, + * preview:list, + * plan:list}> + * } + */ + public function preview(UploadedFile $file, int $companyId): array + { + try { + $spreadsheet = IOFactory::load($file->getRealPath()); + $sheet = $spreadsheet->getSheetByName('提现管理') ?? $spreadsheet->getActiveSheet(); + $matrix = $sheet->toArray(null, false, true, false); + $spreadsheet->disconnectWorksheets(); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => 'Excel 文件无法读取,请确认文件未损坏并使用最新模板。', + ]); + } + [$headerIndex, $headers] = $this->headers($matrix); + $indexes = array_flip($headers); + $balanceDate = now()->subDay()->toDateString(); + $accounts = StoreReceivingAccount::withoutGlobalScopes() + ->where('company_id', $companyId) + ->whereNull('deleted_at') + ->get(); + [$byId, $byName] = $this->indexes($accounts); + $errors = []; + $plan = []; + $preview = []; + $seen = []; + $total = 0; + $unchanged = 0; + + foreach (array_slice($matrix, $headerIndex + 1, null, true) as $matrixIndex => $row) { + $values = []; + foreach (self::CONFIG_HEADERS as $header) { + $values[$header] = trim((string) ($row[$indexes[$header]] ?? '')); + } + $values['提现金额'] = isset($indexes['提现金额']) + ? trim((string) ($row[$indexes['提现金额']] ?? '')) + : ''; + if (count(array_filter($values, static fn (string $value): bool => $value !== '')) === 0) { + continue; + } + + $total++; + if ($total > 5000) { + throw ValidationException::withMessages(['import' => '单次最多导入 5000 行,请拆分文件后重试。']); + } + $line = $matrixIndex + 1; + $platform = mb_substr($values['店铺平台'], 0, 80); + $erpStoreName = mb_substr($values['ERP店铺名称'], 0, 191); + $storeId = mb_substr(ltrim($values['平台店铺ID'], "'"), 0, 191); + + if ($platform === '' || $erpStoreName === '') { + $errors[] = "第 {$line} 行缺少店铺平台或 ERP 店铺名称"; + continue; + } + + $matches = $storeId !== '' + ? ($byId[$this->key($platform, $storeId)] ?? []) + : ($byName[$this->key($platform, $erpStoreName)] ?? []); + if (count($matches) === 0) { + $identity = $storeId !== '' ? "平台店铺ID {$storeId}" : "ERP 店铺名称 {$erpStoreName}"; + $errors[] = "第 {$line} 行未找到 {$platform} / {$identity}"; + continue; + } + if (count($matches) > 1) { + $errors[] = "第 {$line} 行匹配到多家店铺,请补充或核对平台店铺ID"; + continue; + } + + /** @var StoreReceivingAccount $account */ + $account = $matches[0]; + if (isset($seen[(int) $account->id])) { + $errors[] = "第 {$line} 行与第 {$seen[(int) $account->id]} 行重复指向同一家店铺"; + continue; + } + $seen[(int) $account->id] = $line; + + try { + $changes = $this->changes($account, $values, $balanceDate); + } catch (\InvalidArgumentException $exception) { + $errors[] = "第 {$line} 行" . $exception->getMessage(); + continue; + } + + if ($changes === []) { + $unchanged++; + continue; + } + + $labels = [ + 'store_entity_name' => '店铺主体', + 'receiving_method' => '提现路径', + 'receiving_account_name' => '提现账户名称', + 'bank_card_last_four' => '银行卡号后四位', + 'withdrawal_amount' => '提现金额', + 'withdrawal_balance_date' => '提现金额', + ]; + $changedLabels = array_unique(array_map( + static fn (string $field): string => $labels[$field], + array_keys($changes), + )); + $plan[] = [ + 'id' => (int) $account->id, + 'updated_at' => (string) $account->getRawOriginal('updated_at'), + 'changes' => $changes, + ]; + if (count($preview) < 20) { + $preview[] = [ + 'platform' => $platform, + 'erp_store_name' => $erpStoreName, + 'store_id' => $storeId, + 'changes' => implode('、', $changedLabels), + ]; + } + } + + if ($total === 0) { + throw ValidationException::withMessages(['import' => '导入文件中没有可识别的数据行。']); + } + if ($errors !== []) { + $visible = array_slice($errors, 0, 10); + if (count($errors) > count($visible)) { + $visible[] = '另有 ' . (count($errors) - count($visible)) . ' 项错误'; + } + throw ValidationException::withMessages(['import' => implode(';', $visible) . '。']); + } + + return [ + 'total' => $total, + 'changed' => count($plan), + 'unchanged' => $unchanged, + 'preview' => $preview, + 'plan' => $plan, + ]; + } + + /** @param list}> $plan */ + public function commit(array $plan, int $companyId): int + { + return DB::transaction(function () use ($plan, $companyId): int { + $updated = 0; + + foreach ($plan as $item) { + /** @var StoreReceivingAccount|null $account */ + $account = StoreReceivingAccount::withoutGlobalScopes() + ->where('company_id', $companyId) + ->whereNull('deleted_at') + ->whereKey((int) $item['id']) + ->lockForUpdate() + ->first(); + + if ($account === null || (string) $account->getRawOriginal('updated_at') !== (string) $item['updated_at']) { + throw ValidationException::withMessages([ + 'import' => '预览后店铺配置发生变化,请重新上传并预览。', + ]); + } + + if (isset($item['changes']['withdrawal_balance_date']) + && $item['changes']['withdrawal_balance_date'] !== null + && $item['changes']['withdrawal_balance_date'] !== now()->subDay()->toDateString()) { + throw ValidationException::withMessages([ + 'import' => '余额日期已滚动,请重新上传并预览提现金额。', + ]); + } + + foreach ($item['changes'] as $field => $value) { + if ($field === 'bank_card_last_four') { + $account->bank_card_last_four = $value; + } else { + $account->setAttribute($field, $value); + } + } + $account->save(); + $updated++; + } + + return $updated; + }); + } + + private function workbook(array $report): Spreadsheet + { + $headers = [...self::CONFIG_HEADERS, $report['balanceColumnLabel'], '预留标准', '提现金额', '是否达标']; + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('提现管理'); + $this->writeHeader($sheet, $headers); + $this->sizeColumns($sheet, [14, 32, 20, 32, 16, 24, 22, 20, 18, 18, 14]); + + $rowNumber = 2; + foreach ($report['rows'] as $row) { + $match = $report['balances'][(int) $row->id] ?? ['status' => 'not_ready', 'balance' => null]; + $reserve = $report['reserveStandards'][(int) $row->id] ?? null; + $withdrawalAmount = $report['withdrawalAmounts'][(int) $row->id] ?? null; + $compliance = $report['compliance'][(int) $row->id] ?? null; + $textValues = [ + 1 => (string) ($row->store_platform ?? ''), + 2 => (string) ($row->erp_store_name ?? ''), + 3 => (string) ($row->store_id ?? ''), + 4 => (string) ($row->store_entity_name ?? ''), + 5 => (string) ($row->withdrawal_path ?? ''), + 6 => (string) ($row->withdrawal_account_name ?? ''), + 7 => (string) ($row->bank_card_last_four ?? ''), + ]; + foreach ($textValues as $column => $value) { + $sheet->setCellValueExplicit([$column, $rowNumber], $value, DataType::TYPE_STRING); + } + + if ($match['status'] === 'matched') { + $sheet->setCellValue([8, $rowNumber], (float) $match['balance']); + } else { + $sheet->setCellValueExplicit([8, $rowNumber], $this->balanceStatus($match['status']), DataType::TYPE_STRING); + } + if ($reserve === null) { + $sheet->setCellValueExplicit([9, $rowNumber], '待配置', DataType::TYPE_STRING); + } else { + $sheet->setCellValue([9, $rowNumber], $reserve); + } + if ($withdrawalAmount === null) { + $sheet->setCellValueExplicit([10, $rowNumber], '待接入', DataType::TYPE_STRING); + } else { + $sheet->setCellValue([10, $rowNumber], $withdrawalAmount); + } + $sheet->setCellValueExplicit([11, $rowNumber], match ($compliance) { + 'yes' => '是', + 'no' => '否', + default => '待核验', + }, DataType::TYPE_STRING); + $rowNumber++; + } + + if ($rowNumber > 2) { + $sheet->getStyle('H2:J' . ($rowNumber - 1))->getNumberFormat()->setFormatCode('#,##0.00'); + $sheet->getStyle('H2:J' . ($rowNumber - 1))->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); + } + $sheet->getStyle('C2:C' . max(2, $rowNumber - 1))->getNumberFormat()->setFormatCode('@'); + $sheet->getStyle('G2:G' . max(2, $rowNumber - 1))->getNumberFormat()->setFormatCode('@'); + $spreadsheet->getProperties()->setTitle('提现管理')->setDescription('余额数据日期:' . $report['balanceDate']); + + return $spreadsheet; + } + + /** @return array{0:int,1:list} */ + private function headers(array $matrix): array + { + foreach (array_slice($matrix, 0, 10, true) as $index => $row) { + $headers = array_map(static fn (mixed $value): string => trim((string) $value), $row); + if (in_array('店铺平台', $headers, true) && in_array('ERP店铺名称', $headers, true)) { + foreach (self::CONFIG_HEADERS as $required) { + if (count(array_keys($headers, $required, true)) !== 1) { + throw ValidationException::withMessages([ + 'import' => "导入表头必须且只能包含一个“{$required}”列,请下载最新模板。", + ]); + } + } + if (count(array_keys($headers, '提现金额', true)) > 1) { + throw ValidationException::withMessages(['import' => '导入表头只能包含一个“提现金额”列。']); + } + + return [(int) $index, $headers]; + } + } + + throw ValidationException::withMessages([ + 'import' => '未找到提现管理导入表头,请下载最新模板。', + ]); + } + + /** @return array{0:array>,1:array>} */ + private function indexes($accounts): array + { + $byId = []; + $byName = []; + + foreach ($accounts as $account) { + $platform = trim((string) $account->store_platform); + $storeId = trim((string) ($account->store_id ?: $account->wallet_number)); + $erpStoreName = trim((string) $account->erp_store_name); + if ($platform !== '' && $storeId !== '') { + $byId[$this->key($platform, $storeId)][] = $account; + } + if ($platform !== '' && $erpStoreName !== '') { + $byName[$this->key($platform, $erpStoreName)][] = $account; + } + } + + return [$byId, $byName]; + } + + /** @param array $values @return array */ + private function changes(StoreReceivingAccount $account, array $values, string $balanceDate): array + { + $fields = [ + '店铺主体' => ['field' => 'store_entity_name', 'current' => $account->store_entity_name, 'max' => 191, 'clear' => ''], + '提现路径' => ['field' => 'receiving_method', 'current' => $account->withdrawal_path, 'max' => 191, 'clear' => ''], + '提现账户名称' => ['field' => 'receiving_account_name', 'current' => $account->withdrawal_account_name, 'max' => 191, 'clear' => null], + '银行卡号(后四位)' => ['field' => 'bank_card_last_four', 'current' => $account->bank_card_last_four, 'max' => 4, 'clear' => null], + ]; + $changes = []; + + foreach ($fields as $header => $definition) { + $raw = trim((string) ($values[$header] ?? '')); + if ($raw === '') { + continue; + } + $value = $raw === self::CLEAR_VALUE ? $definition['clear'] : $raw; + if ($header === '银行卡号(后四位)' && $value !== null) { + if (preg_match('/^\d{4}$/', $value) !== 1) { + throw new \InvalidArgumentException('的银行卡号必须填写后四位数字'); + } + } + if ($value !== null && mb_strlen($value) > $definition['max']) { + throw new \InvalidArgumentException("的{$header}超过 {$definition['max']} 个字符"); + } + $current = trim((string) ($definition['current'] ?? '')) ?: null; + $comparisonValue = $value === '' ? null : $value; + if ($current !== $comparisonValue) { + $changes[$definition['field']] = $value; + } + } + + $amount = $values['提现金额'] ?? ''; + if ($amount !== '' && $amount !== '待接入') { + if ($amount === self::CLEAR_VALUE) { + if ($account->withdrawal_amount !== null || $account->withdrawal_balance_date !== null) { + $changes['withdrawal_amount'] = null; + $changes['withdrawal_balance_date'] = null; + } + } else { + if (preg_match('/^\d{1,10}(?:\.\d{1,2})?$/', $amount) !== 1) { + throw new \InvalidArgumentException('的提现金额须为非负数,最多两位小数'); + } + $normalized = number_format((float) $amount, 2, '.', ''); + if ($account->withdrawal_amount !== $normalized || $account->withdrawal_balance_date !== $balanceDate) { + $changes['withdrawal_amount'] = $normalized; + $changes['withdrawal_balance_date'] = $balanceDate; + } + } + } + + return $changes; + } + + private function key(string $platform, string $identity): string + { + return trim($platform) . "\0" . trim($identity); + } + + private function balanceStatus(string $status): string + { + return match ($status) { + 'ambiguous' => '多条匹配', + 'unmatched' => '未匹配', + default => '待同步', + }; + } + + private function writeHeader($sheet, array $headers): void + { + $lastColumn = Coordinate::stringFromColumnIndex(count($headers)); + $sheet->fromArray($headers, null, 'A1'); + $sheet->freezePane('A2'); + $sheet->setAutoFilter("A1:{$lastColumn}1"); + $sheet->getRowDimension(1)->setRowHeight(26); + $sheet->getStyle("A1:{$lastColumn}1")->getFont()->setBold(true)->getColor()->setARGB('FFFFFFFF'); + $sheet->getStyle("A1:{$lastColumn}1")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF856632'); + $sheet->getStyle("A1:{$lastColumn}1")->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); + } + + private function sizeColumns($sheet, array $widths): void + { + foreach ($widths as $index => $width) { + $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width); + } + } + + private function download(Spreadsheet $spreadsheet, string $filename): StreamedResponse + { + return response()->streamDownload(function () use ($spreadsheet): void { + (new Xlsx($spreadsheet))->save('php://output'); + $spreadsheet->disconnectWorksheets(); + }, $filename, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } +} diff --git a/app/Business/WithdrawalReserveStandard.php b/app/Business/WithdrawalReserveStandard.php new file mode 100644 index 00000000..1e3e38cd --- /dev/null +++ b/app/Business/WithdrawalReserveStandard.php @@ -0,0 +1,35 @@ + 20000, + '淘宝' => 10000, + '淘宝分销' => 10000, + '阿里巴巴' => 10000, + '京东' => 5000, + '京喜' => 5000, + '抖音' => 5000, + '拼多多' => 5000, + ]; + + public static function amountFor(?string $platform, ?string $erpStoreName): ?int + { + $platform = trim((string) $platform); + $erpStoreName = trim((string) $erpStoreName); + + if ($platform === '天猫' && in_array($erpStoreName, self::TMALL_HIGH_RESERVE_STORES, true)) { + return 50000; + } + + return self::PLATFORM_DEFAULTS[$platform] ?? null; + } +} diff --git a/app/Console/Commands/ComputeProductMonthlyWeightedAverage.php b/app/Console/Commands/ComputeProductMonthlyWeightedAverage.php new file mode 100644 index 00000000..16f5e029 --- /dev/null +++ b/app/Console/Commands/ComputeProductMonthlyWeightedAverage.php @@ -0,0 +1,301 @@ +argument('month'))->startOfMonth(); + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $table = 'product_monthly_weighted_average_rows'; + $deadline = $month->addMonthNoOverflow()->day(2)->startOfDay(); + + $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)); + + $cost = $this->costPrices($connection, $codes); + $work = $this->workPlatformPrices($connection, $codes); + $change = $this->priceChanges($connection, $codes); + $inbound = $this->inboundAggregate($connection, $month); + $costRecordSkus = $this->costPriceRecordSkus($connection, $codes); + + $total = (clone $query)->count(); + $computed = 0; + $now = now(); + + for ($offset = 0; $offset < $total; $offset += 1000) { + $rows = (clone $query)->orderBy('row_key')->offset($offset)->limit(1000) + ->get([ + 'row_key', 'barcode_warehouse', 'warehouse_short_name', 'product_code', 'base_source', 'imported_at', + 'opening_quantity', 'opening_unit_price', 'previous_pricing_status', 'purchase_quantity', + ]); + + $updates = []; + foreach ($rows as $row) { + // 普通商品资料与进销存的商品编码大小写不一致,统一按大写匹配。 + $code = mb_strtoupper(trim((string) $row->product_code)); + $costPrice = is_array($cost) ? ($cost[$code] ?? null) : null; + $workPrice = is_array($work) ? ($work[$code] ?? null) : null; + $changePrice = is_array($change) ? ($change[$code] ?? null) : null; + $inboundKey = $code . "\0" . trim((string) $row->warehouse_short_name); + $payload = $this->calculate( + $row, + $costPrice, + $workPrice, + $changePrice, + $deadline, + $inbound[$inboundKey] ?? null, + isset($costRecordSkus[$code]), + ); + $updates[] = array_merge([ + 'report_month' => $month->toDateString(), + 'row_key' => $row->row_key, + 'barcode_warehouse' => $row->barcode_warehouse, + 'warehouse_short_name' => $row->warehouse_short_name, + 'product_code' => $row->product_code, + 'base_source' => $row->base_source, + 'imported_at' => $row->imported_at, + 'computed_at' => $now, + ], $payload); + $computed++; + } + + if ($updates !== []) { + DB::connection($connection)->table($table)->upsert( + $updates, + ['report_month', 'row_key'], + ['adjusted_unit_price', 'opening_amount', 'purchase_quantity', 'purchase_unit_price', 'purchase_amount', 'weighted_average_unit_price', 'pricing_status', 'computed_at'], + ); + } + } + + DB::connection($connection)->table('product_monthly_weighted_average_states')->updateOrInsert( + ['report_month' => $month->toDateString()], + ['status' => 'computed', 'computed_rows' => $computed, 'last_computed_at' => $now, 'updated_at' => $now, 'created_at' => $now], + ); + + $this->info($month->format('Y-m') . " 计算完成:{$computed} 行"); + + return self::SUCCESS; + } + + /** + * @return array + */ + private function costPrices(string $connection, array $codes): array + { + $map = []; + foreach (array_chunk($codes, 2000) as $chunk) { + foreach (DB::connection($connection)->table('ops_jst_sku') + ->whereIn('sku_id', $chunk)->whereNotNull('cost_price')->get(['sku_id', 'cost_price']) as $row) { + $map[mb_strtoupper(trim((string) $row->sku_id))] = (float) $row->cost_price; + } + } + + return $map; + } + + /** + * @return array + */ + private function workPlatformPrices(string $connection, array $codes): array + { + $map = []; + $now = now(); + foreach (array_chunk($codes, 2000) as $chunk) { + $rows = DB::connection($connection)->table('js_pm_price_adjustment') + ->whereIn('skuCode', $chunk) + ->whereNotNull('purchasePrice') + ->where(function ($query) use ($now): void { + $query->whereNull('effectTime')->orWhere('effectTime', '<=', $now); + }) + ->orderBy('effectTime') + ->get(['skuCode', 'purchasePrice', 'effectTime']); + foreach ($rows as $row) { + $map[mb_strtoupper(trim((string) $row->skuCode))] = [ + 'price' => (float) $row->purchasePrice, + 'effect' => $row->effectTime === null ? null : (string) $row->effectTime, + ]; + } + } + + return $map; + } + + /** + * @return array + */ + /** + * 入库明细汇总:按「大写条码 + 仓库简称」汇总库存变动量与总计(金额 + 预估金额)。 + * + * @return array + */ + private function inboundAggregate(string $connection, CarbonImmutable $month): array + { + $map = []; + if (! \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('inventory_inbound_detail_rows')) { + return $map; + } + + foreach (DB::connection($connection)->table('inventory_inbound_detail_rows') + ->where('report_month', $month->toDateString()) + ->selectRaw('warehouse_short_name, upper(barcode) as code, sum(quantity) as quantity, sum(coalesce(amount, 0) + coalesce(estimated_amount, 0)) as total') + ->groupBy('warehouse_short_name') + ->groupByRaw('upper(barcode)') + ->get() as $row) { + $key = mb_strtoupper(trim((string) $row->code)) . "\0" . trim((string) $row->warehouse_short_name); + $map[$key] = ['quantity' => (float) $row->quantity, 'total' => (float) $row->total]; + } + + return $map; + } + + /** + * 有"聚水潭成本价记录"(operated_at 非空)的商品编码集合。 + * + * @return array + */ + private function costPriceRecordSkus(string $connection, array $codes): array + { + $map = []; + if (! \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('jushuitan_cost_price_history_rows')) { + return $map; + } + + foreach (array_chunk($codes, 2000) as $chunk) { + $rows = DB::connection($connection)->table('jushuitan_cost_price_history_rows') + ->whereNotNull('operated_at') + ->where(function ($query) use ($chunk): void { + $query->whereIn('sku_id', $chunk)->orWhereIn('sku_id_normalized', $chunk); + }) + ->get(['sku_id', 'sku_id_normalized']); + foreach ($rows as $row) { + foreach ([$row->sku_id, $row->sku_id_normalized] as $value) { + $key = mb_strtoupper(trim((string) $value)); + if ($key !== '') { + $map[$key] = true; + } + } + } + } + + return $map; + } + + private function priceChanges(string $connection, array $codes): array + { + $map = []; + foreach (array_chunk($codes, 2000) as $chunk) { + $rows = DB::connection($connection)->table('js_pm_price_adjustment_log') + ->whereIn('skucode', $chunk) + ->whereNotNull('afterPrice') + ->orderBy('effectStartTime') + ->get(['skucode', 'afterPrice', 'originalPrice', 'effectStartTime', 'createTime']); + foreach ($rows as $row) { + $map[mb_strtoupper(trim((string) $row->skucode))] = [ + 'price' => (float) $row->afterPrice, + 'before' => $row->originalPrice === null ? null : (float) $row->originalPrice, + 'time' => $row->effectStartTime === null ? null : (string) $row->effectStartTime, + 'created' => $row->createTime === null ? null : (string) $row->createTime, + ]; + } + } + + return $map; + } + + /** + * @param array{price:float,effect:?string}|null $work + * @param array{price:float,time:?string}|null $change + * @return array + */ + private function calculate(object $row, ?float $cost, ?array $work, ?array $change, CarbonImmutable $deadline, ?array $inbound = null, bool $hasCostRecord = false): array + { + $openingQuantity = $row->opening_quantity === null ? 0.0 : (float) $row->opening_quantity; + $purchaseQuantity = $row->purchase_quantity === null ? 0.0 : (float) $row->purchase_quantity; + $openingUnitPrice = $row->opening_unit_price === null ? null : (float) $row->opening_unit_price; + $previousStatus = trim((string) ($row->previous_pricing_status ?? '')); + $changePrice = $change['price'] ?? null; + $workPrice = $work['price'] ?? null; + // 最终规则:生效开始日期为空 → 未匹配到工作平台价格; + // 生效开始日期 > 本月,或记录时间 > 次月2号(记录时间为空视为 ≤ 次月2号)→ 新价当月未生效,取变价前价格。 + $changeTime = $change['time'] ?? null; + $changeCreated = $change['created'] ?? null; + $monthStart = $deadline->startOfMonth(); + $hasWorkPlatformRecord = $changePrice !== null && $changeTime !== null; + $newPricePending = false; + if ($hasWorkPlatformRecord) { + $newPricePending = CarbonImmutable::parse($changeTime)->greaterThanOrEqualTo($monthStart) + || ($changeCreated !== null && CarbonImmutable::parse($changeCreated)->greaterThan($deadline)); + $changePrice = $newPricePending ? ($change['before'] ?? $changePrice) : $changePrice; + } + $previousStatus = in_array($previousStatus, ['预估价', '未定价'], true) ? '未定价' : $previousStatus; + + // 更改价格 + 定价状态(表2 第10条) + if ($openingUnitPrice !== null) { + if ($previousStatus !== '未定价') { + $adjusted = $openingUnitPrice; + $status = $previousStatus !== '' ? $previousStatus : '已定价'; + } elseif ($hasWorkPlatformRecord) { + $adjusted = $changePrice; + $status = $newPricePending ? '未定价' : '已定价'; + } else { + $adjusted = $openingUnitPrice; + $status = '未定价'; + } + } elseif ($hasWorkPlatformRecord) { + $adjusted = $changePrice; + $status = $newPricePending ? '未定价' : '已定价'; + } elseif ($cost !== null) { + // 方案②:只有"聚水潭成本价记录"里有生效记录(operated_at 非空)才算有生效日期 → 已定价。 + $adjusted = $cost; + $status = $hasCostRecord ? '已定价' : '未定价'; + } else { + $adjusted = null; + $status = '待人工核查'; + } + + // 采购数量/入库金额来自入库明细(大写条码 + 仓库简称汇总),采购单价 = 入库金额 ÷ 采购数量 + $purchaseQuantity = (float) ($inbound['quantity'] ?? 0); + // 加权平均单价按“先除再舍入”计算,因此这里保留未舍入的金额参与除法。 + $purchaseAmountRaw = $inbound === null ? 0.0 : (float) ($inbound['total'] ?? 0); + $purchaseAmount = $inbound === null ? null : round($purchaseAmountRaw, 2); + $purchaseUnitPrice = ($inbound === null || $purchaseQuantity == 0.0) + ? null + : round((float) ($inbound['total'] ?? 0) / $purchaseQuantity, 2); + + $openingAmountRaw = $adjusted === null ? 0.0 : $openingQuantity * $adjusted; + $openingAmount = $adjusted === null ? null : round($openingAmountRaw, 2); + $denominator = $openingQuantity + $purchaseQuantity; + if ($denominator === 0.0) { + // 四项全 0:加权平均单价取"更改价格"(按两位舍入后的值)。 + $weighted = $adjusted === null ? null : round($adjusted, 2); + } else { + // 先除再舍入:用未舍入的期初金额与入库金额相除,最后统一保留两位。 + $weighted = round(($openingAmountRaw + $purchaseAmountRaw) / $denominator, 4); + } + + return [ + 'purchase_quantity' => $purchaseQuantity, + 'adjusted_unit_price' => $adjusted === null ? null : round($adjusted, 2), + 'opening_amount' => $openingAmount, + 'purchase_unit_price' => $purchaseUnitPrice === null ? null : round($purchaseUnitPrice, 2), + 'purchase_amount' => $purchaseAmount, + 'weighted_average_unit_price' => $weighted, + 'pricing_status' => $status, + ]; + } +} diff --git a/app/Console/Commands/DedupAt.php b/app/Console/Commands/DedupAt.php index 6d2d6a11..94e292d6 100644 --- a/app/Console/Commands/DedupAt.php +++ b/app/Console/Commands/DedupAt.php @@ -6,14 +6,14 @@ use Illuminate\Console\Command; use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer; /** - * 一次性:删除现有发货数据里以 @ 开头、去@后已存在的重复单号。 + * 一次性:全表扫描,仅删除同订单、同发货日有干净单号对应的 @ 包裹。 * php artisan jst:dedup-at */ class DedupAt extends Command { protected $signature = 'jst:dedup-at'; - protected $description = '去除 @ 开头的重复单号(去@后已存在则删)'; + protected $description = '去除同订单、同发货日且有干净单号对应的 @ 包裹'; public function handle(): int { diff --git a/app/Console/Commands/ImportAccountLedgerRemarks.php b/app/Console/Commands/ImportAccountLedgerRemarks.php new file mode 100644 index 00000000..bcfc18c3 --- /dev/null +++ b/app/Console/Commands/ImportAccountLedgerRemarks.php @@ -0,0 +1,139 @@ +argument('path'); + if (! is_file($path)) { + $this->error('文件不存在:' . $path); + + return self::FAILURE; + } + + try { + $rows = $this->readRows($path); + } catch (Throwable $e) { + $this->error('读取失败:' . $e->getMessage()); + + return self::FAILURE; + } + + if ($rows === []) { + $this->error('没有解析到有效数据(需要表头:平台 / 账单项目 / 总账备注)。'); + + return self::FAILURE; + } + + $now = now(); + DB::transaction(function () use ($rows, $now): void { + if ($this->option('replace')) { + DB::table('ec_account_ledger_remarks')->delete(); + } + + foreach (array_chunk($rows, 500) as $chunk) { + DB::table('ec_account_ledger_remarks')->upsert( + array_map(static fn (array $row): array => $row + ['created_at' => $now, 'updated_at' => $now], $chunk), + ['platform', 'bill_item'], + ['ledger_remark', 'updated_at'], + ); + } + }); + + $map->forget(); + + $platforms = []; + foreach ($rows as $row) { + $platforms[$row['platform']] = ($platforms[$row['platform']] ?? 0) + 1; + } + ksort($platforms); + + $this->info(sprintf('已导入 %d 条总账备注映射。', count($rows))); + foreach ($platforms as $platform => $count) { + $this->line(sprintf(' %s:%d 条', $platform, $count)); + } + + return self::SUCCESS; + } + + /** + * @return list + */ + private function readRows(string $path): array + { + $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + $readerType = match ($extension) { + 'xlsx' => 'Xlsx', + 'xls' => 'Xls', + 'csv' => 'Csv', + default => throw new \InvalidArgumentException('只支持 xlsx / xls / csv 文件。'), + }; + + $reader = IOFactory::createReader($readerType); + $reader->setReadDataOnly(true); + if ($readerType === 'Csv') { + $reader->setInputEncoding('UTF-8'); + } + $book = $reader->load($path); + $sheetOption = trim((string) $this->option('sheet')); + if ($sheetOption !== '' && ctype_digit($sheetOption)) { + $index = (int) $sheetOption - 1; + if ($index < 0 || $index >= $book->getSheetCount()) { + throw new \InvalidArgumentException('工作表序号超出范围:' . $sheetOption); + } + $sheet = $book->getSheet($index); + } else { + $sheet = $sheetOption === '' ? $book->getActiveSheet() : $book->getSheetByName($sheetOption); + if ($sheet === null) { + throw new \InvalidArgumentException('找不到工作表:' . $sheetOption); + } + } + + $rows = []; + $header = null; + foreach ($sheet->getRowIterator() as $row) { + $cells = []; + $cellIterator = $row->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(false); + foreach ($cellIterator as $cell) { + $cells[] = trim((string) $cell->getValue()); + } + + if ($header === null) { + $cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', $cells[0] ?? ''); + $header = $cells; + continue; + } + + $platform = trim($cells[0] ?? ''); + $item = trim($cells[1] ?? ''); + $remark = trim($cells[2] ?? ''); + if ($platform === '' || $item === '') { + continue; + } + + $rows[] = [ + 'platform' => mb_substr($platform, 0, 32), + 'bill_item' => mb_substr($item, 0, 191), + 'ledger_remark' => mb_substr($remark, 0, 191), + ]; + } + + return $rows; + } +} diff --git a/app/Console/Commands/ImportDewuSettlementBills.php b/app/Console/Commands/ImportDewuSettlementBills.php new file mode 100644 index 00000000..9816c4a3 --- /dev/null +++ b/app/Console/Commands/ImportDewuSettlementBills.php @@ -0,0 +1,72 @@ +option($option)) === '') { + $this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。"); + + return self::FAILURE; + } + } + + try { + $result = $importer->import( + (string) $this->argument('path'), + (string) $this->option('from'), + (string) $this->option('to'), + (int) $this->option('expected-count'), + (string) $this->option('expected-income'), + (string) $this->option('expected-expense'), + (int) $this->option('batch'), + ); + } catch (RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + report($exception); + $this->error('得物完整账单导入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->table(['状态', '账单行数', '跳过行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[ + $result['status'], + $result['row_count'], + $result['excluded_rows'], + $result['store_count'], + $result['bill_item_count'], + $result['income_total'], + $result['expense_total'], + $result['net_total'], + $result['period_start'] . ' 至 ' . $result['period_end'], + ]]); + $this->line('渠道:' . collect($result['channel_counts']) + ->map(fn (int $count, string $channel): string => "{$channel} {$count}") + ->implode(';')); + $this->line('SHA-256: ' . $result['source_sha256']); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportDouyinAuthoritativeBills.php b/app/Console/Commands/ImportDouyinAuthoritativeBills.php index e5a327ce..c096c2b2 100644 --- a/app/Console/Commands/ImportDouyinAuthoritativeBills.php +++ b/app/Console/Commands/ImportDouyinAuthoritativeBills.php @@ -9,21 +9,22 @@ use Throwable; class ImportDouyinAuthoritativeBills extends Command { protected $signature = 'business-mirror:import-douyin-authoritative - {path : 胜算原始明细 UTF-8 CSV} {month : 完整月份 YYYY-MM} - {--count= : 核对笔数} {--income= : 核对收入合计} {--expense= : 核对支出合计}'; + {path : 胜算原始明细 UTF-8 CSV} {month : 所属月份 YYYY-MM} + {--count= : 核对笔数} {--income= : 核对收入合计} {--expense= : 核对支出合计} + {--through= : 月初至此日期的完整数据 YYYY-MM-DD,省略时为整月}'; - protected $description = '校验并原子启用完整月份胜算抖音明细,保留旧版本用于回滚'; + protected $description = '校验并原子启用指定月份或月初至截止日的胜算抖音明细,保留旧版本用于回滚'; public function handle(DouyinAuthoritativeBillImporter $importer): int { try { $result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'), - (int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense')); + (int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through')); } catch (Throwable $e) { $this->error('胜算抖音明细未启用,保留上一版数据。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件和镜像连接。')); return self::FAILURE; } - $this->info('胜算抖音明细已启用,月份:' . $this->argument('month') . ',笔数:' . $result['row_count']); + $this->info('胜算抖音明细已启用,范围:[' . $result['period_start'] . ', ' . $result['period_end'] . '),笔数:' . $result['row_count']); return self::SUCCESS; } } diff --git a/app/Console/Commands/ImportInternalFlowReport.php b/app/Console/Commands/ImportInternalFlowReport.php new file mode 100644 index 00000000..87205068 --- /dev/null +++ b/app/Console/Commands/ImportInternalFlowReport.php @@ -0,0 +1,36 @@ +import((string) $this->argument('path')); + } catch (Throwable $exception) { + report($exception); + $this->error('内部流转报表导入失败:' . $exception->getMessage()); + + return self::FAILURE; + } + + $this->info(sprintf( + '内部流转报表导入完成:明细 %s 行,跳过合计/空行 %s 行,来源文件 %s。', + number_format($result['imported']), + number_format($result['skipped']), + $result['source_file'], + )); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportInventoryInboundDetail.php b/app/Console/Commands/ImportInventoryInboundDetail.php new file mode 100644 index 00000000..212aab56 --- /dev/null +++ b/app/Console/Commands/ImportInventoryInboundDetail.php @@ -0,0 +1,210 @@ +argument('file'); + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $table = 'inventory_inbound_detail_rows'; + $forcedMonth = trim((string) ($this->option('month') ?? '')); + $now = now(); + + $maps = $this->shortNameMap(); + $this->info('仓库名称映射:仓库名 ' . count($maps['warehouse']) . ' 个、仓储方 ' . count($maps['provider']) . ' 个可唯一匹配'); + + // 原样导入:以本次文件为准整体重建,不做去重、不做加工。 + DB::connection($connection)->table($table)->delete(); + + $reader = IOFactory::createReaderForFile($file); + $reader->setReadDataOnly(true); + $sheet = $reader->load($file)->getSheet(0); + + $batch = []; + $imported = 0; + $mapped = 0; + $skipped = 0; + foreach ($sheet->getRowIterator(2) as $row) { + $rowNumber = $row->getRowIndex(); + $cells = []; + foreach ($row->getCellIterator('A', 'U') as $cell) { + $cells[] = $cell->getFormattedValue(); + } + $warehouse = trim((string) ($cells[14] ?? '')); + $createdRaw = trim((string) ($cells[16] ?? '')); + if ($warehouse === '' && $createdRaw === '') { + $skipped++; + continue; + } + + $month = $forcedMonth !== '' ? $forcedMonth : $this->monthOf($createdRaw); + if ($month === '') { + $skipped++; + continue; + } + + // 一般用"仓库"匹配仓库简称;含"代发仓"字样的按"仓储方"匹配。 + $shortName = ''; + if ($warehouse !== '') { + $shortName = str_contains($warehouse, '代发仓') + ? ($maps['provider'][$warehouse] ?? $maps['warehouse'][$warehouse] ?? '') + : ($maps['warehouse'][$warehouse] ?? ''); + } + if ($shortName !== '') { + $mapped++; + } + + $batch[] = [ + 'report_month' => $month . '-01', + // 唯一键按 Excel 行号生成,保留原表每一行(含重复行)。 + 'row_key' => sha1($month . '|' . $rowNumber), + 'source_no' => $this->text($cells[0] ?? ''), + 'document_no' => $this->text($cells[1] ?? ''), + 'created_serial' => $this->text($cells[2] ?? ''), + 'supplier' => $this->text($cells[3] ?? ''), + 'item_no' => $this->text($cells[4] ?? ''), + 'barcode' => $this->text($cells[5] ?? ''), + 'spec_name' => $this->text($cells[6] ?? ''), + 'quantity' => $this->number($cells[7] ?? ''), + 'unit_price' => $this->number($cells[8] ?? ''), + 'amount' => $this->number($cells[9] ?? ''), + 'estimated_unit_price' => $this->number($cells[10] ?? ''), + 'estimated_amount' => $this->number($cells[11] ?? ''), + 'supplier_barcode' => $this->text($cells[12] ?? ''), + 'remark' => $this->text($cells[13] ?? ''), + 'warehouse' => $warehouse !== '' ? $warehouse : null, + 'warehouse_short_name' => $shortName !== '' ? $shortName : null, + 'created_at_raw' => $this->moment($createdRaw), + 'express_name' => $this->text($cells[17] ?? ''), + 'express_no' => $this->text($cells[18] ?? ''), + 'not_sent' => $this->text($cells[19] ?? ''), + 'owner_name' => $this->text($cells[20] ?? ''), + 'imported_at' => $now, + ]; + $imported++; + + if (count($batch) >= 1000) { + DB::connection($connection)->table($table)->insertOrIgnore($batch); + $this->info('已写入 ' . $imported . ' 行'); + $batch = []; + } + } + + if ($batch !== []) { + DB::connection($connection)->table($table)->insertOrIgnore($batch); + } + + $this->info(sprintf( + '导入完成:%d 行,仓库简称匹配上 %d 行,跳过 %d 行;库中该表共 %d 行', + $imported, + $mapped, + $skipped, + DB::connection($connection)->table($table)->count(), + )); + + return self::SUCCESS; + } + + /** + * @return array{warehouse:array,provider:array} + * 仅保留能唯一匹配的键 + */ + private function shortNameMap(): array + { + $rows = InventoryWarehouseNameMapping::withoutGlobalScopes() + ->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']); + $grouped = []; + foreach ($rows as $row) { + $warehouse = trim((string) $row->warehouse); + if ($warehouse === '') { + continue; + } + $grouped[$warehouse][] = trim((string) $row->warehouse_short_name); + } + + $byWarehouse = []; + foreach ($grouped as $warehouse => $names) { + $unique = array_values(array_unique($names)); + if (count($unique) === 1 && $unique[0] !== '') { + $byWarehouse[$warehouse] = $unique[0]; + } + } + + $byProvider = []; + foreach ($rows as $row) { + $provider = trim((string) $row->warehouse_provider); + if ($provider === '') { + continue; + } + $byProvider[$provider][] = trim((string) $row->warehouse_short_name); + } + foreach ($byProvider as $provider => $names) { + $unique = array_values(array_unique($names)); + if (count($unique) === 1 && $unique[0] !== '') { + $byProvider[$provider] = $unique[0]; + } + } + + return ['warehouse' => $byWarehouse, 'provider' => $byProvider]; + } + + private function monthOf(string $value): string + { + $value = trim($value); + if ($value === '') { + return ''; + } + foreach (['Y/m/d H:i:s', 'Y-m-d H:i:s', 'Y/m/d', 'Y-m-d'] as $format) { + $parsed = \DateTimeImmutable::createFromFormat($format, $value); + if ($parsed instanceof \DateTimeImmutable) { + return $parsed->format('Y-m'); + } + } + $timestamp = strtotime($value); + + return $timestamp === false ? '' : date('Y-m', $timestamp); + } + + private function moment(string $value): ?string + { + $value = trim($value); + if ($value === '') { + return null; + } + $timestamp = strtotime($value); + + return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp); + } + + private function text(mixed $value): ?string + { + $text = trim((string) $value); + + return $text === '' ? null : $text; + } + + private function number(mixed $value): ?float + { + $text = str_replace(',', '', trim((string) $value)); + if ($text === '' || ! is_numeric($text)) { + return null; + } + + return (float) $text; + } +} diff --git a/app/Console/Commands/ImportInventoryReportAuthoritativeMonth.php b/app/Console/Commands/ImportInventoryReportAuthoritativeMonth.php new file mode 100644 index 00000000..46d75528 --- /dev/null +++ b/app/Console/Commands/ImportInventoryReportAuthoritativeMonth.php @@ -0,0 +1,36 @@ +import((string) $this->argument('path')); + } catch (Throwable $exception) { + report($exception); + $this->error('进销存权威月报导入失败:' . $exception->getMessage()); + $this->warn('已保留上一版有效数据。'); + + return self::FAILURE; + } + + $this->info(sprintf( + '进销存权威月报导入完成:月份 %s,明细 %d 行。', + $result['source_month'], + $result['source_rows'], + )); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportJdDailyBills.php b/app/Console/Commands/ImportJdDailyBills.php new file mode 100644 index 00000000..3b0ccb3c --- /dev/null +++ b/app/Console/Commands/ImportJdDailyBills.php @@ -0,0 +1,37 @@ +get()) { + $this->error('京东日账单正在导入,请稍后重试。'); + return self::FAILURE; + } + try { + $result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'), + (int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through')); + $this->info('京东日账单已启用,笔数:' . $result['row_count']); + return self::SUCCESS; + } catch (Throwable $e) { + $this->error('京东日账单未启用,保留上一版本。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件、重复记录及镜像连接。')); + return self::FAILURE; + } finally { + $lock->release(); + } + } +} diff --git a/app/Console/Commands/ImportJdWalletBills.php b/app/Console/Commands/ImportJdWalletBills.php new file mode 100644 index 00000000..dae9c717 --- /dev/null +++ b/app/Console/Commands/ImportJdWalletBills.php @@ -0,0 +1,37 @@ +get()) { + $this->error('京东钱包正在导入,请稍后重试。'); + return self::FAILURE; + } + try { + $result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'), + (int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through')); + $this->info('京东钱包已启用,笔数:' . $result['row_count']); + return self::SUCCESS; + } catch (Throwable $e) { + $this->error('京东钱包未启用,保留上一版本。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件、重复记录及镜像连接。')); + return self::FAILURE; + } finally { + $lock->release(); + } + } +} diff --git a/app/Console/Commands/ImportJstOrderLabels.php b/app/Console/Commands/ImportJstOrderLabels.php new file mode 100644 index 00000000..6e71a18d --- /dev/null +++ b/app/Console/Commands/ImportJstOrderLabels.php @@ -0,0 +1,42 @@ +option('from'); + $to = (string) $this->option('to'); + + try { + $result = $importer->import( + $from, + $to, + (int) $this->option('company'), + (bool) $this->option('replace'), + 'jst-order-label-import', + ); + } catch (Throwable $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(json_encode($result, JSON_UNESCAPED_UNICODE)); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportPinduoduoSettlementBills.php b/app/Console/Commands/ImportPinduoduoSettlementBills.php new file mode 100644 index 00000000..fd32f2cf --- /dev/null +++ b/app/Console/Commands/ImportPinduoduoSettlementBills.php @@ -0,0 +1,72 @@ +option($option)) === '') { + $this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。"); + + return self::FAILURE; + } + } + + try { + $result = $importer->import( + (string) $this->argument('path'), + (string) $this->option('from'), + (string) $this->option('to'), + (int) $this->option('expected-count'), + (string) $this->option('expected-income'), + (string) $this->option('expected-expense'), + (int) $this->option('batch'), + ); + } catch (RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + report($exception); + $this->error('拼多多完整货款账单导入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->table(['状态', '账单行数', '跳过行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[ + $result['status'], + $result['row_count'], + $result['excluded_account_rows'], + $result['store_count'], + $result['bill_item_count'], + $result['income_total'], + $result['expense_total'], + $result['net_total'], + $result['period_start'] . ' 至 ' . $result['period_end'], + ]]); + $this->line('账户类型:' . collect($result['account_type_counts']) + ->map(fn (int $count, string $account): string => "{$account} {$count}") + ->implode(';')); + $this->line('SHA-256: ' . $result['source_sha256']); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportPlantingDetails.php b/app/Console/Commands/ImportPlantingDetails.php new file mode 100644 index 00000000..00a283ef --- /dev/null +++ b/app/Console/Commands/ImportPlantingDetails.php @@ -0,0 +1,38 @@ +import( + (string) $this->argument('file'), + (int) $this->option('company'), + (bool) $this->option('replace'), + null, + 'planting-detail-import', + ); + } catch (Throwable $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(json_encode($result, JSON_UNESCAPED_UNICODE)); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportProductMonthlyWeightedAverageBase.php b/app/Console/Commands/ImportProductMonthlyWeightedAverageBase.php new file mode 100644 index 00000000..9b5f259b --- /dev/null +++ b/app/Console/Commands/ImportProductMonthlyWeightedAverageBase.php @@ -0,0 +1,333 @@ +argument('month'))->startOfMonth(); + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $rowsTable = 'product_monthly_weighted_average_rows'; + $now = now(); + + $inventory = $this->inventoryAggregate($connection, $month); + $jiangxiPurchase = $this->jiangxiDeliveryPurchase($connection, $month); + $nanchangOpening = $this->nanchangOpeningQuantity($connection, $month); + $this->info('进销存(排除不看)合计 ' . count($inventory) . ' 个 仓库简称+商品编码'); + + DB::connection($connection)->table($rowsTable)->where('report_month', $month->toDateString())->delete(); + + $payload = []; + $baseRows = 0; + $deliveryRows = 0; + $mirrorRows = 0; + + $file = (string) ($this->option('file') ?? ''); + if ($file !== '') { + foreach ($this->readBaseFile($file) as $row) { + $payload[$this->rowKey($month, $row['warehouse_short_name'], $row['product_code'])] = [ + 'report_month' => $month->toDateString(), + 'row_key' => $this->rowKey($month, $row['warehouse_short_name'], $row['product_code']), + 'barcode_warehouse' => $row['barcode_warehouse'], + 'warehouse_short_name' => $row['warehouse_short_name'], + 'product_code' => $row['product_code'], + 'opening_unit_price' => $row['opening_unit_price'], + 'previous_pricing_status' => $row['previous_pricing_status'], + 'base_source' => 'base', + 'imported_at' => $now, + ]; + $baseRows++; + } + } elseif ($this->option('from-previous')) { + $previous = $month->subMonthNoOverflow(); + foreach (DB::connection($connection)->table($rowsTable) + ->where('report_month', $previous->toDateString()) + ->get(['barcode_warehouse', 'warehouse_short_name', 'product_code', 'pricing_status', 'weighted_average_unit_price']) as $row) { + $key = $this->rowKey($month, $row->warehouse_short_name, $row->product_code); + $payload[$key] = [ + 'report_month' => $month->toDateString(), + 'row_key' => $key, + 'barcode_warehouse' => $row->barcode_warehouse, + 'warehouse_short_name' => $row->warehouse_short_name, + 'product_code' => $row->product_code, + 'opening_unit_price' => $row->weighted_average_unit_price, + 'previous_pricing_status' => $row->pricing_status, + 'base_source' => 'base', + 'imported_at' => $now, + ]; + $baseRows++; + } + } else { + $this->error('请给出 --file=表1.xlsx(首月)或 --from-previous(滚动月份)。'); + + return self::FAILURE; + } + + // 代发仓:没有库存,但必须出现在这张表里,采购数量取销售出库。 + foreach ($inventory as $key => $item) { + $rowKey = $this->rowKey($month, $item['warehouse_short_name'], $item['product_code']); + if (isset($payload[$rowKey])) { + continue; + } + $isDelivery = $this->isDeliveryWarehouse($item['warehouse_short_name']); + $payload[$rowKey] = [ + 'report_month' => $month->toDateString(), + 'row_key' => $rowKey, + // 条码+仓库 = 商品编码 + 仓库简称 + 'barcode_warehouse' => $item['product_code'] . $item['warehouse_short_name'], + 'warehouse_short_name' => $item['warehouse_short_name'], + 'product_code' => $item['product_code'], + 'opening_unit_price' => null, + 'previous_pricing_status' => null, + 'base_source' => $isDelivery ? 'delivery' : 'mirror', + 'imported_at' => $now, + ]; + $isDelivery ? $deliveryRows++ : $mirrorRows++; + } + + // 南昌樵舍仓的采购数量取自"简尚-江西仓送货主仓",这些条码也要一并纳入行维度, + // 否则只存在于江西仓送货的单据会因为表里没有对应行而丢掉采购数量。 + foreach (array_keys($jiangxiPurchase) as $code) { + $rowKey = $this->rowKey($month, '南昌樵舍仓', $code); + if (isset($payload[$rowKey])) { + continue; + } + $payload[$rowKey] = [ + 'report_month' => $month->toDateString(), + 'row_key' => $rowKey, + 'barcode_warehouse' => $code . '南昌樵舍仓', + 'warehouse_short_name' => '南昌樵舍仓', + 'product_code' => $code, + 'opening_unit_price' => null, + 'previous_pricing_status' => null, + 'base_source' => 'mirror', + 'imported_at' => $now, + ]; + $mirrorRows++; + } + + $matched = 0; + foreach ($payload as $key => $row) { + $item = $inventory[$row['warehouse_short_name'] . "\0" . $row['product_code']] ?? null; + // 代发仓判定不能只看 base_source(滚动月份会丢标记),按仓库简称再兜一层。 + $isDelivery = $row['base_source'] === 'delivery' + || str_contains((string) $row['warehouse_short_name'], '代发仓'); + $isNanchang = $row['warehouse_short_name'] === '南昌樵舍仓'; + // 原始数量只取"主仓"的期初数量(仓库名称含主仓字样)。 + $openingQuantity = $isDelivery ? 0.0 : (float) ($item['opening_quantity'] ?? 0); + if ($isNanchang) { + // 南昌樵舍仓是特殊仓库:期初数量取"三方-南昌樵舍仓主仓"对应商品的期初数量。 + $openingQuantity = (float) ($nanchangOpening[$row['product_code']] ?? 0); + } + $purchaseQuantity = $isDelivery + ? abs((float) ($item['sales_out'] ?? 0)) + : ($isNanchang + // 南昌樵舍仓是特殊仓库:采购数量取"简尚-江西仓送货主仓"对应商品的采购进仓数量。 + ? (float) ($jiangxiPurchase[$row['product_code']] ?? 0) + : (float) ($item['purchase_in'] ?? 0)); + if ($item !== null) { + $matched++; + } + $payload[$key]['product_name'] = $item['category'] ?? null; + $payload[$key]['opening_quantity'] = $openingQuantity; + $payload[$key]['purchase_quantity'] = $purchaseQuantity; + $payload[$key]['opening_original_amount'] = $row['opening_unit_price'] === null + ? null + : round($openingQuantity * (float) $row['opening_unit_price'], 2); + } + + foreach (array_chunk($payload, 1000, true) as $chunk) { + DB::connection($connection)->table($rowsTable)->insert(array_values($chunk)); + } + + DB::connection($connection)->table('product_monthly_weighted_average_states')->updateOrInsert( + ['report_month' => $month->toDateString()], + [ + 'status' => 'base_imported', + 'base_filename' => $file !== '' ? basename($file) : null, + 'base_rows' => $baseRows, + 'delivery_rows' => $deliveryRows, + 'matched_rows' => $matched, + 'last_error' => null, + 'updated_at' => $now, + 'created_at' => $now, + ], + ); + + $this->info(sprintf( + '%s 基数导入完成:基表 %d 行 + 代发仓 %d 行,合计 %d 行,其中 %d 行在进销存总表匹配到数据。', + $month->format('Y-m'), + $baseRows, + $deliveryRows, + count($payload), + $matched, + )); + + return self::SUCCESS; + } + + /** @return array */ + private function inventoryAggregate(string $connection, CarbonImmutable $month): array + { + $generation = DB::connection($connection)->table('inventory_report_authoritative_months') + ->where('source_month', $month->toDateString()) + ->value('active_generation'); + if (! $generation) { + throw new \RuntimeException($month->format('Y-m') . ' 的进销存总表尚未导入。'); + } + + $mappingTable = (new InventoryWarehouseNameMapping)->getConnection()->getDatabaseName() + . '.' . DB::connection((new InventoryWarehouseNameMapping)->getConnectionName())->getTablePrefix() + . (new InventoryWarehouseNameMapping)->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, + sum(r.purchase_in) as purchase_in, + sum(r.sales_out) as sales_out, max(r.category) as category + from inventory_report_authoritative_rows r + join {$mappingTable} m + on m.warehouse_provider = r.warehouse_provider + and m.warehouse = r.warehouse + and m.company_id = 1 + and m.deleted_at is null + where r.generation = ? + and m.warehouse_short_name not like '%不看%' + and r.warehouse like '%主仓%' + and m.warehouse_short_name <> '南昌樵舍仓' + group by m.warehouse_short_name, r.product_code"; + + $aggregate = []; + foreach (DB::connection($connection)->select($sql, [$generation]) as $row) { + $aggregate[$row->short_name . "\0" . mb_strtoupper(trim((string) $row->product_code))] = [ + 'warehouse_short_name' => (string) $row->short_name, + // 商品编码统一按大写建索引,避免与表1/普通商品资料大小写不一致导致匹配不上。 + 'product_code' => mb_strtoupper(trim((string) $row->product_code)), + 'opening_quantity' => (string) $row->opening_quantity, + 'purchase_in' => (string) $row->purchase_in, + 'sales_out' => (string) $row->sales_out, + 'category' => (string) ($row->category ?? ''), + ]; + } + + return $aggregate; + } + + /** @return \Generator */ + private function readBaseFile(string $file): \Generator + { + $reader = IOFactory::createReaderForFile($file); + $reader->setReadDataOnly(true); + $spreadsheet = $reader->load($file); + $sheet = $spreadsheet->getSheetByName('7月份期初基数') ?? $spreadsheet->getSheet(0); + + foreach ($sheet->getRowIterator(3) as $row) { + $cells = []; + foreach ($row->getCellIterator('A', 'P') as $cell) { + $cells[] = $cell->getFormattedValue(); + } + $shortName = trim((string) ($cells[2] ?? '')); + $productCode = trim((string) ($cells[4] ?? '')); + if ($shortName === '' || $productCode === '') { + continue; + } + $price = trim((string) ($cells[7] ?? '')); + $previousStatus = trim((string) ($cells[15] ?? '')); + + yield [ + // 条码+仓库统一为「仓库简称 + 商品编码」,不再沿用表1 里的单元格写法。 + 'barcode_warehouse' => $shortName . $productCode, + 'warehouse_short_name' => $shortName, + 'product_code' => mb_strtoupper($productCode), + // 原始价格保留源表精度(不提前舍入),保证加权平均单价与手工表一致;页面展示仍按两位。 + 'opening_unit_price' => $price === '' ? null : (float) str_replace(',', '', $price), + 'previous_pricing_status' => $previousStatus === '' ? null : $previousStatus, + ]; + } + } + + private function isDeliveryWarehouse(string $shortName): bool + { + return str_contains($shortName, '代发'); + } + + /** + * 南昌樵舍仓的采购数量取"简尚-江西仓送货主仓"对应商品的采购进仓数量。 + * + * @return array + */ + private function jiangxiDeliveryPurchase(string $connection, CarbonImmutable $month): array + { + $generation = DB::connection($connection)->table('inventory_report_authoritative_months') + ->where('source_month', $month->toDateString()) + ->value('active_generation'); + if (! $generation) { + return []; + } + + $map = []; + foreach (DB::connection($connection)->table('inventory_report_authoritative_rows') + ->where('generation', $generation) + ->where('warehouse', '简尚-江西仓送货主仓') + ->selectRaw('product_code, sum(purchase_in) as quantity') + ->groupBy('product_code') + ->get() as $row) { + $map[mb_strtoupper(trim((string) $row->product_code))] = (string) $row->quantity; + } + + return $map; + } + + /** + * 南昌樵舍仓的期初数量取"三方-南昌樵舍仓主仓"对应商品的期初数量。 + * + * @return array + */ + private function nanchangOpeningQuantity(string $connection, CarbonImmutable $month): array + { + $generation = DB::connection($connection)->table('inventory_report_authoritative_months') + ->where('source_month', $month->toDateString()) + ->value('active_generation'); + if (! $generation) { + return []; + } + + $map = []; + foreach (DB::connection($connection)->table('inventory_report_authoritative_rows') + ->where('generation', $generation) + ->where('warehouse', '三方-南昌樵舍仓主仓') + ->selectRaw('product_code, sum(opening_quantity) as quantity') + ->groupBy('product_code') + ->get() as $row) { + $map[mb_strtoupper(trim((string) $row->product_code))] = (string) $row->quantity; + } + + return $map; + } + + private function rowKey(CarbonImmutable $month, string $shortName, string $productCode): string + { + return sha1($month->format('Y-m') . '|' . $shortName . '|' . $productCode); + } +} diff --git a/app/Console/Commands/ImportTaobaoAlipayBills.php b/app/Console/Commands/ImportTaobaoAlipayBills.php index 57dae215..3e4b228e 100644 --- a/app/Console/Commands/ImportTaobaoAlipayBills.php +++ b/app/Console/Commands/ImportTaobaoAlipayBills.php @@ -10,7 +10,8 @@ class ImportTaobaoAlipayBills extends Command { protected $signature = 'business:import-taobao-alipay-bills {file : 淘系支付宝账户 Excel 文件路径} - {--company=1 : 数据所属公司 ID}'; + {--company=1 : 数据所属公司 ID} + {--replace : 校验通过后替换该公司的全部淘系支付宝账单}'; protected $description = '从标准附件导入店铺收款账户账单的淘系支付宝账户数据'; @@ -20,6 +21,7 @@ class ImportTaobaoAlipayBills extends Command $result = $importer->import( (string) $this->argument('file'), max(1, (int) $this->option('company')), + (bool) $this->option('replace'), ); } catch (Throwable $e) { $this->components->error($e->getMessage()); @@ -28,7 +30,7 @@ class ImportTaobaoAlipayBills extends Command } $this->components->info( - "导入完成:新增 {$result['inserted']} 条,更新 {$result['updated']} 条,跳过 {$result['skipped']} 条。" + "导入完成:新增 {$result['inserted']} 条,更新 {$result['updated']} 条,替换旧数据 {$result['replaced']} 条,跳过 {$result['skipped']} 条。" ); return self::SUCCESS; diff --git a/app/Console/Commands/ImportTaobaoAlipaySettlementBills.php b/app/Console/Commands/ImportTaobaoAlipaySettlementBills.php new file mode 100644 index 00000000..edd274f9 --- /dev/null +++ b/app/Console/Commands/ImportTaobaoAlipaySettlementBills.php @@ -0,0 +1,71 @@ +option($option)) === '') { + $this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。"); + + return self::FAILURE; + } + } + + try { + $result = $importer->import( + (string) $this->argument('path'), + (string) $this->option('from'), + (string) $this->option('to'), + (int) $this->option('expected-count'), + (string) $this->option('expected-income'), + (string) $this->option('expected-expense'), + (int) $this->option('batch'), + ); + } catch (RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + report($exception); + $this->error('淘系支付宝完整账单导入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->table(['状态', '账单行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[ + $result['status'], + $result['row_count'], + $result['store_count'], + $result['bill_item_count'], + $result['income_total'], + $result['expense_total'], + $result['net_total'], + $result['period_start'] . ' 至 ' . $result['period_end'], + ]]); + $this->line('业务类型:' . collect($result['business_type_counts']) + ->map(fn (int $count, string $type): string => "{$type} {$count}") + ->implode(';')); + $this->line('SHA-256: ' . $result['source_sha256']); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ImportTaobaoWechatSettlementBills.php b/app/Console/Commands/ImportTaobaoWechatSettlementBills.php new file mode 100644 index 00000000..28c6c92e --- /dev/null +++ b/app/Console/Commands/ImportTaobaoWechatSettlementBills.php @@ -0,0 +1,72 @@ +option($option)) === '') { + $this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。"); + + return self::FAILURE; + } + } + + try { + $result = $importer->import( + (string) $this->argument('path'), + (string) $this->option('from'), + (string) $this->option('to'), + (int) $this->option('expected-count'), + (string) $this->option('expected-income'), + (string) $this->option('expected-expense'), + (int) $this->option('batch'), + ); + } catch (RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + report($exception); + $this->error('淘系微信完整账单导入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->table(['状态', '账单行数', '跳过行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[ + $result['status'], + $result['row_count'], + $result['excluded_rows'], + $result['store_count'], + $result['bill_item_count'], + $result['income_total'], + $result['expense_total'], + $result['net_total'], + $result['period_start'] . ' 至 ' . $result['period_end'], + ]]); + $this->line('入账类型:' . collect($result['entry_type_counts']) + ->map(fn (int $count, string $type): string => "{$type} {$count}") + ->implode(';')); + $this->line('SHA-256: ' . $result['source_sha256']); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/SyncJushuitanCostPriceHistory.php b/app/Console/Commands/SyncJushuitanCostPriceHistory.php index ddda7a45..110ab52b 100644 --- a/app/Console/Commands/SyncJushuitanCostPriceHistory.php +++ b/app/Console/Commands/SyncJushuitanCostPriceHistory.php @@ -12,7 +12,7 @@ class SyncJushuitanCostPriceHistory extends Command { protected $signature = 'business-mirror:sync-jushuitan-cost-price-history {--full : 强制启动或继续首次全量同步} - {--page-size= : 聚水潭接口每页读取条数,最大 2000} + {--page-size= : 聚水潭接口每页读取条数,最大 50} {--max-pages= : 本轮最多读取页数,0 表示直到完成}'; protected $description = '按时间窗和页码同步聚水潭商品操作日志中的采购价变更到共享业务镜像'; @@ -35,13 +35,17 @@ class SyncJushuitanCostPriceHistory extends Command ); } catch (Throwable $exception) { Log::error('聚水潭历史成本价镜像同步失败。', ['exception' => $exception::class]); - $this->error('聚水潭成本价历史同步失败,已保留上一版共享数据。'); + $this->error(match ($exception->getMessage()) { + 'jushuitan_classic_api_credentials_missing' => '聚水潭经典开放接口凭据未配置,请配置 partnerid、partnerkey 和 token。', + 'jushuitan_classic_api_partner_id_invalid' => '聚水潭经典开放接口 partnerid 无效,请核对同一应用的 partnerid、partnerkey 和 token。', + default => '聚水潭成本价历史同步失败,已保留上一版共享数据。', + }); return self::FAILURE; } if ($result['status'] === 'requires_full_sync') { - $this->warn('聚水潭成本价历史尚未完成首次全量同步,请在凭据和备份确认后显式使用 --full。'); + $this->warn('聚水潭成本价历史尚未完成首次全量同步,请配置经典开放接口凭据后显式使用 --full。'); return self::SUCCESS; } diff --git a/app/Console/Commands/SyncProductPurchasePriceMirror.php b/app/Console/Commands/SyncProductPurchasePriceMirror.php index f657358b..ea766fe9 100644 --- a/app/Console/Commands/SyncProductPurchasePriceMirror.php +++ b/app/Console/Commands/SyncProductPurchasePriceMirror.php @@ -16,7 +16,7 @@ class SyncProductPurchasePriceMirror extends Command {--batch= : 每批最多读取行数} {--max-batches= : 本轮最多批次数,0 表示直到完成}'; - protected $description = '同步采购单管理的普通商品单价,并保留可断点的共享业务镜像'; + protected $description = '同步采购单管理明细和普通商品单价,并保留可断点的共享业务镜像'; public function handle( ProductPurchasePriceMirrorRepository $mirror, diff --git a/app/Console/Commands/SyncStoreReceiptOrderMatches.php b/app/Console/Commands/SyncStoreReceiptOrderMatches.php new file mode 100644 index 00000000..060d4c98 --- /dev/null +++ b/app/Console/Commands/SyncStoreReceiptOrderMatches.php @@ -0,0 +1,374 @@ + 0 的有效行 + * - 单号清洗:去除日期前缀(如 260630-)、空格、横杠后按核心号匹配 + * - 店铺:账单用「线上真实店铺」优先,订单侧用销售全量店铺名,统一把下划线归一为横杠 + * - 同一店铺同一订单号多笔收款 → 标注「一单多笔」,商品金额只挂一次 + */ +class SyncStoreReceiptOrderMatches extends Command +{ + protected $signature = 'store-receipt:order-match:sync + {month : 账单月份,格式 YYYY-MM} + {--platform=taobao-alipay : 收款账户,目前支持 taobao-alipay} + {--chunk=1200 : 单次向上游查询的订单号数量} + {--limit=0 : 仅处理前 N 笔账单(调试用,0 表示全量)}'; + + protected $description = '按店铺收款账户账单匹配订单侧商品金额,生成「业绩明细」核对镜像'; + + /** 收款账户 → 账单镜像表 */ + private const BILL_TABLES = [ + 'taobao-alipay' => 'taobao_alipay_bill_rows', + 'taobao-wechat' => 'taobao_wechat_bill_rows', + 'pinduoduo' => 'pdd_settlement_bill_rows', + ]; + + /** 账单项目:计入收款的账单类型 */ + private const BILL_ITEMS = [ + '交易收款', + '1688增值服务-诚e赊订单红包', + '1688增值服务-诚e赊买家还款', + '1688增值服务先采后付担保付款', + '1688增值服务先采后付买家还款', + '1688增值服务先采后付收款', + '交易分账_货款', + '其它交易收款', + '先采后付账单付款', + '百补超级版消费者实付款', + '店铺过户', + ]; + + private const TARGET_TABLE = 'store_receipt_order_match_rows'; + + private const STATUS_MATCHED = '已匹配'; + + private const STATUS_UNMATCHED = '未匹配'; + + private const REMARK_EMPTY_NO = '空单号'; + + private const REMARK_BAD_FORMAT = '格式不一致'; + + private const REMARK_NO_ORDER = '订单表无此单'; + + private const REMARK_NO_AMOUNT = '订单无商品金额'; + + private const REMARK_SHOP_DIFF = '店铺不一致'; + + private const REMARK_DUP_ORDER = '订单侧同号多条'; + + private const REMARK_MULTI_PAY = '一单多笔'; + + public function handle(UpstreamReadOnlyQueryFactory $factory): int + { + $month = trim((string) $this->argument('month')); + if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + throw new InvalidArgumentException('月份格式应为 YYYY-MM,例如 2026-08。'); + } + + $platform = (string) $this->option('platform'); + if (! isset(self::BILL_TABLES[$platform])) { + throw new InvalidArgumentException('暂不支持的收款账户:' . $platform); + } + + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $billTable = self::BILL_TABLES[$platform]; + $chunkSize = max(50, (int) $this->option('chunk')); + $limit = max(0, (int) $this->option('limit')); + + $start = Carbon::createFromFormat('Y-m-d', $month . '-01')->startOfDay(); + $end = $start->copy()->addMonthNoOverflow(); + $reportMonth = $start->toDateString(); + + $this->info(sprintf('账期 %s(%s ~ %s),账单来源 %s', $month, $start->toDateString(), $end->copy()->subDay()->toDateString(), $billTable)); + + $bills = DB::connection($connection)->table($billTable) + ->selectRaw('store_name, online_real_store, online_order_no, occurred_at, income_amount') + ->whereIn('bill_item', self::BILL_ITEMS) + ->where('occurred_at', '>=', $start->toDateTimeString()) + ->where('occurred_at', '<', $end->toDateTimeString()) + ->orderBy('occurred_at') + ->get(); + + if ($limit > 0) { + $bills = $bills->take($limit); + } + + if ($bills->isEmpty()) { + $this->warn('该账期没有符合条件的账单记录,未写入任何数据。'); + + return self::SUCCESS; + } + + /** @var array> $groups 账单侧按「店铺 + 订单号」聚合 */ + $groups = []; + $paymentTotal = 0; + $incomeTotal = 0.0; + foreach ($bills as $bill) { + $rawNo = trim((string) ($bill->online_order_no ?? '')); + $core = self::cleanOrderNo($rawNo); + $shopKey = self::normalizeShop((string) (($bill->online_real_store ?? '') !== '' ? $bill->online_real_store : $bill->store_name)); + $key = $shopKey . '|' . $core; + + if (! isset($groups[$key])) { + $groups[$key] = [ + 'store_name' => (string) ($bill->store_name ?? ''), + 'shop_key' => $shopKey, + 'online_order_no' => $rawNo, + 'order_core_no' => $core, + 'occurred_date' => substr((string) $bill->occurred_at, 0, 10), + 'payment_count' => 0, + 'income_amount' => 0.0, + ]; + } + + $groups[$key]['payment_count']++; + $groups[$key]['income_amount'] += (float) $bill->income_amount; + $paymentTotal++; + $incomeTotal += (float) $bill->income_amount; + } + + $this->info('账单收款笔数:' . $paymentTotal . ',按「店铺 + 订单号」聚合后:' . count($groups) . ' 行'); + + $cores = []; + foreach ($groups as $group) { + if ($group['order_core_no'] !== '') { + $cores[$group['order_core_no']] = true; + } + } + + $upstream = $factory->forSource('operations_replica'); + $dwsFrom = $start->copy()->subDays(150)->toDateString(); + $dwsTo = $end->copy()->addDays(7)->toDateString(); + + /** @var array $orderAmount 订单侧按「店铺 + 核心单号」聚合的商品金额(仅 goods_count>0 的有效行) */ + $orderAmount = []; + /** @var array $orderSeen 订单侧出现过的「店铺 + 核心单号」(含 0 元行) */ + $orderSeen = []; + /** @var array> $coresByCore 核心单号 → 出现过的店铺集合 */ + $coresByCore = []; + /** @var array $coreSeen 订单侧出现过的核心单号(含店铺名为空的行) */ + $coreSeen = []; + $chunks = array_chunk(array_keys($cores), $chunkSize); + $totalChunks = count($chunks); + + foreach ($chunks as $index => $chunk) { + $in = implode(',', array_map(static fn (string $no): string => "'" . str_replace("'", "''", $no) . "'", $chunk)); + + try { + $rows = $upstream->select( + "SELECT sourceno, shop_name, sales_amount, goods_count FROM rpt.dws_sn_sales_full_info_di + WHERE sourceno IN ({$in}) AND stat_date >= '{$dwsFrom}' AND stat_date < '{$dwsTo}'" + ); + } catch (Throwable $exception) { + $this->error('订单侧查询失败(第 ' . ($index + 1) . ' 批):' . $exception->getMessage()); + + return self::FAILURE; + } + + foreach ($rows as $row) { + $core = self::cleanOrderNo((string) $row['sourceno']); + if ($core === '') { + continue; + } + $shopKey = self::normalizeShop((string) ($row['shop_name'] ?? '')); + $key = $shopKey . '|' . $core; + $orderSeen[$key] = true; + $coreSeen[$core] = true; + if ($shopKey !== '') { + $coresByCore[$core][$shopKey] = true; + } + if ((int) ($row['goods_count'] ?? 0) <= 0) { + // 退款/冲减/0 元赠品行不计入商品金额,差额列另行体现。 + continue; + } + $orderAmount[$key] = ($orderAmount[$key] ?? 0.0) + (float) $row['sales_amount']; + } + + if (($index + 1) % 10 === 0 || $index + 1 === $totalChunks) { + $this->info(sprintf('订单侧进度 %d/%d 批', $index + 1, $totalChunks)); + } + } + + DB::connection($connection)->table(self::TARGET_TABLE) + ->where('report_month', $reportMonth) + ->delete(); + + $target = DB::connection($connection)->table(self::TARGET_TABLE); + $now = now(); + $buffer = []; + $imported = 0; + $stats = ['已匹配' => 0, '未匹配' => 0, '一单多笔' => 0]; + $remarked = []; + $goodsTotal = 0.0; + $differenceTotal = 0.0; + + foreach ($groups as $group) { + $core = (string) $group['order_core_no']; + $income = round((float) $group['income_amount'], 2); + $remark = ''; + $productAmount = null; + $status = self::STATUS_UNMATCHED; + + if ($core === '') { + $remark = self::REMARK_EMPTY_NO; + } elseif (preg_match('/^\d{8,}$/', $core) !== 1) { + $remark = self::REMARK_BAD_FORMAT; + } else { + $exactKey = $group['shop_key'] . '|' . $core; + if (isset($orderSeen[$exactKey])) { + if (isset($orderAmount[$exactKey])) { + $status = self::STATUS_MATCHED; + $productAmount = round((float) $orderAmount[$exactKey], 2); + if (count($coresByCore[$core] ?? []) > 1) { + $remark = self::REMARK_DUP_ORDER; + } + } else { + // 订单侧有记录,但全是 0 元/退款行:没有商品金额可比对。 + $remark = self::REMARK_NO_AMOUNT; + } + } elseif (isset($coreSeen[$core]) && count($coresByCore[$core] ?? []) === 1) { + // 单号一致但店铺名称对不上:仍然带上金额,标注「店铺不一致」便于复核。 + $onlyShop = array_key_first($coresByCore[$core]); + $otherKey = $onlyShop . '|' . $core; + if (isset($orderAmount[$otherKey])) { + $status = self::STATUS_MATCHED; + $productAmount = round((float) $orderAmount[$otherKey], 2); + $remark = self::REMARK_SHOP_DIFF; + } else { + $remark = self::REMARK_NO_AMOUNT; + } + } elseif (isset($coreSeen[$core]) && count($coresByCore[$core] ?? []) > 1) { + $sum = 0.0; + $hasAmount = false; + foreach (array_keys($coresByCore[$core]) as $shopKey) { + $key2 = $shopKey . '|' . $core; + if (isset($orderAmount[$key2])) { + $sum += (float) $orderAmount[$key2]; + $hasAmount = true; + } + } + if ($hasAmount) { + $status = self::STATUS_MATCHED; + $productAmount = round($sum, 2); + $remark = self::REMARK_DUP_ORDER; + } else { + $remark = self::REMARK_NO_AMOUNT; + } + } elseif (isset($coreSeen[$core])) { + // 订单侧只有店铺名为空的记录:按订单号兜底匹配。 + $blankKey = '|' . $core; + if (isset($orderAmount[$blankKey])) { + $status = self::STATUS_MATCHED; + $productAmount = round((float) $orderAmount[$blankKey], 2); + } else { + $remark = self::REMARK_NO_AMOUNT; + } + } else { + $remark = self::REMARK_NO_ORDER; + } + } + + if ($status === self::STATUS_MATCHED && (int) $group['payment_count'] > 1 && $remark === '') { + $remark = self::REMARK_MULTI_PAY; + } + + $difference = $productAmount === null ? null : round($income - $productAmount, 2); + if ($productAmount !== null) { + $goodsTotal += $productAmount; + $differenceTotal += (float) $difference; + } + + $stats[$status] = ($stats[$status] ?? 0) + 1; + if ((int) $group['payment_count'] > 1) { + $stats['一单多笔']++; + } + if ($remark !== '') { + $remarked[$remark] = ($remarked[$remark] ?? 0) + 1; + } + + $buffer[] = [ + 'report_month' => $reportMonth, + 'row_key' => md5($reportMonth . '|' . $group['shop_key'] . '|' . $core), + 'occurred_date' => $group['occurred_date'], + 'store_name' => $group['store_name'], + 'online_order_no' => $group['online_order_no'] !== '' ? $group['online_order_no'] : null, + 'order_core_no' => $core !== '' ? $core : null, + 'payment_count' => (int) $group['payment_count'], + 'income_amount' => $income, + 'product_amount' => $productAmount, + 'difference' => $difference, + 'match_status' => $status, + 'remark' => $remark !== '' ? $remark : null, + 'imported_at' => $now, + ]; + + if (count($buffer) >= 500) { + $target->insertOrIgnore($buffer); + $imported += count($buffer); + $buffer = []; + } + } + + if ($buffer !== []) { + $target->insertOrIgnore($buffer); + $imported += count($buffer); + } + + $this->info('写入完成,共 ' . $imported . ' 行(账单收款 ' . $paymentTotal . ' 笔)。'); + foreach ($stats as $status => $count) { + $this->line(' ' . $status . ':' . $count); + } + foreach ($remarked as $remark => $count) { + $this->line(' 标注 ' . $remark . ':' . $count); + } + $this->line(' 账单收入合计:' . number_format($incomeTotal, 2)); + $this->line(' 订单侧商品金额合计:' . number_format($goodsTotal, 2)); + $this->line(' 差额合计:' . number_format($differenceTotal, 2)); + + return self::SUCCESS; + } + + /** 单号清洗:去掉日期前缀(如 260630-)、空格、横杠,得到核心号。 */ + public static function cleanOrderNo(string $value): string + { + $value = str_replace("\u{3000}", ' ', trim($value)); + if ($value === '') { + return ''; + } + + // 日期前缀形如「260630-」:只有明确带 6 位数字 + 横杠时才去除, + // 避免误伤本身就是纯数字的订单号(如 5126322747312081812)。 + if (preg_match('/^\d{6}\s*[-\x{FF0D}\x{2014}\x{2013}\x{2010}]/u', $value) === 1) { + $value = preg_replace('/^\d{6}\s*[-\x{FF0D}\x{2014}\x{2013}\x{2010}]/u', '', $value) ?? $value; + } + + $value = preg_replace('/[\s\-\x{FF0D}\x{2014}\x{2013}\x{2010}]+/u', '', $value) ?? ''; + + return strtoupper($value); + } + + /** 店铺名归一:下划线视为横杠,去掉空白。 */ + public static function normalizeShop(string $value): string + { + $value = str_replace(["\u{3000}", '_'], [' ', '-'], trim($value)); + $value = preg_replace('/\s+/', '', $value) ?? ''; + + return strtoupper($value); + } +} diff --git a/app/Console/Commands/SyncStoreReportMirror.php b/app/Console/Commands/SyncStoreReportMirror.php index e6ca9adf..ba82fb3a 100644 --- a/app/Console/Commands/SyncStoreReportMirror.php +++ b/app/Console/Commands/SyncStoreReportMirror.php @@ -38,9 +38,12 @@ class SyncStoreReportMirror extends Command } $this->info(sprintf( - '店铺报表镜像:生命周期 %s/%d 行,账单 %s/%d 行,日汇总 %s/%d 行。', + '店铺报表镜像:流程期间 %s/%d 行,主体变更 %s(检查 %d 店,新增 %d 条),账单 %s/%d 行,日汇总 %s/%d 行。', $result['lifecycles']['status'], $result['lifecycles']['source_rows'], + $result['period_changes']['status'], + $result['period_changes']['checked'], + $result['period_changes']['created'], $result['bills']['status'], $result['bills']['source_rows'], $result['daily']['status'], diff --git a/app/Console/Commands/SyncStoreViolations.php b/app/Console/Commands/SyncStoreViolations.php new file mode 100644 index 00000000..6884eb64 --- /dev/null +++ b/app/Console/Commands/SyncStoreViolations.php @@ -0,0 +1,135 @@ +available()) { + $this->error('统一表 store_violation_records 尚未建立,请先执行数据库迁移。'); + + return self::FAILURE; + } + + $platform = trim((string) $this->option('platform')); + $platforms = (array) config('store_violations.platforms', []); + if ($platform !== '' && ! array_key_exists($platform, $platforms)) { + $this->error('未知平台:' . $platform); + + return self::FAILURE; + } + + $sourceValues = []; + foreach ($platforms as $slug => $definition) { + if ($platform !== '' && $slug !== $platform) { + continue; + } + foreach ($definition['source_values'] ?? [] as $value) { + $sourceValues[] = (string) $value; + } + } + $sourceValues = array_values(array_unique($sourceValues)); + + $batchSize = max(min((int) $this->option('batch'), 5000), 100); + + try { + $pdo = UpstreamOdbcConnection::create('operations_replica'); + } catch (Throwable $exception) { + report($exception); + $repository->recordSyncState('failed', $repository->totalRows(), 'connect_failed'); + $this->error('无法连接经营分析副本库:' . $exception->getMessage()); + + return self::FAILURE; + } + + $now = now(); + $lastId = 0; + $upserted = 0; + $skipped = 0; + $read = 0; + + try { + while (true) { + $sql = 'SELECT TOP ' . $batchSize + . ' id, shop_name, violation_no, violation_date, deadline, violation_content,' + . ' status, window_name, platform, crawl_date' + . ' FROM rpt.crawl_shop_violation WHERE id > ?'; + $params = [$lastId]; + + if ($sourceValues !== []) { + $sql .= ' AND platform IN (' . implode(', ', array_fill(0, count($sourceValues), '?')) . ')'; + $params = array_merge($params, $sourceValues); + } + + $sql .= ' ORDER BY id ASC'; + + $statement = $pdo->prepare($sql); + $statement->execute($params); + $rows = $statement->fetchAll(PDO::FETCH_ASSOC); + $statement->closeCursor(); + + if ($rows === []) { + break; + } + + $payload = []; + foreach ($rows as $row) { + $read++; + $lastId = max($lastId, (int) ($row['id'] ?? 0)); + $mapped = $mapper->mapCrawlRow($row); + if ($mapped === null || $mapped['violation_no'] === '') { + $skipped++; + continue; + } + + $payload[] = $mapped + [ + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + $upserted += $repository->upsertRows($payload, StoreViolationRecordRepository::CRAWL_UPDATE_COLUMNS); + } + } catch (Throwable $exception) { + report($exception); + $repository->recordSyncState('failed', $repository->totalRows(), 'sync_failed'); + $this->error('同步失败:' . $exception->getMessage()); + + return self::FAILURE; + } + + $total = $repository->totalRows(); + $repository->recordSyncState('succeeded', $total); + + $this->info(sprintf( + '同步完成:读取 %d 行,写入/更新 %d 行,跳过 %d 行,统一表共 %d 行。', + $read, + $upserted, + $skipped, + $total, + )); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/SyncThirdPartyWarehouseStorage.php b/app/Console/Commands/SyncThirdPartyWarehouseStorage.php index 7cb1d85c..a7f937a0 100644 --- a/app/Console/Commands/SyncThirdPartyWarehouseStorage.php +++ b/app/Console/Commands/SyncThirdPartyWarehouseStorage.php @@ -10,10 +10,10 @@ use Throwable; class SyncThirdPartyWarehouseStorage extends Command { protected $signature = 'business-mirror:sync-third-party-warehouse-storage - {--full : 启动或继续三方仓流水与库存的全量校准} + {--full : 启动或继续聚水潭全仓流水与库存的全量校准} {--max-batches= : 本轮最多批次数,0 表示直到完成}'; - protected $description = '同步南昌樵舍三方仓按商品进销存数据到共享业务镜像'; + protected $description = '同步聚水潭全部仓库按商品进销存数据到共享业务镜像'; public function handle(ThirdPartyWarehouseStorageSynchronizer $synchronizer): int { @@ -27,29 +27,29 @@ class SyncThirdPartyWarehouseStorage extends Command $this->option('max-batches') === null ? null : (int) $this->option('max-batches'), ); } catch (Throwable $exception) { - Log::error('三方仓仓储数据共享镜像同步失败。', [ + Log::error('聚水潭进销存数据共享镜像同步失败。', [ 'dataset' => ThirdPartyWarehouseStorageSynchronizer::DATASET_KEY, 'exception' => $exception::class, ]); - $this->error('三方仓仓储数据同步失败,页面继续读取上一版完整数据。'); + $this->error('聚水潭进销存数据同步失败,页面继续读取上一版完整数据。'); return self::FAILURE; } if ($result['status'] === 'requires_full_sync') { - $this->warn('三方仓仓储数据尚未完成首次全量同步,请显式使用 --full。'); + $this->warn('聚水潭进销存数据尚未完成首次全量同步,请显式使用 --full。'); return self::SUCCESS; } if ($result['status'] === 'already_running') { - $this->line('三方仓仓储数据已有同步任务运行,本次不重复启动。'); + $this->line('聚水潭进销存数据已有同步任务运行,本次不重复启动。'); return self::SUCCESS; } $this->info(sprintf( - '三方仓仓储数据%s:%s,本轮 %d 批;流水 %d 条、明细 %d 条、库存 %d 条。', + '聚水潭进销存数据%s:%s,本轮 %d 批;流水 %d 条、明细 %d 条、库存 %d 条。', $result['mode'] === 'full' ? '全量校准' : '增量同步', $result['status'] === 'succeeded' ? '完成' : '进行中', $result['batches'], diff --git a/app/Console/Commands/WarmReportCaches.php b/app/Console/Commands/WarmReportCaches.php new file mode 100644 index 00000000..52fbfd31 --- /dev/null +++ b/app/Console/Commands/WarmReportCaches.php @@ -0,0 +1,85 @@ +startOfMonth()->subMonth()->format('Y-m'); + $result = $inventory->paginateMonthlyInventoryReport([ + 'month' => $month, + 'product_code' => '', + 'warehouse_provider' => '', + 'category' => '', + ], 1, 25); + $this->info(sprintf('进销存 %s 首页已预热,共 %d 行。', $month, $result['total'])); + } catch (Throwable $exception) { + $failed = true; + Log::error('默认进销存报表缓存预热失败。', ['exception' => $exception::class]); + $this->error('默认进销存报表缓存预热失败。'); + } + + try { + $result = $alipay->paginate([], 'occurred_at', 'desc', 1, 10); + $this->info(sprintf('淘系支付宝首页已预热,共 %d 行。', $result['total'])); + $options = $alipay->filterOptionsForChannel( + 'alipayCSV', + StoreReceivingAlipayBillMirrorRepository::DATASET, + true, + ); + $this->info(sprintf( + '淘系支付宝筛选选项已预热,共 %d 个店铺、%d 个账单项目。', + count($options['shops']), + count($options['bill_items']), + )); + } catch (Throwable $exception) { + $failed = true; + Log::error('淘系支付宝报表缓存预热失败。', ['exception' => $exception::class]); + $this->error('淘系支付宝报表缓存预热失败。'); + } + + try { + $result = $smallPayments->paginate([ + 'from' => now()->subDays(29)->format('Y-m-d') . 'T00:00:00', + 'to' => now()->format('Y-m-d') . 'T23:59:59', + 'work_order_no' => '', + 'shop_name' => '', + 'transaction_no' => '', + 'online_order_no' => '', + 'status' => '', + 'payment_reason' => '', + ], 1, 25); + $options = $smallPayments->filterOptions(); + $this->info(sprintf( + '小额打款首页已预热,共 %d 行、%d 个店铺、%d 个打款原因。', + $result['total'], + count($options['shops']), + count($options['payment_reasons']), + )); + } catch (Throwable $exception) { + $failed = true; + Log::error('小额打款报表缓存预热失败。', ['exception' => $exception::class]); + $this->error('小额打款报表缓存预热失败。'); + } + + return $failed ? self::FAILURE : self::SUCCESS; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index d71c8957..5b484366 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -35,11 +35,27 @@ class Kernel extends ConsoleKernel $schedule->command('storage-temp:clear')->dailyAt('17:00'); $schedule->command('model:prune')->dailyAt('17:00'); - // 线上代发价格:每天凌晨 00:00 全量/增量同步一次钉钉线上代发业务报销流程。 + // 线上代发价格:每天凌晨 05:00 刷新钉钉审批、采购单和订单关联镜像。 // 生产环境由 business-mirror:sync-tables 的 cron 持续增量覆盖,此处保证 - // 一个固定的每日零点刷新入口;命令本身在非刷新环境会安全跳过。 + // 一个固定的每日刷新入口;命令本身在非刷新环境会安全跳过。 $schedule->command('business-mirror:sync-ding-online-daifa-price') - ->dailyAt('00:00') + ->dailyAt('05:00') + ->withoutOverlapping(60) + ->runInBackground(); + + $schedule->command('business-mirror:sync-product-purchase-prices') + ->dailyAt('05:00') + ->withoutOverlapping(60) + ->runInBackground(); + + $schedule->command('business-mirror:sync-tables operations_replica.rpt.jst_Orders') + ->dailyAt('05:00') + ->withoutOverlapping(60) + ->runInBackground(); + + // 店铺违规信息预警:每天同步副本库抓取结果到统一表(本地补充字段不覆盖)。 + $schedule->command('store-violations:sync') + ->dailyAt('05:30') ->withoutOverlapping(60) ->runInBackground(); @@ -55,7 +71,7 @@ class Kernel extends ConsoleKernel ->runInBackground(); } - // 聚水潭发货数据增量同步:每 10 分钟按 modified 水位拉销售出库单。 + // 聚水潭发货数据每日重拉最近三天,覆盖副本库迟到更新。 // 默认关闭(JST_SYNC_ENABLED=false);填好凭证并完成迁移后再打开。 if ((bool) env('JST_SYNC_ENABLED', false)) { $schedule->command('jushuitan:sync-shipping --days=3') diff --git a/app/Exports/ThirdPartyWarehouseStorageDetailExport.php b/app/Exports/ThirdPartyWarehouseStorageDetailExport.php new file mode 100644 index 00000000..c01806d8 --- /dev/null +++ b/app/Exports/ThirdPartyWarehouseStorageDetailExport.php @@ -0,0 +1,49 @@ +> $rows */ + public function __construct(private readonly array $rows) + { + } + + public function title(): string + { + return '每日商品仓储费'; + } + + /** @return array */ + public function headings(): array + { + return [ + '日期', '货主', '商品编码', '商品名称', '供应商', '分类', '单位', + '上日结余', '当日进出净额', '当日库存结余', '当天仓储费', + ]; + } + + /** @return array> */ + public function array(): array + { + return array_map(static fn (array $row): array => [ + $row['date'], + $row['owner'], + $row['sku_code'], + $row['product_name'], + $row['supplier'], + $row['category'], + $row['unit'], + (float) $row['opening'], + (float) $row['net_movement'], + (float) $row['closing'], + (float) $row['storage_fee'], + ], $this->rows); + } +} diff --git a/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php b/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php index 0b7eb648..b4a2a359 100644 --- a/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php +++ b/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php @@ -11,13 +11,14 @@ use Maatwebsite\Excel\Concerns\WithMultipleSheets; use Maatwebsite\Excel\Concerns\WithTitle; /** - * 三方仓仓储费核算明细导出:汇总 / 进销存数据汇总(每日) / 进销存(逐商品) 三张表。 + * 三方仓仓储费核算明细导出:汇总 / 进销存数据汇总(每日) / 进销存(逐商品) / + * 每日商品仓储费四张表。 * 数据来自 ThirdPartyWarehouseStorageFeeCalculator 的核算结果(或存档快照)。 */ class ThirdPartyWarehouseStorageSettlementExport implements WithMultipleSheets { /** - * @param array{summary:array,daily:list>,per_sku:list>} $result + * @param array{summary:array,daily:list>,per_sku:list>,daily_sku?:list>} $result */ public function __construct(private readonly array $result) { @@ -30,6 +31,7 @@ class ThirdPartyWarehouseStorageSettlementExport implements WithMultipleSheets new StorageSettlementSummarySheet($this->result['summary']), new StorageSettlementDailySheet($this->result['summary'], $this->result['daily']), new StorageSettlementSkuSheet($this->result['per_sku']), + new ThirdPartyWarehouseStorageDetailExport($this->result['daily_sku'] ?? []), ]; } } diff --git a/app/Http/Controllers/Auth/Login.php b/app/Http/Controllers/Auth/Login.php index 0c61b49a..3d43c6ff 100644 --- a/app/Http/Controllers/Auth/Login.php +++ b/app/Http/Controllers/Auth/Login.php @@ -85,6 +85,10 @@ class Login extends Controller $path = route('portal.dashboard', ['company_id' => $company->id]); } + if (! $request->expectsJson()) { + return redirect()->to($path); + } + return response()->json([ 'status' => null, 'success' => true, @@ -98,6 +102,10 @@ class Login extends Controller // Redirect to landing page if is user $url = route($user->landing_page, ['company_id' => $company->id]); + if (! $request->expectsJson()) { + return redirect()->intended($url); + } + return response()->json([ 'status' => null, 'success' => true, @@ -118,6 +126,14 @@ class Login extends Controller */ protected function respondLoginFailed() { + $request = app('Illuminate\Http\Request'); + + if (! $request->expectsJson()) { + return redirect()->back() + ->withInput($request->except('password')) + ->withErrors(['email' => trans('auth.failed')]); + } + return response()->json([ 'status' => null, 'success' => false, diff --git a/app/Http/Controllers/Business/AccountMappingActions.php b/app/Http/Controllers/Business/AccountMappingActions.php new file mode 100644 index 00000000..9e6618c4 --- /dev/null +++ b/app/Http/Controllers/Business/AccountMappingActions.php @@ -0,0 +1,578 @@ + '新增', + 'update' => '修改', + 'delete' => '删除', + 'import' => '导入', + 'reset' => '重置', + ]; + + private const HISTORY_FIELD_LABELS = [ + 'platform' => '平台', + 'item' => '账单项目', + 'memo' => '财务备注', + 'invoice' => '票据口径', + 'category' => '大类', + 'dAcct' => '借方科目', + 'dSub' => '借方二级', + 'cAcct' => '贷方科目', + 'cSub' => '贷方二级', + 'basis' => '方向基准', + ]; + + public function __construct( + private readonly AccountMappingStore $store, + private readonly AccountMappingValidator $validator, + private readonly AccountMappingCoa $coa, + private readonly AccountMappingWorkbookImporter $importer, + ) { + $this->middleware('auth'); + $this->middleware('company.identify'); + } + + /** 全量规则 + 校验结果 + 筛选项 */ + public function index(): JsonResponse + { + return response()->json($this->payload()); + } + + public function store(Request $request): JsonResponse + { + $values = $this->payloadValues($request); + if (trim((string) ($values['platform'] ?? '')) === '' || trim((string) ($values['item'] ?? '')) === '') { + throw ValidationException::withMessages(['platform' => '平台和账单项目不能为空。']); + } + + $this->store->create($values, $this->userId()); + + return response()->json(['message' => '已新增 1 条规则。'] + $this->payload()); + } + + public function update(Request $request, int $id): JsonResponse + { + if ($this->store->find($id) === null) { + throw ValidationException::withMessages(['id' => '这条规则已经不存在了,请刷新页面。']); + } + + $this->store->update($id, $this->payloadValues($request), $this->userId()); + + return response()->json(['message' => '已保存。'] + $this->payload()); + } + + public function destroy(int $id): JsonResponse + { + if (! $this->store->destroy($id, $this->userId())) { + throw ValidationException::withMessages(['id' => '这条规则已经不存在了,请刷新页面。']); + } + + return response()->json(['message' => '已删除 1 条规则。'] + $this->payload()); + } + + /** + * 操作记录:最近 500 条(新增 / 修改 / 删除 / 导入 / 重置)。 + * + * 每条含改动前、改动后的完整规则内容,所以能查出「谁在什么时候把哪个字段从什么改成了什么」, + * 也能据此还原被删掉的行。操作人只返回名称,不返回账号等敏感字段。 + */ + public function history(): JsonResponse + { + $events = $this->historyEvents(); + + return response()->json([ + 'events' => $events, + 'total' => count($events), + 'limit' => self::HISTORY_LIMIT, + ]); + } + + /** + * 操作记录导出为 CSV,筛选口径与页面上的「操作记录」一致。 + */ + public function historyExport(Request $request): StreamedResponse + { + $action = trim((string) $request->query('action', '')); + $keyword = trim((string) $request->query('keyword', '')); + + $rows = array_values(array_filter( + $this->historyEvents(), + fn (array $row): bool => $this->historyMatches($row, $action, $keyword) + )); + + return response()->streamDownload(function () use ($rows): void { + $handle = fopen('php://output', 'w'); + fwrite($handle, "\xEF\xBB\xBF"); + fputcsv($handle, ['时间', '操作', '平台', '账单项目', '财务备注', '变更内容', '操作人']); + foreach ($rows as $row) { + fputcsv($handle, [ + $row['at'], $row['action_label'], $row['platform'], $row['item'], $row['memo'], + implode(';', $row['changes']), $row['actor'], + ]); + } + fclose($handle); + }, '科目映射表_操作记录.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * 按操作记录恢复:被删除的规则重新建回来,被改过的规则恢复成改前内容。 + * + * 前端传的是「记录在列表里的位置 + 时间 + 操作 + 规则号」,三者都对得上才动手, + * 避免这期间有人新增了记录、位置发生偏移时恢复错行。 + */ + public function historyRestore(Request $request): JsonResponse + { + $index = (int) $request->input('index', -1); + $at = trim((string) $request->input('at', '')); + $action = trim((string) $request->input('action', '')); + $ruleId = (int) $request->input('id', 0); + + $event = $this->store->events(self::HISTORY_LIMIT)[$index] ?? null; + + if ($event === null + || (string) ($event['at'] ?? '') !== $at + || (string) ($event['action'] ?? '') !== $action + || (int) ($event['id'] ?? 0) !== $ruleId) { + throw ValidationException::withMessages(['history' => '操作记录已经变化,请关掉面板重新打开再试。']); + } + + $before = is_array($event['before'] ?? null) ? $event['before'] : null; + if ($before === null) { + throw ValidationException::withMessages(['history' => '这条记录没有可恢复的内容。']); + } + + if ($action === 'delete') { + foreach ($this->store->all() as $rule) { + if ($this->store->keyOf($rule) === $this->store->keyOf($before)) { + throw ValidationException::withMessages([ + 'history' => '这条规则已经在表里了(记录 #' . (int) $rule['id'] . '),不用恢复。', + ]); + } + } + + $restored = $this->store->create($before, $this->userId()); + + return response()->json([ + 'message' => '已恢复「' . $restored['platform'] . ' · ' . $restored['item'] . '」(新记录 #' . (int) $restored['id'] . ')。', + ] + $this->payload()); + } + + if ($action === 'update') { + if ($this->store->find($ruleId) === null) { + throw ValidationException::withMessages(['history' => '这条规则已经被删掉了,请用同一条的「删除」记录恢复。']); + } + + $this->store->update($ruleId, $before, $this->userId()); + + return response()->json([ + 'message' => '已恢复成这次修改前的内容(记录 #' . $ruleId . ')。', + ] + $this->payload()); + } + + throw ValidationException::withMessages(['history' => '只有「删除」和「修改」的记录可以恢复。']); + } + + /** + * 导入预览:只解析、不落盘。 + * + * 单独一条路由、且不挂 throttle:import —— 因为平台对「导入」限的是 1 次/分钟, + * 而页面上「预览 → 确认导入」天然要发两次请求,预览走限流必然 429。 + */ + public function preview(Request $request): JsonResponse + { + return response()->json($this->previewPayload($this->workbookFile($request))); + } + + /** + * 导入落盘。带 ?dry_run=1 时行为同 preview(保留兼容)。 + */ + public function import(Request $request): JsonResponse + { + $file = $this->workbookFile($request); + + if ($request->boolean('dry_run')) { + return response()->json($this->previewPayload($file)); + } + + $parsed = $this->importer->parse($file); + $result = $this->store->importRows($parsed['rows'], $request->boolean('overwrite'), $this->userId()); + $message = "导入完成:识别 {$result['total']} 行,新增 {$result['created']} 条,更新 {$result['updated']} 条,跳过重复 {$result['skipped']} 条。"; + + return response()->json(['message' => $message, 'result' => $result] + $this->payload()); + } + + /** + * 取上传的工作簿。 + * + * 这里**故意不用** `mimes:xlsx,xls,csv`:那个规则靠 libmagic 嗅探真实类型, + * 而只有两三行的 CSV 会被猜成 `text/plain`、扩展名算成 `txt`,于是合法文件被拒 + * (实测 2 行 231B 的 csv 报「必须是 xlsx, xls, csv 的文件」)。按扩展名判就稳。 + */ + protected function workbookFile(Request $request) + { + $request->validate([ + 'import' => ['required', 'file', 'max:10240'], + ], [ + 'import.required' => '请先选择要导入的文件。', + 'import.file' => '请选择要导入的文件。', + 'import.max' => '文件不能超过 10MB。', + ]); + + $file = $request->file('import'); + $extension = mb_strtolower((string) $file->getClientOriginalExtension()); + + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages([ + 'import' => '只支持 xlsx、xls、csv 三种格式,当前是「' . $extension . '」。', + ]); + } + + return $file; + } + + /** + * @param \Illuminate\Http\UploadedFile $file + * @return array + */ + protected function previewPayload($file): array + { + $parsed = $this->importer->parse($file); + $rows = $parsed['rows']; + + $existing = []; + foreach ($this->store->all() as $rule) { + $existing[$this->store->keyOf($rule)] = true; + } + + $fresh = []; + $duplicated = []; + foreach ($rows as $row) { + $key = $this->store->keyOf($row); + if (isset($existing[$key])) { + $duplicated[$key] = ($duplicated[$key] ?? 0) + 1; + } else { + $fresh[$key] = true; + $existing[$key] = true; + } + } + + return [ + 'dry_run' => true, + 'sheet' => $parsed['sheet'], + 'total' => count($rows), + 'can_create' => count($fresh), + 'can_overwrite' => count($duplicated), + 'duplicate_keys' => array_slice(array_keys($duplicated), 0, 20), + 'sample' => array_slice($rows, 0, 6), + ]; + } + + /** 恢复成初始 112 条 */ + public function reset(): JsonResponse + { + $total = $this->store->reset($this->userId()); + + return response()->json(['message' => "已恢复为初始 {$total} 条规则。"] + $this->payload()); + } + + /** 账套科目(一级 + 各一级下的明细),供下拉使用 */ + public function accounts(): JsonResponse + { + $level1 = $this->coa->level1(); + $children = []; + foreach ($level1 as $account) { + $children[$account['code']] = $this->coa->descendants($account['code']); + } + + return response()->json(['level1' => $level1, 'children' => $children]); + } + + /** 按当前表导出 CSV(Excel 可直接打开) */ + public function export(): StreamedResponse + { + $rules = $this->store->all(); + + return response()->streamDownload(function () use ($rules): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new RuntimeException('无法创建导出文件。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_values(AccountMappingStore::LABELS)); + + foreach ($rules as $rule) { + $row = []; + foreach (array_keys(AccountMappingStore::LABELS) as $field) { + $value = (string) ($rule[$field] ?? ''); + // 商品名称关键词留空时导出成「-」,与页面一致(导回来会按空处理) + if ($field === 'goods' && trim($value) === '') { + $value = '-'; + } + $row[] = $this->csvText($value); + } + fputcsv($csv, $row); + } + fclose($csv); + }, '科目映射表_' . $this->store->platformNow()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** 导入模板(表头 + 两条示例,并且这一份可以直接改完再导回来) */ + public function template(): StreamedResponse + { + $samples = [ + ['得物', '平台服务费', '平台服务费', '0.06', '费用', '销售费用', '平台佣金', '其他货币资金', '', '支出基准'], + ['淘宝', '交易收入', '订单', '-', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'], + ]; + + return response()->streamDownload(function () use ($samples): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new RuntimeException('无法创建模板文件。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_values(AccountMappingStore::LABELS)); + foreach ($samples as $sample) { + fputcsv($csv, $sample); + } + fclose($csv); + }, '科目映射表_导入模板.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return array */ + private function payload(): array + { + $rules = $this->store->all(); + $validated = $this->validator->validate($rules); + + $rows = []; + foreach ($rules as $rule) { + $rows[] = $rule + ['issues' => $validated['issues'][(int) $rule['id']] ?? []]; + } + + return [ + 'rules' => $rows, + 'summary' => $validated['summary'], + 'options' => $this->store->options(), + 'events' => $this->store->events(20), + ]; + } + + /** @return array */ + private function payloadValues(Request $request): array + { + $input = (array) $request->input('values', $request->all()); + + return $this->store->normalize($input); + } + + private function userId(): ?int + { + return user_id() ? (int) user_id() : null; + } + + /** + * 原始操作记录 + 页面/CSV 直接可用的字段(变更内容与操作人只在服务端算一次)。 + * + * @return array> + */ + private function historyEvents(): array + { + $events = $this->store->events(self::HISTORY_LIMIT); + $names = $this->historyUserNames($events); + + $rows = []; + foreach ($events as $event) { + $before = is_array($event['before'] ?? null) ? $event['before'] : null; + $after = is_array($event['after'] ?? null) ? $event['after'] : null; + $rule = $before ?? $after ?? []; + $action = (string) ($event['action'] ?? ''); + + $rows[] = $event + [ + 'action_label' => self::HISTORY_ACTION_LABELS[$action] ?? $action, + 'platform' => trim((string) ($rule['platform'] ?? '')), + 'item' => trim((string) ($rule['item'] ?? '')), + 'memo' => trim((string) ($rule['memo'] ?? '')), + 'changes' => $this->historyChangeParts($event, $before, $after), + 'actor' => $this->historyActor($event, $names), + ]; + } + + return $rows; + } + + /** + * @param array> $events + * @return array + */ + private function historyUserNames(array $events): array + { + $ids = []; + foreach ($events as $event) { + $userId = (int) ($event['user_id'] ?? 0); + if ($userId > 0) { + $ids[$userId] = true; + } + } + + if ($ids === []) { + return []; + } + + return User::query()->whereIn('id', array_keys($ids))->pluck('name', 'id')->all(); + } + + /** + * @param array $event + * @param array $names + */ + private function historyActor(array $event, array $names): string + { + $userId = (int) ($event['user_id'] ?? 0); + + if ($userId <= 0) { + return '脚本 / 系统'; + } + + return $names[$userId] ?? ('用户 #' . $userId); + } + + /** + * 变更内容:修改给出「字段:改前 → 改后」,删除/新增给出科目对摘要,导入/重置给出条数。 + * + * @param array $event + * @param array|null $before + * @param array|null $after + * @return array + */ + private function historyChangeParts(array $event, ?array $before, ?array $after): array + { + $action = (string) ($event['action'] ?? ''); + + if ($action === 'update') { + $parts = []; + foreach (self::HISTORY_FIELD_LABELS as $field => $label) { + $old = trim((string) ($before[$field] ?? '')); + $new = trim((string) ($after[$field] ?? '')); + if ($old === $new) { + continue; + } + $parts[] = $label . ':' . ($old === '' ? '(空)' : $old) . ' → ' . ($new === '' ? '(空)' : $new); + } + + return $parts === [] ? ['未识别到字段变化'] : $parts; + } + + if ($action === 'delete') { + return ['删除前:' . $this->historyRuleSummary($before)]; + } + + if ($action === 'create') { + return ['新增:' . $this->historyRuleSummary($after)]; + } + + if ($action === 'import') { + $parts = []; + foreach (['created' => '新增', 'updated' => '更新', 'skipped' => '跳过'] as $key => $label) { + if (isset($event[$key])) { + $parts[] = $label . ' ' . (int) $event[$key]; + } + } + + return ['导入:' . ($parts === [] ? '—' : implode(' · ', $parts))]; + } + + if ($action === 'reset') { + return ['重置为初始规则' . (isset($event['total']) ? '(' . (int) $event['total'] . ' 条)' : '')]; + } + + return [$this->historyRuleSummary($before ?? $after)]; + } + + /** @param array|null $rule */ + private function historyRuleSummary(?array $rule): string + { + $rule ??= []; + $side = static function (string $acctKey, string $subKey) use ($rule): string { + $acct = trim((string) ($rule[$acctKey] ?? '')); + $sub = trim((string) ($rule[$subKey] ?? '')); + if ($acct === '' && $sub === '') { + return '—'; + } + if ($sub === '' || $sub === $acct) { + return $acct !== '' ? $acct : $sub; + } + + return $acct . ' / ' . $sub; + }; + + return '借 ' . $side('dAcct', 'dSub') . ' | 贷 ' . $side('cAcct', 'cSub') + . ' | ' . (trim((string) ($rule['category'] ?? '')) ?: '—') + . ' · ' . (trim((string) ($rule['basis'] ?? '')) ?: '—') + . ' · 票据 ' . (trim((string) ($rule['invoice'] ?? '')) ?: '—'); + } + + /** @param array $row */ + private function historyMatches(array $row, string $action, string $keyword): bool + { + if ($action !== '' && (string) ($row['action'] ?? '') !== $action) { + return false; + } + + if ($keyword === '') { + return true; + } + + $haystack = mb_strtolower(implode(' ', [ + $row['platform'] ?? '', + $row['item'] ?? '', + $row['memo'] ?? '', + $row['actor'] ?? '', + implode(' ', (array) ($row['changes'] ?? [])), + ])); + + return str_contains($haystack, mb_strtolower($keyword)); + } + + private function csvText(mixed $value): string + { + $value = (string) $value; + + return preg_match('/^[=+\-@\t\r]/u', $value) === 1 ? "\t" . $value : $value; + } +} diff --git a/app/Http/Controllers/Business/CourierAgreementSignatures.php b/app/Http/Controllers/Business/CourierAgreementSignatures.php index 6d65dbbe..60e336cf 100644 --- a/app/Http/Controllers/Business/CourierAgreementSignatures.php +++ b/app/Http/Controllers/Business/CourierAgreementSignatures.php @@ -7,6 +7,7 @@ use App\Models\Business\CourierQuoteSignature; use App\Models\Business\CourierQuoteVersion; use App\Models\Business\CourierSigningSubject; use App\Services\Esign\EsignClient; +use App\Support\CourierAgreementFileArchive; use App\Support\CourierAgreementSignatureService; use App\Support\CourierQuoteConfirmation; use App\Support\CourierQuoteSignatureService; @@ -18,6 +19,7 @@ use Illuminate\Routing\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; +use RuntimeException; use Symfony\Component\HttpFoundation\StreamedResponse; class CourierAgreementSignatures extends Controller @@ -28,6 +30,7 @@ class CourierAgreementSignatures extends Controller private readonly CourierAgreementSignatureService $service, private readonly CourierQuoteSignatureService $quoteSignatureService, private readonly CourierQuoteConfirmation $quoteConfirmation, + private readonly CourierAgreementFileArchive $agreementFileArchive, ) { } @@ -53,6 +56,13 @@ class CourierAgreementSignatures extends Controller ]); } + if (in_array($requestedType, ['account-proof', 'account-change'], true) + && ! $request->filled('counterparty_signer_type')) { + // Existing integrations omit this field and historically meant an + // enterprise signer, so keep that behavior as the compatibility default. + $request->merge(['counterparty_signer_type' => 'organization']); + } + $data = $request->validate($this->rules()); $type = $data['document_type']; if ($type === 'authorization' && count($data['authorization_items'] ?? []) === 0) { @@ -76,6 +86,20 @@ class CourierAgreementSignatures extends Controller $data['shared_courier_name'] = $sharedCouriers[0]; $data['shared_note'] = trim((string) ($data['shared_note'] ?? '')) ?: null; } + if (in_array($type, ['account-proof', 'account-change'], true)) { + $data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization'; + $data['operator_name'] = trim((string) ($data['operator_name'] ?? '')) ?: null; + + if ($data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) { + throw ValidationException::withMessages(['operator_name' => '企业签署主体必须填写 E 签宝实名认证姓名。']); + } + + if ($data['counterparty_signer_type'] === 'person') { + // A personal signer uses the same real name for the signer and + // the E-sign identity; the UI should not require it twice. + $data['operator_name'] = trim((string) $data['counterparty_organization_name']); + } + } $this->validateEsignAccount($data['esign_account'], 'esign_account'); if (! empty($data['secondary_esign_account'])) { $this->validateEsignAccount($data['secondary_esign_account'], 'secondary_esign_account'); @@ -88,7 +112,7 @@ class CourierAgreementSignatures extends Controller // signing_subject identifies our initiating company. The E-sign // organization must be the counterparty that receives this request. $data['organization_name'] = $this->counterpartyOrganizationName($data); - $data['operator_name'] = $data['operator_name'] ?? $data['courier_name']; + $data['operator_name'] = trim((string) ($data['operator_name'] ?? '')) ?: null; $data['operator_account'] = $data['esign_account']; $data['payload'] = $this->payload($data); @@ -205,15 +229,25 @@ class CourierAgreementSignatures extends Controller ->with('success', "{$signature->documentLabel()}已人工确认并归档。"); } - public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse + public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse|RedirectResponse { $this->ensureCanManage(); - [$path, $suffix] = match ($kind) { - 'source' => [$agreementSignature->source_pdf_path, '签署原文'], - 'signed' => [$agreementSignature->signed_pdf_path, '已签署协议'], - 'certificate' => [$agreementSignature->certificate_path, '签署完成证书'], - default => abort(404), - }; + try { + [$path, $suffix] = match ($kind) { + 'source' => [$this->agreementFileArchive->sourcePath($agreementSignature), '签署原文'], + 'signed' => [$agreementSignature->signed_pdf_path, '已签署协议'], + 'certificate' => [$agreementSignature->certificate_path, '签署完成证书'], + default => abort(404), + }; + } catch (RuntimeException $exception) { + return redirect() + ->route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'agreement-signing', + 'agreement_view' => 'tasks', + ]) + ->with('error', $exception->getMessage()); + } abort_if(blank($path) || ! \Storage::disk('uploads')->exists($path), 404, '归档文件不存在。'); @@ -265,10 +299,13 @@ class CourierAgreementSignatures extends Controller 'quote_version_id' => ['required_if:document_type,quote-confirmation', 'nullable', 'integer', 'min:1'], 'signing_subject' => ['required', 'string', 'min:2', 'max:255'], 'company_full_name' => ['required', 'string', 'min:2', 'max:255'], + 'signature_date' => ['required', 'date'], 'signing_deadline' => $date, 'esign_account' => ['required', 'string', 'max:255'], 'secondary_esign_account' => ['required_if:document_type,entity-change,cooperation-contract,authorization', 'nullable', 'string', 'max:255'], - 'operator_name' => ['nullable', 'string', 'max:100'], + 'operator_name' => ['nullable', 'string', 'min:2', 'max:100'], + 'counterparty_organization_name' => ['required_if:document_type,account-proof,account-change', 'nullable', 'string', 'min:2', 'max:255'], + 'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change', 'nullable', 'in:organization,person'], 'archive_mode' => ['required', 'in:auto,manual'], 'account_proof_effective_date' => ['required_if:document_type,account-proof', 'date'], 'account_proof_account_name' => ['required_if:document_type,account-proof', 'string', 'max:255'], @@ -286,12 +323,10 @@ class CourierAgreementSignatures extends Controller 'entity_change_date' => ['required_if:document_type,entity-change', 'date'], 'changed_company_name' => ['required_if:document_type,entity-change', 'string', 'max:255'], 'changed_company_start_date' => ['required_if:document_type,entity-change', 'date'], - 'entity_proof_date' => ['required_if:document_type,entity-change', 'date'], 'contract_partner_name' => ['required_if:document_type,shared-contract', 'string', 'max:255'], 'shared_courier_names' => ['nullable', 'array', 'min:1'], 'shared_courier_names.*' => ['required', 'string', 'max:255'], 'shared_courier_name' => ['nullable', 'string', 'max:255'], - 'shared_proof_date' => ['nullable', 'date'], 'shared_note' => ['nullable', 'string', 'max:2000'], 'cooperation_party_a_name' => ['required_if:document_type,cooperation-contract', 'string', 'max:255'], 'cooperation_party_a_phone' => ['required_if:document_type,cooperation-contract', 'string', 'max:64'], @@ -329,7 +364,7 @@ class CourierAgreementSignatures extends Controller ->findOrFail((int) $data['quote_version_id']); $this->ensureQuoteVersionMatchesCourier($version, $data['courier_name']); - $signature = $this->quoteSignatureService->prepareVersion($version, user_id()); + $signature = $this->quoteSignatureService->prepareVersion($version, user_id(), $data['signature_date']); $account = trim((string) $data['esign_account']); $signature = $this->quoteSignatureService->send($signature, [ 'organization_name' => $version->carrier_name, @@ -357,8 +392,7 @@ class CourierAgreementSignatures extends Controller private function counterpartyOrganizationName(array $data): string { return match ($data['document_type']) { - 'account-proof' => trim((string) $data['account_proof_account_name']), - 'account-change' => trim((string) $data['new_account_name']), + 'account-proof', 'account-change' => trim((string) $data['counterparty_organization_name']), 'shared-contract' => trim((string) (($data['shared_courier_names'][0] ?? null) ?: ($data['shared_courier_name'] ?? $data['courier_name']))), 'entity-change' => trim((string) ($data['former_company_name'] ?? $data['courier_name'])), 'authorization' => trim((string) ($data['principal_name'] ?? $data['courier_name'])), diff --git a/app/Http/Controllers/Business/CourierPayableSummaries.php b/app/Http/Controllers/Business/CourierPayableSummaries.php new file mode 100644 index 00000000..e0bd8e86 --- /dev/null +++ b/app/Http/Controllers/Business/CourierPayableSummaries.php @@ -0,0 +1,170 @@ + [ + 'path' => 'templates/courier-payables/freight-difference-import-template.xlsx', + 'ascii_name' => 'freight_difference_import_template.xlsx', + 'download_name' => '运费差导入模板.xlsx', + ], + 'other-surcharge-summary' => [ + 'path' => 'templates/courier-payables/other-surcharge-import-template.xlsx', + 'ascii_name' => 'other_surcharge_import_template.xlsx', + 'download_name' => '其他附加费导入模板.xlsx', + ], + 'return-fee' => [ + 'path' => 'templates/courier-payables/return-fee-import-template.xlsx', + 'ascii_name' => 'return_fee_import_template.xlsx', + 'download_name' => '退件费导入模板.xlsx', + ], + ]; + + public function __construct( + private readonly CourierPayableSummaryStore $store, + private readonly CourierPayableSummaryFilter $filter, + ) { + $this->middleware('auth'); + $this->middleware('company.identify'); + } + + public function import(Request $request, string $summaryPage): RedirectResponse + { + $this->authorizePage($summaryPage); + $this->store->title($summaryPage); + $request->validate([ + 'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:10240'], + ]); + + try { + $result = $this->store->import( + $request->file('import'), + (int) (company_id() ?: 1), + $summaryPage, + user_id() ? (int) user_id() : null, + ); + } catch (RuntimeException $exception) { + report($exception); + + return $this->redirectToPage($summaryPage)->with('error', '汇总数据保存失败,请稍后重试。'); + } + + return $this->redirectToPage($summaryPage)->with( + 'success', + "导入完成:{$result['rows']} 条数据,{$result['columns']} 个字段。", + ); + } + + public function template(string $summaryPage): BinaryFileResponse + { + $this->authorizePage($summaryPage); + $template = self::IMPORT_TEMPLATES[$summaryPage] ?? null; + abort_unless(is_array($template), 404); + + $path = resource_path($template['path']); + abort_unless(is_file($path), 404); + + $response = response()->download($path, $template['ascii_name'], [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + + return $response->setContentDisposition( + 'attachment', + $template['download_name'], + $template['ascii_name'], + ); + } + + public function export(Request $request, string $summaryPage): StreamedResponse|RedirectResponse + { + $this->authorizePage($summaryPage); + $title = $this->store->title($summaryPage); + + try { + $snapshot = $this->store->snapshot((int) (company_id() ?: 1), $summaryPage); + } catch (RuntimeException) { + return $this->redirectToPage($summaryPage)->with('error', '汇总数据暂时无法读取,请重新导入后再试。'); + } + + if ($snapshot === null) { + return $this->redirectToPage($summaryPage)->with('error', '当前没有可导出的汇总数据。'); + } + + $filters = $this->filter->fromRequest($request); + $headers = $snapshot['headers']; + $rows = $this->filter->apply(collect($snapshot['rows']), $headers, $filters)->values(); + $dateColumn = $this->filter->dateColumnIndex($headers); + + return response()->streamDownload(function () use ($headers, $rows, $dateColumn): void { + $csv = fopen('php://output', 'w'); + + if ($csv === false) { + throw new RuntimeException('无法创建汇总数据导出流。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_map([$this, 'csvText'], $headers)); + + foreach ($rows as $row) { + fputcsv($csv, array_map( + fn (mixed $value, int $column): string => $this->csvText($value, $column === $dateColumn), + $row, + array_keys($row), + )); + } + + fclose($csv); + }, $title . '_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + private function redirectToPage(string $summaryPage): RedirectResponse + { + return redirect()->route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => $summaryPage, + ]); + } + + private function authorizePage(string $summaryPage): void + { + $section = collect(SidebarPermissions::navigationFor(user())) + ->firstWhere('slug', 'courier-payables'); + $pages = collect($section['pages'] ?? [])->flatMap(static fn (array $page): array => [ + $page, + ...($page['children'] ?? []), + ]); + + abort_unless($pages->contains('slug', $summaryPage), 403, '当前账号没有该页面权限。'); + } + + private function csvText(mixed $value, bool $preserveYearMonth = false): string + { + $value = (string) $value; + + if ($preserveYearMonth && preg_match('/^\d{4}-(?:0[1-9]|1[0-2])$/', $value) === 1) { + return '="' . $value . '"'; + } + + if (preg_match('/^[+-]?(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)%?$/u', $value) === 1) { + return $value; + } + + return preg_match('/^[=+\-@\t\r]/u', $value) === 1 ? "\t" . $value : $value; + } +} diff --git a/app/Http/Controllers/Business/CourierQuoteSignatures.php b/app/Http/Controllers/Business/CourierQuoteSignatures.php index 98fb9a7d..bc9c31dc 100644 --- a/app/Http/Controllers/Business/CourierQuoteSignatures.php +++ b/app/Http/Controllers/Business/CourierQuoteSignatures.php @@ -19,11 +19,14 @@ class CourierQuoteSignatures extends Controller { } - public function prepare(CourierQuoteVersion $quoteVersion): RedirectResponse + public function prepare(Request $request, CourierQuoteVersion $quoteVersion): RedirectResponse { $this->ensureCanManage(); abort_unless($quoteVersion->status === 'approved', 422, '只有已审核报价版本可以生成签署文件。'); - $signature = $this->service->prepareVersion($quoteVersion, user_id()); + $data = $request->validate([ + 'signature_date' => ['required', 'date'], + ]); + $signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date']); return redirect()->route('business.courier-quote-changes.show', $quoteVersion->source_change_id) ->with('success', "{$quoteVersion->version_code} 的签署 PDF 已生成,文件校验值已固定。") @@ -40,9 +43,15 @@ class CourierQuoteSignatures extends Controller 'operator_name' => ['required', 'string', 'min:2', 'max:100'], 'operator_account' => ['required', 'string', 'max:255'], 'notice_type' => ['required', 'in:1,2'], + 'signature_date' => ['required', 'date'], 'expires_at' => ['required', 'date', 'after:now', 'before_or_equal:' . now()->addDays(90)->toDateTimeString()], ]); $this->validateAccountForNotice($data['operator_account'], $data['notice_type']); + $quoteSignature = $this->service->prepareVersion( + $quoteSignature->version, + user_id(), + $data['signature_date'], + ); $signature = $this->service->send($quoteSignature, $data, user_id()); $environment = $signature->environment === 'sandbox' ? '沙箱' : '正式环境'; diff --git a/app/Http/Controllers/Business/CourierSurchargeQuotes.php b/app/Http/Controllers/Business/CourierSurchargeQuotes.php index 43893dc5..3364bf36 100644 --- a/app/Http/Controllers/Business/CourierSurchargeQuotes.php +++ b/app/Http/Controllers/Business/CourierSurchargeQuotes.php @@ -3,15 +3,20 @@ namespace App\Http\Controllers\Business; use App\Business\CourierSurchargeQuoteRepository; +use App\Business\CourierSurchargeQuoteWorkbookImporter; use App\Models\Business\CourierSurchargeQuote; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Controller; +use Illuminate\Support\Str; +use Symfony\Component\HttpFoundation\StreamedResponse; class CourierSurchargeQuotes extends Controller { - public function __construct(private readonly CourierSurchargeQuoteRepository $quotes) - { + public function __construct( + private readonly CourierSurchargeQuoteRepository $quotes, + private readonly CourierSurchargeQuoteWorkbookImporter $workbookImporter, + ) { $this->middleware('auth'); $this->middleware('company.identify'); $this->middleware('business.page:courier-payables,courier-surcharge'); @@ -49,6 +54,79 @@ class CourierSurchargeQuotes extends Controller return $this->redirect()->with('success', '报价规则状态已更新。'); } + public function importTemplate(): StreamedResponse + { + abort_unless($this->quotes->ready(), 503, '附加费报价数据表尚未完成迁移,请联系管理员。'); + + return $this->workbookImporter->template(); + } + + public function importPreview(Request $request): RedirectResponse + { + abort_unless($this->quotes->ready(), 503, '附加费报价数据表尚未完成迁移,请联系管理员。'); + + $file = $request->validate([ + 'import_file' => ['required', 'file', 'max:10240'], + ])['import_file']; + $preview = $this->workbookImporter->preview($file); + $token = Str::random(48); + $previews = collect((array) $request->session()->get('courier_surcharge_import_previews', [])) + ->filter(fn (mixed $item): bool => is_array($item) && (int) ($item['expires_at'] ?? 0) >= now()->timestamp) + ->take(-2) + ->all(); + $previews[$token] = [ + 'company_id' => (int) company_id(), + 'user_id' => (int) user_id(), + 'expires_at' => now()->addMinutes(20)->timestamp, + 'rows' => $preview['rows'], + ]; + $request->session()->put('courier_surcharge_import_previews', $previews); + + return $this->redirect()->with('courierSurchargeImportPreview', $preview + ['token' => $token]); + } + + public function importCommit(Request $request): RedirectResponse + { + abort_unless($this->quotes->ready(), 503, '附加费报价数据表尚未完成迁移,请联系管理员。'); + + $validated = $request->validate([ + 'preview_token' => ['required', 'string', 'size:48'], + 'duplicate_policy' => ['required', 'in:' . CourierSurchargeQuoteWorkbookImporter::DUPLICATE_SKIP . ',' . CourierSurchargeQuoteWorkbookImporter::DUPLICATE_UPDATE], + ]); + $previews = (array) $request->session()->get('courier_surcharge_import_previews', []); + $payload = $previews[$validated['preview_token']] ?? null; + + if (! is_array($payload) + || (int) ($payload['company_id'] ?? 0) !== (int) company_id() + || (int) ($payload['user_id'] ?? 0) !== (int) user_id() + || (int) ($payload['expires_at'] ?? 0) < now()->timestamp) { + unset($previews[$validated['preview_token']]); + $request->session()->put('courier_surcharge_import_previews', $previews); + + return $this->redirect()->withErrors([ + 'import' => '导入预览已失效或不属于当前账号,请重新选择文件预览。', + ]); + } + + $counts = $this->workbookImporter->commit( + (array) ($payload['rows'] ?? []), + $validated['duplicate_policy'], + (int) user_id(), + ); + unset($previews[$validated['preview_token']]); + $request->session()->put('courier_surcharge_import_previews', $previews); + + return $this->redirect()->with( + 'success', + sprintf( + '附加费报价导入完成:新增 %d 条,更新 %d 条,跳过 %d 条。', + $counts['created'], + $counts['updated'], + $counts['skipped'], + ), + ); + } + /** @return array */ private function validated(Request $request): array { @@ -56,6 +134,7 @@ class CourierSurchargeQuotes extends Controller 'courier' => ['required', 'string', 'max:191'], 'scope' => ['required', 'in:' . implode(',', CourierSurchargeQuoteRepository::SCOPES)], 'reconciler' => ['required', 'string', 'max:100'], + 'supplier' => ['nullable', 'string', 'max:191'], 'types' => ['required', 'array', 'min:1', 'max:50'], 'types.*' => ['string', 'in:' . implode(',', $this->quotes->activeTypeNames())], 'mode' => ['required', 'in:' . implode(',', CourierSurchargeQuoteRepository::MODES)], @@ -67,6 +146,7 @@ class CourierSurchargeQuotes extends Controller $data['courier'] = trim($data['courier']); $data['reconciler'] = trim($data['reconciler']); + $data['supplier'] = trim((string) ($data['supplier'] ?? '')) ?: null; $data['types'] = array_values(array_unique($data['types'])); return $data; diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index e06d3976..d8eed3ea 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -3,18 +3,26 @@ namespace App\Http\Controllers\Business; use App\Business\BusinessTableImporter; +use App\Business\InventoryWarehouseNameMappingWorkbookImporter; +use App\Business\InventoryWarehouseShortNames; +use App\Business\CourierPayableSummaryFilter; +use App\Business\CourierPayableSummaryStore; use App\Business\FundForecastTemplate; use App\Business\TableRegistry; use App\Business\UpstreamBusinessInformation; use App\Business\StoreReceivingAccountTemplate; use App\Business\StoreReceivingAccountWorkbookImporter; +use App\Business\StoreViolationWorkbookImporter; +use App\Business\WithdrawalManagementReport; +use App\Jobs\Common\InventoryReportExport; use App\Models\Banking\MarketingAccountBill; use App\Models\Business\CourierAgreementSignature; use App\Models\Business\CourierQuoteSignature; use App\Models\Business\CourierQuoteVersion; use App\Models\Business\CourierSigningSubject; use App\Models\Business\InstallationDetail; -use App\Models\Business\StoreReceivingAccount; +use App\Models\Business\InventoryWarehouseNameMapping; +use App\Business\CourierSurchargeAuditLogRepository; use App\Business\CourierSurchargeQuoteRepository; use App\Business\CourierSurchargeTypeRepository; use App\Models\StoreReceivables\StoreZhongcaiReconciliation; @@ -22,11 +30,18 @@ use App\Utilities\SidebarPermissions; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Pagination\LengthAwarePaginator; +use Illuminate\Support\Facades\DB; use Illuminate\Pagination\Paginator; use Illuminate\Support\Collection; use Illuminate\Support\Carbon; +use Illuminate\Support\Str; use Illuminate\Database\QueryException; use Modules\EcommerceFinance\Exceptions\UpstreamSnapshotPendingException; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Style\Alignment; +use PhpOffice\PhpSpreadsheet\Style\Fill; +use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Modules\EcommerceFinance\Repositories\AlibabaAccountBalanceRepository; use Modules\EcommerceFinance\Repositories\AlibabaBillRepository; use Modules\EcommerceFinance\View\BillOffsetPageData; @@ -37,9 +52,9 @@ use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorReposi use Modules\EcommerceFinance\Repositories\EdgeBandingRepository; use Modules\EcommerceFinance\Repositories\InventoryRepository; use Modules\EcommerceFinance\Repositories\InstallationDetailMirrorRepository; +use Modules\EcommerceFinance\Repositories\InternalFlowReportRepository; use Modules\EcommerceFinance\Repositories\JdPromotionAccountBalanceRepository; use Modules\EcommerceFinance\Repositories\JdWalletBillRepository; -use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository; use Modules\EcommerceFinance\Repositories\NonJingxiRefundMirrorRepository; use Modules\EcommerceFinance\Repositories\PinduoduoSpreadBillRepository; use Modules\EcommerceFinance\Repositories\ProductCatalogMirrorRepository; @@ -48,34 +63,38 @@ use Modules\EcommerceFinance\Repositories\RawBoardPayablesRepository; use Modules\EcommerceFinance\Repositories\DingPayableWorkflowMirrorRepository; use Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository; use Modules\EcommerceFinance\Repositories\SmallPaymentWorkOrderMirrorRepository; +use Modules\EcommerceFinance\Repositories\StoreViolationRecordRepository; use Modules\EcommerceFinance\Repositories\SupplierPayableReportRepository; use Modules\EcommerceFinance\Repositories\TmallTaobaoSpreadBillRepository; +use Modules\EcommerceFinance\Services\AccountMappingStore; +use Modules\EcommerceFinance\Services\AccountMappingValidator; +use Modules\EcommerceFinance\Services\StoreReportInitialPeriods; +use Modules\EcommerceFinance\Services\TaxForecastLogic; use Modules\EcommerceFinance\Services\UpstreamQueryCacheFactory; +use Modules\EcommerceFinance\Services\SupplierPayableMaintenanceRegistry; +use Modules\EcommerceFinance\Services\PayablesFinalRegistry; +use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; use Modules\EcommerceFinance\View\PlatformPromotionAccountPageData; use Modules\EcommerceFinance\View\OrderDataPageData; +use RuntimeException; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException; use Throwable; class Pages extends Controller { - /** @var list 快递签署页当前可选的合作方名称 */ - private const AGREEMENT_COURIER_NAMES = [ - '新北中通', - '新北中通其他', - '新德邦快递', - '睢宁中通', - '武进极兔', - '沭阳德邦', - '常州圆通其他', - ]; - private const EDGE_BANDING_SOURCE = 'jiansun'; private const INVENTORY_SOURCE = 'jiansun'; private const RAW_BOARD_SOURCE = 'jiansun'; + /** + * 「终版」目录只提供空的表结构,数据由各自按表导入,不解析其他目录的既有页面内容。 + */ + private const PAYABLES_FINAL_SECTIONS = ['supplier-payables-final', 'courier-payables-final']; + public function __construct( private readonly EdgeBandingRepository $edgeBanding, private readonly InventoryRepository $inventory, @@ -91,10 +110,13 @@ class Pages extends Controller private readonly DingPayableWorkflowMirrorRepository $dingPayableWorkflows, private readonly DingOnlineDaifaPriceMirrorRepository $onlineDaifaPrices, private readonly SupplierPayableReportRepository $supplierPayableReports, + private readonly SupplierPayableOverrideStore $supplierPayableOverrides, + private readonly SupplierPayableMaintenanceRegistry $supplierPayableMaintenance, private readonly UpstreamQueryCacheFactory $upstreamCaches, private readonly CourierSurchargeQuoteRepository $courierSurchargeQuotes, private readonly CourierSurchargeTypeRepository $courierSurchargeTypes, - private readonly JushuitanShopBalanceRepository $jushuitanShopBalances, + private readonly CourierSurchargeAuditLogRepository $courierSurchargeAudits, + private readonly WithdrawalManagementReport $withdrawalManagementReport, private readonly ShippingOrderRepository $shippingOrders, ) { $this->middleware('auth'); @@ -184,7 +206,7 @@ class Pages extends Controller } if ($page === null) { - if ($section === 'courier-payables') { + if ($section === 'courier-payables' || in_array($section, self::PAYABLES_FINAL_SECTIONS, true)) { return view('business.pages.show', $this->viewData($sectionConfig)); } @@ -236,7 +258,7 @@ class Pages extends Controller $pageConfig, $tabs, null, - $this->resolveContent($page, null), + $this->resolveContentForSection($section, $page, null), )); } @@ -253,7 +275,7 @@ class Pages extends Controller $pageConfig, $tabs, $activeTab, - $this->resolveContent($page, $tab), + $this->resolveContentForSection($section, $page, $tab), )); } @@ -269,6 +291,97 @@ class Pages extends Controller return response()->json(['data' => $payload['data'], 'has_more' => $payload['has_more'] ?? false]); } + /** + * 账单明细导出:按页面同一套筛选条件流式导出 CSV(全部筛选结果)。 + */ + public function exportBillingDetails(Request $request): StreamedResponse + { + $section = collect(SidebarPermissions::navigationFor(user()))->firstWhere('slug', 'financial-operations'); + abort_unless($section && collect($section['pages'] ?? [])->contains('slug', 'billing-details'), 403, '当前账号没有该页面权限。'); + + $pageData = app(\Modules\EcommerceFinance\View\BillingDetailsPageData::class); + $filters = $pageData->exportFilters($request->all()); + $columns = $pageData->exportColumns(array_values(array_filter( + (array) $request->get('columns', []), + static fn ($key): bool => is_string($key) && $key !== '', + ))); + + $cell = static function (array $row, string $key): string { + $income = (float) ($row['income'] ?? 0); + $expense = (float) ($row['expense'] ?? 0); + + return match ($key) { + 'amount' => number_format($income - $expense, 2, '.', ''), + 'income' => $income > 0 ? number_format($income, 2, '.', '') : '', + 'expense' => $expense > 0 ? number_format($expense, 2, '.', '') : '', + default => trim((string) ($row[$key] ?? '')), + }; + }; + $csvText = fn (mixed $value): string => $this->csvText($value); + + // 导出进度:前端带 token 发起下载,导出过程中把已导出行数写进缓存,前端轮询显示进度 + $token = trim((string) $request->get('token', '')); + $token = preg_match('/^[A-Za-z0-9_-]{8,64}$/', $token) === 1 ? $token : ''; + $progressKey = $token === '' ? null : self::billingDetailsProgressKey($token); + $total = $pageData->exportTotal($filters); + $putProgress = static function (array $state) use ($progressKey): void { + if ($progressKey !== null) { + \Illuminate\Support\Facades\Cache::put($progressKey, $state, now()->addMinutes(30)); + } + }; + $putProgress(['status' => 'running', 'rows' => 0, 'total' => $total]); + + return response()->streamDownload(function () use ($pageData, $filters, $columns, $cell, $csvText, $putProgress, $total): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建账单明细导出流。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_map(static fn (array $definition): string => $definition[0], array_values($columns))); + + $written = 0; + $putProgress(['status' => 'running', 'rows' => 0, 'total' => $total]); + foreach ($pageData->exportRows($filters, $columns) as $row) { + $line = []; + foreach (array_keys($columns) as $key) { + $value = $cell($row, (string) $key); + // 数值列不做公式转义,否则负数会被写成 '-0.47 + $line[] = ($columns[$key][1] ?? '') === 'num' ? $value : $csvText($value); + } + fputcsv($csv, $line); + $written++; + if ($written % 5000 === 0) { + $putProgress(['status' => 'running', 'rows' => $written, 'total' => $total]); + } + } + + fclose($csv); + $putProgress(['status' => 'done', 'rows' => $written, 'total' => max($total, $written)]); + }, '账单明细_' . $filters['start'] . '_' . $filters['end'] . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** 账单明细导出进度(前端每秒轮询一次) */ + public function billingDetailsExportProgress(Request $request): \Illuminate\Http\JsonResponse + { + $token = trim((string) $request->get('token', '')); + abort_unless(preg_match('/^[A-Za-z0-9_-]{8,64}$/', $token) === 1, 400, '导出标识无效。'); + + $state = \Illuminate\Support\Facades\Cache::get(self::billingDetailsProgressKey($token)); + + return response()->json($state ?? ['status' => 'unknown', 'rows' => 0, 'total' => 0], 200, [ + 'Cache-Control' => 'private, no-store', + ]); + } + + private static function billingDetailsProgressKey(string $token): string + { + return 'billing-details-export:' . (int) user()->id . ':' . $token; + } + public function exportInstallationDetails(Request $request): StreamedResponse { $section = collect(SidebarPermissions::navigationFor(user()))->firstWhere('slug', 'financial-operations'); @@ -368,6 +481,431 @@ class Pages extends Controller ]); } + /** + * 商品月加权平均单价:读取已计算的月份数据,默认最新月份。 + */ + protected function monthlyWeightedAveragePriceRows(): LengthAwarePaginator + { + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $months = DB::connection($connection)->table('product_monthly_weighted_average_states') + ->where('status', 'computed') + ->orderByDesc('report_month') + ->pluck('report_month') + ->map(static fn ($month): string => substr((string) $month, 0, 10)) + ->all(); + + $requested = substr(trim((string) request('month', '')), 0, 10); + if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1) { + // 筛选栏的月份选择器提交 Y-m,这里补成当月 1 号再匹配。 + $requested .= '-01'; + } + // 明确指定月份时严格按该月份取数(该月没算出来就显示空表),避免筛选条件与数据不一致。 + $month = $requested !== '' ? $requested : ($months[0] ?? null); + + $limit = min(max((int) setting('default.list_limit', 25), 1), 50); + $page = max((int) request('page', 1), 1); + $empty = new LengthAwarePaginator([], 0, $limit, $page, [ + 'path' => request()->url(), + 'query' => request()->query(), + ]); + if ($month === null) { + return $empty; + } + + $query = DB::connection($connection)->table('product_monthly_weighted_average_rows') + ->where('report_month', $month); + $productCode = trim((string) request('product_code', '')); + if ($productCode !== '') { + // 与进销存总表一致:商品编码按精确查询。 + $query->where('product_code', $productCode); + } + $provider = trim((string) request('warehouse_provider', '')); + if ($provider !== '') { + $query->where('warehouse_short_name', 'like', '%' . addcslashes($provider, '%_\\') . '%'); + } + $category = trim((string) request('category', '')); + if ($category !== '') { + $query->where('product_name', 'like', '%' . addcslashes($category, '%_\\') . '%'); + } + $total = (clone $query)->count(); + if ($total === 0) { + return $empty; + } + + $items = $query + ->orderBy('warehouse_short_name') + ->orderBy('product_code') + ->forPage($page, $limit) + ->get([ + DB::raw('report_month as month'), + 'barcode_warehouse', + 'warehouse_short_name', + 'supplier', + 'product_code', + 'product_name', + 'opening_quantity', + 'opening_unit_price', + 'opening_original_amount', + DB::raw('adjusted_unit_price as opening_adjusted_price'), + 'opening_amount', + 'purchase_quantity', + 'purchase_unit_price', + 'purchase_amount', + 'weighted_average_unit_price', + 'pricing_status', + ]); + + return new LengthAwarePaginator($items, $total, $limit, $page, [ + 'path' => request()->url(), + 'query' => request()->query(), + ]); + } + + /** + * 业绩明细 → 店铺收款匹配订单明细:以店铺收款账户账单为基数, + * 按「店铺 + 订单号」匹配订单侧商品金额;一行 = 一个店铺的一个订单。 + * + * @return array{0:LengthAwarePaginator,1:?array} + */ + protected function storeReceiptOrderMatchRows(): array + { + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $months = DB::connection($connection)->table('store_receipt_order_match_rows') + ->select('report_month') + ->distinct() + ->orderByDesc('report_month') + ->pluck('report_month') + ->map(static fn ($month): string => substr((string) $month, 0, 10)) + ->all(); + + $requested = substr(trim((string) request('month', '')), 0, 10); + if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1) { + // 筛选栏的月份选择器提交 Y-m,这里补成当月 1 号再匹配。 + $requested .= '-01'; + } + // 明确指定月份时严格按该月份取数(该月没同步就显示空表)。 + $month = $requested !== '' ? $requested : ($months[0] ?? null); + + $limit = min(max((int) setting('default.list_limit', 25), 1), 50); + $page = max((int) request('page', 1), 1); + $empty = new LengthAwarePaginator([], 0, $limit, $page, [ + 'path' => request()->url(), + 'query' => request()->query(), + ]); + if ($month === null) { + return [$empty, null]; + } + + $applyFilters = static function ($query): void { + $store = trim((string) request('store_name', '')); + if ($store !== '') { + $query->where('store_name', 'like', '%' . addcslashes($store, '%_\\') . '%'); + } + $orderNo = trim((string) request('online_order_no', '')); + if ($orderNo !== '') { + $query->where('online_order_no', 'like', '%' . addcslashes($orderNo, '%_\\') . '%'); + } + $status = trim((string) request('match_status', '')); + if ($status !== '') { + // 基础状态(已匹配/未匹配)按状态列过滤,其余按异常标注过滤。 + if (in_array($status, ['已匹配', '未匹配'], true)) { + $query->where('match_status', $status); + } else { + $query->where('remark', $status); + } + } + }; + + // 镜像表本身就是「一个店铺 + 一个订单号 + 一个商品金额」的行口径,直接统计即可。 + $base = static fn () => DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->table('store_receipt_order_match_rows') + ->where('report_month', $month); + + $countQuery = $base(); + $applyFilters($countQuery); + $total = (int) $countQuery->count(); + + $aggQuery = $base(); + $applyFilters($aggQuery); + $agg = $aggQuery->selectRaw(" + SUM(payment_count) as payments, + SUM(income_amount) as income_total, + SUM(product_amount) as goods_total, + SUM(difference) as difference_total, + SUM(CASE WHEN payment_count > 1 THEN 1 ELSE 0 END) as multi_pay, + SUM(CASE WHEN match_status = '已匹配' THEN 1 ELSE 0 END) as matched, + SUM(CASE WHEN match_status = '未匹配' THEN 1 ELSE 0 END) as unmatched + ")->first(); + + $stats = [ + 'month' => $month, + 'rows' => $total, + 'payments' => (int) ($agg->payments ?? 0), + 'orders_matched' => (int) ($agg->matched ?? 0), + 'orders_unmatched' => (int) ($agg->unmatched ?? 0), + 'orders_multi_pay' => (int) ($agg->multi_pay ?? 0), + 'income_total' => round((float) ($agg->income_total ?? 0), 2), + 'goods_total' => round((float) ($agg->goods_total ?? 0), 2), + 'difference_total' => round((float) ($agg->difference_total ?? 0), 2), + ]; + + if ($total === 0) { + return [$empty, $stats]; + } + + $itemsQuery = $base(); + $applyFilters($itemsQuery); + $items = $itemsQuery + ->orderBy('occurred_date') + ->orderBy('store_name') + ->orderBy('online_order_no') + ->forPage($page, $limit) + ->get(); + + return [new LengthAwarePaginator($items, $total, $limit, $page, [ + 'path' => request()->url(), + 'query' => request()->query(), + ]), $stats]; + } + + /** + * 业绩明细 → 店铺收款匹配订单明细导出:按当前月份与筛选条件导出 CSV,列序跟随页面显示列。 + */ + public function exportPerformanceDetails(Request $request): StreamedResponse + { + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + // [列名, 表头, 数值格式] —— 金额统一两位小数,数量取整,与页面展示一致。 + $map = [ + 'occurred_date' => ['occurred_date', '发生时间', 'text'], + 'store_name' => ['store_name', '店铺名称', 'text'], + 'online_order_no' => ['online_order_no', '线上单号', 'text'], + 'income_amount' => ['income_amount', '收入金额', 'money'], + 'product_amount' => ['product_amount', '商品金额', 'money'], + 'difference' => ['difference', '差额', 'money'], + 'match_status' => ['match_status', '匹配状态', 'text'], + 'remark' => ['remark', '异常标注', 'text'], + ]; + + $months = DB::connection($connection)->table('store_receipt_order_match_rows') + ->select('report_month')->distinct()->orderByDesc('report_month') + ->pluck('report_month') + ->map(static fn ($month): string => substr((string) $month, 0, 10))->all(); + $requested = substr(trim((string) $request->query('month', '')), 0, 10); + if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1) { + $requested .= '-01'; + } + $month = $requested !== '' ? $requested : ($months[0] ?? null); + + $query = DB::connection($connection)->table('store_receipt_order_match_rows') + ->when($month !== null, static fn ($builder) => $builder->where('report_month', $month)); + + $store = trim((string) $request->query('store_name', '')); + if ($store !== '') { + $query->where('store_name', 'like', '%' . addcslashes($store, '%_\\') . '%'); + } + $orderNo = trim((string) $request->query('online_order_no', '')); + if ($orderNo !== '') { + $query->where('online_order_no', 'like', '%' . addcslashes($orderNo, '%_\\') . '%'); + } + $status = trim((string) $request->query('match_status', '')); + if ($status !== '') { + if (in_array($status, ['已匹配', '未匹配'], true)) { + $query->where('match_status', $status); + } else { + $query->where('remark', $status); + } + } + + $selected = array_values(array_intersect( + array_filter(explode(',', (string) $request->query('columns', ''))), + array_keys($map), + )); + if ($selected === []) { + $selected = array_keys($map); + } + + $size = min(max((int) setting('default.list_limit', 25), 1), 50); + if ($request->query('scope') === 'page') { + $query->forPage(max((int) $request->query('page', 1), 1), $size); + } + + $filename = '店铺收款匹配订单明细_' . ($month ?? 'all') . '.csv'; + + return response()->streamDownload(function () use ($query, $selected, $map): void { + $out = fopen('php://output', 'w'); + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, array_map(static fn (string $key): string => $map[$key][1], $selected)); + $query->orderBy('occurred_date')->orderBy('store_name')->orderBy('online_order_no') + ->chunk(1000, function ($rows) use ($out, $selected, $map): void { + foreach ($rows as $row) { + $line = []; + foreach ($selected as $key) { + [$column, , $format] = $map[$key]; + $value = $row->{$map[$key][0]} ?? ''; + if ($format === 'money') { + $line[] = $value === null || $value === '' ? '' : number_format((float) $value, 2, '.', ''); + + continue; + } + if ($format === 'int') { + $line[] = $value === null || $value === '' ? '' : (string) (int) $value; + + continue; + } + $line[] = is_string($value) ? $value : (string) $value; + } + fputcsv($out, $line); + } + }); + fclose($out); + }, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']); + } + + /** + * 商品月加权平均单价导出:按当前月份与筛选条件导出 CSV,列序跟随页面显示列。 + */ + public function exportMonthlyWeightedAveragePrice(Request $request): StreamedResponse + { + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $map = [ + 'month' => ['report_month', '月份'], + 'barcode_warehouse' => ['barcode_warehouse', '条码+仓库'], + 'warehouse_short_name' => ['warehouse_short_name', '仓库简称'], + 'supplier' => ['supplier', '供应商'], + 'product_code' => ['product_code', '商品编码'], + 'product_name' => ['product_name', '商品名称'], + 'opening_quantity' => ['opening_quantity', '原始数量'], + 'opening_unit_price' => ['opening_unit_price', '原始价格'], + 'opening_original_amount' => ['opening_original_amount', '原始期初金额'], + 'opening_adjusted_price' => ['adjusted_unit_price', '更改价格'], + 'opening_amount' => ['opening_amount', '期初金额'], + 'purchase_quantity' => ['purchase_quantity', '采购数量'], + 'purchase_unit_price' => ['purchase_unit_price', '采购单价'], + 'purchase_amount' => ['purchase_amount', '入库金额'], + 'weighted_average_unit_price' => ['weighted_average_unit_price', '加权平均单价'], + 'pricing_status' => ['pricing_status', '定价状态'], + ]; + + $months = DB::connection($connection)->table('product_monthly_weighted_average_states') + ->where('status', 'computed')->orderByDesc('report_month')->pluck('report_month') + ->map(static fn ($month): string => substr((string) $month, 0, 10))->all(); + $requested = substr(trim((string) $request->query('month', '')), 0, 10); + if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1) { + // 导出时筛选栏提交的也是 Y-m,同样补成当月 1 号。 + $requested .= '-01'; + } + $month = $requested !== '' ? $requested : ($months[0] ?? null); + + $query = DB::connection($connection)->table('product_monthly_weighted_average_rows'); + if ($month !== null) { + $query->where('report_month', $month); + } + $code = trim((string) $request->query('product_code', '')); + if ($code !== '') { + $query->where('product_code', $code); + } + $provider = trim((string) $request->query('warehouse_provider', '')); + if ($provider !== '') { + $query->where('warehouse_short_name', 'like', '%' . addcslashes($provider, '%_\\') . '%'); + } + $category = trim((string) $request->query('category', '')); + if ($category !== '') { + $query->where('product_name', 'like', '%' . addcslashes($category, '%_\\') . '%'); + } + + $selected = array_values(array_intersect( + array_filter(explode(',', (string) $request->query('columns', ''))), + array_keys($map), + )); + if ($selected === []) { + $selected = array_keys($map); + } + + $size = min(max((int) setting('default.list_limit', 25), 1), 50); + if ($request->query('scope') === 'page') { + $query->forPage(max((int) $request->query('page', 1), 1), $size); + } + + $filename = '商品月加权平均单价_' . ($month ?? 'all') . '.csv'; + + return response()->streamDownload(function () use ($query, $selected, $map): void { + $out = fopen('php://output', 'w'); + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, array_map(static fn (string $key): string => $map[$key][1], $selected)); + $query->orderBy('warehouse_short_name')->orderBy('product_code') + ->chunk(1000, function ($rows) use ($out, $selected, $map): void { + foreach ($rows as $row) { + $line = []; + foreach ($selected as $key) { + $value = $row->{$map[$key][0]} ?? ''; + $line[] = is_string($value) ? $value : (string) $value; + } + fputcsv($out, $line); + } + }); + fclose($out); + }, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']); + } + + /** + * 进销存报表 → 入库明细数据导出(按月份/仓库/条码筛选,列顺序与页面一致)。 + */ + public function exportInventoryInboundDetail(Request $request): StreamedResponse + { + $connection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $labels = [ + 'source_no' => '来源单号', 'document_no' => '单据编号(采购单号)', 'created_serial' => '创建时间', + 'supplier' => '供应商', 'item_no' => '货号', 'barcode' => '条码', 'spec_name' => '规格名', + 'quantity' => '库存变动量', 'unit_price' => '单价', 'amount' => '金额', + 'estimated_unit_price' => '预估单价', 'estimated_amount' => '预估金额', + 'total' => '总计', + 'supplier_barcode' => '供应商条码', 'remark' => '备注', 'warehouse' => '仓库', + 'warehouse_short_name' => '仓库简称', 'created_at_raw' => '创建时间(实际)', + 'express_name' => '快递名称', 'express_no' => '快递单号', 'not_sent' => '未发出', 'owner_name' => '负责人', + ]; + + $query = DB::connection($connection)->table('inventory_inbound_detail_rows'); + $month = substr(trim((string) $request->query('detail_month', '')), 0, 10); + if ($month !== '') { + $query->where('report_month', $month); + } + $warehouse = trim((string) $request->query('detail_warehouse', '')); + if ($warehouse !== '') { + $like = '%' . addcslashes($warehouse, '%_\\') . '%'; + $query->where(function ($inner) use ($like): void { + $inner->where('warehouse', 'like', $like)->orWhere('warehouse_short_name', 'like', $like); + }); + } + $barcode = trim((string) $request->query('detail_barcode', '')); + if ($barcode !== '') { + $query->where('barcode', 'like', '%' . addcslashes($barcode, '%_\\') . '%'); + } + + $filename = '入库明细数据_' . ($month !== '' ? $month : 'all') . '.csv'; + + return response()->streamDownload(function () use ($query, $labels): void { + $out = fopen('php://output', 'w'); + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, array_values($labels)); + $query->orderBy('row_key')->chunk(1000, function ($rows) use ($out, $labels): void { + foreach ($rows as $row) { + $line = []; + foreach (array_keys($labels) as $column) { + if ($column === 'total') { + // 总计 = 金额 + 预估金额 + $line[] = number_format((float) ($row->amount ?? 0) + (float) ($row->estimated_amount ?? 0), 2); + continue; + } + $value = $row->{$column} ?? ''; + $line[] = is_string($value) ? $value : (string) $value; + } + fputcsv($out, $line); + } + }); + fclose($out); + }, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']); + } + protected function viewData( array $section, ?array $page = null, @@ -380,6 +918,37 @@ class Pages extends Controller $tabValue = null; $tabColumn = null; $upstreamError = null; + $inventoryWarehouseMappings = collect(); + $receiptStats = null; + $agreementCourierNames = $this->agreementCourierNames($page['slug'] ?? null); + $agreementCourierAccounts = $this->agreementCourierAccounts($page['slug'] ?? null, $agreementCourierNames); + + // 内部流转报表读取共享业务镜像中由工作簿导入的数据集,不走上游只读查询。 + if ($page && $content === null && $this->isInternalFlowReportPage($section, $page)) { + [$rows, $upstreamError] = $this->internalFlowReportRows(); + } + + if (($section['slug'] ?? null) === 'product-inventory' && ($page['slug'] ?? null) === 'inventory-report') { + if (request()->boolean('mapping')) { + $rows = new LengthAwarePaginator([], 0, 1, 1, [ + 'path' => request()->url(), + 'query' => request()->query(), + ]); + } else { + [$rows, $upstreamError] = $this->inventoryReportRows(); + } + $inventoryWarehouseMappings = $this->inventoryWarehouseMappingRows(); + } + + if (($section['slug'] ?? null) === 'product-inventory' + && ($page['slug'] ?? null) === 'monthly-weighted-average-price') { + $rows = $this->monthlyWeightedAveragePriceRows(); + } + + if (($section['slug'] ?? null) === 'financial-operations' + && ($page['slug'] ?? null) === 'performance-details') { + [$rows, $receiptStats] = $this->storeReceiptOrderMatchRows(); + } if ($page && $content === null) { $descriptor = TableRegistry::describe( @@ -389,7 +958,7 @@ class Pages extends Controller ); if ($descriptor) { - if ($descriptor->readOnly) { + if ($descriptor->readOnly) { try { $rows = app(UpstreamBusinessInformation::class)->paginate( $section['slug'], @@ -423,12 +992,19 @@ class Pages extends Controller 'agreementTasks' => $this->agreementTasks($page['slug']), 'agreementQuoteSignatures' => $this->agreementQuoteSignatures($page['slug']), 'agreementSubjects' => $this->agreementSubjects($page['slug']), - 'agreementCourierAccounts' => $this->agreementCourierAccounts($page['slug']), + 'agreementCourierNames' => $agreementCourierNames, + 'agreementCourierAccounts' => $agreementCourierAccounts, 'agreementQuoteVersions' => $this->agreementQuoteVersions($page['slug']), + 'inventoryWarehouseMappings' => $inventoryWarehouseMappings, + 'receiptStats' => $receiptStats, ]; } - if ($this->isStoreReceivingAccountPage($section['slug'], $page['slug'])) { + if (($section['slug'] ?? null) === 'product-inventory' + && ($page['slug'] ?? null) === 'inventory-report') { + // inventoryReportRows() 已从聚水潭共享镜像按全仓口径取数。 + // 这里必须保留该结果,不能再被目录表的旧演示数据覆盖。 + } elseif ($this->isStoreReceivingAccountPage($section['slug'], $page['slug'])) { try { app(\App\Business\StoreReceivingAccountSynchronizer::class)->sync((int) (company_id() ?: 1)); } catch (Throwable $exception) { @@ -476,8 +1052,301 @@ class Pages extends Controller 'agreementTasks' => $this->agreementTasks($page['slug'] ?? null), 'agreementQuoteSignatures' => $this->agreementQuoteSignatures($page['slug'] ?? null), 'agreementSubjects' => $this->agreementSubjects($page['slug'] ?? null), - 'agreementCourierAccounts' => $this->agreementCourierAccounts($page['slug'] ?? null), + 'agreementCourierNames' => $agreementCourierNames, + 'agreementCourierAccounts' => $agreementCourierAccounts, 'agreementQuoteVersions' => $this->agreementQuoteVersions($page['slug'] ?? null), + 'inventoryWarehouseMappings' => $inventoryWarehouseMappings, + 'receiptStats' => $receiptStats, + 'payablesFinal' => $this->payablesFinalData($section, $page), + ]; + } + + /** + * 「终版」目录的按表数据:独立存放,初始为空,由页面上的导入/导出/查询/编辑维护。 + * + * @return array|null + */ + protected function payablesFinalData(array $section, ?array $page): ?array + { + $sectionSlug = (string) ($section['slug'] ?? ''); + if (empty($page) || ! in_array($sectionSlug, [ + PayablesFinalRegistry::SECTION_SUPPLIER, + PayablesFinalRegistry::SECTION_COURIER, + ], true)) { + return null; + } + + $dataset = (string) ($page['slug'] ?? ''); + $registry = app(PayablesFinalRegistry::class); + if (! $registry->supports($sectionSlug, $dataset)) { + return null; + } + + $keyword = trim((string) request('keyword', '')); + $rows = $this->supplierPayableOverrides->listRows( + PayablesFinalActions::DATASET_PREFIX + . ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:') + . $dataset, + (int) (company_id() ?: 1), + ); + + if ($keyword !== '') { + $needle = mb_strtolower($keyword); + $rows = array_values(array_filter($rows, static function (array $row) use ($needle): bool { + foreach ($row as $key => $value) { + if ($key === '_action_key' || $value === null) { + continue; + } + if (str_contains(mb_strtolower((string) $value), $needle)) { + return true; + } + } + + return false; + })); + } + + $perPage = 50; + $currentPage = max((int) request('page', 1), 1); + + return [ + 'dataset' => $dataset, + 'fields' => collect($registry->fields($sectionSlug, $dataset)) + ->map(static fn (array $definition, string $name): array => ['name' => $name] + $definition) + ->values() + ->all(), + 'rows' => new LengthAwarePaginator( + array_slice($rows, ($currentPage - 1) * $perPage, $perPage), + count($rows), + $perPage, + $currentPage, + ['path' => request()->url(), 'query' => request()->query()], + ), + 'keyword' => $keyword, + 'actions' => url('/' . (company_id() ?: 1) . '/workspace/' . $sectionSlug . '/actions/' . $dataset), + ]; + } + + /** @return array{0:LengthAwarePaginator,1:?string} */ + private function inventoryReportRows(): array + { + $page = max(1, request()->integer('page', 1)); + $perPage = min(max((int) setting('default.list_limit', 25), 1), 100); + $filters = $this->inventoryReportFilters(request()); + $error = null; + + try { + if (! $this->thirdPartyWarehouseStorage->available()) { + $error = '进销存共享镜像尚未建立,暂时无法读取。'; + } elseif (! $this->thirdPartyWarehouseStorage->allWarehousesReady()) { + $error = '进销存全仓库共享镜像正在执行首次同步,完成前不会展示不完整的单仓数据。'; + } else { + $result = $this->thirdPartyWarehouseStorage->paginateMonthlyInventoryReport( + $filters, + $page, + $perPage, + ); + + $shortNames = app(InventoryWarehouseShortNames::class); + $names = $shortNames->forCompany((int) (company_id() ?: 1)); + + return [new LengthAwarePaginator( + array_map(static fn (object $row): object => $shortNames->fill($row, $names), $result['data']), + $result['total'], + $perPage, + $page, + [ + 'path' => request()->url(), + 'query' => request()->except('page'), + ], + ), null]; + } + } catch (Throwable $exception) { + report($exception); + $error = '进销存共享镜像暂时无法读取,请稍后重试。'; + } + + return [new LengthAwarePaginator([], 0, $perPage, $page, [ + 'path' => request()->url(), + 'query' => request()->except('page'), + ]), $error]; + } + + private function inventoryWarehouseMappingRows(): LengthAwarePaginator + { + $query = InventoryWarehouseNameMapping::query()->orderBy('warehouse_provider')->orderBy('warehouse'); + $provider = mb_substr(trim((string) request('mapping_warehouse_provider', '')), 0, 191); + $warehouse = mb_substr(trim((string) request('mapping_warehouse', '')), 0, 191); + + if ($provider !== '') { + $query->where('warehouse_provider', 'like', '%' . addcslashes($provider, '%_\\') . '%'); + } + if ($warehouse !== '') { + $query->where('warehouse', 'like', '%' . addcslashes($warehouse, '%_\\') . '%'); + } + + return $query->paginate(50)->withQueryString(); + } + + public function storeInventoryWarehouseMapping(Request $request) + { + $data = $request->validate([ + 'warehouse_provider' => ['required', 'string', 'max:191'], + 'warehouse' => ['required', 'string', 'max:191'], + 'warehouse_short_name' => ['nullable', 'string', 'max:191'], + ]); + $data['warehouse_provider'] = trim($data['warehouse_provider']); + $data['warehouse'] = trim($data['warehouse']); + $data['warehouse_short_name'] = trim((string) ($data['warehouse_short_name'] ?? '')) + ?: InventoryWarehouseNameMappingWorkbookImporter::suggestion($data['warehouse_provider'], $data['warehouse']); + + if (InventoryWarehouseNameMapping::query() + ->where('warehouse_provider', $data['warehouse_provider']) + ->where('warehouse', $data['warehouse']) + ->exists()) { + return back()->withInput()->withErrors(['warehouse' => '相同“仓储方 + 仓库”已存在,请使用修改功能。']); + } + + InventoryWarehouseNameMapping::create($data + [ + 'company_id' => company_id() ?: 1, + 'created_by' => auth()->id(), + 'updated_by' => auth()->id(), + ]); + + return $this->inventoryWarehouseMappingRedirect()->with('success', '仓库名称映射已新增。'); + } + + public function updateInventoryWarehouseMapping(Request $request, int $id) + { + $mapping = InventoryWarehouseNameMapping::query()->findOrFail($id); + $data = $request->validate([ + 'warehouse_provider' => ['required', 'string', 'max:191'], + 'warehouse' => ['required', 'string', 'max:191'], + 'warehouse_short_name' => ['required', 'string', 'max:191'], + ]); + $data = array_map(static fn (string $value): string => trim($value), $data); + + if (InventoryWarehouseNameMapping::query() + ->where('id', '!=', $mapping->id) + ->where('warehouse_provider', $data['warehouse_provider']) + ->where('warehouse', $data['warehouse']) + ->exists()) { + return back()->withInput()->withErrors(['warehouse' => '相同“仓储方 + 仓库”已存在,不能产生重复台账。']); + } + + $mapping->update($data + ['updated_by' => auth()->id()]); + + return $this->inventoryWarehouseMappingRedirect()->with('success', '仓库名称映射已修改。'); + } + + public function previewInventoryWarehouseMappingImport( + Request $request, + InventoryWarehouseNameMappingWorkbookImporter $importer, + ) { + $request->validate([ + 'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:10240'], + ]); + $preview = $importer->preview($request->file('import')); + $token = Str::random(40); + session()->put('inventory_warehouse_mapping_previews.' . $token, $preview); + + return $this->inventoryWarehouseMappingRedirect() + ->with('warehouse_mapping_preview', $preview + ['token' => $token]); + } + + public function commitInventoryWarehouseMappingImport( + Request $request, + InventoryWarehouseNameMappingWorkbookImporter $importer, + ) { + $token = (string) $request->input('preview_token'); + $preview = session()->pull('inventory_warehouse_mapping_previews.' . $token); + abort_if($token === '' || ! is_array($preview), 422, '导入预览已过期,请重新上传文件。'); + $result = $importer->commit($preview); + + return $this->inventoryWarehouseMappingRedirect()->with( + 'success', + "导入完成:新增 {$result['created']} 条,跳过 {$result['skipped']} 条重复映射。", + ); + } + + public function exportInventoryWarehouseMappings(Request $request): StreamedResponse + { + $query = InventoryWarehouseNameMapping::query()->orderBy('warehouse_provider')->orderBy('warehouse'); + $provider = mb_substr(trim((string) $request->query('mapping_warehouse_provider', '')), 0, 191); + $warehouse = mb_substr(trim((string) $request->query('mapping_warehouse', '')), 0, 191); + if ($provider !== '') { + $query->where('warehouse_provider', 'like', '%' . addcslashes($provider, '%_\\') . '%'); + } + if ($warehouse !== '') { + $query->where('warehouse', 'like', '%' . addcslashes($warehouse, '%_\\') . '%'); + } + + return response()->streamDownload(function () use ($query): void { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('仓库名称映射表'); + $headers = ['仓储方', '仓库', '仓库简称']; + $sheet->fromArray($headers, null, 'A1'); + $lastColumn = Coordinate::stringFromColumnIndex(count($headers)); + $headerRange = "A1:{$lastColumn}1"; + $sheet->getStyle($headerRange)->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER], + ]); + $sheet->getRowDimension(1)->setRowHeight(24); + $sheet->freezePane('A2'); + $sheet->setAutoFilter($headerRange); + foreach ([20, 32, 20] as $index => $width) { + $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width); + } + $rowNumber = 2; + foreach ($query->cursor() as $mapping) { + $sheet->fromArray([ + $mapping->warehouse_provider, + $mapping->warehouse, + $mapping->warehouse_short_name, + ], null, "A{$rowNumber}"); + $rowNumber++; + } + (new Xlsx($spreadsheet))->save('php://output'); + $spreadsheet->disconnectWorksheets(); + }, '仓库名称映射表_' . now()->format('Ymd_His') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store, no-cache, must-revalidate', + ]); + } + + private function inventoryWarehouseMappingRedirect() + { + return redirect()->route('business.pages.show', [ + 'company_id' => company_id() ?: 1, + 'section' => 'product-inventory', + 'page' => 'inventory-report', + 'mapping' => 1, + 'mapping_warehouse_provider' => request('mapping_warehouse_provider', ''), + 'mapping_warehouse' => request('mapping_warehouse', ''), + ]); + } + + /** @return array */ + private function inventoryReportFilters(Request $request): array + { + $month = trim((string) $request->query('month', now()->startOfMonth()->subMonth()->format('Y-m'))); + if (preg_match('/^(\d{4})-(\d{2})$/', $month, $matches) !== 1 + || ! checkdate((int) $matches[2], 1, (int) $matches[1])) { + $month = now()->startOfMonth()->subMonth()->format('Y-m'); + } + $minimumMonth = substr(ThirdPartyWarehouseStorageMirrorRepository::INVENTORY_REPORT_START_DATE, 0, 7); + if ($month < $minimumMonth) { + $month = $minimumMonth; + } + + return [ + 'month' => $month, + 'product_code' => mb_substr(trim((string) $request->query('product_code', '')), 0, 100), + 'warehouse_provider' => mb_substr(trim((string) $request->query('warehouse_provider', '')), 0, 191), + 'category' => mb_substr(trim((string) $request->query('category', '')), 0, 191), ]; } @@ -486,6 +1355,53 @@ class Pages extends Controller return $section === 'fund-management' && $page === 'store-receiving-accounts'; } + private function isInternalFlowReportPage(array $section, array $page): bool + { + return ($section['slug'] ?? null) === 'store-management' + && ($page['slug'] ?? null) === 'internal-flow-report'; + } + + /** + * 内部流转报表明细。数据来自共享业务镜像中按工作簿整份替换的导入结果, + * 尚未导入时保留空页面并说明原因,不把“未导入”当成业务数据为 0。 + * + * @return array{0: LengthAwarePaginator, 1: ?string} + */ + private function internalFlowReportRows(): array + { + $perPage = 50; + $currentPage = max((int) request('page', 1), 1); + $paginate = fn (array $items, int $total): LengthAwarePaginator => new LengthAwarePaginator( + $items, + $total, + $perPage, + $currentPage, + ['path' => request()->url(), 'query' => request()->query()], + ); + + $repository = app(InternalFlowReportRepository::class); + + if (! $repository->ready()) { + return [ + $paginate([], 0), + '内部流转数据尚未导入。导入《一般纳税人内部流转》工作簿后,本页会显示明细。', + ]; + } + + $payload = $repository->paginate( + $currentPage, + $perPage, + [ + 'company_name' => (string) request('company_name', ''), + 'tag' => (string) request('tag', ''), + ], + request('sort') === null ? null : (string) request('sort'), + (string) request('direction', 'asc'), + ); + + return [$paginate($payload['data'], $payload['total']), null]; + } + private function storeReceivingAccountRows(?string $tab): LengthAwarePaginator { $query = \App\Models\Business\StoreReceivingAccount::query(); @@ -526,15 +1442,32 @@ class Pages extends Controller ); } + protected function agreementCourierNames(?string $page): Collection + { + if ($page !== 'agreement-signing') { + return collect(); + } + + try { + return collect($this->courierInformation->names()); + } catch (Throwable $exception) { + // 快递镜像不可用时仍允许打开签署页,并明确展示暂无可选资料。 + report($exception); + return collect(); + } + } + /** @return array */ - protected function agreementCourierAccounts(?string $page): array + protected function agreementCourierAccounts(?string $page, ?Collection $courierNames = null): array { if ($page !== 'agreement-signing') { return []; } try { - return $this->courierInformation->signingAccountsByName(self::AGREEMENT_COURIER_NAMES); + return $this->courierInformation->signingAccountsByName( + ($courierNames ?? $this->agreementCourierNames($page))->values()->all(), + ); } catch (Throwable $exception) { // 快递镜像不可用时仍可手工填写 E 签宝账号,不能阻断签署页。 report($exception); @@ -702,6 +1635,15 @@ class Pages extends Controller } } + protected function resolveContentForSection(string $section, string $page, ?string $tab): ?array + { + if (in_array($section, self::PAYABLES_FINAL_SECTIONS, true)) { + return null; + } + + return $this->resolveContent($page, $tab); + } + protected function resolveContent(string $page, ?string $tab): ?array { return match ($page) { @@ -721,13 +1663,721 @@ class Pages extends Controller 'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(), 'online-daifa-price' => $this->contentForOnlineDaifaPrice(), 'courier-surcharge' => $this->contentForCourierSurcharge(), + 'freight-difference', 'other-surcharge-summary', 'return-fee' => $this->contentForCourierPayableSummary($page), 'shipping-data' => $this->contentForShippingData(), + 'return-pickup-management' => $this->contentForReturnPickupManagement(), 'withdrawal-management' => $this->contentForWithdrawalManagement(), 'bill-offset' => app(\Modules\EcommerceFinance\View\BillOffsetPageData::class)->page(), + 'account-mapping' => $this->contentForAccountMapping(), + 'billing-details' => app(\Modules\EcommerceFinance\View\BillingDetailsPageData::class)->page(), + 'store-violation-alert' => $this->contentForStoreViolationAlerts(), + 'planting-details' => $this->contentForPlantingDetails(), + 'jst-order-labels' => $this->contentForJstOrderLabels(), + 'store-report-data-logic' => $this->prepareStoreReportLogic(), + 'tax-forecast-data-logic' => $this->contentForTaxForecastLogic(), default => null, }; } + /** + * 税金预测表逻辑配置:规则清单、数据源状态和运行参数。 + */ + protected function contentForTaxForecastLogic(): array + { + return [ + 'view' => 'business.pages.company-management.tax-forecast-data-logic', + 'taxRules' => TaxForecastLogic::rules(), + 'taxSettings' => TaxForecastLogic::current(), + 'taxHealth' => TaxForecastLogic::health(), + ]; + } + + public function editTaxForecastLogic() + { + return view('business.pages.company-management.tax-forecast-data-logic-edit', [ + 'section' => ['slug' => 'trademark-management', 'title' => '商标管理'], + 'page' => ['slug' => 'tax-forecast-data-logic', 'title' => '税金预测表逻辑配置'], + 'settings' => TaxForecastLogic::current(), + 'incomeForecastSources' => TaxForecastLogic::INCOME_FORECAST_SOURCES, + ]); + } + + public function updateTaxForecastLogic(Request $request) + { + $data = $request->validate([ + 'vat_small_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'vat_free_threshold' => ['required', 'numeric', 'min:0'], + 'vat_general_enabled' => ['required', 'in:0,1'], + 'surtax_city_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'surtax_education_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'surtax_local_education_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'surtax_halved' => ['required', 'in:0,1'], + 'stamp_duty_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'stamp_duty_halved' => ['required', 'in:0,1'], + 'cit_effective_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'cit_threshold' => ['required', 'numeric', 'min:0'], + 'individual_halved_threshold' => ['required', 'numeric', 'min:0'], + 'assessed_income_rate' => ['required', 'numeric', 'min:0', 'max:100'], + 'income_forecast_source' => ['required', 'in:' . implode(',', array_keys(TaxForecastLogic::INCOME_FORECAST_SOURCES))], + ]); + + TaxForecastLogic::save($data); + + return redirect() + ->route('business.pages.show', ['section' => 'trademark-management', 'page' => 'tax-forecast-data-logic']) + ->with('success', '税金预测表逻辑配置已保存,下次预测按新参数计算。'); + } + + /** 首次打开店铺维度报表逻辑页时把代码里的期初数据固化成可编辑设置。 */ + protected function prepareStoreReportLogic(): ?array + { + StoreReportInitialPeriods::seedFromConfig(); + + return null; + } + + /** 店铺维度报表逻辑配置:期初主体数据编辑页。 */ + public function editStoreReportLogic() + { + $periods = StoreReportInitialPeriods::current(); + $shops = $periods['shops']; + uasort($shops, static fn (array $left, array $right): int => strcmp($left['changed_at'], $right['changed_at'])); + + return view('business.pages.trademark-management.store-report-data-logic-edit', [ + 'section' => ['slug' => 'trademark-management', 'title' => '商标管理'], + 'page' => ['slug' => 'store-report-data-logic', 'title' => '店铺维度报表逻辑配置'], + 'initialEffectiveAt' => $periods['initial_effective_at'], + 'initialShops' => $shops, + ]); + } + + public function updateStoreReportInitialPeriod(Request $request) + { + $data = $request->validate([ + 'store_name' => ['required', 'string', 'max:191'], + 'previous_company' => ['required', 'string', 'max:191'], + 'company' => ['required', 'string', 'max:191'], + 'changed_at' => ['required', 'date_format:Y-m-d'], + ]); + + StoreReportInitialPeriods::putShop($data['store_name'], [ + 'previous_company' => $data['previous_company'], + 'company' => $data['company'], + 'changed_at' => $data['changed_at'], + ]); + + return redirect() + ->route('business.store-report-logic.edit') + ->with('success', sprintf('店铺「%s」的期初主体已保存。', $data['store_name'])); + } + + public function destroyStoreReportInitialPeriod(Request $request) + { + $data = $request->validate([ + 'store_name' => ['required', 'string', 'max:191'], + ]); + + StoreReportInitialPeriods::forgetShop($data['store_name']); + + return redirect() + ->route('business.store-report-logic.edit') + ->with('success', sprintf('店铺「%s」的期初主体已删除。', $data['store_name'])); + } + + /** + * 账单流水数据 › 聚水潭订单标签明细。 + * + * 按标签拆行展示(一个标签一行),不做标签汇总、不对订单去重。 + */ + protected function contentForJstOrderLabels(): array + { + $request = request(); + $filters = $this->jstOrderLabelFilters($request); + $query = $this->jstOrderLabelQuery($filters); + + $limit = min(max((int) setting('default.list_limit', 25), 10), 100); + $page = max((int) $request->query('page', 1), 1); + $hasFilters = collect($filters)->contains(static fn (string $value): bool => $value !== ''); + // 无筛选时复用缓存总数,避免每次翻页都在 233 万行上重跑 COUNT(*)。 + $total = $hasFilters + ? (clone $query)->count() + : app(\App\Business\JstOrderLabelOptions::class)->total((int) company_id()); + $records = new \Illuminate\Pagination\LengthAwarePaginator( + $query->orderByDesc('ordered_at')->orderByDesc('id')->forPage($page, $limit)->get(), + $total, + $limit, + $page, + ['path' => $request->url(), 'query' => $request->query()], + ); + + return [ + 'view' => 'business.pages.billing-transactions.jst-order-labels', + 'records' => $records, + 'filters' => $filters, + 'totalRows' => $records->total(), + 'filterOptions' => [ + 'shops' => app(\App\Business\JstOrderLabelOptions::class)->shops((int) company_id()), + 'labels' => app(\App\Business\JstOrderLabelOptions::class)->labels((int) company_id()), + ], + ]; + } + + /** @return array */ + private function jstOrderLabelFilters(Request $request): array + { + return [ + 'date_from' => $this->dateFilter($request->query('date_from')), + 'date_to' => $this->dateFilter($request->query('date_to')), + 'shop_name' => mb_substr(trim((string) $request->query('shop_name')), 0, 191), + 'label' => mb_substr(trim((string) $request->query('label')), 0, 191), + 'keyword' => mb_substr(trim((string) $request->query('keyword')), 0, 100), + ]; + } + + /** @param array $filters */ + private function jstOrderLabelQuery(array $filters): \Illuminate\Database\Eloquent\Builder + { + $query = \App\Models\Business\JstOrderLabel::query()->where('company_id', company_id()); + + if ($filters['date_from'] !== '') { + $query->where('ordered_at', '>=', $filters['date_from'] . ' 00:00:00'); + } + if ($filters['date_to'] !== '') { + $query->where('ordered_at', '<', date('Y-m-d', strtotime($filters['date_to'] . ' +1 day')) . ' 00:00:00'); + } + if ($filters['shop_name'] !== '') { + $query->where('shop_name', $filters['shop_name']); + } + if ($filters['label'] !== '') { + $query->where('label', 'like', '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['label']) . '%'); + } + if ($filters['keyword'] !== '') { + $query->where('order_no', 'like', '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['keyword']) . '%'); + } + + return $query; + } + + /** 账单流水数据 › 聚水潭订单标签明细导出(按当前筛选,全量) */ + public function exportJstOrderLabels(Request $request): StreamedResponse + { + $query = $this->jstOrderLabelQuery($this->jstOrderLabelFilters($request)); + + return response()->streamDownload(function () use ($query): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建聚水潭订单标签明细导出流。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, ['线上订单号', '店铺名称', '下单时间', '标签']); + + $query->orderBy('id')->chunkById(2000, function ($rows) use ($csv): void { + foreach ($rows as $row) { + fputcsv($csv, [ + $row->order_no, + $row->shop_name, + $row->ordered_at?->format('Y-m-d H:i:s'), + $row->label, + ]); + } + }); + fclose($csv); + }, '聚水潭订单标签明细_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * 财务经营风险管控 › 店铺违规信息预警。 + * + * 六个平台页签共用统一表头;数据来自统一表 store_violation_records + * (上游抓取同步 + 手工导入),页面不直接读取上游。 + */ + protected function contentForStoreViolationAlerts(): array + { + $request = request(); + $platforms = (array) config('store_violations.platforms', []); + $requested = (string) $request->query('platform', (string) array_key_first($platforms)); + $activePlatform = array_key_exists($requested, $platforms) ? $requested : (string) array_key_first($platforms); + + $filters = $this->storeViolationFilters($request); + $repository = app(StoreViolationRecordRepository::class); + $limit = min(max((int) setting('default.list_limit', 25), 10), 100); + $error = null; + $panels = []; + + if (! $repository->available()) { + $error = '店铺违规统一表尚未建立,暂时无法读取数据。'; + } + + foreach (array_keys($platforms) as $slug) { + $page = $slug === $activePlatform ? max((int) $request->query('page', 1), 1) : 1; + $records = Collection::make(); + $total = 0; + + if ($error === null) { + try { + $result = $repository->paginate((string) $slug, $filters, $page, $limit); + $records = Collection::make($result['data']); + $total = (int) $result['total']; + } catch (Throwable $exception) { + report($exception); + $error = '店铺违规数据暂时无法读取,请稍后重试。'; + } + } + + $panels[$slug] = [ + 'rows' => new LengthAwarePaginator($records, $total, $limit, $page, [ + 'path' => $request->url(), + 'query' => array_merge($request->query(), ['platform' => (string) $slug]), + ]), + 'total' => $total, + ]; + } + + return [ + 'view' => 'business.pages.financial-risk-control.index', + 'storeViolationPlatforms' => $platforms, + 'storeViolationActivePlatform' => $activePlatform, + 'storeViolationPanels' => $panels, + 'storeViolationFilters' => $filters, + 'storeViolationFilterOptions' => $error === null + ? $repository->filterOptions($activePlatform) + : ['statuses' => [], 'handling_statuses' => [], 'categories' => [], 'shops' => []], + 'storeViolationPlatformCounts' => $error === null ? $repository->platformCounts() : [], + 'storeViolationSync' => $repository->syncStatus(), + 'storeViolationError' => $error, + 'storeViolationPreview' => session('store_violation_preview'), + ]; + } + + /** @return array */ + private function storeViolationFilters(Request $request): array + { + return [ + 'keyword' => mb_substr(trim((string) $request->query('keyword')), 0, 100), + 'status' => mb_substr(trim((string) $request->query('status')), 0, 64), + 'handling_status' => mb_substr(trim((string) $request->query('handling_status')), 0, 32), + 'category' => mb_substr(trim((string) $request->query('category')), 0, 64), + 'date_from' => $this->dateFilter($request->query('date_from')), + 'date_to' => $this->dateFilter($request->query('date_to')), + ]; + } + + /** 店铺违规信息预警:按当前筛选导出统一表头(Excel)。 */ + public function exportStoreViolations(Request $request): StreamedResponse + { + $platforms = (array) config('store_violations.platforms', []); + $platform = (string) $request->query('platform', (string) array_key_first($platforms)); + abort_unless(array_key_exists($platform, $platforms), 404); + + $repository = app(StoreViolationRecordRepository::class); + abort_unless($repository->available(), 503, '店铺违规统一表尚未建立,暂时不能导出。'); + + $filters = $this->storeViolationFilters($request); + $columns = (array) config('store_violations.columns', []); + $rows = $repository->exportRows($platform, $filters); + $label = (string) ($platforms[$platform]['label'] ?? $platform); + + return response()->streamDownload(function () use ($rows, $columns): void { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('店铺违规信息'); + + $headers = array_map(static fn (array $column): string => (string) $column['label'], $columns); + $sheet->fromArray($headers, null, 'A1'); + $lastColumn = Coordinate::stringFromColumnIndex(max(count($headers), 1)); + $sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER], + ]); + $sheet->getRowDimension(1)->setRowHeight(24); + + $rowNumber = 2; + foreach ($rows as $row) { + $values = []; + foreach ($columns as $column) { + $key = (string) $column['key']; + $value = $row->{$key} ?? null; + if ($key === 'points_deducted' && $value !== null) { + $value = (float) $value; + } + $values[] = $value === null ? '' : $value; + } + $sheet->fromArray($values, null, 'A' . $rowNumber); + $rowNumber++; + } + + foreach (['A' => 30, 'B' => 36, 'C' => 14, 'D' => 24, 'E' => 14, 'F' => 10, 'G' => 16, 'H' => 14, 'I' => 16, 'J' => 12] as $column => $width) { + $sheet->getColumnDimension($column)->setWidth($width); + } + $sheet->freezePane('A2'); + + (new Xlsx($spreadsheet))->save('php://output'); + }, '店铺违规信息_' . $label . '_' . now()->format('Ymd_His') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** 店铺违规信息预警:导入模板(统一表头 + 填写说明)。 */ + public function storeViolationTemplate(): StreamedResponse + { + $columns = (array) config('store_violations.columns', []); + $handling = implode('、', (array) config('store_violations.handling_statuses', [])); + + return response()->streamDownload(function () use ($columns, $handling): void { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('店铺违规信息'); + + $headers = array_map(static fn (array $column): string => (string) $column['label'], $columns); + $sheet->fromArray($headers, null, 'A1'); + $sheet->fromArray( + ['示例·某某旗舰店', '延迟发货/缺货无货', '发货履约', 'JD202610040001', '2026-10-04', 2, '待处理', '', '2026-10-11', '未处理'], + null, + 'A2', + ); + $lastColumn = Coordinate::stringFromColumnIndex(max(count($headers), 1)); + $sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER], + ]); + $sheet->getRowDimension(1)->setRowHeight(24); + foreach (['A' => 30, 'B' => 36, 'C' => 14, 'D' => 24, 'E' => 14, 'F' => 10, 'G' => 16, 'H' => 14, 'I' => 16, 'J' => 12] as $column => $width) { + $sheet->getColumnDimension($column)->setWidth($width); + } + $sheet->freezePane('A2'); + + $notes = $spreadsheet->createSheet(); + $notes->setTitle('填写说明'); + $notes->fromArray([ + ['字段', '说明'], + ['店铺名', '必填。'], + ['违规单号', '必填。同一平台内唯一;已存在的单号会按文件内容更新(导入预览会逐行提示)。'], + ['违规类型', '选填。平台显示的违规内容/类型,例如“延迟发货/缺货无货”。'], + ['违规分类', '选填。留空时按违规类型关键词自动归类。'], + ['违规日期 / 处罚日期 / 申诉截止日期', '选填。格式 YYYY-MM-DD,例如 2026-10-04。'], + ['扣分', '选填。数字,例如 2 或 0.5。'], + ['状态', '选填。平台状态,例如“待处理”“超期未申诉”。'], + ['处理状态', '选填。可选值:' . $handling . ';留空按“未处理”写入。'], + ['平台', '无需填写。导入时按当前页签决定平台。'], + ['提示', '请保留第一行表头;示例行可直接替换为实际数据。'], + ], null, 'A1'); + $notes->getStyle('A1:B1')->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + ]); + $notes->getColumnDimension('A')->setWidth(34); + $notes->getColumnDimension('B')->setWidth(72); + $notes->getStyle('B1:B11')->getAlignment()->setWrapText(true); + + (new Xlsx($spreadsheet))->save('php://output'); + }, '店铺违规信息导入模板_' . now()->format('Ymd') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** 店铺违规信息预警:导入预览(先校验,不写库)。 */ + public function previewStoreViolationImport(Request $request, StoreViolationWorkbookImporter $importer) + { + $maxKilobytes = (int) config('store_violations.import.max_kilobytes', 10240); + $request->validate([ + 'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:' . $maxKilobytes], + 'platform' => ['required', 'string'], + ]); + + $platform = (string) $request->input('platform'); + abort_unless(array_key_exists($platform, (array) config('store_violations.platforms', [])), 422); + + try { + $preview = $importer->preview($request->file('import'), $platform); + } catch (\Illuminate\Validation\ValidationException $exception) { + return redirect() + ->route('business.pages.show', [ + 'section' => 'financial-risk-control', + 'page' => 'store-violation-alert', + 'platform' => $platform, + ]) + ->withErrors($exception->errors()) + ->withInput(); + } + + $token = Str::random(40); + session()->put('store_violation_previews.' . $token, $preview); + + return redirect() + ->route('business.pages.show', [ + 'section' => 'financial-risk-control', + 'page' => 'store-violation-alert', + 'platform' => $platform, + ]) + ->with('store_violation_preview', $preview + ['token' => $token]); + } + + /** 店铺违规信息预警:确认导入。 */ + public function commitStoreViolationImport(Request $request, StoreViolationWorkbookImporter $importer) + { + $token = (string) $request->input('preview_token'); + $preview = session()->pull('store_violation_previews.' . $token); + abort_if($token === '' || ! is_array($preview), 422, '导入预览已过期,请重新上传文件。'); + + $result = $importer->commit($preview); + + return redirect() + ->route('business.pages.show', [ + 'section' => 'financial-risk-control', + 'page' => 'store-violation-alert', + 'platform' => (string) ($preview['platform'] ?? array_key_first((array) config('store_violations.platforms', []))), + ]) + ->with('success', "导入完成:新增 {$result['created']} 条,更新 {$result['updated']} 条。"); + } + + /** + * 账单流水数据 › 种菜明细表。 + */ + protected function contentForPlantingDetails(): array + { + $request = request(); + $filters = $this->plantingDetailFilters($request); + $query = $this->plantingDetailQuery($filters); + + $summaryRow = (clone $query)->selectRaw( + 'COUNT(*) AS rows_count, COALESCE(SUM(pieces), 0) AS pieces_total, ' + . 'COALESCE(SUM(finance_selling_price), 0) AS selling_price_total, ' + . 'COALESCE(SUM(finance_payment_amount), 0) AS payment_amount_total, ' + . 'COALESCE(SUM(deduction), 0) AS deduction_total, ' + . 'COALESCE(SUM(jingxi_price_diff), 0) AS jingxi_diff_total' + )->first(); + + $limit = min(max((int) setting('default.list_limit', 25), 10), 100); + $records = (clone $query) + ->orderByDesc('bill_date') + ->orderByDesc('id') + ->paginate($limit) + ->withQueryString(); + + return [ + 'view' => 'business.pages.billing-transactions.planting-details', + 'records' => $records, + 'filters' => $filters, + 'summary' => [ + 'rows' => (int) ($summaryRow->rows_count ?? 0), + 'pieces' => (int) ($summaryRow->pieces_total ?? 0), + 'selling_price' => (float) ($summaryRow->selling_price_total ?? 0), + 'payment_amount' => (float) ($summaryRow->payment_amount_total ?? 0), + 'deduction' => (float) ($summaryRow->deduction_total ?? 0), + 'jingxi_diff' => (float) ($summaryRow->jingxi_diff_total ?? 0), + ], + 'filterOptions' => [ + 'stores' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('store')->distinct()->orderBy('store')->limit(500)->pluck('store')->all(), + 'owners' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('owner')->distinct()->orderBy('owner')->limit(500)->pluck('owner')->all(), + 'types' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('type')->distinct()->orderBy('type')->limit(200)->pluck('type')->all(), + 'tags' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('tag')->distinct()->orderBy('tag')->limit(200)->pluck('tag')->all(), + ], + ]; + } + + /** @return array 种菜明细表筛选条件 */ + private function plantingDetailFilters(Request $request): array + { + return [ + 'date_from' => $this->dateFilter($request->query('date_from')), + 'date_to' => $this->dateFilter($request->query('date_to')), + 'store' => mb_substr(trim((string) $request->query('store')), 0, 191), + 'owner' => mb_substr(trim((string) $request->query('owner')), 0, 191), + 'type' => mb_substr(trim((string) $request->query('type')), 0, 191), + 'tag' => mb_substr(trim((string) $request->query('tag')), 0, 191), + 'keyword' => mb_substr(trim((string) $request->query('keyword')), 0, 191), + ]; + } + + /** @param array $filters */ + private function plantingDetailQuery(array $filters): \Illuminate\Database\Eloquent\Builder + { + $query = \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()); + + if ($filters['date_from'] !== '') { + $query->where('bill_date', '>=', $filters['date_from']); + } + if ($filters['date_to'] !== '') { + $query->where('bill_date', '<=', $filters['date_to']); + } + foreach (['store', 'owner', 'type', 'tag'] as $field) { + if ($filters[$field] !== '') { + $query->where($field, $filters[$field]); + } + } + if ($filters['keyword'] !== '') { + $like = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['keyword']) . '%'; + $query->where(function ($sub) use ($like): void { + $sub->where('order_no', 'like', $like) + ->orWhere('remark', 'like', $like) + ->orWhere('account', 'like', $like) + ->orWhere('external_id', 'like', $like) + ->orWhere('creator', 'like', $like); + }); + } + + return $query; + } + + /** 账单流水数据 › 种菜明细表导出(按当前筛选,全量) */ + public function exportPlantingDetails(Request $request): StreamedResponse + { + $query = $this->plantingDetailQuery($this->plantingDetailFilters($request)); + + return response()->streamDownload(function () use ($query): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建种菜明细导出流。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, [ + '日期', '订单编号', '财务售价', '财务运费', '财务佣金', '京喜差价', '扣款', + '财务空包费', '财务打款金额', '笔数', '备注', '正确店铺', '负责人', '账户', + '类型', '创建人', '标签', '所属利润中心', '负责平台', 'ID', + ]); + + $query->orderBy('id')->chunkById(2000, function ($rows) use ($csv): void { + foreach ($rows as $row) { + fputcsv($csv, [ + $row->bill_date?->toDateString(), + $row->order_no, + $row->finance_selling_price, + $row->finance_freight, + $row->finance_commission, + $row->jingxi_price_diff, + $row->deduction, + $row->finance_empty_package_fee, + $row->finance_payment_amount, + $row->pieces, + $row->remark, + $row->store, + $row->owner, + $row->account, + $row->type, + $row->creator, + $row->tag, + $row->profit_center, + $row->responsible_platform, + $row->external_id, + ]); + } + }); + fclose($csv); + }, '种菜明细表_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * 财务规则 · 科目映射表 + * + * 表里存的是「科目对 + 方向基准」,不存最终借贷方向;记账时按账单实际收支代入。 + * 页面支持导入追加、单条修改、新增、删除,并实时给出账套科目校验结果。 + */ + protected function contentForAccountMapping(): array + { + $store = app(AccountMappingStore::class); + $validator = app(AccountMappingValidator::class); + + $rows = []; + $summary = [ + 'total' => 0, 'error_rows' => 0, 'warning_rows' => 0, 'ok_rows' => 0, + 'error_count' => 0, 'warning_count' => 0, 'tip_count' => 0, + ]; + $options = ['platforms' => [], 'categories' => [], 'basis' => [], 'invoices' => []]; + $error = null; + + try { + $rules = $store->all(); + $validated = $validator->validate($rules); + foreach ($rules as $rule) { + $rows[] = $rule + ['issues' => $validated['issues'][(int) $rule['id']] ?? []]; + } + $summary = $validated['summary']; + $options = $store->options(); + } catch (Throwable $exception) { + $error = '映射表存储暂时读不出来,请稍后重试。'; + } + + return [ + 'view' => 'business.pages.financial-rules.account-mapping', + 'amRows' => $rows, + 'amSummary' => $summary, + 'amOptions' => $options, + 'amEndpoint' => $this->accountMappingEndpoint(), + 'amError' => $error, + ]; + } + + /** 维护接口前缀(去掉末尾的 /rules) */ + protected function accountMappingEndpoint(): string + { + try { + $url = route('business.financial-rules.account-mapping.actions.rules'); + } catch (Throwable) { + $url = url((int) (company_id() ?: 1) . '/workspace/financial-rules/account-mapping/actions/rules'); + } + + return (string) preg_replace('#/rules$#', '', $url); + } + + protected function contentForCourierPayableSummary(string $page): array + { + $store = app(CourierPayableSummaryStore::class); + $snapshot = null; + $error = null; + + try { + $snapshot = $store->snapshot((int) (company_id() ?: 1), $page); + } catch (RuntimeException) { + $error = '汇总数据暂时无法读取,请重新导入后再试。'; + } + + $headers = $snapshot['headers'] ?? []; + $allRows = collect($snapshot['rows'] ?? []); + $filter = app(CourierPayableSummaryFilter::class); + $filters = $filter->fromRequest(request()); + $filteredRows = $filter->apply($allRows, $headers, $filters); + $perPage = 50; + $lastPage = max((int) ceil($filteredRows->count() / $perPage), 1); + $currentPage = min(max((int) request()->query('page', 1), 1), $lastPage); + + return [ + 'view' => 'business.pages.courier-payables.summary-table', + 'courierSummaryPage' => $page, + 'courierSummaryTitle' => $store->title($page), + 'courierSummaryHeaders' => $headers, + 'courierSummaryRows' => new LengthAwarePaginator( + $filteredRows->forPage($currentPage, $perPage)->values(), + $filteredRows->count(), + $perPage, + $currentPage, + ['path' => request()->url(), 'query' => array_filter( + $filters, + static fn (string $value): bool => $value !== '', + )], + ), + 'courierSummaryFilters' => $filters, + 'courierSummaryHasFilters' => $filter->hasFilters($filters), + 'courierSummarySourceTotal' => $allRows->count(), + 'courierSummarySourceName' => $snapshot['source_name'] ?? null, + 'courierSummaryImportedAt' => $snapshot['imported_at'] ?? null, + 'courierSummaryError' => $error, + ]; + } + /** * Consolidated, non-destructive view of the withdrawal configuration kept * with each store receiving account. Updates remain in the source page so @@ -735,75 +2385,8 @@ class Pages extends Controller */ protected function contentForWithdrawalManagement(): array { - $clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length); - $platform = $clean(request()->query('platform')); - $withdrawalPath = $clean(request()->query('withdrawal_path')); - $keyword = $clean(request()->query('keyword'), 191); - $balanceStatus = $clean(request()->query('balance_status')); - if (! in_array($balanceStatus, ['matched', 'unmatched', 'ambiguous', 'not_ready'], true)) { - $balanceStatus = ''; - } - - $platforms = StoreReceivingAccount::query() - ->whereNotNull('store_platform') - ->distinct() - ->orderBy('store_platform') - ->pluck('store_platform') - ->filter() - ->values() - ->all(); - $withdrawalPaths = StoreReceivingAccount::query() - ->whereNotNull('receiving_method') - ->distinct() - ->orderBy('receiving_method') - ->pluck('receiving_method') - ->filter() - ->values() - ->all(); - - $query = StoreReceivingAccount::query(); - - if ($platform !== '') { - $query->where('store_platform', $platform); - } - - if ($withdrawalPath !== '') { - $query->where('receiving_method', $withdrawalPath); - } - - if ($keyword !== '') { - $query->where('store_name', 'like', '%' . addcslashes($keyword, '%_\\') . '%'); - } - - $today = now()->startOfDay(); - $balanceDate = $today->copy()->subDay(); - $withdrawalRows = $query->orderByDesc('id')->get(); - $withdrawalBalances = $this->jushuitanShopBalances->matchesForStores( - $withdrawalRows, - $balanceDate->toDateString(), - ); - $balanceCounts = collect($withdrawalBalances)->countBy( - static fn (array $match): string => $match['status'], - ); - - if ($balanceStatus !== '') { - $withdrawalRows = $withdrawalRows->filter( - static fn (StoreReceivingAccount $row): bool => ($withdrawalBalances[(int) $row->id]['status'] ?? 'not_ready') === $balanceStatus, - ); - } - - $statusOrder = ['matched' => 0, 'ambiguous' => 1, 'unmatched' => 2, 'not_ready' => 3]; - $withdrawalRows = $withdrawalRows->sort( - static function (StoreReceivingAccount $left, StoreReceivingAccount $right) use ($withdrawalBalances, $statusOrder): int { - $leftStatus = $withdrawalBalances[(int) $left->id]['status'] ?? 'not_ready'; - $rightStatus = $withdrawalBalances[(int) $right->id]['status'] ?? 'not_ready'; - $statusComparison = ($statusOrder[$leftStatus] ?? 99) <=> ($statusOrder[$rightStatus] ?? 99); - - return $statusComparison !== 0 - ? $statusComparison - : ((int) $right->id <=> (int) $left->id); - }, - )->values(); + $report = $this->withdrawalManagementReport->results(request()); + $withdrawalRows = $report['rows']; $page = max((int) request()->query('page', 1), 1); $perPage = 50; @@ -814,23 +2397,21 @@ class Pages extends Controller $page, ['path' => request()->url(), 'query' => request()->except('page')], ); - return [ 'view' => 'business.pages.fund-management.withdrawal-management', 'withdrawalRows' => $withdrawalRows, - 'withdrawalFilters' => compact('platform', 'withdrawalPath', 'keyword', 'balanceStatus'), - 'withdrawalPlatforms' => $platforms, - 'withdrawalPaths' => $withdrawalPaths, - 'withdrawalBalances' => $withdrawalBalances, - 'withdrawalBalanceSummary' => [ - 'source' => $this->jushuitanShopBalances->countForDate($balanceDate->toDateString()), - 'matched' => (int) $balanceCounts->get('matched', 0), - 'ambiguous' => (int) $balanceCounts->get('ambiguous', 0), - 'unmatched' => (int) $balanceCounts->get('unmatched', 0), - 'not_ready' => (int) $balanceCounts->get('not_ready', 0), - ], - 'withdrawalBalanceColumnLabel' => $today->format('n月j日') . '店铺余额', - 'withdrawalBalanceDate' => $balanceDate->toDateString(), + 'withdrawalFilters' => $report['filters'], + 'withdrawalPlatforms' => $report['platforms'], + 'withdrawalPaths' => $report['paths'], + 'withdrawalStoreEntities' => $report['storeEntities'], + 'withdrawalBalances' => $report['balances'], + 'withdrawalReserveStandards' => $report['reserveStandards'], + 'withdrawalAmounts' => $report['withdrawalAmounts'], + 'withdrawalCompliance' => $report['compliance'], + 'withdrawalBalanceSummary' => $report['summary'], + 'withdrawalBalanceColumnLabel' => $report['balanceColumnLabel'], + 'withdrawalBalanceDate' => $report['balanceDate'], + 'withdrawalSort' => $report['sort'], ]; } @@ -1048,9 +2629,11 @@ class Pages extends Controller 'mode' => $clean(request('mode', ''), 40), 'scope' => $clean(request('scope', ''), 20), 'reconciler' => $clean(request('reconciler', ''), 40), + 'supplier' => $clean(request('supplier', ''), 191), 'status' => $clean(request('status', ''), 20), ]; $data = $this->courierSurchargeQuotes->pageData($filters); + $auditReady = $this->courierSurchargeAudits->ready(); return [ 'view' => 'business.pages.courier-payables.courier-surcharge', @@ -1058,8 +2641,11 @@ class Pages extends Controller 'courierSurchargeFilters' => $filters, 'courierSurchargeSummary' => $data['summary'], 'courierSurchargeOptions' => $data['options'], - 'courierSurchargeReady' => $data['ready'], + 'courierSurchargeReady' => $data['ready'] && $auditReady, + 'courierSurchargeDataReady' => $data['ready'], + 'courierSurchargeAuditReady' => $auditReady, 'courierSurchargeTypeUsage' => $this->courierSurchargeTypes->usageCounts($data['options']['type_records'] ?? collect()), + 'courierSurchargeAuditLogs' => $this->courierSurchargeAudits->recent(), ]; } @@ -1237,6 +2823,132 @@ class Pages extends Controller ]); } + public function exportInventoryReport(Request $request): Response + { + abort_unless( + $this->thirdPartyWarehouseStorage->available() + && $this->thirdPartyWarehouseStorage->allWarehousesReady(), + 503, + ); + + $filters = $this->inventoryReportFilters($request); + $productInventory = collect(config('business_navigation'))->firstWhere('slug', 'product-inventory'); + $inventoryPage = collect($productInventory['pages'] ?? [])->firstWhere('slug', 'inventory-report'); + $availableColumns = collect($inventoryPage['directory']['fields'] ?? []) + ->reject(static fn (array $column): bool => in_array($column['kind'] ?? '', ['secret', 'password'], true)) + ->keyBy('name'); + $requestedColumnsParam = $request->query('columns', ''); + abort_unless(is_string($requestedColumnsParam), 422); + $requestedColumns = trim($requestedColumnsParam); + $columns = $availableColumns->values()->all(); + if ($requestedColumns !== '') { + $names = explode(',', $requestedColumns); + abort_if(count($names) > $availableColumns->count() || count($names) !== count(array_unique($names)), 422); + $columns = []; + foreach ($names as $name) { + abort_unless($availableColumns->has($name), 422); + $columns[] = $availableColumns->get($name); + } + } + $scope = $request->query('scope', 'all'); + abort_unless(in_array($scope, ['all', 'page'], true), 422); + $page = max(1, $request->integer('page', 1)); + $perPage = min(max((int) setting('default.list_limit', 25), 1), 100); + + if ($scope === 'all' && should_queue()) { + $fileName = Str::filename('进销存报表') . '-' . now()->format('Ymd_His') . '-' . Str::random(8) . '.csv'; + dispatch(new InventoryReportExport(user(), $filters, $columns, $fileName, (int) (company_id() ?: 1)))->onQueue('exports'); + flash('进销存报表已提交后台生成,完成后可从通知中心下载。')->success(); + + return back(); + } + + if ($scope === 'all') { + // The local environment intentionally uses the sync queue and has + // no worker process. Defer the same export job until the response + // has been sent so a large CSV never depends on a live browser + // download connection. The job stores the completed file and + // raises the existing notification when it is ready. + $fileName = Str::filename('进销存报表') . '-' . now()->format('Ymd_His') . '-' . Str::random(8) . '.csv'; + dispatch(new InventoryReportExport(user(), $filters, $columns, $fileName, (int) (company_id() ?: 1)))->afterResponse(); + flash('进销存报表已提交后台生成,完成后可从通知中心下载。')->success(); + + return back(); + } + + // Build the complete CSV before opening the HTTP response. Streaming + // rows directly from the database keeps the browser request open for + // the whole aggregation and makes a slow client look like a failed + // export. A disk-backed file keeps memory bounded and lets the web + // server send a framed response with a known length. + set_time_limit(0); + $filePath = tempnam(sys_get_temp_dir(), 'inventory-report-'); + if ($filePath === false) { + throw new RuntimeException('无法创建进销存报表导出临时文件。'); + } + + try { + $csv = fopen($filePath, 'wb'); + if ($csv === false) { + throw new RuntimeException('无法写入进销存报表导出临时文件。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_column($columns, 'label')); + $rows = $scope === 'page' + ? $this->thirdPartyWarehouseStorage->paginateMonthlyInventoryReport($filters, $page, $perPage, false)['data'] + : $this->thirdPartyWarehouseStorage->exportMonthlyInventoryReportRows($filters); + $shortNames = app(InventoryWarehouseShortNames::class); + $names = $shortNames->forCompany((int) (company_id() ?: 1)); + $written = 0; + foreach ($rows as $row) { + $row = $shortNames->fill($row, $names); + fputcsv($csv, array_map(function (array $column) use ($row): mixed { + $value = data_get($row, $column['name']); + + return $column['name'] === 'product_code' + ? $this->csvIdentifier($value) + : (($column['kind'] ?? null) === 'integer' + ? ($value === null || $value === '' ? '' : $value) + : $this->csvText($value)); + }, $columns)); + $written++; + if ($written % 5000 === 0) { + fflush($csv); + gc_collect_cycles(); + } + } + fclose($csv); + clearstatcache(true, $filePath); + $fileSize = filesize($filePath); + if ($fileSize === false) { + throw new RuntimeException('无法读取进销存报表导出文件大小。'); + } + } catch (Throwable $exception) { + if (isset($csv) && is_resource($csv)) { + fclose($csv); + } + @unlink($filePath); + throw $exception; + } + + $fileName = '进销存报表_' . str_replace('-', '', $filters['month']) . '_' . now()->format('Ymd_His') . '.csv'; + + return response()->streamDownload(function () use ($filePath): void { + try { + set_time_limit(0); + readfile($filePath); + } finally { + @unlink($filePath); + } + }, $fileName, [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + 'X-Accel-Buffering' => 'no', + 'Content-Length' => (string) $fileSize, + ]); + } + /** @return array */ private function thirdPartyWarehouseStorageFilters(Request $request): array { @@ -1390,6 +3102,7 @@ class Pages extends Controller 'onlineDaifaStatus' => $result['status'] ?? 'unknown', 'onlineDaifaSyncedAt' => $result['last_synced_at'] ?? null, 'onlineDaifaSummary' => $result['summary'] ?? [], + 'onlineDaifaSources' => $result['source_statuses'] ?? [], 'onlineDaifaError' => null, ]; } catch (Throwable $exception) { @@ -1404,6 +3117,7 @@ class Pages extends Controller 'onlineDaifaStatus' => 'unavailable', 'onlineDaifaSyncedAt' => null, 'onlineDaifaSummary' => [], + 'onlineDaifaSources' => [], 'onlineDaifaError' => '线上代发价格镜像尚未完成同步,请稍后重试。', ]; } @@ -1434,9 +3148,11 @@ class Pages extends Controller $originator = trim((string) ($workflow['originatorUserName'] ?? '')) ?: trim((string) ($workflow['originatorUserId'] ?? '')); $matchedProduct = (array) ($row['matched_product'] ?? []); - $productName = ($matchedProduct['matched'] ?? false) - ? (string) ($matchedProduct['name'] ?? '') - : '(未匹配)'; + $productName = ($row['source_type'] ?? 'ding') === 'purchase' + ? '' + : (($matchedProduct['matched'] ?? false) + ? (string) ($matchedProduct['name'] ?? '') + : '(未匹配)'); fputcsv($csv, [ $this->csvIdentifier($approvalNumber), @@ -1706,6 +3422,9 @@ class Pages extends Controller ]); $syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null]; $pagePaymentAmount = '0.00'; + $filteredPaymentAmount = '0.00'; + $shopNames = []; + $paymentReasons = []; $error = null; $pending = false; $indexPending = false; @@ -1730,6 +3449,10 @@ class Pages extends Controller ['path' => $request->url(), 'query' => $request->query()], ); $pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00'); + $filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00'); + $filterOptions = $this->smallPaymentWorkOrders->filterOptions(); + $shopNames = $filterOptions['shops']; + $paymentReasons = $filterOptions['payment_reasons']; } } } catch (Throwable $exception) { @@ -1743,6 +3466,13 @@ class Pages extends Controller 'rows' => $rows, 'smallPaymentSyncStatus' => $syncStatus, 'smallPaymentPageAmount' => $pagePaymentAmount, + 'smallPaymentFilteredAmount' => $filteredPaymentAmount, + 'smallPaymentShops' => $shopNames, + 'smallPaymentReasons' => $paymentReasons, + 'smallPaymentStatuses' => [ + '待审核', '审核驳回', '待确认', '确认中', '已完成', '已作废', + '支付宝已打款', '银行卡已打款', '已打款', + ], 'smallPaymentError' => $error, 'smallPaymentPending' => $pending, 'smallPaymentIndexPending' => $indexPending, @@ -1791,12 +3521,15 @@ class Pages extends Controller */ private function smallPaymentWorkOrderFilters(Request $request): array { - $defaultTo = now()->toDateString(); - $defaultFrom = now()->subDays(29)->toDateString(); - $from = $this->dateFilter($request->query('from', $defaultFrom)) ?: $defaultFrom; - $to = $this->dateFilter($request->query('to', $defaultTo)) ?: $defaultTo; + $defaultTo = now()->format('Y-m-d') . 'T23:59:59'; + $defaultFrom = now()->subDays(29)->format('Y-m-d') . 'T00:00:00'; + $rawFrom = $request->query('from', $defaultFrom); + $rawTo = $request->query('to', $defaultTo); + $from = $this->smallPaymentDateTimeFilter($rawFrom, false) ?: $defaultFrom; + $to = $this->smallPaymentDateTimeFilter($rawTo, true) ?: $defaultTo; if ($from > $to) { - [$from, $to] = [$to, $from]; + $from = $this->smallPaymentDateTimeFilter($rawTo, false) ?: $defaultFrom; + $to = $this->smallPaymentDateTimeFilter($rawFrom, true) ?: $defaultTo; } $text = static fn (mixed $value, int $length = 100): string => mb_substr(trim((string) $value), 0, $length); @@ -1813,6 +3546,35 @@ class Pages extends Controller ]; } + private function smallPaymentDateTimeFilter(mixed $value, bool $upperBound): string + { + $value = trim((string) $value); + if (preg_match('/^(\d{4}-\d{2}-\d{2})$/', $value, $dateMatch) === 1) { + if ($this->dateFilter($dateMatch[1]) === '') { + return ''; + } + + return $dateMatch[1] . ($upperBound ? 'T23:59:59' : 'T00:00:00'); + } + + if (preg_match( + '/^(\d{4}-\d{2}-\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?$/', + $value, + $matches, + ) !== 1 || $this->dateFilter($matches[1]) === '') { + return ''; + } + + $hour = (int) $matches[2]; + $minute = (int) $matches[3]; + $second = isset($matches[4]) ? (int) $matches[4] : ($upperBound ? 59 : 0); + if ($hour > 23 || $minute > 59 || $second > 59) { + return ''; + } + + return sprintf('%sT%02d:%02d:%02d', $matches[1], $hour, $minute, $second); + } + private function streamSmallPaymentWorkOrderCsv(iterable $rows, array $filters, array $redirectParameters, mixed $requestedFields = null) { $columns = [ @@ -1873,10 +3635,13 @@ class Pages extends Controller ->with('error', '小额打款工单导出暂时无法完成,请稍后重试。'); } + $filenameFrom = str_replace(['T', ':'], ['_', '-'], $filters['from']); + $filenameTo = str_replace(['T', ':'], ['_', '-'], $filters['to']); + return response()->streamDownload(function () use ($csv): void { fpassthru($csv); fclose($csv); - }, 'small_payment_work_orders_' . $filters['from'] . '_' . $filters['to'] . '.csv', [ + }, 'small_payment_work_orders_' . $filenameFrom . '_' . $filenameTo . '.csv', [ 'Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store', ]); @@ -2446,10 +4211,16 @@ class Pages extends Controller ['filters' => $filters, 'page' => $page, 'limit' => $limit], fn () => $this->supplierPayableReports->boardDeductions($filters, $page, $limit), ); + $rows = $this->supplierPayableOverrides->decorate( + 'board-deductions', + (array) ($result['rows'] ?? []), + (int) (company_id() ?: 1), + ); return [ - 'boardDeductions' => $this->supplierPayablePaginator((array) ($result['rows'] ?? []), $limit, $page), + 'boardDeductions' => $this->supplierPayablePaginator($rows, $limit, $page), 'boardDeductionFilters' => $filters, + 'supplierPayableMaintenance' => $this->supplierPayableMaintenance->publicDefinition('board-deductions'), 'boardDeductionStatus' => $cache->responseHeaders(), 'boardDeductionError' => null, ]; @@ -2457,6 +4228,7 @@ class Pages extends Controller return [ 'boardDeductions' => $this->supplierPayablePaginator([], $limit, $page), 'boardDeductionFilters' => $filters, + 'supplierPayableMaintenance' => $this->supplierPayableMaintenance->publicDefinition('board-deductions'), 'boardDeductionStatus' => [], 'boardDeductionError' => $exception->getMessage(), ]; @@ -2466,6 +4238,7 @@ class Pages extends Controller return [ 'boardDeductions' => $this->supplierPayablePaginator([], $limit, $page), 'boardDeductionFilters' => $filters, + 'supplierPayableMaintenance' => $this->supplierPayableMaintenance->publicDefinition('board-deductions'), 'boardDeductionStatus' => [], 'boardDeductionError' => '板材扣款数据暂时无法读取,请稍后重试。', ]; @@ -2491,10 +4264,16 @@ class Pages extends Controller ['filters' => $filters, 'page' => $page, 'limit' => $limit], fn () => $this->supplierPayableReports->supplierPayables($filters, $page, $limit), ); + $rows = $this->supplierPayableOverrides->decorate( + 'supplier-payables-report', + (array) ($result['rows'] ?? []), + (int) (company_id() ?: 1), + ); return [ - 'supplierPayables' => $this->supplierPayablePaginator((array) ($result['rows'] ?? []), $limit, $page), + 'supplierPayables' => $this->supplierPayablePaginator($rows, $limit, $page), 'supplierPayableFilters' => $filters, + 'supplierPayableMaintenance' => $this->supplierPayableMaintenance->publicDefinition('supplier-payables-report'), 'supplierPayableStatus' => $cache->responseHeaders(), 'supplierPayableError' => null, ]; @@ -2502,6 +4281,7 @@ class Pages extends Controller return [ 'supplierPayables' => $this->supplierPayablePaginator([], $limit, $page), 'supplierPayableFilters' => $filters, + 'supplierPayableMaintenance' => $this->supplierPayableMaintenance->publicDefinition('supplier-payables-report'), 'supplierPayableStatus' => [], 'supplierPayableError' => $exception->getMessage(), ]; @@ -2511,6 +4291,7 @@ class Pages extends Controller return [ 'supplierPayables' => $this->supplierPayablePaginator([], $limit, $page), 'supplierPayableFilters' => $filters, + 'supplierPayableMaintenance' => $this->supplierPayableMaintenance->publicDefinition('supplier-payables-report'), 'supplierPayableStatus' => [], 'supplierPayableError' => '供应商应付数据暂时无法读取,请稍后重试。', ]; @@ -2595,6 +4376,11 @@ class Pages extends Controller 'initialized' => false, 'last_succeeded_at' => null, ], + 'productCatalogJushuitanCostPriceHistorySyncStatus' => $result['jushuitan_cost_price_history_sync_status'] ?? [ + 'code' => 'unavailable', + 'initialized' => false, + 'last_succeeded_at' => null, + ], ]; } catch (Throwable $exception) { report($exception); @@ -2789,6 +4575,31 @@ class Pages extends Controller return preg_match('/^[=+\-@]/u', $text) === 1 ? "'" . $text : $text; } + /** + * XLSX 文本单元格值:空值返回 null(跳过单元格)。 + * 文本单元格不会被当作公式执行,因此不需要 csvText 的公式前缀保护。 + */ + private function xlsxText(mixed $value): ?string + { + $text = trim((string) ($value ?? '')); + + return $text === '' ? null : $text; + } + + /** + * XLSX 日期时间单元格值:去掉 SQL Server 微秒尾缀(.000000),空值返回 null。 + */ + private function xlsxDateTime(mixed $value): ?string + { + $text = trim((string) ($value ?? '')); + + if ($text === '') { + return null; + } + + return preg_replace('/\.\d{1,6}$/', '', $text) ?? $text; + } + /** * Keep client-selected exports within the fields declared by the page. * An omitted or invalid selection falls back to the complete safe schema. @@ -2874,6 +4685,11 @@ class Pages extends Controller 'initialized' => false, 'last_succeeded_at' => null, ], + 'productCatalogJushuitanCostPriceHistorySyncStatus' => [ + 'code' => 'unavailable', + 'initialized' => false, + 'last_succeeded_at' => null, + ], ]; } @@ -3000,6 +4816,317 @@ class Pages extends Controller ); } + protected function contentForReturnPickupManagement(): array + { + $filters = $this->returnPickupFilters(request()); + $page = max((int) request('pickup_page', 1), 1); + $limit = min(max((int) setting('default.list_limit', 25), 1), 100); + $repository = app(\Modules\EcommerceFinance\Repositories\ReturnPickupManagementMirrorRepository::class); + $rows = null; + $state = null; + $syncStatus = ['code' => 'unavailable', 'lag_minutes' => null]; + $error = null; + $pending = false; + $carriers = []; + $statuses = []; + $detail = null; + + try { + if (! $repository->available()) { + $error = '共享业务镜像尚未建立,退货取件管理暂时无法读取。'; + } else { + $state = $repository->state(); + $syncStatus = $repository->syncStatus($state); + + if (! $repository->ready()) { + $pending = true; + $error = '退货取件管理正在执行首次全量同步,完成前不会把未同步数据误判为无数据。'; + } else { + $result = $repository->paginate($filters, $page, $limit); + $rows = new LengthAwarePaginator( + Collection::make($result['data'] ?? []), + (int) ($result['total'] ?? 0), + $limit, + $page, + [ + 'path' => request()->url(), + 'query' => request()->except('pickup_page'), + ], + ); + $carriers = $repository->carriers(); + $statuses = $repository->statuses(); + + $detailId = (int) request('pickup_id', 0); + + if ($detailId > 0) { + $detail = $this->enrichReturnPickupDetail( + $repository->detail($detailId), + $repository->warehouseDirectory(), + ); + } + } + } + } catch (Throwable $exception) { + report($exception); + $error = '退货取件管理共享镜像暂时无法读取,请稍后重试。'; + } + + return [ + 'view' => 'business.pages.courier-payables.return-pickup-management', + 'returnPickupFilters' => $filters, + 'returnPickupRows' => $rows, + 'returnPickupState' => $state, + 'returnPickupSyncStatus' => $syncStatus, + 'returnPickupError' => $error, + 'returnPickupPending' => $pending, + 'returnPickupCarriers' => $carriers, + 'returnPickupStatuses' => $statuses, + 'returnPickupDetail' => $detail, + ]; + } + + /** @return array */ + private function returnPickupFilters(Request $request): array + { + $filters = [ + 'created_from' => $this->dateFilter($request->query('created_from')), + 'created_to' => $this->dateFilter($request->query('created_to')), + 'carrier' => mb_substr(trim((string) $request->query('carrier', '')), 0, 64), + 'status' => mb_substr(trim((string) $request->query('status', '')), 0, 64), + 'shop' => mb_substr(trim((string) $request->query('shop', '')), 0, 191), + 'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 100), + ]; + + if ($filters['created_from'] !== '' + && $filters['created_to'] !== '' + && $filters['created_from'] > $filters['created_to']) { + [$filters['created_from'], $filters['created_to']] = [ + $filters['created_to'], + $filters['created_from'], + ]; + } + + return $filters; + } + + /** + * 用逆向物流报价为退货取件明细补「实际运费」和「差异(预估−实际)」。 + * + * @param array{main:object,items:list,truth_numbers:list}|null $detail + * @param array $warehouseDirectory 发货仓编码 → 名称 + * @return array|null + */ + private function enrichReturnPickupDetail(?array $detail, array $warehouseDirectory = []): ?array + { + if ($detail === null) { + return null; + } + + try { + $calculator = app(\App\Support\ReturnPickupFreightCalculator::class); + } catch (Throwable $exception) { + report($exception); + $calculator = null; + } + + $main = $detail['main']; + $items = []; + $estimatedTotal = 0.0; + $actualTotal = 0.0; + $surchargeTotal = 0.0; + $hasActual = false; + + foreach ($detail['items'] as $item) { + $result = $calculator?->calculate( + $main->express_company ?? null, + $main->province ?? null, + $item->receiverAddress ?? null, + (float) ($item->grossWeight ?? 0), + $item->length ?? null, + $item->width ?? null, + $item->height ?? null, + ) ?? ['covered' => false, 'reason' => '逆向物流报价快照不可用', 'total' => null, 'surcharge' => 0.0, 'billable' => null, 'formula' => null, 'note' => null, 'surcharge_note' => null]; + + $estimated = $item->estimatedFreight !== null ? (float) $item->estimatedFreight : null; + $actual = $result['total'] !== null ? (float) $result['total'] : null; + $surcharge = (float) ($result['surcharge'] ?? 0); + $values = (array) $item; + $values['actual_freight'] = $actual; + $values['freight_surcharge'] = $surcharge; + $values['freight_settlement'] = $result['settlement']; + $values['freight_base_amount'] = $result['base_amount']; + $values['freight_increment_amount'] = $result['increment_amount']; + $values['freight_billable'] = $result['billable']; + $values['freight_formula'] = $result['formula']; + $values['freight_note'] = $result['covered'] + ? trim(($result['note'] ?? '') . ($result['surcharge_note'] !== null ? ';' . $result['surcharge_note'] : '')) + : $result['reason']; + $values['freight_process'] = $result['process'] ?? $result['reason']; + $values['freight_covered'] = $result['covered']; + $values['freight_diff'] = ($estimated !== null && $actual !== null) ? round($estimated - $actual, 2) : null; + $warehouseCode = trim((string) ($values['warehouse'] ?? '')); + $values['warehouse_name'] = $warehouseCode === '' + ? null + : ($warehouseDirectory[$warehouseCode] ?? null); + $items[] = (object) $values; + + if ($estimated !== null) { + $estimatedTotal += $estimated; + } + + if ($actual !== null) { + $actualTotal += $actual; + $hasActual = true; + } + + $surchargeTotal += $surcharge; + } + + $detail['items'] = $items; + $detail['totals'] = [ + 'estimated' => round($estimatedTotal, 2), + 'actual' => $hasActual ? round($actualTotal, 2) : null, + 'surcharge' => round($surchargeTotal, 2), + 'diff' => $hasActual ? round($estimatedTotal - $actualTotal, 2) : null, + ]; + + return $detail; + } + + public function exportReturnPickupManagement(Request $request): StreamedResponse + { + $filters = $this->returnPickupFilters($request); + $repository = app(\Modules\EcommerceFinance\Repositories\ReturnPickupManagementMirrorRepository::class); + $calculator = app(\App\Support\ReturnPickupFreightCalculator::class); + $limit = 50000; + + return response()->streamDownload(function () use ($filters, $repository, $calculator, $limit): void { + $writer = new \App\Support\StreamingXlsxWriter('退货取件明细'); + + $writer->appendRow([ + '订单号', '快递公司', '订单状态', '紧急程度', '店铺名称', '交易单号', '出发省', '到达省', + '应退货号', '实退货号', '条形码', '品名', '平台商品id', '平台skuid', + '应退数量', '实退数量', '待核销数量', '总件数', '长', '宽', '高', + '毛重(kg)', '体积重(kg)', '重量取大(kg)', '计费重量(kg)', '面单(元)', '费率(元/kg)', + '预估运费(元)', '实际运费(元)', '加收(元)', '差异(元)', + '明细退货进度', '发货仓', '收货人', '收货电话', '收货地址', '实退单号', '实退快递单号', + '预计取件时间', '退货进度', '付款方式', '取件类型', '发件人姓名', '备注', + '问题类型', '问题描述', '问题跟进状态', '问题跟进结果', '问题跟进说明', + '快递下单时间', '快递取件时间', '创建人', '取消人', '创建时间', '更新时间', + ]); + + $warehouseDirectory = $repository->warehouseDirectory(); + $number = static fn (?float $value): ?float => $value === null ? null : round($value, 2); + $quantity = static fn (mixed $value): ?int => $value === null ? null : (int) $value; + $exported = 0; + + foreach ($repository->exportRows($filters, $limit) as $row) { + $length = (float) ($row->length ?? 0); + $width = (float) ($row->width ?? 0); + $height = (float) ($row->height ?? 0); + $volumeWeight = ($length > 0 && $width > 0 && $height > 0) + ? round($length * $width * $height / 6000, 2) + : null; + $result = $calculator->calculate( + $row->express_company ?? null, + $row->province ?? null, + $row->receiverAddress ?? null, + (float) ($row->grossWeight ?? 0), + $length, + $width, + $height, + ); + $estimated = $row->estimatedFreight !== null ? round((float) $row->estimatedFreight, 2) : null; + $actual = $result['total']; + $warehouseCode = trim((string) ($row->warehouse ?? '')); + $followStatus = $this->xlsxText($row->expressFollowStatus ?? ''); + $followResult = $this->xlsxText($row->expressFollowResult ?? ''); + $returnProgress = $followStatus === null + ? $followResult + : ($followResult === null ? $followStatus : $followStatus . '(' . $followResult . ')'); + + $writer->appendRow([ + $this->xlsxText($row->orderId ?? ''), + $this->xlsxText($row->express_company ?? ''), + $this->xlsxText(\App\Support\ReturnPickupOrderStatus::label($row->orderStatus ?? null)), + $this->xlsxText($row->urgencyLevel ?? ''), + $this->xlsxText($row->shopName ?? ''), + $this->xlsxText($row->transactionNo ?? ''), + $this->xlsxText($row->province ?? ''), + $this->xlsxText($result['covered'] + ? \App\Support\ReverseLogisticsQuoteSnapshot::provinceKey( + \App\Support\ReturnPickupFreightCalculator::destinationProvince((string) ($row->receiverAddress ?? '')) + ) + : ''), + $this->xlsxText($row->returnProcode ?? ''), + $this->xlsxText($row->actualReturnProcode ?? ''), + $this->xlsxText($row->barcode ?? ''), + $this->xlsxText($row->productName ?? ''), + $this->xlsxText($row->platformProductId ?? ''), + $this->xlsxText($row->platformSkuId ?? ''), + $quantity($row->returnQuantity ?? null), + $quantity($row->actualReturnQuantity ?? null), + $quantity($row->unverifiedQuantity ?? null), + $quantity($row->totalReturnQuantity ?? null), + $number($length > 0 ? $length : null), + $number($width > 0 ? $width : null), + $number($height > 0 ? $height : null), + $number($row->grossWeight !== null ? (float) $row->grossWeight : null), + $number($volumeWeight), + $number($result['settlement']), + $number($result['billable']), + $number($result['base_amount']), + $number($result['increment_amount']), + $number($estimated), + $number($actual), + $number(($result['surcharge'] ?? 0) > 0 ? (float) $result['surcharge'] : null), + $number($estimated !== null && $actual !== null ? round($estimated - $actual, 2) : null), + $this->xlsxText($row->returnProgress ?? ''), + $this->xlsxText($warehouseCode === '' ? '' : ($warehouseDirectory[$warehouseCode] ?? $warehouseCode)), + $this->xlsxText($row->receiverName ?? ''), + $this->xlsxText($row->receiverPhone ?? ''), + $this->xlsxText($row->receiverAddress ?? ''), + $this->xlsxText($row->actualReturnOrderNo ?? ''), + $this->xlsxText($row->returnExpressNo ?? ''), + $this->xlsxDateTime($row->expectedPickupTime ?? null), + $this->xlsxText($returnProgress ?? ''), + $this->xlsxText($row->paymentMethod ?? ''), + $this->xlsxText($row->pickupType ?? ''), + $this->xlsxText($row->senderName ?? ''), + $this->xlsxText($row->note ?? ''), + $this->xlsxText($row->issueType ?? ''), + $this->xlsxText($row->issueDescription ?? ''), + $this->xlsxText($row->expressFollowStatus ?? ''), + $this->xlsxText($row->expressFollowResult ?? ''), + $this->xlsxText($row->expressFollowDescription ?? ''), + $this->xlsxDateTime($row->expressOrderTime ?? null), + $this->xlsxDateTime($row->expressPickupTime ?? null), + $this->xlsxText($row->creator ?? ''), + $this->xlsxText($row->canceler ?? ''), + $this->xlsxDateTime($row->createTime ?? null), + $this->xlsxDateTime($row->updateTime ?? null), + ]); + $exported++; + } + + if ($exported >= $limit) { + $writer->appendRow(['(已按上限截断,仅导出前 ' . $limit . ' 行,请缩小筛选范围后重试)']); + } + + $output = fopen('php://output', 'wb'); + + if ($output === false) { + throw new RuntimeException('无法创建退货取件管理导出流。'); + } + + $writer->writeTo($output); + fclose($output); + }, '退货取件管理_' . now()->format('Ymd_His') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } + protected function contentForProductPrices(): array { $filters = [ diff --git a/app/Http/Controllers/Business/PayablesFinalActions.php b/app/Http/Controllers/Business/PayablesFinalActions.php new file mode 100644 index 00000000..c8112f22 --- /dev/null +++ b/app/Http/Controllers/Business/PayablesFinalActions.php @@ -0,0 +1,152 @@ +:<页面>),初始为空,由页面上的导入、导出、查询、编辑维护。 + */ +class PayablesFinalActions extends Controller +{ + public const DATASET_PREFIX = 'final:'; + + public function __construct( + private readonly PayablesFinalRegistry $registry, + private readonly SupplierPayableImportTemplate $template, + private readonly SupplierPayableOverrideStore $overrides, + private readonly PayablesFinalImporter $importer, + private readonly PayablesFieldNormalizer $normalizer, + ) { + $this->middleware('auth'); + $this->middleware('company.identify'); + } + + public function definition(Request $request): JsonResponse + { + return response()->json([ + 'dataset' => $this->dataset($request), + 'fields' => collect($this->fields($request)) + ->map(static fn (array $definition, string $name): array => ['name' => $name] + $definition) + ->values() + ->all(), + ]); + } + + public function template(Request $request): StreamedResponse + { + return $this->template->download( + $this->registry->title($this->section($request), $this->dataset($request)), + $this->fields($request), + true, + ); + } + + public function import(Request $request): JsonResponse|RedirectResponse + { + $request->validate(['import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:10240']]); + $result = $this->importer->import( + $this->fields($request), + $this->storeDataset($request), + $request->file('import'), + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + ); + $message = "导入完成:新增 {$result['created']} 条,更新 {$result['updated']} 条。"; + + return $request->expectsJson() + ? response()->json(['message' => $message] + $result) + : back()->with('success', $message); + } + + public function update(Request $request, string $recordKey): JsonResponse|RedirectResponse + { + $values = $this->normalizer->normalize($this->fields($request), (array) $request->input('values', [])); + $result = $this->overrides->save( + $this->storeDataset($request), + $recordKey, + $values, + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + ); + + return $request->expectsJson() + ? response()->json(['message' => '保存成功。'] + $result) + : back()->with('success', '保存成功。'); + } + + public function export(Request $request): StreamedResponse + { + $fields = $this->fields($request); + $title = $this->registry->title($this->section($request), $this->dataset($request)); + $rows = $this->overrides->listRows($this->storeDataset($request), (int) (company_id() ?: 1)); + + return response()->streamDownload(function () use ($rows, $fields): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new RuntimeException('无法创建导出文件。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_merge(['记录标识'], array_column($fields, 'label'))); + + foreach ($rows as $row) { + $values = [$this->csvText($row['_action_key'] ?? '')]; + foreach ($fields as $field => $definition) { + $value = $row[$field] ?? ''; + $values[] = $definition['type'] === 'number' && is_numeric($value) + ? $value + : $this->csvText($value); + } + fputcsv($csv, $values); + } + fclose($csv); + }, $title . '_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + private function section(Request $request): string + { + return (string) $request->route('finalSection'); + } + + private function dataset(Request $request): string + { + $dataset = (string) $request->route('dataset'); + $this->registry->title($this->section($request), $dataset); + + return $dataset; + } + + /** @return array */ + private function fields(Request $request): array + { + return $this->registry->fields($this->section($request), $this->dataset($request)); + } + + private function storeDataset(Request $request): string + { + $section = $this->section($request) === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier'; + + return self::DATASET_PREFIX . $section . ':' . $this->dataset($request); + } + + private function csvText(mixed $value): string + { + $value = (string) $value; + + return preg_match('/^[=+\-@\t\r]/u', $value) === 1 ? "\t" . $value : $value; + } +} diff --git a/app/Http/Controllers/Business/ProductPrices.php b/app/Http/Controllers/Business/ProductPrices.php new file mode 100644 index 00000000..44a90f55 --- /dev/null +++ b/app/Http/Controllers/Business/ProductPrices.php @@ -0,0 +1,196 @@ +middleware('auth'); + $this->middleware('company.identify'); + } + + public function export(Request $request): StreamedResponse|RedirectResponse + { + if (! $this->repository->ready() || ! $this->repository->initialized()) { + return $this->redirectToPage($request) + ->with('error', '商品价格镜像尚未完成首次同步,暂时不能导出。'); + } + + $filters = $this->filters($request); + $companyId = (int) (company_id() ?: 1); + + return response()->streamDownload(function () use ($filters, $companyId): void { + $csv = fopen('php://output', 'w'); + + if ($csv === false) { + throw new RuntimeException('无法创建商品价格导出流。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, [ + '记录标识', '业务编号', '商品编码', 'SPU', '商品名称', '类目', '生产状态', + '最低售价', '计算限价', '采购价', '运费', '京喜限价', '流程状态', + '审批结果', '流程标题', '流程完成时间', '人工维护', '维护时间', + ]); + + foreach ($this->repository->exportRows($filters, $companyId) as $row) { + fputcsv($csv, [ + $this->csvText($row->upstream_key ?? ''), + $this->csvText($row->business_id ?? ''), + $this->csvText($row->barcode ?? ''), + $this->csvText($row->spu ?? ''), + $this->csvText($row->product_name ?? ''), + $this->csvText($row->category ?? ''), + $this->csvText($row->production_status ?? ''), + $row->minimum_price ?? null, + $row->price_limit ?? null, + $row->purchase_price ?? null, + $row->shipping_fee ?? null, + $row->jingxi_limit_price ?? null, + $this->csvText($row->approval_status ?? ''), + $this->csvText($row->approval_result ?? ''), + $this->csvText($row->workflow_title ?? ''), + $this->csvText($row->completed_at ?? ''), + (int) ($row->is_overridden ?? 0) === 1 ? '是' : '否', + $this->csvText($row->override_updated_at ?? ''), + ]); + } + + fclose($csv); + }, '商品价格_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + public function import(Request $request): RedirectResponse + { + $request->validate([ + 'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:10240'], + ]); + + $result = $this->importer->import( + $request->file('import'), + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + ); + + return $this->redirectToPage($request)->with( + 'success', + "导入完成:新增维护 {$result['created']} 条,更新维护 {$result['updated']} 条。", + ); + } + + public function template(): StreamedResponse + { + return $this->template->download('商品价格', $this->importer->templateFields()); + } + + public function update(Request $request, string $upstreamKey): RedirectResponse + { + $values = $request->validate( + [ + 'barcode' => ['required', 'string', 'max:191'], + 'spu' => ['nullable', 'string', 'max:191'], + 'product_name' => ['nullable', 'string', 'max:5000'], + 'category' => ['nullable', 'string', 'max:255'], + 'production_status' => ['nullable', 'string', 'max:120'], + 'minimum_price' => ['nullable', 'numeric', 'decimal:0,4', 'min:0', 'max:9999999999999999.9999'], + 'price_limit' => ['nullable', 'numeric', 'decimal:0,4', 'min:0', 'max:9999999999999999.9999'], + 'purchase_price' => ['nullable', 'numeric', 'decimal:0,4', 'min:0', 'max:9999999999999999.9999'], + 'shipping_fee' => ['nullable', 'numeric', 'decimal:0,4', 'min:0', 'max:9999999999999999.9999'], + 'jingxi_limit_price' => ['nullable', 'numeric', 'decimal:0,4', 'min:0', 'max:9999999999999999.9999'], + ], + [ + 'minimum_price.decimal' => '最低售价最多支持 4 位小数。', + 'price_limit.decimal' => '计算限价最多支持 4 位小数。', + 'purchase_price.decimal' => '采购价最多支持 4 位小数。', + 'shipping_fee.decimal' => '运费最多支持 4 位小数。', + 'jingxi_limit_price.decimal' => '京喜限价最多支持 4 位小数。', + ], + ); + + try { + $this->repository->applyOverrides( + [$upstreamKey => $values], + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + 'manual', + ); + } catch (RuntimeException $exception) { + if (str_starts_with($exception->getMessage(), 'product_price_record_not_found:')) { + abort(404, '商品价格记录不存在。'); + } + + if ($exception->getMessage() === 'product_price_maintenance_schema_missing') { + throw ValidationException::withMessages([ + 'barcode' => '商品价格维护功能尚未完成初始化,请稍后重试。', + ]); + } + + throw $exception; + } + + return $this->redirectToPage($request)->with('success', '商品价格已保存。'); + } + + /** @return array{barcode:string,completed_from:string,completed_to:string} */ + private function filters(Request $request): array + { + return [ + 'barcode' => mb_substr(trim((string) $request->query('barcode', '')), 0, 191), + 'completed_from' => $this->date((string) $request->query('completed_from', '')), + 'completed_to' => $this->date((string) $request->query('completed_to', '')), + ]; + } + + private function redirectToPage(Request $request): RedirectResponse + { + $filters = $this->filters($request); + $query = array_filter([ + ...$filters, + 'page' => max((int) $request->query('page', 1), 1), + ], static fn (mixed $value): bool => $value !== ''); + $url = route('business.pages.show', [ + 'company_id' => company_id() ?: 1, + 'section' => 'supplier-payables', + 'page' => 'product-prices', + ]); + + return redirect()->to($url . ($query === [] ? '' : '?' . http_build_query($query))); + } + + private function date(string $value): string + { + $value = trim($value); + + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return ''; + } + + [$year, $month, $day] = array_map('intval', explode('-', $value)); + + return checkdate($month, $day, $year) ? $value : ''; + } + + private function csvText(mixed $value): string + { + $value = (string) $value; + + return preg_match('/^[=+\-@\t\r]/u', $value) === 1 ? "\t" . $value : $value; + } +} diff --git a/app/Http/Controllers/Business/SupplierPayableActions.php b/app/Http/Controllers/Business/SupplierPayableActions.php new file mode 100644 index 00000000..520315f8 --- /dev/null +++ b/app/Http/Controllers/Business/SupplierPayableActions.php @@ -0,0 +1,196 @@ +middleware('auth'); + $this->middleware('company.identify'); + } + + public function definition(Request $request): JsonResponse + { + return response()->json($this->registry->publicDefinition($this->dataset($request))); + } + + public function update(Request $request, string $recordKey): JsonResponse|RedirectResponse + { + $dataset = $this->dataset($request); + $values = $this->registry->normalize($dataset, (array) $request->input('values', [])); + $result = $this->overrides->save( + $dataset, + $recordKey, + $values, + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + ); + + return $request->expectsJson() + ? response()->json(['message' => '保存成功。'] + $result) + : back()->with('success', '保存成功。'); + } + + public function import(Request $request): JsonResponse|RedirectResponse + { + $request->validate(['import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:10240']]); + $result = $this->importer->import( + $this->dataset($request), + $request->file('import'), + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + ); + $message = "导入完成:新增维护 {$result['created']} 条,更新维护 {$result['updated']} 条。"; + + return $request->expectsJson() + ? response()->json(['message' => $message] + $result) + : back()->with('success', $message); + } + + public function template(Request $request): StreamedResponse + { + $dataset = $this->dataset($request); + + return $this->template->download($this->title($dataset), $this->registry->fields($dataset)); + } + + public function export(Request $request): StreamedResponse + { + $dataset = $this->dataset($request); + $fields = $this->registry->fields($dataset); + $filters = $this->filters($dataset, $request); + $companyId = (int) (company_id() ?: 1); + + return response()->streamDownload(function () use ($dataset, $fields, $filters, $companyId): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new RuntimeException('无法创建导出文件。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_merge(['记录标识'], array_column($fields, 'label'))); + + foreach ($this->allRows($dataset, $filters) as $batch) { + foreach ($this->overrides->decorate($dataset, $batch, $companyId) as $row) { + $values = [$this->csvText($row['_action_key'] ?? '')]; + foreach ($fields as $field => $definition) { + $values[] = $definition['type'] === 'number' && is_numeric($row[$field] ?? null) + ? $row[$field] + : $this->csvText($row[$field] ?? ''); + } + fputcsv($csv, $values); + } + } + fclose($csv); + }, $this->title($dataset) . '_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return iterable>> */ + private function allRows(string $dataset, array $filters): iterable + { + if ($dataset === 'payment-reconciliation' && ($filters['record_type'] ?? 'all') === 'all') { + foreach (['purchase', 'sale'] as $type) { + yield from $this->allRows($dataset, array_replace($filters, ['record_type' => $type])); + } + return; + } + + $page = 1; + do { + $result = $this->page($dataset, $filters, $page, 100); + $rows = array_slice((array) ($result['data'] ?? $result['rows'] ?? []), 0, 100); + if ($rows !== []) { + yield $rows; + } + $total = (int) ($result['total'] ?? -1); + $more = $rows !== [] && ($total < 0 ? count($rows) === 100 : $page * 100 < $total); + $page++; + } while ($more); + } + + private function page(string $dataset, array $filters, int $page, int $limit): array + { + return match ($dataset) { + 'payment-reconciliation' => $this->goods->list($filters, $page, $limit), + 'return-reconciliation' => $this->supplier->returnReconciliations($filters, $page, $limit), + 'invoice-deductions' => $this->supplier->invoiceDeductions($filters, $page, $limit), + 'compensation-details' => $this->supplier->compensationDetails($filters, $page, $limit), + 'advance-details' => $this->supplier->advanceDetails($filters, $page, $limit), + 'sample-deductions' => $this->supplier->sampleDeductions($filters, $page, $limit), + 'delivery-unpriced' => $this->supplier->deliveryUnpriced($filters, $page, $limit), + 'return-unpriced' => $this->supplier->returnUnpriced($filters, $page, $limit), + 'other-adjustments' => $this->supplier->otherAdjustments($filters, $page, $limit), + 'dropshipping-express' => $this->supplier->dropshippingExpress($filters, $page, $limit), + 'board-deductions' => $this->reports->boardDeductions($filters, $page, $limit), + 'supplier-payables-report' => $this->reports->supplierPayables($filters, $page, $limit), + }; + } + + private function filters(string $dataset, Request $request): array + { + $allowed = match ($dataset) { + 'payment-reconciliation' => ['record_type', 'supplier', 'warehouse', 'stock_no', 'purchase_no', 'product_code', 'express_no', 'send_time_from', 'send_time_to', 'create_time_from', 'create_time_to', 'sent_status', 'has_diff'], + 'return-reconciliation', 'return-unpriced' => ['supplier', 'warehouse', 'sku_id', 'express_no', 'date_from', 'date_to'], + 'invoice-deductions', 'compensation-details', 'advance-details', 'other-adjustments' => ['supplier', 'month_from', 'month_to'], + 'sample-deductions' => ['supplier', 'department', 'creator', 'sku_id', 'date_from', 'date_to'], + 'delivery-unpriced' => ['supplier', 'warehouse', 'purchase', 'barcode', 'express_no', 'date_from', 'date_to'], + 'dropshipping-express' => ['supplier', 'express_name', 'month_from', 'month_to'], + 'board-deductions' => ['stock_in_date', 'stock_out_date', 'furniture_factory', 'lamination_factory', 'deduction_type', 'material_name', 'claim_number'], + 'supplier-payables-report' => ['month', 'supplier', 'checker', 'settlement_method'], + }; + + return collect($request->only($allowed)) + ->map(static fn (mixed $value): mixed => is_string($value) ? trim($value) : $value) + ->reject(static fn (mixed $value): bool => $value === '' || $value === null || $value === false) + ->all(); + } + + private function dataset(Request $request): string + { + $dataset = (string) $request->route('dataset'); + $this->registry->fields($dataset); + return $dataset; + } + + private function title(string $dataset): string + { + return [ + 'payment-reconciliation' => '货款对账', 'return-reconciliation' => '退货对账', + 'invoice-deductions' => '发票扣款', 'compensation-details' => '赔偿明细', + 'advance-details' => '借支明细', 'sample-deductions' => '样品扣款', + 'delivery-unpriced' => '送货未定价', 'return-unpriced' => '退货未定价', + 'other-adjustments' => '其他扣款补款', 'dropshipping-express' => '代发快递', + 'board-deductions' => '板材扣款', 'supplier-payables-report' => '供应商应付表', + ][$dataset]; + } + + private function csvText(mixed $value): string + { + $value = (string) $value; + return preg_match('/^[=+\-@\t\r]/u', $value) === 1 ? "\t" . $value : $value; + } +} diff --git a/app/Http/Controllers/Business/WithdrawalManagement.php b/app/Http/Controllers/Business/WithdrawalManagement.php new file mode 100644 index 00000000..12cd0082 --- /dev/null +++ b/app/Http/Controllers/Business/WithdrawalManagement.php @@ -0,0 +1,106 @@ +middleware('auth'); + $this->middleware('company.identify'); + $this->middleware('business.page:fund-management,withdrawal-management'); + } + + public function export(Request $request): StreamedResponse + { + return $this->spreadsheet->export($this->report->results($request)); + } + + public function template(): StreamedResponse + { + return $this->spreadsheet->template(); + } + + public function importPreview(Request $request): RedirectResponse + { + $file = $request->validate([ + 'import' => ['required', 'file', 'mimes:xlsx,xls', 'max:10240'], + ])['import']; + $preview = $this->spreadsheet->preview($file, (int) company_id()); + $token = Str::random(48); + Cache::put($this->cacheKey($token), [ + 'company_id' => (int) company_id(), + 'user_id' => (int) user_id(), + 'plan' => $preview['plan'], + ], now()->addMinutes(30)); + unset($preview['plan']); + + return $this->redirect($request)->with( + 'withdrawalImportPreview', + $preview + ['token' => $token], + ); + } + + public function importCommit(Request $request): RedirectResponse + { + $token = $request->validate([ + 'preview_token' => ['required', 'string', 'size:48'], + ])['preview_token']; + $payload = Cache::pull($this->cacheKey($token)); + + if (! is_array($payload) + || (int) ($payload['company_id'] ?? 0) !== (int) company_id() + || (int) ($payload['user_id'] ?? 0) !== (int) user_id() + || ! is_array($payload['plan'] ?? null)) { + return $this->redirect($request)->withErrors([ + 'import' => '导入预览已失效或不属于当前账号,请重新上传并预览。', + ]); + } + + $updated = $this->spreadsheet->commit($payload['plan'], (int) company_id()); + + return $this->redirect($request)->with('success', "提现配置导入完成,共更新 {$updated} 家店铺。"); + } + + private function cacheKey(string $token): string + { + return self::PREVIEW_CACHE_PREFIX . hash('sha256', $token); + } + + private function redirect(Request $request): RedirectResponse + { + $filters = $this->report->filters($request); + $parameters = [ + 'section' => 'fund-management', + 'page' => 'withdrawal-management', + ]; + $queryNames = [ + 'platform' => 'platform', + 'withdrawalPath' => 'withdrawal_path', + 'storeEntity' => 'store_entity', + 'keyword' => 'keyword', + 'balanceStatus' => 'balance_status', + ]; + + foreach ($queryNames as $filterName => $queryName) { + if ($filters[$filterName] !== '') { + $parameters[$queryName] = $filters[$filterName]; + } + } + + return redirect()->route('business.pages.show', $parameters); + } +} diff --git a/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php b/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php index 083d837e..3427a468 100644 --- a/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php +++ b/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php @@ -4,6 +4,7 @@ namespace App\Http\Livewire\Business; use App\Business\ThirdPartyWarehouseQuoteRepository; use App\Business\ThirdPartyWarehouseStorageFeeCalculator; +use App\Exports\ThirdPartyWarehouseStorageDetailExport; use App\Exports\ThirdPartyWarehouseStorageSettlementExport; use App\Models\Business\ThirdPartyWarehouseQuote; use App\Models\Business\ThirdPartyWarehouseStorageSettlement; @@ -45,6 +46,15 @@ class ThirdPartyWarehouseQuotes extends Component public ?string $settlementError = null; + public ?string $settlementDetailPeriod = null; + + public string $settlementDetailDate = ''; + + /** @var list */ + public array $settlementDetailDates = []; + + public ?string $settlementDetailMessage = null; + public function mount(): void { $this->effectiveAt = now()->toDateString(); @@ -130,7 +140,11 @@ class ThirdPartyWarehouseQuotes extends Component 'loss_fee' => $summary['loss_fee'], 'compensation_fee' => $summary['compensation_fee'], 'total_fee' => $summary['total_fee'], - 'detail_json' => ['daily' => $result['daily'], 'per_sku' => $result['per_sku']], + 'detail_json' => [ + 'daily' => $result['daily'], + 'per_sku' => $result['per_sku'], + 'daily_sku' => $result['daily_sku'], + ], 'calculated_by' => (int) user_id(), ], ); @@ -144,6 +158,7 @@ class ThirdPartyWarehouseQuotes extends Component $this->ensureAuthenticated(); $settlement = ThirdPartyWarehouseStorageSettlement::query() + ->where('company_id', (int) company_id()) ->where('warehouse_id', self::WAREHOUSE_ID) ->where('period', $period) ->first(); @@ -154,11 +169,12 @@ class ThirdPartyWarehouseQuotes extends Component return null; } - $detail = $settlement->detail_json ?: ['daily' => [], 'per_sku' => []]; + $detail = $settlement->detail_json ?: ['daily' => [], 'per_sku' => [], 'daily_sku' => []]; $result = [ 'summary' => $this->summaryFromSettlement($settlement), 'daily' => $detail['daily'] ?? [], 'per_sku' => $detail['per_sku'] ?? [], + 'daily_sku' => $detail['daily_sku'] ?? [], ]; $fileName = $settlement->warehouse_name . '仓储费用_' . $period . '.xlsx'; @@ -166,11 +182,77 @@ class ThirdPartyWarehouseQuotes extends Component return Excel::download(new ThirdPartyWarehouseStorageSettlementExport($result), $fileName); } + public function exportSettlementDetails(string $period): ?BinaryFileResponse + { + $this->ensureAuthenticated(); + abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422); + + $settlement = $this->settlementForPeriod($period); + if ($settlement === null) { + $this->settlementError = '未找到 ' . $period . ' 的核算存档,请先核算。'; + + return null; + } + + $dailySku = ($settlement->detail_json ?: [])['daily_sku'] ?? []; + if ($dailySku === []) { + $this->showMissingSettlementDetails($period); + + return null; + } + + $fileName = $settlement->warehouse_name . '每日商品仓储费明细_' . $period . '.xlsx'; + + return Excel::download(new ThirdPartyWarehouseStorageDetailExport($dailySku), $fileName); + } + + public function viewSettlementDetails(string $period): void + { + $this->ensureAuthenticated(); + abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422); + + $this->settlementDetailPeriod = $period; + $this->settlementDetailDate = ''; + $this->settlementDetailDates = []; + $this->settlementDetailMessage = null; + + $settlement = $this->settlementForPeriod($period); + if ($settlement === null) { + $this->settlementDetailMessage = '未找到 ' . $period . ' 的核算存档。'; + $this->dispatch('warehouse-settlement-details-opened'); + + return; + } + + $detail = $settlement->detail_json ?: []; + $dailySku = $detail['daily_sku'] ?? []; + if ($dailySku === []) { + $this->showMissingSettlementDetails($period); + + return; + } + + $dates = array_values(array_unique(array_column($dailySku, 'date'))); + sort($dates); + $this->settlementDetailDates = $dates; + $this->settlementDetailDate = $dates[0] ?? ''; + $this->dispatch('warehouse-settlement-details-opened'); + } + + public function closeSettlementDetails(): void + { + $this->settlementDetailPeriod = null; + $this->settlementDetailDate = ''; + $this->settlementDetailDates = []; + $this->settlementDetailMessage = null; + } + public function render(): View { $data = $this->repository()->pageData(); $history = ThirdPartyWarehouseStorageSettlement::query() + ->where('company_id', (int) company_id()) ->where('warehouse_id', self::WAREHOUSE_ID) ->orderByDesc('period') ->limit(24) @@ -184,12 +266,15 @@ class ThirdPartyWarehouseQuotes extends Component 'calculated_at' => optional($row->updated_at)->format('Y-m-d H:i'), ]) ->all(); + $settlementDetail = $this->settlementDetailData(); return view('business.pages.courier-payables.partials.third-party-warehouse-quotes', [ 'warehouseQuotes' => $data['rows'], 'warehouseQuoteSummary' => $data['summary'], 'warehouseQuotesReady' => $data['ready'], 'settlementHistory' => $history, + 'settlementDetailRows' => $settlementDetail['rows'], + 'settlementDetailSummary' => $settlementDetail['summary'], ]); } @@ -219,6 +304,66 @@ class ThirdPartyWarehouseQuotes extends Component ]; } + /** + * 明细行只参与当前服务端渲染,不进入 Livewire 公共快照,避免日期切换时回传整张表。 + * + * @return array{rows:list>,summary:array|null} + */ + private function settlementDetailData(): array + { + $empty = ['rows' => [], 'summary' => null]; + + if ($this->settlementDetailPeriod === null + || ! in_array($this->settlementDetailDate, $this->settlementDetailDates, true)) { + return $empty; + } + + $settlement = $this->settlementForPeriod($this->settlementDetailPeriod); + if ($settlement === null) { + return $empty; + } + + $detail = $settlement->detail_json ?: []; + $rows = array_values(array_filter( + $detail['daily_sku'] ?? [], + fn (array $row): bool => ($row['date'] ?? null) === $this->settlementDetailDate, + )); + usort($rows, static fn (array $left, array $right): int => strcmp( + (string) ($left['sku_code'] ?? ''), + (string) ($right['sku_code'] ?? ''), + )); + + return [ + 'rows' => $rows, + 'summary' => [ + 'sku_count' => count($rows), + 'opening' => array_sum(array_column($rows, 'opening')), + 'net_movement' => array_sum(array_column($rows, 'net_movement')), + 'closing' => array_sum(array_column($rows, 'closing')), + 'storage_fee' => array_sum(array_column($rows, 'storage_fee')), + ], + ]; + } + + private function settlementForPeriod(string $period): ?ThirdPartyWarehouseStorageSettlement + { + return ThirdPartyWarehouseStorageSettlement::query() + ->where('company_id', (int) company_id()) + ->where('warehouse_id', self::WAREHOUSE_ID) + ->where('period', $period) + ->first(); + } + + private function showMissingSettlementDetails(string $period): void + { + $this->settlementPeriod = $period; + $this->settlementDetailPeriod = $period; + $this->settlementDetailDate = ''; + $this->settlementDetailDates = []; + $this->settlementDetailMessage = $period . ' 的原存档没有每日商品明细,请重新核算该月份后查看和导出。'; + $this->dispatch('warehouse-settlement-details-opened'); + } + /** @return array> */ protected function rules(): array { diff --git a/app/Jobs/Common/InventoryReportExport.php b/app/Jobs/Common/InventoryReportExport.php new file mode 100644 index 00000000..f566f45a --- /dev/null +++ b/app/Jobs/Common/InventoryReportExport.php @@ -0,0 +1,83 @@ +company_id = $companyId ?? 1; + $this->onQueue('exports'); + } + + public function handle(ThirdPartyWarehouseStorageMirrorRepository $repository, InventoryWarehouseShortNames $shortNames): void + { + $path = storage_path('app/temp/' . $this->file_name); + File::ensureDirectoryExists(dirname($path)); + + try { + $csv = fopen($path, 'wb'); + if ($csv === false) { + throw new \RuntimeException('无法创建进销存报表导出文件。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_column($this->columns, 'label')); + $names = $shortNames->forCompany($this->company_id); + foreach ($repository->exportMonthlyInventoryReportRows($this->filters) as $row) { + $row = $shortNames->fill($row, $names); + fputcsv($csv, array_map(function (array $column) use ($row): mixed { + $value = data_get($row, $column['name']); + + return $column['name'] === 'product_code' + ? $this->csvIdentifier($value) + : (($column['kind'] ?? null) === 'integer' + ? ($value === null || $value === '' ? '' : $value) + : $this->csvText($value)); + }, $this->columns)); + } + fclose($csv); + + dispatch(new CreateMediableForExport($this->user, $this->file_name, '进销存报表')); + } catch (Throwable $exception) { + if (isset($csv) && is_resource($csv)) { + fclose($csv); + } + @unlink($path); + report($exception); + $this->user->notify(new ExportFailed($exception->getMessage())); + throw $exception; + } + } + + private function csvIdentifier(mixed $value): string + { + $text = trim((string) ($value ?? '')); + + return $text === '' ? '' : "'" . $text; + } + + private function csvText(mixed $value): string + { + return trim((string) ($value ?? '')); + } +} diff --git a/app/Listeners/Menu/ShowInAdmin.php b/app/Listeners/Menu/ShowInAdmin.php index fce6be26..487b36e1 100644 --- a/app/Listeners/Menu/ShowInAdmin.php +++ b/app/Listeners/Menu/ShowInAdmin.php @@ -15,6 +15,16 @@ class ShowInAdmin 'prototype-finance-reports', ]; + /** + * 这些目录以工作区形式进入:侧边栏只保留一个入口,子页面在页面内的横向页签切换。 + */ + private const WORKSPACE_SECTION_SLUGS = [ + 'supplier-payables', + 'courier-payables', + 'supplier-payables-final', + 'courier-payables-final', + ]; + /** * Build the business navigation defined by the imported directory workbook. */ @@ -52,13 +62,7 @@ class ShowInAdmin public static function groupPayables(array $navigation): array { - $legacyKeys = ['supplier-payables-final', 'courier-payables-final']; - $navigation = array_values(array_filter( - $navigation, - static fn (array $section): bool => ! in_array($section['slug'], $legacyKeys, true) - )); - - $keys = ['supplier-payables', 'courier-payables', 'raw-board-payables', + $keys = ['supplier-payables-final', 'courier-payables-final', 'supplier-payables', 'courier-payables', 'raw-board-payables', 'lamination-factory-payables', 'paper-materials', 'edge-banding-materials']; $children = array_values(array_filter($navigation, static fn (array $section): bool => in_array($section['slug'], $keys, true))); if ($children === []) { @@ -114,7 +118,7 @@ class ShowInAdmin : $this->sortByTitleLength($section['pages'] ?? []); $order = ($sectionIndex + 1) * 10; - if (empty($pages) || in_array($section['slug'], ['supplier-payables', 'courier-payables'], true)) { + if (empty($pages) || in_array($section['slug'], self::WORKSPACE_SECTION_SLUGS, true)) { $menu->route( 'business.pages.show', $section['title'], diff --git a/app/Models/Business/CourierAgreementSignature.php b/app/Models/Business/CourierAgreementSignature.php index 8087cced..59190e8a 100644 --- a/app/Models/Business/CourierAgreementSignature.php +++ b/app/Models/Business/CourierAgreementSignature.php @@ -3,6 +3,7 @@ namespace App\Models\Business; use App\Abstracts\Model; +use App\Support\EsignErrorMessage; class CourierAgreementSignature extends Model { @@ -97,11 +98,21 @@ class CourierAgreementSignature extends Model self::STATUS_EXPIRED => '已过期', self::STATUS_REJECTED => '已拒签', self::STATUS_FAILED => '处理失败', - self::STATUS_UNKNOWN => '状态未知,请人工核对', + self::STATUS_UNKNOWN => $this->hasDefinitiveFailure() ? '处理失败' : '状态未知,请人工核对', default => $this->status, }; } + public function hasDefinitiveFailure(): bool + { + return EsignErrorMessage::isDefinitiveFailure($this->last_error); + } + + public function lastErrorSummary(): ?string + { + return EsignErrorMessage::sanitize($this->last_error); + } + public function canSend(): bool { return in_array($this->status, [self::STATUS_PREPARED, self::STATUS_FAILED], true) diff --git a/app/Models/Business/CourierQuoteSignature.php b/app/Models/Business/CourierQuoteSignature.php index 09474c94..9c8b5b91 100644 --- a/app/Models/Business/CourierQuoteSignature.php +++ b/app/Models/Business/CourierQuoteSignature.php @@ -3,6 +3,7 @@ namespace App\Models\Business; use App\Abstracts\Model; +use App\Support\EsignErrorMessage; use Illuminate\Database\Eloquent\Relations\BelongsTo; class CourierQuoteSignature extends Model @@ -65,4 +66,9 @@ class CourierQuoteSignature extends Model return in_array($this->status, [self::STATUS_PREPARED, self::STATUS_FAILED], true) && blank($this->esign_sign_flow_id); } + + public function lastErrorSummary(): ?string + { + return EsignErrorMessage::sanitize($this->last_error); + } } diff --git a/app/Models/Business/CourierSurchargeAuditLog.php b/app/Models/Business/CourierSurchargeAuditLog.php new file mode 100644 index 00000000..70657901 --- /dev/null +++ b/app/Models/Business/CourierSurchargeAuditLog.php @@ -0,0 +1,44 @@ + 'integer', + 'actor_id' => 'integer', + 'target_id' => 'integer', + 'changes' => 'array', + ]; + + public function actor() + { + return $this->belongsTo(user_model_class(), 'actor_id'); + } +} diff --git a/app/Models/Business/CourierSurchargeQuote.php b/app/Models/Business/CourierSurchargeQuote.php index 8cf53c08..5f3ff814 100644 --- a/app/Models/Business/CourierSurchargeQuote.php +++ b/app/Models/Business/CourierSurchargeQuote.php @@ -17,6 +17,7 @@ class CourierSurchargeQuote extends Model 'courier', 'scope', 'reconciler', + 'supplier', 'types', 'mode', 'standard', diff --git a/app/Models/Business/InventoryWarehouseNameMapping.php b/app/Models/Business/InventoryWarehouseNameMapping.php new file mode 100644 index 00000000..fda10996 --- /dev/null +++ b/app/Models/Business/InventoryWarehouseNameMapping.php @@ -0,0 +1,34 @@ + 'integer', + 'created_by' => 'integer', + 'updated_by' => 'integer', + ]; + + public static function columnLabels(): array + { + return [ + 'warehouse_provider' => '仓储方', + 'warehouse' => '仓库', + 'warehouse_short_name' => '仓库简称', + ]; + } +} diff --git a/app/Models/Business/JstOrderLabel.php b/app/Models/Business/JstOrderLabel.php new file mode 100644 index 00000000..b86cd338 --- /dev/null +++ b/app/Models/Business/JstOrderLabel.php @@ -0,0 +1,26 @@ + 'datetime', + ]; +} diff --git a/app/Models/Business/PlantingDetail.php b/app/Models/Business/PlantingDetail.php new file mode 100644 index 00000000..8be6d95e --- /dev/null +++ b/app/Models/Business/PlantingDetail.php @@ -0,0 +1,54 @@ + 'date', + 'finance_selling_price' => 'decimal:4', + 'finance_freight' => 'decimal:4', + 'finance_commission' => 'decimal:4', + 'jingxi_price_diff' => 'decimal:4', + 'deduction' => 'decimal:4', + 'finance_empty_package_fee' => 'decimal:4', + 'finance_payment_amount' => 'decimal:4', + 'pieces' => 'integer', + ]; +} diff --git a/app/Models/Business/StoreReceivingAccount.php b/app/Models/Business/StoreReceivingAccount.php index 5b9a98cd..2dba7cf0 100644 --- a/app/Models/Business/StoreReceivingAccount.php +++ b/app/Models/Business/StoreReceivingAccount.php @@ -23,6 +23,8 @@ class StoreReceivingAccount extends Model 'bank_card_last_four' => 'b', 'store_id' => 'i', 'source_platform' => 'r', + 'withdrawal_amount' => 'm', + 'withdrawal_balance_date' => 'd', ]; protected $table = 'business_store_receiving_accounts'; @@ -35,6 +37,7 @@ class StoreReceivingAccount extends Model 'payment_password', 'payment_verification_method', 'financial_account', 'financial_password', 'payment_verification_method_secondary', 'withdrawal_path', 'withdrawal_account_name', 'bank_card_last_four', 'store_id', 'source_platform', + 'withdrawal_amount', 'withdrawal_balance_date', ]; protected $casts = [ @@ -213,6 +216,26 @@ class StoreReceivingAccount extends Model $this->setMeta('source_platform', $this->clean($value)); } + public function getWithdrawalAmountAttribute(): ?string + { + return $this->meta('withdrawal_amount'); + } + + public function setWithdrawalAmountAttribute($value): void + { + $this->setMeta('withdrawal_amount', $this->clean($value)); + } + + public function getWithdrawalBalanceDateAttribute(): ?string + { + return $this->meta('withdrawal_balance_date'); + } + + public function setWithdrawalBalanceDateAttribute($value): void + { + $this->setMeta('withdrawal_balance_date', $this->clean($value)); + } + private function clean($value): ?string { $value = trim((string) $value); diff --git a/app/Services/Esign/EsignClient.php b/app/Services/Esign/EsignClient.php index 0f64f3be..8b99694a 100644 --- a/app/Services/Esign/EsignClient.php +++ b/app/Services/Esign/EsignClient.php @@ -184,6 +184,20 @@ final class EsignClient ]); } + public function downloadUploadedPdf(string $fileId): string + { + $data = $this->request('GET', "/v3/files/{$fileId}"); + $downloadUrl = (string) ($data['fileDownloadUrl'] + ?? $data['downloadUrl'] + ?? data_get($data, 'files.0.downloadUrl', '')); + + if ($downloadUrl === '') { + throw new RuntimeException('E 签宝未返回历史原文件下载地址。'); + } + + return $this->download($downloadUrl); + } + public function download(string $url): string { $response = Http::timeout($this->timeout())->get($url); diff --git a/app/Support/CourierAgreementFileArchive.php b/app/Support/CourierAgreementFileArchive.php new file mode 100644 index 00000000..a31150d1 --- /dev/null +++ b/app/Support/CourierAgreementFileArchive.php @@ -0,0 +1,55 @@ +source_pdf_path); + if ($path === '') { + throw new RuntimeException('该历史任务没有保存签署原文路径,无法下载。'); + } + + $disk = Storage::disk('uploads'); + if ($disk->exists($path)) { + return $path; + } + + if (blank($signature->esign_file_id)) { + throw new RuntimeException('本地历史文件缺失,且该任务未成功上传至 E 签宝,无法自动恢复。'); + } + + $expectedHash = strtolower(trim((string) $signature->source_pdf_sha256)); + if (preg_match('/^[a-f0-9]{64}$/', $expectedHash) !== 1) { + throw new RuntimeException('本地历史文件缺失,且没有可用于校验的原文件摘要,已停止自动恢复。'); + } + + $bytes = app(EsignClient::class)->downloadUploadedPdf((string) $signature->esign_file_id); + if (! str_starts_with($bytes, '%PDF-')) { + throw new RuntimeException('E 签宝返回的历史原文件不是有效 PDF,已停止自动恢复。'); + } + + if (! hash_equals($expectedHash, hash('sha256', $bytes))) { + throw new RuntimeException('E 签宝历史原文件与系统留存摘要不一致,已停止自动恢复。'); + } + + if (! $disk->put($path, $bytes)) { + throw new RuntimeException('历史原文件无法写回私有业务存储。'); + } + + $storedBytes = $disk->get($path); + if (! str_starts_with($storedBytes, '%PDF-') + || ! hash_equals($expectedHash, hash('sha256', $storedBytes))) { + $disk->delete($path); + throw new RuntimeException('历史原文件写回后校验失败,已移除不完整文件。'); + } + + return $path; + } +} diff --git a/app/Support/CourierAgreementPdf.php b/app/Support/CourierAgreementPdf.php index d64ae502..8629db0d 100644 --- a/app/Support/CourierAgreementPdf.php +++ b/app/Support/CourierAgreementPdf.php @@ -3,17 +3,26 @@ namespace App\Support; use App\Models\Business\CourierAgreementSignature; +use Illuminate\Support\Carbon; use RuntimeException; final class CourierAgreementPdf { public function render(CourierAgreementSignature $signature): string { + $payload = $signature->payload ?? []; + $signatureDate = (string) ($payload['signature_date'] ?? $payload['entity_proof_date'] ?? $payload['shared_proof_date'] ?? ''); + try { + $signatureDate = $signatureDate !== '' ? Carbon::parse($signatureDate)->format('Y年n月j日') : '待填写'; + } catch (\Throwable) { + $signatureDate = '待填写'; + } $html = view('business.pdf.courier-agreement', [ 'signature' => $signature, 'type' => $signature->document_type, 'title' => $this->title($signature), - 'payload' => $signature->payload ?? [], + 'payload' => $payload, + 'signatureDate' => $signatureDate, 'fontPath' => str_replace('\\', '/', resource_path('fonts/DroidSansFallback.ttf')), ])->render(); diff --git a/app/Support/CourierAgreementSignatureService.php b/app/Support/CourierAgreementSignatureService.php index 37987323..f10dfa51 100644 --- a/app/Support/CourierAgreementSignatureService.php +++ b/app/Support/CourierAgreementSignatureService.php @@ -96,6 +96,10 @@ final class CourierAgreementSignatureService $bytes = Storage::disk('uploads')->get($signature->source_pdf_path); $fileName = 'agreement-' . $signature->business_no . '.pdf'; $fileId = $client->uploadPdf($bytes, $fileName); + $signature->update([ + 'esign_file_id' => $fileId, + 'updated_by' => $userId, + ]); $signer = [ 'flow_title' => $this->safeTitle($signature->company_full_name . ' ' . $signature->documentLabel()), 'organization_name' => $signature->organization_name, @@ -120,9 +124,12 @@ final class CourierAgreementSignatureService return $signature->fresh(); } catch (Throwable $exception) { + $error = EsignErrorMessage::sanitize($exception->getMessage(), 1000) ?? 'E 签宝处理失败。'; $signature->update([ - 'status' => $flowCreationStarted ? CourierAgreementSignature::STATUS_UNKNOWN : CourierAgreementSignature::STATUS_FAILED, - 'last_error' => mb_substr((string) preg_replace('/[[:cntrl:]]+/u', ' ', $exception->getMessage()), 0, 1000), + 'status' => $flowCreationStarted && ! EsignErrorMessage::isDefinitiveFailure($exception->getMessage()) + ? CourierAgreementSignature::STATUS_UNKNOWN + : CourierAgreementSignature::STATUS_FAILED, + 'last_error' => $error, 'updated_by' => $userId, ]); throw ValidationException::withMessages(['signature' => $signature->last_error]); @@ -278,15 +285,12 @@ final class CourierAgreementSignatureService $payload = $signature->payload ?? []; if (in_array($signature->document_type, ['account-proof', 'account-change'], true)) { - $name = $signature->organization_name; - $isOrganization = $this->looksLikeOrganization($name); + $isPerson = ($payload['counterparty_signer_type'] ?? 'organization') === 'person'; return [[ - 'signer_type' => $isOrganization ? 1 : 0, - 'organization_name' => $isOrganization ? $name : null, - 'operator_name' => $isOrganization - ? ($signature->operator_name ?: $signature->courier_name) - : $name, + 'signer_type' => $isPerson ? 0 : 1, + 'organization_name' => $isPerson ? null : $signature->organization_name, + 'operator_name' => $isPerson ? ($signature->operator_name ?: $signature->organization_name) : $signature->operator_name, 'operator_account' => $signature->operator_account, ]]; } @@ -345,11 +349,6 @@ final class CourierAgreementSignatureService return [$primary]; } - private function looksLikeOrganization(string $name): bool - { - return preg_match('/公司|有限公司|有限责任|企业|集团|合作社|事务所|中心|厂/u', $name) === 1; - } - private function safeTitle(string $title): string { $title = preg_replace('/[^\p{Han}\p{L}\p{N}_ -]/u', '-', $title) ?: '协议签署'; diff --git a/app/Support/CourierQuotePdf.php b/app/Support/CourierQuotePdf.php index b85b85dc..04c267de 100644 --- a/app/Support/CourierQuotePdf.php +++ b/app/Support/CourierQuotePdf.php @@ -3,6 +3,7 @@ namespace App\Support; use App\Models\Business\CourierQuoteVersion; +use Illuminate\Support\Carbon; use RuntimeException; final class CourierQuotePdf @@ -11,9 +12,10 @@ final class CourierQuotePdf { } - public function render(CourierQuoteVersion $version): string + public function render(CourierQuoteVersion $version, ?string $signatureDate = null): string { $data = $this->confirmation->data($version); + $signatureDate = Carbon::parse($signatureDate ?: now())->format('Y年n月j日'); $html = view('business.pdf.courier-quote', [ 'version' => $version, 'change' => $version->change, @@ -23,6 +25,7 @@ final class CourierQuotePdf 'expiryDate' => $data['expiry_date'], 'faceFee' => $data['face_fee'], 'bubbleCoefficient' => $data['bubble_coefficient'], + 'signatureDate' => $signatureDate, 'generatedAt' => now(), 'fontPath' => str_replace('\\', '/', resource_path('fonts/DroidSansFallback.ttf')), ])->render(); diff --git a/app/Support/CourierQuoteSignatureService.php b/app/Support/CourierQuoteSignatureService.php index 72f60bae..c9bf7b2e 100644 --- a/app/Support/CourierQuoteSignatureService.php +++ b/app/Support/CourierQuoteSignatureService.php @@ -18,11 +18,11 @@ final class CourierQuoteSignatureService { } - public function prepareVersion(CourierQuoteVersion $version, int $userId): CourierQuoteSignature + public function prepareVersion(CourierQuoteVersion $version, int $userId, ?string $signatureDate = null): CourierQuoteSignature { $existing = $version->signature; - if ($existing && $this->sourcePdfIsIntact($existing)) { + if ($signatureDate === null && $existing && $this->sourcePdfIsIntact($existing)) { return $existing; } @@ -32,7 +32,7 @@ final class CourierQuoteSignatureService ]); } - $bytes = $this->pdf->render($version); + $bytes = $this->pdf->render($version, $signatureDate); $path = $this->path($version, 'source.pdf'); $sha256 = hash('sha256', $bytes); diff --git a/app/Support/EsignErrorMessage.php b/app/Support/EsignErrorMessage.php new file mode 100644 index 00000000..0796ef48 --- /dev/null +++ b/app/Support/EsignErrorMessage.php @@ -0,0 +1,32 @@ + mb_substr($matches[1], 0, 1) . '***@' . $matches[2], + $message, + ); + $message = (string) preg_replace('/(? '申通', + '申通' => '申通', + '德邦' => '德邦', + '中通快运' => '中通快运', + ]; + + private const PROVINCES = [ + '北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', + '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', + '甘肃', '青海', '内蒙古', '广西', '西藏', '宁夏', '新疆', + ]; + + /** @var array>>|null */ + private ?array $rateIndex = null; + + /** @var array>|null */ + private ?array $rules = null; + + public function __construct(private readonly ReverseLogisticsQuoteSnapshot $snapshot) + { + } + + /** + * @return array{ + * carrier:?string,covered:bool,reason:?string,billable:?float,total:?float,surcharge:float, + * total_with_surcharge:?float,formula:?string,note:?string,surcharge_note:?string,source:?string, + * settlement:?float,gross_weight:?float,volume_weight:?float,base_amount:?float,increment_amount:?float, + * process:?string + * } + */ + public function calculate( + ?string $expressCompany, + ?string $originProvince, + ?string $receiverAddress, + float $grossWeight, + ?float $length = null, + ?float $width = null, + ?float $height = null, + ): array { + $carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null; + + if ($carrier === null) { + return $this->missing('该快递公司不在逆向物流报价范围内'); + } + + $length = max((float) $length, 0); + $width = max((float) $width, 0); + $height = max((float) $height, 0); + $volumeWeight = ($length > 0 && $width > 0 && $height > 0) + ? round($length * $width * $height / 6000, 4) + : 0.0; + $settlement = round(max($grossWeight, $volumeWeight), 4); + + if ($settlement <= 0) { + return $this->missing('缺少重量与尺寸,无法计算实际运费'); + } + + $origin = ReverseLogisticsQuoteSnapshot::provinceKey((string) $originProvince); + $destination = ReverseLogisticsQuoteSnapshot::provinceKey(self::destinationProvince((string) $receiverAddress)); + $this->load(); + $bucket = $this->rateIndex[$carrier][$origin . '|' . $destination] ?? []; + + if ($bucket === []) { + return $this->missing(sprintf('逆向物流报价未覆盖 %s→%s', $origin !== '' ? $origin : '(未知出发省)', $destination !== '' ? $destination : '(未知到达省)')); + } + + $rule = $this->rules[$carrier] ?? []; + $mode = (string) ($rule['pricing_mode'] ?? ''); + $maxSide = max($length, $width, $height); + $sideSum = $length + $width + $height; + $billable = 0.0; + $total = 0.0; + $surcharge = 0.0; + $surchargeNote = null; + $formula = ''; + $note = ''; + $source = ''; + $baseAmount = 0.0; + $incrementAmount = 0.0; + $process = []; + $number = static function (float $value): string { + return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.'); + }; + + if ($volumeWeight > 0) { + $process[] = '重量取大:max(毛重 ' . $number($grossWeight) . 'kg,体积重 ' . $number($volumeWeight) . 'kg) = ' . $number($settlement) . 'kg'; + } else { + $process[] = '未填长宽高,按毛重 ' . $number($grossWeight) . 'kg 作为结算重量'; + } + + if ($mode === 'first_weight_increment') { + $rate = $bucket['base'] ?? null; + if ($rate === null || ! ($rate['available'] ?? false)) { + return $this->missing('该线路无可用报价'); + } + + $baseAmount = (float) $rate['base_amount']; + $incrementAmount = (float) $rate['increment_amount']; + $billable = (float) max(1, (int) ceil($settlement)); + $total = $baseAmount + $incrementAmount * ($billable - 1); + $formula = '面单 ' . $rate['base_amount'] . ' + 续重 ' . $rate['increment_amount'] . ' ×(' . $billable . ' − 1)'; + $note = '续重按结算重量取整(原表备注 3)'; + $source = (string) ($rate['source'] ?? ''); + $process[] = '续重向上取整:' . $number($settlement) . 'kg → ' . $number($billable) . 'kg'; + $process[] = '面单 ' . $number($baseAmount) . ' 元 + 续重 ' . $number($incrementAmount) . ' 元/kg ×(' . $number($billable) . ' − 1)= ' . $number($total) . ' 元'; + } elseif (($rule['weight_bands'] ?? []) !== []) { + $billable = (float) max(15, (int) ceil($settlement)); + $band = $billable > 30 ? '31-60kg' : '0-30kg'; + $rate = $bucket[$band] ?? ($bucket['base'] ?? null); + + // 重量段版式以“重量段费率”判断可用性:面单费存在但费率为“/”时视为无报价。 + if ($rate === null || ($rate['increment_amount'] ?? null) === null) { + return $this->missing('该线路重量段无报价'); + } + + $baseAmount = (float) $rate['base_amount']; + $incrementAmount = (float) $rate['increment_amount']; + $total = $baseAmount + $incrementAmount * $billable; + $formula = '面单 ' . $rate['base_amount'] . ' + 费率 ' . $rate['increment_amount'] . ' × ' . $billable . '(' . $band . ')'; + $note = '不足 15kg 按 15kg 计费并向上取整(原表备注 2)'; + $process[] = '不足 15kg 按 15kg 计并向上取整:' . $number($settlement) . 'kg → ' . $number($billable) . 'kg'; + $process[] = '面单 ' . $number($baseAmount) . ' 元 + 费率 ' . $number($incrementAmount) . ' 元/kg × ' . $number($billable) . 'kg(' . $band . ')= ' . $number($total) . ' 元'; + + if ($billable > 60 || $maxSide > 200) { + $surcharge = max(20, $billable); + $surchargeNote = '超长超重附加费 ' . round($surcharge, 2) . ' 元(最长边>2m 或 计费重量>60kg,1 元/kg 最低 20 元)'; + } + + $source = (string) ($rate['source'] ?? ''); + } else { + $rate = $bucket['base'] ?? null; + if ($rate === null || ! ($rate['available'] ?? false)) { + return $this->missing('该线路无可用报价'); + } + + $baseAmount = (float) $rate['base_amount']; + $incrementAmount = (float) $rate['increment_amount']; + $billable = round($settlement, 2); + $total = $baseAmount + $incrementAmount * $billable; + $formula = '面单 ' . $rate['base_amount'] . ' + 费率 ' . $rate['increment_amount'] . ' × ' . $billable; + $note = '按原表「面单+重量×费率」'; + $process[] = '按结算重量计费(不取整):' . $number($billable) . 'kg'; + $process[] = '面单 ' . $number($baseAmount) . ' 元 + 费率 ' . $number($incrementAmount) . ' 元/kg × ' . $number($billable) . 'kg = ' . $number($total) . ' 元'; + + if ($maxSide > 160 || $sideSum > 250) { + $surcharge = 7.0; + $surchargeNote = '单边>1.6m 或 三边>2.5m,加收 7 元/单(原表备注 1)'; + } + + $source = (string) ($rate['source'] ?? ''); + } + + if ($surcharge > 0) { + $process[] = '加收单列:' . $number($surcharge) . ' 元(' . $surchargeNote . ')'; + } + + return [ + 'carrier' => $carrier, + 'covered' => true, + 'reason' => null, + 'billable' => $billable, + 'total' => round($total, 2), + 'surcharge' => round($surcharge, 2), + 'total_with_surcharge' => round($total + $surcharge, 2), + 'formula' => $formula, + 'note' => $note, + 'surcharge_note' => $surchargeNote, + 'source' => $source, + 'settlement' => $settlement, + 'gross_weight' => round($grossWeight, 4), + 'volume_weight' => round($volumeWeight, 4), + 'base_amount' => $baseAmount, + 'increment_amount' => $incrementAmount, + 'process' => implode(';', $process), + ]; + } + + /** @return array{carrier:?string,covered:bool,reason:string,billable:?float,total:?float,surcharge:float,total_with_surcharge:?float,formula:?string,note:?string,surcharge_note:?string,source:?string,settlement:?float,gross_weight:?float,volume_weight:?float,base_amount:?float,increment_amount:?float,process:?string} */ + private function missing(string $reason): array + { + return [ + 'carrier' => null, + 'covered' => false, + 'reason' => $reason, + 'billable' => null, + 'total' => null, + 'surcharge' => 0.0, + 'total_with_surcharge' => null, + 'formula' => null, + 'note' => null, + 'surcharge_note' => null, + 'source' => null, + 'settlement' => null, + 'gross_weight' => null, + 'volume_weight' => null, + 'base_amount' => null, + 'increment_amount' => null, + 'process' => null, + ]; + } + + private function load(): void + { + if ($this->rateIndex !== null) { + return; + } + + $this->rateIndex = []; + $this->rules = []; + $payload = $this->snapshot->load(); + $this->rules = collect($payload['rate_groups'] ?? [])->keyBy('carrier')->all(); + + foreach ($payload['rates'] ?? [] as $rate) { + $key = ($rate['origin_key'] ?? '') . '|' . ($rate['destination_key'] ?? ''); + $this->rateIndex[$rate['carrier']][$key][$rate['weight_band'] ?: 'base'] = $rate; + } + } + + /** 从收货地址里取出发往省份(用于匹配报价的到达省)。 */ + public static function destinationProvince(string $address): string + { + $address = trim($address); + + foreach (self::PROVINCES as $province) { + if (str_starts_with($address, $province)) { + return $province; + } + } + + return ''; + } +} diff --git a/app/Support/ReturnPickupOrderStatus.php b/app/Support/ReturnPickupOrderStatus.php new file mode 100644 index 00000000..3571e52d --- /dev/null +++ b/app/Support/ReturnPickupOrderStatus.php @@ -0,0 +1,28 @@ + '待快递下单', + 'WaitExpAccept' => '待快递接单', + 'ExpAccepted' => '快递已接单', + 'ExpCanceled' => '快递已取消订单', + 'CustomerServiceConfirmed' => '客服已确认', + 'WaitServerComfrim' => '待客服确认', + 'TicketTimeoutClose' => '工单超时关闭', + ]; + + public static function label(?string $code): string + { + $code = trim((string) $code); + + if ($code === '') { + return ''; + } + + return self::LABELS[$code] ?? $code; + } +} diff --git a/app/Support/ReverseLogisticsQuoteSnapshot.php b/app/Support/ReverseLogisticsQuoteSnapshot.php new file mode 100644 index 00000000..a88b0987 --- /dev/null +++ b/app/Support/ReverseLogisticsQuoteSnapshot.php @@ -0,0 +1,712 @@ +path ?? storage_path(self::RELATIVE_PATH); + + if (! is_file($path)) { + return $this->emptySnapshot('missing', '尚未导入本机逆向物流报价文件。'); + } + + try { + $payload = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return $this->emptySnapshot('invalid', '本机逆向物流报价快照无法读取,请重新导入源文件。'); + } + + if (! is_array($payload) || ! is_array($payload['sheets'] ?? null)) { + return $this->emptySnapshot('invalid', '本机逆向物流报价快照结构不完整,请重新导入源文件。'); + } + + $quotes = []; + + foreach (array_values($payload['sheets']) as $position => $sheet) { + if (! is_array($sheet) || trim((string) ($sheet['name'] ?? '')) === '') { + continue; + } + + $quotes[] = $this->normalizeSheet($sheet, $position); + } + + $rates = []; + $rateGroups = []; + $unparsedSheets = []; + $originKeys = []; + $destinationKeys = []; + + foreach ($quotes as $quote) { + $extracted = $this->extractRates($quote); + + if ($extracted === null) { + $unparsedSheets[] = $quote['sheet_name']; + + continue; + } + + $rateGroups[] = $extracted['rule']; + + foreach ($extracted['rates'] as $rate) { + $rates[] = $rate; + + if (! in_array($rate['origin_key'], $originKeys, true)) { + $originKeys[] = $rate['origin_key']; + } + + if (! in_array($rate['destination_key'], $destinationKeys, true)) { + $destinationKeys[] = $rate['destination_key']; + } + } + } + + return [ + 'available' => true, + 'state' => 'ready', + 'message' => null, + 'source_file' => basename(str_replace('\\', '/', (string) ($payload['sourcePath'] ?? '逆向物流报价.xlsx'))), + 'generated_at' => (string) ($payload['generatedAt'] ?? ''), + 'quotes' => $quotes, + 'rates' => $rates, + 'rate_groups' => $rateGroups, + 'unparsed_sheets' => $unparsedSheets, + 'provinces' => [ + 'origins' => $originKeys, + 'destinations' => $destinationKeys, + ], + 'summary' => [ + 'quote_count' => count($quotes), + 'carrier_count' => count(array_unique(array_column($quotes, 'carrier'))), + 'dated_count' => count(array_filter($quotes, fn (array $quote) => $quote['effective_date'] !== null)), + 'formula_count' => array_sum(array_column($quotes, 'formula_count')), + ], + 'rate_summary' => [ + 'rate_count' => count($rates), + 'carrier_count' => count($rateGroups), + 'origin_count' => count(array_unique(array_column($rates, 'origin'))), + 'destination_count' => count(array_unique(array_column($rates, 'destination'))), + 'weight_band_count' => count(array_unique(array_filter( + array_column($rates, 'weight_band'), + static fn ($band) => $band !== null && $band !== '' + ))), + 'available_count' => count(array_filter($rates, static fn (array $rate) => $rate['available'])), + 'missing_count' => count(array_filter($rates, static fn (array $rate) => ! $rate['available'])), + ], + ]; + } + + /** + * 把一个报价工作表拆分为运价明细;无法识别版式时返回 null。 + * + * @return array{rule:array,rates:list>}|null + */ + private function extractRates(array $quote): ?array + { + $values = $quote['values']; + $layout = $this->detectLayout($values); + + if ($layout === null) { + return null; + } + + $notes = $this->noteLines($values, $layout); + $context = [ + 'carrier' => $quote['carrier'], + 'sheet_name' => $quote['sheet_name'], + 'quote_type' => $quote['quote_type'], + 'effective_date' => $quote['effective_date'], + 'layout' => $layout, + 'notes' => $notes, + ]; + + return match ($layout) { + self::LAYOUT_MATRIX => $this->extractMatrixRates($values, $context), + self::LAYOUT_SINGLE_DESTINATION => $this->extractSingleDestinationRates($values, $context), + self::LAYOUT_WEIGHT_BAND => $this->extractWeightBandRates($values, $context), + default => null, + }; + } + + /** @param list> $values */ + private function detectLayout(array $values): ?string + { + $header = $values[1] ?? []; + + foreach ($header as $index => $label) { + if (! is_string($label)) { + continue; + } + + if ($index >= 3 && preg_match('/^\d+\s*-\s*\d+\s*kg$/u', trim($label)) === 1) { + return self::LAYOUT_WEIGHT_BAND; + } + } + + if (isset($header[0], $header[1]) + && trim((string) $header[0]) === '出发省份' + && trim((string) $header[1]) === '到达省份') { + return self::LAYOUT_MATRIX; + } + + if (isset($header[1]) && is_string($header[1]) && str_starts_with(trim($header[1]), '到达省份')) { + return self::LAYOUT_SINGLE_DESTINATION; + } + + return null; + } + + /** + * 矩阵版式:列方向按“到达省份”成组,每组两列(面单价格、续重价格),行方向为出发省份。 + * + * @param list> $values + * @param array $context + * @return array{rule:array,rates:list>} + */ + private function extractMatrixRates(array $values, array $context): array + { + $destinations = []; + $subHeader = $values[2] ?? []; + + foreach ($subHeader as $index => $label) { + if (! is_string($label) || trim($label) !== '面单价格') { + continue; + } + + $name = trim((string) ($values[1][$index] ?? '')); + + if ($name === '' || $name === '到达省份') { + continue; + } + + $destinations[$index] = ['name' => $name, 'increment' => $index + 1]; + } + + $rates = []; + $position = 0; + + foreach ($values as $rowIndex => $row) { + if ($rowIndex < 3) { + continue; + } + + $origin = trim((string) ($row[1] ?? '')); + + if ($origin === '') { + continue; + } + + foreach ($destinations as $baseIndex => $destination) { + $position++; + $baseAmount = $this->amount($row[$baseIndex] ?? null); + $incrementAmount = $this->amount($row[$destination['increment']] ?? null); + + $rates[] = $this->rateRow($context, $position, [ + 'origin' => $origin, + 'destination' => $destination['name'], + 'weight_band' => null, + 'base_amount' => $baseAmount, + 'increment_amount' => $incrementAmount, + 'source' => $this->cellRef($baseIndex, $rowIndex) . ':' . $this->cellRef($destination['increment'], $rowIndex), + ]); + } + } + + return [ + 'rule' => $this->rateRule($context, [ + 'pricing_mode' => 'first_weight_increment', + 'pricing_label' => '首重 + 续重 × (结算重量 - 1)', + 'base_label' => '面单价格(首重 1kg)', + 'increment_label' => '续重价格', + 'route_label' => sprintf('行=出发省份,列=到达省份(%d 个到达省)', count($destinations)), + 'weight_bands' => [], + 'rates' => $rates, + ]), + 'rates' => $rates, + ]; + } + + /** + * 单一到达省版式:A 列出发省份,随后两列为面单价格、续重价格。 + * + * @param list> $values + * @param array $context + * @return array{rule:array,rates:list>} + */ + private function extractSingleDestinationRates(array $values, array $context): array + { + $destination = trim((string) ($values[1][1] ?? '')); + $destination = trim((string) preg_replace('/^到达省份/u', '', $destination)); + + if ($destination === '') { + $destination = '江苏'; + } + + $rates = []; + $position = 0; + + foreach ($values as $rowIndex => $row) { + if ($rowIndex < 3) { + continue; + } + + $origin = trim((string) ($row[0] ?? '')); + + if ($origin === '') { + continue; + } + + $baseAmount = $this->amount($row[1] ?? null); + $incrementAmount = $this->amount($row[2] ?? null); + + if ($baseAmount === null && $incrementAmount === null) { + continue; + } + + $position++; + $rates[] = $this->rateRow($context, $position, [ + 'origin' => $origin, + 'destination' => $destination, + 'weight_band' => null, + 'base_amount' => $baseAmount, + 'increment_amount' => $incrementAmount, + 'source' => $this->cellRef(1, $rowIndex) . ':' . $this->cellRef(2, $rowIndex), + ]); + } + + return [ + 'rule' => $this->rateRule($context, [ + 'pricing_mode' => 'base_plus_weight_rate', + 'pricing_label' => '面单 + 重量 × 费率', + 'base_label' => '面单价格', + 'increment_label' => '续重价格', + 'route_label' => '行=出发省份,到达固定为 ' . $destination, + 'weight_bands' => [], + 'rates' => $rates, + ]), + 'rates' => $rates, + ]; + } + + /** + * 重量段版式:A 列出发省份、B 列面单费,其后每列一个重量段费率。 + * + * @param list> $values + * @param array $context + * @return array{rule:array,rates:list>} + */ + private function extractWeightBandRates(array $values, array $context): array + { + $bands = []; + $header = $values[1] ?? []; + + foreach ($header as $index => $label) { + if ($index < 3 || ! is_string($label)) { + continue; + } + + $label = trim($label); + + if ($label === '' || $label === '备注') { + continue; + } + + $bands[$index] = $label; + } + + $destination = $this->weightBandDestination($context['notes']); + + $rates = []; + $position = 0; + + foreach ($values as $rowIndex => $row) { + if ($rowIndex < 2) { + continue; + } + + $origin = trim((string) ($row[0] ?? '')); + + if ($origin === '') { + continue; + } + + $baseAmount = $this->amount($row[1] ?? null); + + foreach ($bands as $index => $band) { + $position++; + $rates[] = $this->rateRow($context, $position, [ + 'origin' => $origin, + 'destination' => $destination, + 'weight_band' => $band, + 'base_amount' => $baseAmount, + 'increment_amount' => $this->amount($row[$index] ?? null), + 'source' => $this->cellRef($index, $rowIndex), + ]); + } + } + + return [ + 'rule' => $this->rateRule($context, [ + 'pricing_mode' => 'base_plus_weight_rate', + 'pricing_label' => '面单 + 重量段费率 × 结算重量(不足 15kg 按 15kg 计费,向上取整)', + 'base_label' => '面单费', + 'increment_label' => '重量段费率', + 'route_label' => '行=出发省份,到达固定为 ' . $destination, + 'weight_bands' => array_values($bands), + 'rates' => $rates, + ]), + 'rates' => $rates, + ]; + } + + /** + * @param array $context + * @param array $values + * @return array + */ + private function rateRow(array $context, int $position, array $values): array + { + return [ + 'id' => sprintf('%s-%03d', $context['sheet_name'], $position), + 'carrier' => $context['carrier'], + 'sheet_name' => $context['sheet_name'], + 'quote_type' => $context['quote_type'], + 'origin' => $values['origin'], + 'destination' => $values['destination'], + 'origin_key' => self::provinceKey($values['origin']), + 'destination_key' => self::provinceKey($values['destination']), + 'weight_band' => $values['weight_band'], + 'base_amount' => $values['base_amount'], + 'increment_amount' => $values['increment_amount'], + 'available' => $values['base_amount'] !== null || $values['increment_amount'] !== null, + 'source' => $values['source'], + ]; + } + + /** + * @param array $context + * @param array $values + * @return array + */ + private function rateRule(array $context, array $values): array + { + $rates = $values['rates']; + + return [ + 'carrier' => $context['carrier'], + 'sheet_name' => $context['sheet_name'], + 'quote_type' => $context['quote_type'], + 'layout' => $context['layout'], + 'pricing_mode' => $values['pricing_mode'], + 'pricing_label' => $values['pricing_label'], + 'base_label' => $values['base_label'], + 'increment_label' => $values['increment_label'], + 'route_label' => $values['route_label'], + 'base_unit' => '元/票', + 'increment_unit' => '元/kg', + 'weight_bands' => $values['weight_bands'], + 'effective_date' => $context['effective_date'], + 'constraints' => $this->constraintLines($context['notes']), + 'notes' => $context['notes'], + 'rate_count' => count($rates), + 'available_count' => count(array_filter($rates, static fn (array $rate) => $rate['available'])), + 'origin_count' => count(array_unique(array_column($rates, 'origin'))), + 'destination_count' => count(array_unique(array_column($rates, 'destination'))), + ]; + } + + /** + * 备注列:矩阵版式取 A 列尾部说明行,其余版式取最后一列说明。 + * + * @param list> $values + * @return list + */ + private function noteLines(array $values, string $layout): array + { + [$startRow, $column] = match ($layout) { + self::LAYOUT_MATRIX => [3, 0], + self::LAYOUT_SINGLE_DESTINATION => [3, 3], + self::LAYOUT_WEIGHT_BAND => [2, 5], + default => [null, null], + }; + + if ($column === null) { + return []; + } + + $lines = []; + + foreach ($values as $rowIndex => $row) { + if ($rowIndex < $startRow) { + continue; + } + + $cell = $row[$column] ?? null; + + if (! is_string($cell) || trim($cell) === '') { + continue; + } + + foreach (preg_split('/\r\n|\r|\n/u', $cell) ?: [] as $line) { + $line = trim($line); + + if ($line !== '') { + $lines[] = $line; + } + } + } + + return $lines; + } + + /** @param list $notes @return list */ + private function constraintLines(array $notes): array + { + $keywords = ['限重', '限长', '超标', '超长超重', '保丢', '计泡', '记泡', '抛比']; + + return array_values(array_filter( + $notes, + static function (string $line) use ($keywords): bool { + foreach ($keywords as $keyword) { + if (str_contains($line, $keyword)) { + return true; + } + } + + return false; + } + )); + } + + /** @param list $notes */ + private function weightBandDestination(array $notes): string + { + foreach ($notes as $line) { + if (str_contains($line, '常州仓')) { + return '常州仓(江苏)'; + } + } + + return '江苏'; + } + + private function amount(mixed $value): ?float + { + if (is_int($value) || is_float($value)) { + return round((float) $value, 4); + } + + if (! is_string($value)) { + return null; + } + + $value = trim($value); + + if ($value === '' || in_array($value, ['/', '-', '—', '无'], true)) { + return null; + } + + return is_numeric($value) ? round((float) $value, 4) : null; + } + + private function cellRef(int $columnIndex, int $rowIndex): string + { + $label = ''; + $value = $columnIndex + 1; + + while ($value > 0) { + $value--; + $label = chr(65 + ($value % 26)) . $label; + $value = intdiv($value, 26); + } + + return $label . ($rowIndex + 1); + } + + /** 省份归一口径:去掉“省/市/自治区”后缀,仓名取括号内省份(如“常州仓(江苏)”)。 */ + public static function provinceKey(string $name): string + { + $text = trim($name); + + if (preg_match('/^[^((]*[((]([^))]+)[))]$/u', $text, $matches) === 1) { + $text = trim($matches[1]); + } + + $text = (string) preg_replace('/(维吾尔自治区|壮族自治区|回族自治区|自治区|特别行政区|省|市)$/u', '', $text); + + return $text === '内蒙' ? '内蒙古' : $text; + } + private function normalizeSheet(array $sheet, int $position): array + { + $name = trim((string) $sheet['name']); + $values = $this->normalizeMatrix($sheet['values'] ?? []); + $formulas = $this->normalizeMatrix($sheet['formulas'] ?? []); + $columnCount = max(array_map('count', $values ?: [[]])); + + return [ + 'id' => sprintf('RL-%03d', $position + 1), + 'sheet_index' => (int) ($sheet['index'] ?? $position), + 'sheet_name' => $name, + 'company_name' => $this->inferCompanyName($name), + 'carrier' => $this->inferCarrier($name), + 'quote_type' => $this->inferQuoteType($name), + 'effective_date' => $this->extractEffectiveDate($values), + 'source_range' => trim((string) ($sheet['address'] ?? '')), + 'row_count' => count($values), + 'column_count' => $columnCount, + 'formula_count' => $this->formulaCount($formulas), + 'status' => $this->extractEffectiveDate($values) === null ? '未标执行日期' : '已标执行日期', + 'signature_status' => 'Excel 未提供', + 'values' => $values, + 'formulas' => $formulas, + ]; + } + + private function inferCompanyName(string $name): string + { + $companyName = trim((string) preg_replace('/(?:逆向|退货|报价表|报价)$/u', '', $name)); + + return $companyName !== '' ? $companyName : $name; + } + + private function inferCarrier(string $name): string + { + foreach ([ + '中通快运', '顺心捷达', '安能快运', '京广', 'EMS', '中通', '圆通', '德邦', + '申通', '极兔', '安能', '邮政', '韵达', '顺丰', + ] as $carrier) { + if (str_contains($name, $carrier)) { + return $carrier; + } + } + + return '其他快递'; + } + + private function inferQuoteType(string $name): string + { + if (str_contains($name, '退货')) { + return '退货报价'; + } + + if (str_contains($name, '快运')) { + return '逆向快运报价'; + } + + return '逆向报价'; + } + + private function extractEffectiveDate(array $values): ?string + { + foreach ($values as $row) { + foreach ($row as $cell) { + if (! is_string($cell)) { + continue; + } + + if (preg_match('/(20\d{2})[.\/\-年]\s*(\d{1,2})[.\/\-月]\s*(\d{1,2})日?/u', $cell, $match) === 1) { + return sprintf('%04d-%02d-%02d', (int) $match[1], (int) $match[2], (int) $match[3]); + } + } + } + + return null; + } + + private function normalizeMatrix(mixed $matrix): array + { + if (! is_array($matrix)) { + return []; + } + + return array_map(function ($row) { + if (! is_array($row)) { + return [$this->normalizeCell($row)]; + } + + return array_map(fn ($cell) => $this->normalizeCell($cell), array_values($row)); + }, array_values($matrix)); + } + + private function normalizeCell(mixed $cell): string|int|float|bool|null + { + if ($cell === null || is_string($cell) || is_int($cell) || is_float($cell) || is_bool($cell)) { + return $cell; + } + + return (string) $cell; + } + + private function formulaCount(array $formulas): int + { + $count = 0; + + foreach ($formulas as $row) { + foreach ($row as $formula) { + if (is_string($formula) && trim($formula) !== '') { + $count++; + } + } + } + + return $count; + } + + private function emptySnapshot(string $state, string $message): array + { + return [ + 'available' => false, + 'state' => $state, + 'message' => $message, + 'source_file' => '逆向物流报价.xlsx', + 'generated_at' => '', + 'quotes' => [], + 'rates' => [], + 'rate_groups' => [], + 'unparsed_sheets' => [], + 'provinces' => [ + 'origins' => [], + 'destinations' => [], + ], + 'summary' => [ + 'quote_count' => 0, + 'carrier_count' => 0, + 'dated_count' => 0, + 'formula_count' => 0, + ], + 'rate_summary' => [ + 'rate_count' => 0, + 'carrier_count' => 0, + 'origin_count' => 0, + 'destination_count' => 0, + 'weight_band_count' => 0, + 'available_count' => 0, + 'missing_count' => 0, + ], + ]; + } +} diff --git a/app/Support/StreamingXlsxWriter.php b/app/Support/StreamingXlsxWriter.php new file mode 100644 index 00000000..87b405db --- /dev/null +++ b/app/Support/StreamingXlsxWriter.php @@ -0,0 +1,224 @@ +sheetPath = $path; + $this->sheet = $handle; + + fwrite($handle, '' + . '' + . ''); + } + + /** + * @param list $cells + */ + public function appendRow(array $cells): void + { + if (++$this->row > self::MAX_ROWS) { + throw new RuntimeException('导出行数超过 XLSX 单表上限。'); + } + + $xml = ''; + + foreach (array_values($cells) as $index => $value) { + if ($value === null || $value === '') { + continue; + } + + $reference = $this->columnName($index + 1) . $this->row; + $xml .= is_int($value) || is_float($value) + ? '' . $this->number($value) . '' + : '' + . $this->escape((string) $value) . ''; + } + + fwrite($this->sheet, $xml . ''); + } + + /** + * 收尾并写入给定输出流(例如 php://output)。 + * + * @param resource $output + */ + public function writeTo($output): void + { + fwrite($this->sheet, ''); + fclose($this->sheet); + + $zipPath = tempnam(sys_get_temp_dir(), 'xlsx_zip_'); + + if ($zipPath === false) { + $this->cleanup(); + + throw new RuntimeException('无法创建 XLSX 打包文件。'); + } + + try { + $zip = new ZipArchive(); + + if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { + throw new RuntimeException('无法创建 XLSX 压缩包。'); + } + + $zip->addFromString('[Content_Types].xml', $this->contentTypes()); + $zip->addFromString('_rels/.rels', $this->rootRelationships()); + $zip->addFromString('xl/workbook.xml', $this->workbook()); + $zip->addFromString('xl/_rels/workbook.xml.rels', $this->workbookRelationships()); + $zip->addFromString('xl/styles.xml', $this->styles()); + $zip->addFile($this->sheetPath, 'xl/worksheets/sheet1.xml'); + $zip->close(); + + $handle = fopen($zipPath, 'rb'); + + if ($handle === false) { + throw new RuntimeException('无法读取 XLSX 压缩包。'); + } + + stream_copy_to_stream($handle, $output); + fclose($handle); + } finally { + @unlink($zipPath); + $this->cleanup(); + } + } + + private function cleanup(): void + { + if ($this->sheetPath !== '' && is_file($this->sheetPath)) { + @unlink($this->sheetPath); + } + } + + private function number(int|float $value): string + { + if (is_int($value)) { + return (string) $value; + } + + if (! is_finite($value)) { + return '0'; + } + + $text = rtrim(rtrim(sprintf('%.10F', $value), '0'), '.'); + + return ($text === '' || $text === '-') ? '0' : $text; + } + + private function escape(string $value): string + { + if (! mb_check_encoding($value, 'UTF-8')) { + $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); + } + + $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $value) ?? $value; + + return htmlspecialchars($value, ENT_QUOTES | ENT_XML1, 'UTF-8'); + } + + private function columnName(int $index): string + { + $name = ''; + + while ($index > 0) { + $index--; + $name = chr(65 + ($index % 26)) . $name; + $index = intdiv($index, 26); + } + + return $name; + } + + private function contentTypes(): string + { + return '' + . '' + . '' + . '' + . '' + . '' + . '' + . ''; + } + + private function rootRelationships(): string + { + return '' + . '' + . '' + . ''; + } + + private function workbook(): string + { + $name = htmlspecialchars($this->sheetName, ENT_QUOTES | ENT_XML1, 'UTF-8'); + + return '' + . '' + . '' + . ''; + } + + private function workbookRelationships(): string + { + return '' + . '' + . '' + . '' + . ''; + } + + private function styles(): string + { + return '' + . '' + . '' + . '' + . '' + . '' + . '' + . '' + . ''; + } +} diff --git a/app/Utilities/SidebarPermissions.php b/app/Utilities/SidebarPermissions.php index 6c1e2c40..25567d0a 100644 --- a/app/Utilities/SidebarPermissions.php +++ b/app/Utilities/SidebarPermissions.php @@ -11,6 +11,11 @@ class SidebarPermissions 'refunds/small-payment-work-orders' => 'financial-operations/small-payment-work-orders', ]; + private const FINAL_SECTION_KEYS = [ + 'supplier-payables' => 'supplier-payables-final', + 'courier-payables' => 'courier-payables-final', + ]; + public static function settings(): array { $value = setting('system.sidebar_permissions', []); @@ -71,7 +76,7 @@ class SidebarPermissions return $navigation; } - return array_values(array_filter(array_map(function (array $section) use ($allowed) { + $navigation = array_values(array_filter(array_map(function (array $section) use ($allowed) { $sectionKey = $section['slug']; if (in_array($sectionKey, $allowed, true)) { @@ -113,6 +118,38 @@ class SidebarPermissions return null; }, $navigation))); + + // 新增的公司成本安排、税金预测表与主体经营报表共用公司经营报表权限。 + // 对已经保存过精确权限的账号兼容旧配置,避免新增页面被旧权限集合隐藏。 + foreach ($navigation as &$section) { + if (($section['slug'] ?? null) !== 'company-management') { + continue; + } + + $hasSubjectReport = collect($section['pages'] ?? [])->contains('slug', 'subject-operating-report'); + + if ($hasSubjectReport) { + $configuredPages = collect(BusinessNavigation::all()) + ->firstWhere('slug', 'company-management')['pages'] ?? []; + + foreach (['company-cost-arrangement', 'tax-forecast'] as $sharedReportSlug) { + $alreadyVisible = collect($section['pages'] ?? [])->contains('slug', $sharedReportSlug); + + if ($alreadyVisible) { + continue; + } + + $sharedReportPage = collect($configuredPages)->firstWhere('slug', $sharedReportSlug); + + if ($sharedReportPage) { + $section['pages'][] = $sharedReportPage; + } + } + } + } + unset($section); + + return $navigation; } public static function allKeys(): array @@ -140,7 +177,17 @@ class SidebarPermissions foreach ($keys as $key) { $key = (string) $key; - $normalized[] = self::LEGACY_PAGE_KEYS[$key] ?? $key; + $normalizedKey = self::LEGACY_PAGE_KEYS[$key] ?? $key; + $normalized[] = $normalizedKey; + + foreach (self::FINAL_SECTION_KEYS as $sectionKey => $finalSectionKey) { + if ($normalizedKey === $sectionKey) { + $normalized[] = $finalSectionKey; + } elseif (str_starts_with($normalizedKey, $sectionKey . '/')) { + // 「终版」目录已是独立目录,按同样的子页面粒度跟着授权。 + $normalized[] = $finalSectionKey . substr($normalizedKey, strlen($sectionKey)); + } + } if ($key === 'refunds') { $normalized[] = self::LEGACY_PAGE_KEYS['refunds/small-payment-work-orders']; diff --git a/app/View/Components/Title.php b/app/View/Components/Title.php index 63a7d9ef..a78647e2 100644 --- a/app/View/Components/Title.php +++ b/app/View/Components/Title.php @@ -60,6 +60,7 @@ class Title extends Component $context = Str::lower($routeName . ' ' . request()->path()); $icons = [ + 'financial-risk-control' => 'security', 'store-receiving-bills' => 'account_balance_wallet', 'marketing-account-bills' => 'account_balance_wallet', 'supplier-payables' => 'local_shipping', diff --git a/compose.jiangling.yml b/compose.jiangling.yml index d7ec45c0..c2ce3e39 100644 --- a/compose.jiangling.yml +++ b/compose.jiangling.yml @@ -27,11 +27,16 @@ services: env_file: - ./runtime/config-db.env command: - - "--innodb-buffer-pool-size=512M" - - "--innodb-log-buffer-size=32M" + - "--innodb-buffer-pool-size=4G" + - "--innodb-log-buffer-size=64M" - "--max-connections=60" - "--table-open-cache=600" - "--performance-schema=OFF" + - "--slow-query-log=ON" + - "--long-query-time=5" + - "--min-examined-row-limit=10000" + - "--log-output=FILE" + - "--slow-query-log-file=/var/lib/mysql/caiwu-slow.log" ports: - "0.0.0.0:13306:3306" volumes: @@ -40,8 +45,8 @@ services: networks: - default - config_database - mem_limit: 1536m - cpus: "2.00" + mem_limit: 6g + cpus: "4.00" healthcheck: test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] interval: 10s @@ -95,6 +100,8 @@ services: condition: service_healthy environment: RUN_MIGRATIONS: ${RUN_MIGRATIONS:-0} + SUPPLIER_PAYABLE_MAINTENANCE_DB_CONNECTION: business_mirror + JST_DB_CONNECTION: business_mirror env_file: - ./runtime/qiniu-storage.env - ./runtime/clickhouse.env diff --git a/config/app.php b/config/app.php index 71ba6c27..d935a57c 100644 --- a/config/app.php +++ b/config/app.php @@ -92,6 +92,18 @@ return [ 'timezone' => env('APP_TIMEZONE', 'UTC'), + /* + |-------------------------------------------------------------------------- + | 平台固定时区 + |-------------------------------------------------------------------------- + | + | app.timezone 会被 App\Utilities\Overrider 按公司设置 localisation.timezone 覆盖, + | 没有该设置时回落到 Europe/London,导致页面请求写入的时间比北京时间晚 7 小时。 + | 需要稳定时间的地方(如科目映射表的操作记录)用这个值,不随公司设置变化。 + | + */ + 'platform_timezone' => env('APP_TIMEZONE', 'UTC'), + /* |-------------------------------------------------------------------------- | Application Locale Configuration diff --git a/config/business_data.php b/config/business_data.php index 7a1c31aa..73a976e2 100644 --- a/config/business_data.php +++ b/config/business_data.php @@ -47,6 +47,7 @@ return [ 'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'], 'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'], 'operations_replica.rpt.fys_TrademarkInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '商标资料'], + 'operations_replica.rpt.crawl_shop_company' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺基础信息/店铺主体期间'], 'operations_replica.rpt.jst_sku' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '商品资料/售后费用'], 'jiansun.dbo.pm_priceAdjustment' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '普通商品资料/工作平台价格'], 'operations_replica.rpt.jst_warehouseInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '售后费用'], @@ -97,6 +98,9 @@ return [ 'jiansun.dbo.jst_originalBillInfo.pinduoduo_receiving' => [ 'role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '店铺收款账单/拼多多账户', ], + 'jiansun.dbo.jst_originalBillInfo.dewu_receiving' => [ + 'role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '店铺收款账单/得物账户', + ], 'jiansun.dbo.alipay_Bill_Detail' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '店铺收款账单/淘系支付宝账户'], 'jiansun.dbo.tmall_spread_bills' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '淘宝推广账单'], 'jiansun.dbo.pdd_spread_bills' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '拼多多推广账单'], diff --git a/config/business_navigation.php b/config/business_navigation.php index 3c1d337d..272d5294 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -26,6 +26,62 @@ $navigation = [ ], ], ], + [ + 'slug' => 'company-cost-arrangement', + 'title' => '公司成本安排', + 'directory' => [ + 'icon' => 'account_balance_wallet', + 'status' => '报表待定义', + 'description' => '按公司主体查看当月收入、成本缺口及成本费用安排。', + 'empty' => '公司成本安排尚未同步数据。', + 'fields' => [ + ['name' => 'company', 'label' => '公司'], + ['name' => 'company_type', 'label' => '公司类型'], + ['name' => 'invoice_type', 'label' => '发票类型'], + ['name' => 'current_month_income_forecast', 'label' => '当月收入预测', 'kind' => 'number'], + ['name' => 'historical_cost_gap', 'label' => '往期成本缺口', 'kind' => 'number'], + ['name' => 'supplier_cost_arrangement', 'label' => '供应商成本安排', 'kind' => 'number'], + ['name' => 'courier_cost_arrangement', 'label' => '快递成本安排', 'kind' => 'number'], + ['name' => 'current_month_tax_forecast', 'label' => '当月税金预测', 'kind' => 'number'], + ['name' => 'labor_cost_forecast', 'label' => '人工成本预测', 'kind' => 'number'], + ['name' => 'other_expense_forecast', 'label' => '其他费用预测', 'kind' => 'number'], + ], + ], + ], + [ + 'slug' => 'tax-forecast', + 'title' => '税金预测表', + 'directory' => [ + 'icon' => 'calculate', + 'status' => '字段已定义', + 'index_label' => '序号', + 'description' => '按公司主体预测当月税金:先按公司税务类型、工商类型和征收方式确定口径,再计算增值税及附加、印花税和所得税;取数公式见 docs/税金预测表需求说明.md。', + 'empty' => '税金预测表尚未接入取数:工商类型、征收方式(查账征收/核定征收)确认并补齐数据来源后开始计算。', + 'fields' => [ + ['name' => 'company_name', 'label' => '公司名称'], + ['name' => 'taxpayer_type', 'label' => '公司税务类型'], + ['name' => 'business_registration_type', 'label' => '工商类型'], + ['name' => 'collection_method', 'label' => '征收方式'], + ['name' => 'assessed_income_rate', 'label' => '核定应税所得率(%)', 'kind' => 'number'], + ['name' => 'forecast_month', 'label' => '预测月份'], + ['name' => 'revenue_incl_tax', 'label' => '当月含税收入预测', 'kind' => 'number'], + ['name' => 'revenue_excl_tax', 'label' => '当月不含税收入', 'kind' => 'number'], + ['name' => 'quarter_sales_excl_tax', 'label' => '季度累计销售额(不含税)', 'kind' => 'number'], + ['name' => 'cost_forecast', 'label' => '当月成本费用预测', 'kind' => 'number'], + ['name' => 'taxable_income', 'label' => '预计应纳税所得额', 'kind' => 'number'], + ['name' => 'vat_rate', 'label' => '增值税征收率/税率'], + ['name' => 'vat_payable', 'label' => '预计增值税', 'kind' => 'number'], + ['name' => 'urban_maintenance_tax', 'label' => '城建税', 'kind' => 'number'], + ['name' => 'education_surcharge', 'label' => '教育费附加', 'kind' => 'number'], + ['name' => 'local_education_surcharge', 'label' => '地方教育附加', 'kind' => 'number'], + ['name' => 'stamp_duty', 'label' => '印花税', 'kind' => 'number'], + ['name' => 'income_tax', 'label' => '企业所得税/经营所得个税', 'kind' => 'number'], + ['name' => 'total_tax', 'label' => '税金合计', 'kind' => 'number'], + ['name' => 'tax_burden_rate', 'label' => '综合税负率(%)', 'kind' => 'number'], + ['name' => 'notes', 'label' => '备注'], + ], + ], + ], [ 'slug' => 'basic-information', 'title' => '公司基础信息', @@ -173,6 +229,14 @@ $navigation = [ 'fields' => [], ], ], + [ + 'slug' => 'store-report-data-logic', + 'title' => '店铺维度报表逻辑配置', + ], + [ + 'slug' => 'tax-forecast-data-logic', + 'title' => '税金预测表逻辑配置', + ], ], ], ], @@ -213,6 +277,33 @@ $navigation = [ ], ], ], + [ + 'slug' => 'internal-flow-report', + 'title' => '内部流转报表', + 'directory' => [ + 'icon' => 'swap_horiz', + 'status' => '共享镜像', + 'description' => '按《一般纳税人内部流转》工作簿导入:一行一个抬头,展示预计销量、开票、所需进项成本、收票来源与剩余缺口。', + 'empty' => '内部流转数据尚未导入。导入工作簿后这里会显示明细。', + 'fields' => [ + ['name' => 'company_name', 'label' => '抬头'], + ['name' => 'tag', 'label' => '标签'], + ['name' => 'projected_sales', 'label' => '预计9月销量', 'kind' => 'number'], + ['name' => 'invoiced_to_buyer', 'label' => '开票-给买家开票', 'kind' => 'number'], + ['name' => 'internal_invoiced', 'label' => '开票-内部开票', 'kind' => 'number'], + ['name' => 'required_input_cost', 'label' => '所需进项成本', 'kind' => 'number'], + ['name' => 'receipt_from_supplier', 'label' => '收票-供应商', 'kind' => 'number'], + ['name' => 'receipt_from_suofeiya', 'label' => '收票-索菲亚', 'kind' => 'number'], + ['name' => 'receipt_from_gujia', 'label' => '收票-顾家', 'kind' => 'number'], + ['name' => 'internal_transfer_1', 'label' => '收票-内部流转(来源)1', 'kind' => 'number'], + ['name' => 'internal_transfer_2', 'label' => '收票-内部流转(来源)2', 'kind' => 'number'], + ['name' => 'internal_transfer_3', 'label' => '收票-内部流转(来源)3', 'kind' => 'number'], + ['name' => 'receipt_total', 'label' => '收票-合计', 'kind' => 'number'], + ['name' => 'remaining_gap', 'label' => '剩余缺口', 'kind' => 'number'], + ['name' => 'invoicing_ratio', 'label' => '开票比例'], + ], + ], + ], [ 'slug' => 'basic-information', 'title' => '店铺基础信息', @@ -302,6 +393,68 @@ $navigation = [ 'pages' => [ ['slug' => 'normal-products', 'title' => '普通商品资料'], ['slug' => 'online-daifa-price', 'title' => '线上代发价格'], + [ + 'slug' => 'monthly-weighted-average-price', + 'title' => '商品月加权平均单价', + 'directory' => [ + 'icon' => 'calculate', + 'status' => '共享镜像', + 'description' => '商品月加权平均单价页面入口已建立;接入数据前需确认采购入库范围、金额字段和退货处理口径。', + 'empty' => '商品月加权平均单价尚未同步。确认取数规则后再接入经营分析副本库数据。', + 'fields' => [ + ['name' => 'month', 'label' => '月份', 'kind' => 'date'], + ['name' => 'barcode_warehouse', 'label' => '条码+仓库'], + ['name' => 'warehouse_short_name', 'label' => '仓库简称'], + ['name' => 'supplier', 'label' => '供应商'], + ['name' => 'product_code', 'label' => '商品编码'], + ['name' => 'product_name', 'label' => '商品名称'], + ['name' => 'opening_quantity', 'label' => '原始数量', 'kind' => 'number', 'group' => '期初数据'], + ['name' => 'opening_unit_price', 'label' => '原始价格', 'kind' => 'number', 'group' => '期初数据'], + ['name' => 'opening_original_amount', 'label' => '原始期初金额', 'kind' => 'number', 'group' => '期初数据'], + ['name' => 'opening_adjusted_price', 'label' => '更改价格', 'kind' => 'number', 'group' => '期初数据'], + ['name' => 'opening_amount', 'label' => '期初金额', 'kind' => 'number', 'group' => '期初数据'], + ['name' => 'purchase_quantity', 'label' => '采购数量', 'kind' => 'number', 'group' => '入库数据'], + ['name' => 'purchase_unit_price', 'label' => '采购单价', 'kind' => 'number', 'group' => '入库数据'], + ['name' => 'purchase_amount', 'label' => '入库金额', 'kind' => 'number', 'group' => '入库数据'], + ['name' => 'weighted_average_unit_price', 'label' => '加权平均单价', 'kind' => 'number'], + ['name' => 'pricing_status', 'label' => '定价状态'], + ], + ], + ], + [ + 'slug' => 'inventory-report', + 'title' => '进销存报表', + 'directory' => [ + 'icon' => 'inventory', + 'status' => '共享镜像', + 'description' => '复用“应付款项 → 快递应付 → 三方仓进销存”的已确认流水、库存锚点和业务类型口径,按所有仓库、商品和月份汇总。', + 'empty' => '进销存共享镜像尚未完成首次同步。', + 'fields' => [ + ['name' => 'owner', 'label' => '货主'], + ['name' => 'month', 'label' => '月份', 'kind' => 'date'], + ['name' => 'warehouse_provider', 'label' => '仓储方'], + ['name' => 'warehouse', 'label' => '仓库'], + ['name' => 'warehouse_short_name', 'label' => '仓库简称'], + ['name' => 'product_code', 'label' => '商品编码'], + ['name' => 'category', 'label' => '分类'], + ['name' => 'opening_quantity', 'label' => '期初数量', 'kind' => 'integer'], + ['name' => 'closing_quantity', 'label' => '期末数量', 'kind' => 'integer'], + ['name' => 'processing_in', 'label' => '加工进仓', 'kind' => 'integer'], + ['name' => 'processing_out', 'label' => '加工出仓', 'kind' => 'integer'], + ['name' => 'purchase_in', 'label' => '采购进仓', 'kind' => 'integer'], + ['name' => 'purchase_return', 'label' => '采购退货', 'kind' => 'integer'], + ['name' => 'other_in', 'label' => '其它进仓', 'kind' => 'integer'], + ['name' => 'other_return', 'label' => '其它退货', 'kind' => 'integer'], + ['name' => 'sales_out', 'label' => '销售出仓', 'kind' => 'integer'], + ['name' => 'sales_return', 'label' => '销售退货', 'kind' => 'integer'], + ['name' => 'stocktake', 'label' => '盘点', 'kind' => 'integer'], + ['name' => 'transfer_out', 'label' => '调拨出', 'kind' => 'integer'], + ['name' => 'transfer_in', 'label' => '调拨入', 'kind' => 'integer'], + ['name' => 'opening', 'label' => '期初', 'kind' => 'integer'], + ['name' => 'other_out', 'label' => '其它出库', 'kind' => 'integer'], + ], + ], + ], ], ], [ @@ -339,9 +492,12 @@ $navigation = [ ['slug' => 'taobao-wechat', 'title' => '淘系微信账户'], ['slug' => 'pinduoduo', 'title' => '拼多多账户'], ['slug' => 'jd-wallet', 'title' => '京东网银钱包账户'], - ['slug' => 'jd-transactions', 'title' => '京东流水'], + ['slug' => 'jd-transactions', 'title' => '京东账单'], + ['slug' => 'jingxi', 'title' => '京喜账单'], ['slug' => 'douyin', 'title' => '抖音账户'], ['slug' => 'dewu', 'title' => '得物账户'], + ['slug' => 'vipshop', 'title' => '唯品会MP账户'], + ['slug' => 'vipshop-jx', 'title' => '唯品会JX账户'], ], ], [ @@ -368,11 +524,20 @@ $navigation = [ ['slug' => 'jd-wallet', 'title' => '京东网银钱包账户'], ['slug' => 'douyin', 'title' => '抖音账户'], ['slug' => 'dewu', 'title' => '得物账户'], - ['slug' => 'vipshop', 'title' => '唯品会账户'], + ['slug' => 'vipshop', 'title' => '唯品会MP账户'], ], ], ], ], + [ + 'slug' => 'planting-data', + 'title' => '种菜数据汇总', + 'icon' => 'grass', + 'pages' => [ + ['slug' => 'planting-details', 'title' => '种菜明细表'], + ['slug' => 'jst-order-labels', 'title' => '聚水潭订单标签明细'], + ], + ], [ 'slug' => 'account-balance-data', 'title' => '账单余额数据', @@ -390,7 +555,7 @@ $navigation = [ ['slug' => 'jd-wallet', 'title' => '京东账户'], ['slug' => 'douyin', 'title' => '抖音账户'], ['slug' => 'dewu', 'title' => '得物账户'], - ['slug' => 'vipshop', 'title' => '唯品会账户'], + ['slug' => 'vipshop', 'title' => '唯品会MP账户'], ], ], ['slug' => 'deposit-account-balance', 'title' => '店铺保证金账户余额'], @@ -455,13 +620,50 @@ $navigation = [ 'slug' => 'supplier-payables-final', 'title' => '供应商应付(终版)', 'icon' => 'local_shipping', - 'pages' => [], + 'pages' => [ + ['slug' => 'product-prices', 'title' => '商品价格'], + ['slug' => 'payment-reconciliation', 'title' => '货款对账'], + ['slug' => 'return-reconciliation', 'title' => '退货对账'], + ['slug' => 'invoice-deductions', 'title' => '发票扣款'], + ['slug' => 'board-deductions', 'title' => '板材扣款'], + ['slug' => 'compensation-details', 'title' => '赔偿明细'], + ['slug' => 'advance-details', 'title' => '借支明细'], + ['slug' => 'sample-deductions', 'title' => '样品扣款'], + ['slug' => 'other-adjustments', 'title' => '其他扣款补款'], + [ + 'slug' => 'unpriced-details', + 'title' => '未定价明细', + 'children' => [ + ['slug' => 'delivery-unpriced', 'title' => '送货未定价'], + ['slug' => 'return-unpriced', 'title' => '退货未定价'], + ], + ], + ['slug' => 'dropshipping-express', 'title' => '代发快递'], + ['slug' => 'supplier-payables-report', 'title' => '供应商应付表'], + ], ], [ 'slug' => 'courier-payables-final', 'title' => '快递应付(终版)', 'icon' => 'local_shipping', - 'pages' => [], + 'pages' => [ + ['slug' => 'quote-management', 'title' => '报价管理'], + ['slug' => 'courier-information', 'title' => '快递资料'], + ['slug' => 'agreement-signing', 'title' => '协议签署'], + ['slug' => 'freight-reconciliation', 'title' => '运费对账'], + ['slug' => 'shipping-data', 'title' => '发货数据'], + ['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'], + ['slug' => 'bookkeeping-details', 'title' => '记账明细'], + ['slug' => 'compensation-details', 'title' => '赔偿明细'], + ['slug' => 'advance-details', 'title' => '借支明细'], + ['slug' => 'other-adjustments', 'title' => '其他扣款补款'], + ['slug' => 'courier-surcharge', 'title' => '附加费报价维护'], + ['slug' => 'payable-cloud-warehouse-vehicle-fee', 'title' => '应付云仓车费'], + ['slug' => 'courier-payables-report', 'title' => '快递应付表'], + ['slug' => 'freight-difference', 'title' => '运费差'], + ['slug' => 'other-surcharge-summary', 'title' => '其他附加费汇总'], + ['slug' => 'return-fee', 'title' => '退件费'], + ], ], [ 'slug' => 'supplier-payables', @@ -499,6 +701,7 @@ $navigation = [ ['slug' => 'agreement-signing', 'title' => '协议签署'], ['slug' => 'freight-reconciliation', 'title' => '运费对账'], ['slug' => 'shipping-data', 'title' => '发货数据'], + ['slug' => 'return-pickup-management', 'title' => '退货取件管理'], ['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'], ['slug' => 'bookkeeping-details', 'title' => '记账明细'], ['slug' => 'compensation-details', 'title' => '赔偿明细'], @@ -507,6 +710,9 @@ $navigation = [ ['slug' => 'courier-surcharge', 'title' => '附加费报价维护'], ['slug' => 'payable-cloud-warehouse-vehicle-fee', 'title' => '应付云仓车费'], ['slug' => 'courier-payables-report', 'title' => '快递应付表'], + ['slug' => 'freight-difference', 'title' => '运费差'], + ['slug' => 'other-surcharge-summary', 'title' => '其他附加费汇总'], + ['slug' => 'return-fee', 'title' => '退件费'], ], ], [ @@ -575,7 +781,27 @@ $navigation = [ 'title' => '财务经营报表', 'icon' => 'analytics', 'pages' => [ - ['slug' => 'performance-details', 'title' => '业绩明细'], + [ + 'slug' => 'performance-details', + 'title' => '业绩明细', + 'directory' => [ + 'icon' => 'receipt_long', + 'status' => '共享镜像', + 'description' => '以店铺收款账户账单为基数,按「店铺 + 订单号」匹配订单侧商品金额;一行 = 一个店铺的一个订单,商品金额只挂一次,差额保留供后续分类。', + 'empty' => '店铺收款匹配订单明细尚未同步,请先执行 store-receipt:order-match:sync。', + 'fields' => [ + ['name' => 'occurred_date', 'label' => '发生时间', 'kind' => 'date'], + ['name' => 'store_name', 'label' => '店铺名称'], + ['name' => 'online_order_no', 'label' => '线上单号'], + ['name' => 'income_amount', 'label' => '收入金额', 'kind' => 'number'], + ['name' => 'product_amount', 'label' => '商品金额', 'kind' => 'number'], + ['name' => 'difference', 'label' => '差额', 'kind' => 'number'], + ['name' => 'match_status', 'label' => '匹配状态'], + ['name' => 'remark', 'label' => '异常标注'], + ], + ], + ], + ['slug' => 'billing-details', 'title' => '账单明细'], ['slug' => 'product-costs', 'title' => '商品成本'], ['slug' => 'courier-freight', 'title' => '快递运费'], ['slug' => 'installation-details', 'title' => '安装明细'], @@ -591,6 +817,14 @@ $navigation = [ ['slug' => 'financial-analysis', 'title' => '财务经营分析表'], ], ], + [ + 'slug' => 'financial-risk-control', + 'title' => '财务经营风险管控', + 'icon' => 'security', + 'pages' => [ + ['slug' => 'store-violation-alert', 'title' => '店铺违规信息预警'], + ], + ], [ 'slug' => 'financial-sw', 'title' => '财务SW报表', @@ -600,6 +834,17 @@ $navigation = [ ['slug' => 'actual-statistics', 'title' => '实际SW统计表'], ], ], + // 注意:新分组要放在 financial-sw 之后。 + // NavigationTest 断言 financial-risk-control 的下一个分组必须是 financial-sw, + // 插在它俩之间会让既有测试失败(等于改动了别人的页面顺序)。 + [ + 'slug' => 'financial-rules', + 'title' => '财务规则', + 'icon' => 'rule', + 'pages' => [ + ['slug' => 'account-mapping', 'title' => '科目映射表'], + ], + ], [ 'slug' => 'data-monitoring', 'title' => '数据监控', @@ -680,6 +925,7 @@ $requestedSectionOrder = [ 'order-data', 'refunds', 'billing-transactions', + 'planting-data', 'account-balance-data', 'product-inventory', ]; diff --git a/config/database.php b/config/database.php index 8ba5dcc7..36321b8e 100644 --- a/config/database.php +++ b/config/database.php @@ -45,6 +45,13 @@ return [ 'default' => env('DB_CONNECTION', 'mysql'), + // Supplier payable edits and imports must never write to the shared + // system database used by the rest of the application. + 'supplier_payable_maintenance_connection' => env( + 'SUPPLIER_PAYABLE_MAINTENANCE_DB_CONNECTION', + 'supplier_payable_maintenance' + ), + /* |-------------------------------------------------------------------------- | Database Connections @@ -169,6 +176,30 @@ return [ 'prefix_indexes' => true, 'strict' => true, 'engine' => 'InnoDB ROW_FORMAT=DYNAMIC', + + ], + + 'supplier_payable_maintenance' => [ + 'driver' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_DRIVER', 'mysql'), + 'host' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_HOST'), + 'port' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_PORT', '3306'), + 'database' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_DATABASE'), + 'username' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_USERNAME'), + 'password' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_PASSWORD'), + 'unix_socket' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_SOCKET', ''), + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => env('SUPPLIER_PAYABLE_MAINTENANCE_DB_PREFIX', 'ak_'), + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => 'InnoDB ROW_FORMAT=DYNAMIC', + 'modes' => [ + 'STRICT_TRANS_TABLES', + 'NO_ZERO_IN_DATE', + 'NO_ZERO_DATE', + 'ERROR_FOR_DIVISION_BY_ZERO', + 'NO_ENGINE_SUBSTITUTION', + ], ], 'mariadb' => [ diff --git a/config/firewall.php b/config/firewall.php index d3675728..cdcac1dc 100644 --- a/config/firewall.php +++ b/config/firewall.php @@ -418,7 +418,10 @@ return [ 'inputs' => [ 'only' => [], // i.e. 'first_name' - 'except' => [], // i.e. 'password' + // Livewire cryptographically signs this serialized component + // state. Its large JSON payload produces false positives; user + // updates and every other request field remain protected. + 'except' => ['snapshot'], ], 'patterns' => [ diff --git a/config/jd_bill_platform.php b/config/jd_bill_platform.php new file mode 100644 index 00000000..004145e2 --- /dev/null +++ b/config/jd_bill_platform.php @@ -0,0 +1,24 @@ + '京喜', + + // 口径切换起始日期(按记账日期/费用结算时间,格式 Y-m-d)。null = 全量历史。 + // 改成 '2026-09-01' 后:该日期起的京喜行归入京喜账单,之前的京喜行仍留在京东账单,总数保持守恒。 + 'scope_start_date' => null, + +]; diff --git a/config/services.php b/config/services.php index 3c1bdf21..58b7392b 100644 --- a/config/services.php +++ b/config/services.php @@ -59,16 +59,18 @@ return [ 'jushuitan' => [ // 聚水潭开放平台凭据只从私有 runtime/.env 读取,不进入代码仓库。 - 'base_url' => env('JUSHUITAN_OPEN_API_URL', 'https://openapi.jushuitan.com'), - 'app_key' => env('JUSHUITAN_APP_KEY'), - 'app_secret' => env('JUSHUITAN_APP_SECRET'), - 'access_token' => env('JUSHUITAN_ACCESS_TOKEN'), + // 商品操作日志使用经典开放接口。经典接口的 partnerid / partnerkey / token + // 与新开放平台的 App Key / App Secret / Access Token 不是同一套凭据,禁止混用。 + 'base_url' => env('JUSHUITAN_CLASSIC_API_URL', 'https://open.erp321.com/api/open/query.aspx'), + 'partner_id' => env('JUSHUITAN_PARTNER_ID'), + 'partner_key' => env('JUSHUITAN_PARTNER_KEY'), + 'token' => env('JUSHUITAN_TOKEN'), 'timeout' => (int) env('JUSHUITAN_OPEN_API_TIMEOUT', 20), - 'product_operation_history_path' => '/open/webapi/itemapi/itemsku/queryitemskuopshistory', + 'product_operation_history_method' => 'worklog.query', 'cost_price_history_start' => env('JUSHUITAN_COST_PRICE_HISTORY_START', '2000-01-01 00:00:00'), - 'cost_price_history_window_days' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_WINDOW_DAYS', 30), + 'cost_price_history_window_days' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_WINDOW_DAYS', 7), 'cost_price_history_overlap_hours' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_OVERLAP_HOURS', 48), - 'cost_price_history_page_size' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_PAGE_SIZE', 2000), + 'cost_price_history_page_size' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_PAGE_SIZE', 50), 'cost_price_history_max_pages' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_MAX_PAGES', 30), ], diff --git a/config/store_report_initial_periods.php b/config/store_report_initial_periods.php new file mode 100644 index 00000000..a8965b32 --- /dev/null +++ b/config/store_report_initial_periods.php @@ -0,0 +1,587 @@ + '2026-07-01', + 'shops' => [ + '京东-万客达家具旗舰店' => [ + 'previous_company' => '常州微振家居有限公司', + 'company' => '武汉市朵莹米贸易有限公司', + 'changed_at' => '2026-07-27', + ], + '京东-亿家木家具旗舰店' => [ + 'previous_company' => '常州玺之橙家居有限公司', + 'company' => '株洲市森境商贸有限公司', + 'changed_at' => '2026-09-14', + ], + '京东-亿家达家居旗舰店' => [ + 'previous_company' => '常州州圣家居有限公司', + 'company' => '广州芯喻科技有限公司', + 'changed_at' => '2026-09-11', + ], + '京东-俚库节华专卖店' => [ + 'previous_company' => '常州淘之牧家居有限公司', + 'company' => '武汉市跨星河贸易有限公司', + 'changed_at' => '2026-09-10', + ], + '京东-全颐家具旗舰店' => [ + 'previous_company' => '常州酷积吉电子商务有限公司', + 'company' => '深圳市匠师科技有限公司', + 'changed_at' => '2026-07-30', + ], + '京东-励树旗舰店' => [ + 'previous_company' => '常州在木居家居有限公司', + 'company' => '珠海市澄澄成贸易有限公司', + 'changed_at' => '2026-08-05', + ], + '京东-半隅雅居旗舰店' => [ + 'previous_company' => '常州尚之荷电子商务有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-07-27', + ], + '京东-卓禾客厅家具旗舰店' => [ + 'previous_company' => '常州幂佳电子商务有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-08-25', + ], + '京东-卓禾桌旗舰店' => [ + 'previous_company' => '常州素柚电子商务有限公司', + 'company' => '武汉市焕独树科技有限公司', + 'changed_at' => '2026-09-11', + ], + '京东-墨尚思家具官方旗舰店' => [ + 'previous_company' => '常州米之信家居有限公司', + 'company' => '深圳市澄镜贸易有限公司', + 'changed_at' => '2026-08-05', + ], + '京东-宛初家具旗舰店' => [ + 'previous_company' => '常州迈之时家居有限公司', + 'company' => '武汉市跨星河贸易有限公司', + 'changed_at' => '2026-09-28', + ], + '京东-宜造旗舰店' => [ + 'previous_company' => '常州泰赫家居有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-24', + ], + '京东-左印卧室家具旗舰店' => [ + 'previous_company' => '常州格之简电子商务有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '京东-左印旗舰店' => [ + 'previous_company' => '常州正琳电子商务有限公司', + 'company' => '义乌市答馥贸易有限公司', + 'changed_at' => '2026-09-11', + ], + '京东-巷予家具旗舰店' => [ + 'previous_company' => '常州鹏冒家居有限公司', + 'company' => '株洲市晞飏盛商贸有限公司', + 'changed_at' => '2026-08-05', + ], + '京东-新卓禾旗舰店' => [ + 'previous_company' => '常州仁之云家居有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '京东-木本诗家具旗舰店' => [ + 'previous_company' => '常州瓦铭家居有限公司', + 'company' => '深圳市匠师科技有限公司', + 'changed_at' => '2026-08-03', + ], + '京东-未时旗舰店' => [ + 'previous_company' => '常州和之非家居有限公司', + 'company' => '义乌市答馥贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '京东-柯诺苏家具旗舰店' => [ + 'previous_company' => '常州旭致家居有限公司', + 'company' => '株洲市晞飏盛商贸有限公司', + 'changed_at' => '2026-08-05', + ], + '京东-橡野里家具小店' => [ + 'previous_company' => '武进区潞城木易家具店', + 'company' => '武汉市焕独树科技有限公司', + 'changed_at' => '2026-07-09', + ], + '京东-爱家猫' => [ + 'previous_company' => '常州峰麟电子商务有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '京东-爱木儿旗舰店' => [ + 'previous_company' => '常州泽之云家居有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-07-28', + ], + '京东-礼想木旗舰店' => [ + 'previous_company' => '常州歆之吉家居有限公司', + 'company' => '武汉市金逐玉贸易有限公司', + 'changed_at' => '2026-08-15', + ], + '京东-第一森林客厅家具旗舰店' => [ + 'previous_company' => '常州连音电子商务有限公司', + 'company' => '广州芯喻科技有限公司', + 'changed_at' => '2026-08-04', + ], + '京东-第一森林家具旗舰店' => [ + 'previous_company' => '常州旭可电子商务有限公司', + 'company' => '义乌市答馥贸易有限公司', + 'changed_at' => '2026-07-27', + ], + '京东-米客米家家具旗舰店' => [ + 'previous_company' => '常州欧鹰朗家居有限公司', + 'company' => '上海臻磊居电子商务有限公司', + 'changed_at' => '2026-09-10', + ], + '京东-米昊旗舰店' => [ + 'previous_company' => '常州州圣家居有限公司', + 'company' => '义乌市育旬贸易有限公司', + 'changed_at' => '2026-07-30', + ], + '京东-素成木旗舰店' => [ + 'previous_company' => '常州泱涵家居有限公司', + 'company' => '武汉市金逐玉贸易有限公司', + 'changed_at' => '2026-09-11', + ], + '京东-纪辰家具旗舰店' => [ + 'previous_company' => '常州念晶家居有限公司', + 'company' => '杭州照萍芋贸易有限公司', + 'changed_at' => '2026-09-14', + ], + '京东-贝壳家具旗舰店' => [ + 'previous_company' => '常州致圣家居有限公司', + 'company' => '常州研选供应链有限公司', + 'changed_at' => '2026-08-03', + ], + '京东-赛初家具旗舰店' => [ + 'previous_company' => '常州嘉之钰家居有限公司', + 'company' => '武汉市焕独树科技有限公司', + 'changed_at' => '2026-09-11', + ], + '京东-首升瓦舟迪专卖店' => [ + 'previous_company' => '常州绒灿家居有限公司', + 'company' => '株洲市棱斛盛商贸有限公司', + 'changed_at' => '2026-08-05', + ], + '抖音-乾廷润凯家具专卖店' => [ + 'previous_company' => '常州迈而昕家居有限公司', + 'company' => '武汉市焕独树科技有限公司', + 'changed_at' => '2026-07-24', + ], + '抖音-亿家达官方旗舰店' => [ + 'previous_company' => '常州格之简电子商务有限公司', + 'company' => '广州市椿风贸易有限公司', + 'changed_at' => '2026-07-22', + ], + '抖音-亿家达家居专卖店' => [ + 'previous_company' => '常州庆之图家居有限公司', + 'company' => '杭州背多爱贸易有限公司', + 'changed_at' => '2026-08-24', + ], + '抖音-佰汇家具店' => [ + 'previous_company' => '常州巴宣家居有限公司', + 'company' => '武汉市跨星河贸易有限公司', + 'changed_at' => '2026-09-10', + ], + '抖音-凌木家具店' => [ + 'previous_company' => '常州马月家居有限公司', + 'company' => '武汉市焕独树科技有限公司', + 'changed_at' => '2026-07-17', + ], + '抖音-务原家具店' => [ + 'previous_company' => '常州格之麦家居有限公司', + 'company' => '深圳市宙桦奇贸易有限公司', + 'changed_at' => '2026-08-04', + ], + '抖音-勤松苏得荷家具专卖店' => [ + 'previous_company' => '常州米之信家居有限公司', + 'company' => '上海禄美佳商贸有限公司', + 'changed_at' => '2026-07-26', + ], + '抖音-吉友爱塑荣家居专卖店' => [ + 'previous_company' => '常州洁才家居有限公司', + 'company' => '深圳市鑫鑫向洋科技有限公司', + 'changed_at' => '2026-08-24', + ], + '抖音-和辉家具店' => [ + 'previous_company' => '常州阳之红家居有限公司', + 'company' => '武汉市跨星河贸易有限公司', + 'changed_at' => '2026-09-07', + ], + '抖音-常州科斯能家居有限公司' => [ + 'previous_company' => '常州俪能家居有限公司', + 'company' => '义乌市络翘贸易有限公司', + 'changed_at' => '2026-08-04', + ], + '抖音-德朗蒂家具店' => [ + 'previous_company' => '常州蓝瞳家居有限公司', + 'company' => '广州市墨拓贸易有限公司', + 'changed_at' => '2026-07-17', + ], + '抖音-星程家具店' => [ + 'previous_company' => '常州初之语家居有限公司', + 'company' => '株洲市晞飏盛商贸有限公司', + 'changed_at' => '2026-08-03', + ], + '抖音-林舸家具店' => [ + 'previous_company' => '常州迈之时家居有限公司', + 'company' => '珠海市澄澄成贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '抖音-柯诺苏来导专卖店' => [ + 'previous_company' => '常州瓦铭家居有限公司', + 'company' => '珠海市澄澄成贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '抖音-柯诺苏艾利华家具专卖店' => [ + 'previous_company' => '常州初之语家居有限公司', + 'company' => '武汉市跨星河贸易有限公司', + 'changed_at' => '2026-09-07', + ], + '抖音-樛木家具店' => [ + 'previous_company' => '常州绒美家居有限公司', + 'company' => '深圳市澄镜贸易有限公司', + 'changed_at' => '2026-08-03', + ], + '抖音-畅森家具店' => [ + 'previous_company' => '常州茶木家居有限公司', + 'company' => '义乌市答馥贸易有限公司', + 'changed_at' => '2026-08-10', + ], + '抖音-素屑家塑荣家具专卖店' => [ + 'previous_company' => '常州洁才家居有限公司', + 'company' => '珠海市澄澄成贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '抖音-纪辰欢而专卖店' => [ + 'previous_company' => '常州幂佳电子商务有限公司', + 'company' => '广州市鼎流拓科技有限公司', + 'changed_at' => '2026-07-24', + ], + '抖音-艺煦白墙专卖店' => [ + 'previous_company' => '常州梦彬家居有限公司', + 'company' => '深圳市澄镜贸易有限公司', + 'changed_at' => '2026-08-04', + ], + '抖音-蓝悦家具店' => [ + 'previous_company' => '常州初之语家居有限公司', + 'company' => '株洲市晞飏盛商贸有限公司', + 'changed_at' => '2026-08-03', + ], + '抖音-赛初家具旗舰店' => [ + 'previous_company' => '常州绒美家居有限公司', + 'company' => '义乌市育旬贸易有限公司', + 'changed_at' => '2026-08-04', + ], + '抖音-赛初莱夫特家具专卖店' => [ + 'previous_company' => '常州义之迈电子商务有限公司', + 'company' => '珠海市澄澄成贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '抖音-越堂家具店' => [ + 'previous_company' => '常州幂佳电子商务有限公司', + 'company' => '广州市鼎流拓科技有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-UCU官方旗舰店' => [ + 'previous_company' => '常州格之简电子商务有限公司', + 'company' => '青岛婳欣妍商贸有限公司', + 'changed_at' => '2026-09-14', + ], + '拼多多-久伴吾家具旗舰店' => [ + 'previous_company' => '常州格之简电子商务有限公司', + 'company' => '武汉市福流贸易有限公司', + 'changed_at' => '2026-07-17', + ], + '拼多多-亿佳木住宅家具官方旗舰店' => [ + 'previous_company' => '常州洁秋家居有限公司', + 'company' => '杭州背多爱贸易有限公司', + 'changed_at' => '2026-07-16', + ], + '拼多多-亿家木点好多专卖店' => [ + 'previous_company' => '常州欣之露电子商务有限公司', + 'company' => '上海臻潭寨电子商务有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-亿家达书房家具官方旗舰店' => [ + 'previous_company' => '常州连音电子商务有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-亿家达住宅家具官方旗舰店' => [ + 'previous_company' => '常州悠益电子商务有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-17', + ], + '拼多多-亿家达卧室家具官方旗舰店' => [ + 'previous_company' => '常州锋翎家居有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-亿家达官方旗舰店' => [ + 'previous_company' => '常州连音电子商务有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-16', + ], + '拼多多-亿家达实木家具官方旗舰店' => [ + 'previous_company' => '常州连音电子商务有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-亿家达客厅家具官方旗舰店' => [ + 'previous_company' => '常州锋翎家居有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-亿家达旗舰店' => [ + 'previous_company' => '常州锋翎家居有限公司', + 'company' => '青岛哲晖义商贸有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-亿家达桌椅官方旗舰店' => [ + 'previous_company' => '常州锋翎家居有限公司', + 'company' => '武汉市鼎新致远科技有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-优乐熊家具旗舰店' => [ + 'previous_company' => '常州旭可电子商务有限公司', + 'company' => '深圳市鑫鑫向洋科技有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-优乐猫家具旗舰店' => [ + 'previous_company' => '常州君之兰家居有限公司', + 'company' => '义乌市竺芽电子商务有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-全米家具旗舰店' => [ + 'previous_company' => '常州酷积吉电子商务有限公司', + 'company' => '武汉市福流贸易有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-华斯乐畅专卖店' => [ + 'previous_company' => '常州云栀电子商务有限公司', + 'company' => '武汉市跨星河贸易有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-华斯予之福专卖店' => [ + 'previous_company' => '常州予之福家居有限公司', + 'company' => '上海臻潭寨电子商务有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-卓禾住宅家具旗舰店' => [ + 'previous_company' => '常州歆森电子商务有限公司', + 'company' => '安阳县峋庭电子商务有限公司', + 'changed_at' => '2026-08-14', + ], + '拼多多-卓禾家纺家具家装旗舰店' => [ + 'previous_company' => '常州庆之图家居有限公司', + 'company' => '杭州背多爱贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-卓禾家纺家具旗舰店' => [ + 'previous_company' => '常州笛莫电子商务有限公司', + 'company' => '安阳县峋庭电子商务有限公司', + 'changed_at' => '2026-08-14', + ], + '拼多多-卓禾旗舰店' => [ + 'previous_company' => '常州庆之图家居有限公司', + 'company' => '杭州背多爱贸易有限公司', + 'changed_at' => '2026-08-12', + ], + '拼多多-哈利木丫官方旗舰店' => [ + 'previous_company' => '常州旭可电子商务有限公司', + 'company' => '深圳市鑫鑫向洋科技有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-墨尚思家具旗舰店' => [ + 'previous_company' => '常州苡宝家居有限公司', + 'company' => '武汉市福流贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '拼多多-宜卡木住宅家具旗舰店' => [ + 'previous_company' => '常州书心家居有限公司', + 'company' => '青岛婳欣妍商贸有限公司', + 'changed_at' => '2026-08-24', + ], + '拼多多-宜自然住宅家具旗舰店' => [ + 'previous_company' => '常州笛莫电子商务有限公司', + 'company' => '深圳市澜祺科技有限公司', + 'changed_at' => '2026-07-16', + ], + '拼多多-宜造家具旗舰店' => [ + 'previous_company' => '常州州圣家居有限公司', + 'company' => '深圳市澄镜贸易有限公司', + 'changed_at' => '2026-07-16', + ], + '拼多多-屿林间家具旗舰店' => [ + 'previous_company' => '常州欣之露电子商务有限公司', + 'company' => '广州市墨拓贸易有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-左印家具旗舰店' => [ + 'previous_company' => '常州歆森电子商务有限公司', + 'company' => '青岛婳欣妍商贸有限公司', + 'changed_at' => '2026-07-17', + ], + '拼多多-左昊家具旗舰店' => [ + 'previous_company' => '常州青号电子商务有限公司', + 'company' => '深圳市匠师科技有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-归来舍下住宅家具旗舰店' => [ + 'previous_company' => '常州凯之贝家居有限公司', + 'company' => '青岛铧胜靖商贸有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-惠木家特坤森专卖店' => [ + 'previous_company' => '常州冬之实家居有限公司', + 'company' => '义乌市竺芽电子商务有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-慕加家具旗舰店' => [ + 'previous_company' => '常州青号电子商务有限公司', + 'company' => '青岛哲晖义商贸有限公司', + 'changed_at' => '2026-09-14', + ], + '拼多多-星空夏日家纺家具家装官方旗舰店' => [ + 'previous_company' => '常州山之海家居有限公司', + 'company' => '青岛婳欣妍商贸有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-木小乐住宅家具旗舰店' => [ + 'previous_company' => '常州烟之雨家居有限公司', + 'company' => '青岛疆拓杰商贸有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-木庭乐家具官方旗舰店' => [ + 'previous_company' => '常州赫晟电子商务有限公司', + 'company' => '广州芯喻科技有限公司', + 'changed_at' => '2026-07-13', + ], + '拼多多-木野拾趣家具官方旗舰店' => [ + 'previous_company' => '常州笛莫电子商务有限公司', + 'company' => '深圳市鑫鑫向洋科技有限公司', + 'changed_at' => '2026-07-14', + ], + '拼多多-橡野里家具旗舰店' => [ + 'previous_company' => '常州橙兮电子商务有限公司', + 'company' => '武汉市朵莹米贸易有限公司', + 'changed_at' => '2026-07-17', + ], + '拼多多-橡野里纳熙专卖店' => [ + 'previous_company' => '常州仁之云家居有限公司', + 'company' => '武汉市福流贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '拼多多-欧意朗住宅家具旗舰店' => [ + 'previous_company' => '常州羽之间电子商务有限公司', + 'company' => '安阳县峋庭电子商务有限公司', + 'changed_at' => '2026-08-12', + ], + '拼多多-欧意朗办公家具旗舰店' => [ + 'previous_company' => '常州莱夫特家居有限公司', + 'company' => '安阳县峋庭电子商务有限公司', + 'changed_at' => '2026-08-12', + ], + '拼多多-欧意朗家具官方旗舰店' => [ + 'previous_company' => '常州森静电子商务有限公司', + 'company' => '杭州背多爱贸易有限公司', + 'changed_at' => '2026-08-12', + ], + '拼多多-欧意朗生活家具旗舰店' => [ + 'previous_company' => '常州锋翎家居有限公司', + 'company' => '安阳县峋庭电子商务有限公司', + 'changed_at' => '2026-08-12', + ], + '拼多多-润万卓家具旗舰店' => [ + 'previous_company' => '常州平灿家居有限公司', + 'company' => '武汉市福流贸易有限公司', + 'changed_at' => '2026-07-24', + ], + '拼多多-润典达旗舰店' => [ + 'previous_company' => '常州橙兮电子商务有限公司', + 'company' => '上海禄美佳商贸有限公司', + 'changed_at' => '2026-07-16', + ], + '拼多多-满富油家具旗舰店' => [ + 'previous_company' => '常州皓熠电子商务有限公司', + 'company' => '深圳市宙桦奇贸易有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-爱木儿家具旗舰店' => [ + 'previous_company' => '常州艺之瑾家居有限公司', + 'company' => '南召县栎安商贸有限公司', + 'changed_at' => '2026-09-10', + ], + '拼多多-百里香晟陶专卖店' => [ + 'previous_company' => '常州晟陶电子商务有限公司', + 'company' => '青岛铧胜靖商贸有限公司', + 'changed_at' => '2026-09-14', + ], + '拼多多-礼想木家具旗舰店' => [ + 'previous_company' => '常州雅之荷电子商务有限公司', + 'company' => '武汉市朵莹米贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '拼多多-第一森林旗舰店' => [ + 'previous_company' => '常州思温家居有限公司', + 'company' => '杭州照萍芋贸易有限公司', + 'changed_at' => '2026-07-14', + ], + '拼多多-米昊家具旗舰店' => [ + 'previous_company' => '常州素柚电子商务有限公司', + 'company' => '青岛婳欣妍商贸有限公司', + 'changed_at' => '2026-07-30', + ], + '拼多多-美栖家家具官方旗舰店' => [ + 'previous_company' => '常州州圣家居有限公司', + 'company' => '深圳市匠师科技有限公司', + 'changed_at' => '2026-07-14', + ], + '拼多多-花木涧家具旗舰店' => [ + 'previous_company' => '常州盈橡家居有限公司', + 'company' => '杭州背多爱贸易有限公司', + 'changed_at' => '2026-09-14', + ], + '拼多多-莫埃家具旗舰店' => [ + 'previous_company' => '常州昀禾家居有限公司', + 'company' => '青岛婳欣妍商贸有限公司', + 'changed_at' => '2026-07-15', + ], + '拼多多-迈磊凯家具专营店' => [ + 'previous_company' => '常州目之本电子商务有限公司', + 'company' => '武汉市福流贸易有限公司', + 'changed_at' => '2026-07-16', + ], + '淘宝-平提家具源头工厂' => [ + 'previous_company' => '常州平提电子商务有限公司', + 'company' => '义乌市育旬贸易有限公司', + 'changed_at' => '2026-08-20', + ], + '淘宝-康帕斯家具店' => [ + 'previous_company' => '永康市康帕斯贸易有限公司', + 'company' => '深圳市澄镜贸易有限公司', + 'changed_at' => '2026-08-20', + ], + '淘宝-知木家具源头工厂店' => [ + 'previous_company' => '常州聪恩家居有限公司', + 'company' => '广州市鼎流拓科技有限公司', + 'changed_at' => '2026-08-14', + ], + '阿里巴巴-达轩家居' => [ + 'previous_company' => '常州末屿家居有限公司', + 'company' => '上海臻希鹏电子商务有限公司', + 'changed_at' => '2026-09-24', + ], + ], +]; diff --git a/config/store_violations.php b/config/store_violations.php new file mode 100644 index 00000000..1618e164 --- /dev/null +++ b/config/store_violations.php @@ -0,0 +1,72 @@ + [ + ['key' => 'shop_name', 'label' => '店铺名'], + ['key' => 'violation_type', 'label' => '违规类型'], + ['key' => 'violation_category', 'label' => '违规分类'], + ['key' => 'violation_no', 'label' => '违规单号'], + ['key' => 'violation_date', 'label' => '违规日期'], + ['key' => 'points_deducted', 'label' => '扣分'], + ['key' => 'status', 'label' => '状态'], + ['key' => 'penalty_date', 'label' => '处罚日期'], + ['key' => 'appeal_deadline', 'label' => '申诉截止日期'], + ['key' => 'handling_status', 'label' => '处理状态'], + ], + + // 页面平台页签;source_values 为上游/导入文件中平台字段的取值 + 'platforms' => [ + 'taobao' => ['label' => '淘系', 'icon' => 'shopping_bag', 'source_values' => ['淘宝', '天猫', '淘系', 'taobao', 'tmall']], + 'alibaba' => ['label' => '阿里巴巴', 'icon' => 'inventory_2', 'source_values' => ['阿里巴巴', '1688', 'alibaba']], + 'jd' => ['label' => '京东', 'icon' => 'local_mall', 'source_values' => ['京东', 'jd', 'jingdong']], + 'jingxi' => ['label' => '京喜', 'icon' => 'storefront', 'source_values' => ['京喜', 'jingxi']], + 'pinduoduo' => ['label' => '拼多多', 'icon' => 'grid_view', 'source_values' => ['拼多多', 'pdd', 'pinduoduo']], + 'douyin' => ['label' => '抖音', 'icon' => 'play_circle', 'source_values' => ['抖音', 'douyin']], + ], + + // 处理状态(本地维护) + 'handling_statuses' => ['未处理', '处理中', '已处理', '无需处理'], + 'default_handling_status' => '未处理', + + // 导入表头别名 → 统一列键(不区分大小写、忽略空格) + 'header_aliases' => [ + 'shop_name' => ['店铺名', '店铺名称', '店铺', '商家名称', '商家', 'shop_name', 'shopname'], + 'violation_type' => ['违规类型', '违规内容', '违规行为', '违规原因', '违规描述', 'violation_type'], + 'violation_category' => ['违规分类', '违规类别', '分类', 'violation_category'], + 'violation_no' => ['违规单号', '违规编号', '违规id', '违规ID', '单号', 'violation_no'], + 'violation_date' => ['违规日期', '违规时间', '违规发生时间', 'violation_date'], + 'points_deducted' => ['扣分', '扣分数', '扣除分数', '罚分', 'points_deducted'], + 'status' => ['状态', '平台状态', '处罚状态', '违规状态', 'status'], + 'penalty_date' => ['处罚日期', '处罚时间', 'penalty_date'], + 'appeal_deadline' => ['申诉截止日期', '申诉截止时间', '申诉期限', '申诉截止', 'appeal_deadline'], + 'handling_status' => ['处理状态', '我方处理状态', '处理进度', 'handling_status'], + ], + + // 违规分类规则:命中顺序从上到下 + 'category_rules' => [ + '发货履约' => ['发货', '缺货', '无货', '揽收', '出库', '延迟', '物流轨迹'], + '物流异常' => ['物流', '轨迹', '签收', '少件', '错件', '快递', '虚假轨迹'], + '交易违规' => ['虚假交易', '销量', '评价', '虚假发货', '刷单', '虚假服务'], + '商品合规' => ['商品属性', '商品信息', '质量', '劣质', '不合格', '标题', '卖点', '描述不符', '空包'], + '服务体验' => ['服务', '投诉', '差评', '售后', '客服', '负面反馈'], + '发票与考核' => ['发票', '考核', '工单', '及时率', '上传率'], + ], + 'default_category' => '其他', + + // 导入限制 + 'import' => [ + 'max_rows' => 20000, + 'max_kilobytes' => 10240, + ], +]; diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index 585a67d5..a11b72a2 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -87,8 +87,8 @@ return [ 'overlap_rows' => (int) env('STORE_REPORT_MIRROR_OVERLAP_ROWS', 50000), ], - // 聚水潭进销存报表:固定只读“三方-南昌樵舍仓”,页面只读共享镜像。 - // 头表按 Id 区间小批读取并固定仓库,避免对上游流水表做无界扫描。 + // 聚水潭进销存共享流水镜像:头表按 Id 区间小批读取全部仓库。 + // 三方仓页面在 Repository 层继续固定南昌樵舍仓,进销存报表按全仓库汇总。 'third_party_warehouse_storage' => [ 'dataset_key' => 'jiansun.third-party-warehouse-storage', 'source_key' => 'jiansun', @@ -147,6 +147,11 @@ return [ 'stale_after_minutes' => (int) env('COURIER_INFORMATION_MIRROR_STALE_MINUTES', 60), ], + // 工作平台退货取件管理:客服取件单按天更新,允许比快递资料更长的同步间隔。 + 'return_pickup' => [ + 'stale_after_minutes' => (int) env('RETURN_PICKUP_MIRROR_STALE_MINUTES', 180), + ], + // 工作平台采购价格按 SKU 补充到普通商品资料;页面只读取共享镜像。 'work_platform_prices' => [ 'dataset_key' => 'jiansun.dbo.pm_priceAdjustment', @@ -187,6 +192,18 @@ return [ 'operations_replica.rpt.fys_companyInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'fys_companyInfo', 'target' => 'ops_fys_company_info', 'keys' => ['Id'], 'watermark' => 'updateTIme'], 'operations_replica.rpt.fys_shopInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'fys_shopInfo', 'target' => 'ops_fys_shop_info', 'keys' => ['Id'], 'watermark' => 'updateTime'], 'operations_replica.rpt.fys_TrademarkInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'fys_TrademarkInfo', 'target' => 'ops_fys_trademark_info', 'keys' => ['Id'], 'watermark' => 'updateTime'], + // 店铺后台每天抓取的店铺→主体映射:店铺维度报表用它识别主体接替并生成新期间。 + 'operations_replica.rpt.crawl_shop_company' => [ + 'source_key' => 'operations_replica', + 'schema' => 'rpt', + 'object' => 'crawl_shop_company', + 'target' => 'ops_crawl_shop_company', + 'keys' => ['id'], + 'watermark' => 'update_time', + 'indexes' => [ + ['shop_name', 'crawl_date', 'id'], + ], + ], 'operations_replica.rpt.jst_Orders' => [ 'source_key' => 'operations_replica', 'schema' => 'rpt', @@ -198,7 +215,9 @@ return [ ['o_id', 'Id'], ['order_date', 'o_id', 'Id'], // 账单明细按线上订单号 so_id 关联订单表;缺这个索引会让关联退化成百万行全表扫描。 - ['so_id', 'Id'], + // SQL Server 的历史 so_id 字段可能超过 MariaDB 联合索引上限; + // 订单号关联使用前 64 个字符已覆盖实际单号格式,同时保留 Id 唯一定位。 + ['so_id(64)', 'Id'], ], ], 'operations_replica.rpt.jst_OrderItem' => [ @@ -222,6 +241,7 @@ return [ ['sku_type', 'autoid'], ['sku_type', 'i_id', 'autoid'], ['sku_type', 'sku_id', 'autoid'], + ['sku_id', 'autoid'], ['sku_type', 'enabled', 'autoid'], ['sku_type', 'stock_disabled', 'autoid'], ], @@ -436,6 +456,31 @@ return [ ['fee_name'], ], ], + // 聚水潭得物货款账户:复制主账单、退货退款和其他费用扣减渠道; + // 保证金及其他账户域流水不混入店铺收款账户页面。 + 'jiansun.dbo.jst_originalBillInfo.dewu_receiving' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'jst_originalBillInfo', + 'target' => 'js_jst_dewu_receiving_bill_rows', + 'keys' => ['Id'], + 'watermark' => 'updateTime', + 'fixed_filters' => [ + 'channel' => ['Dewu', 'DewuTK', 'DewuKJ'], + ], + 'columns' => [ + 'Id', 'shop_id', 'channel', 'fee_time', 'del_flag', 'primary_key', + 'createTime', 'updateTime', 'auto_id', 'fee_name', 'inout_type', + 'oc_amount', 'p_auto_id', 'shop_i_id', 'shop_sku_id', 'sku_id', + 'so_id', 'combine_type', 'amount', + ], + 'indexes' => [ + ['Id'], + ['fee_time', 'Id', 'inout_type', 'amount'], + ['shop_id', 'fee_time', 'Id', 'inout_type', 'amount', 'fee_name'], + ['fee_name'], + ], + ], 'jiansun.dbo.alipay_Bill_Detail' => [ 'source_key' => 'jiansun', 'schema' => 'dbo', @@ -600,5 +645,94 @@ return [ 'keys' => ['Id'], 'watermark' => 'modifyTime', ], + + // 工作平台 2.0:客服系统 → 退款数据 → 退货取件管理(主表 + 明细 + 实退快递单号映射)。 + // 逆向物流运费核算与退件跟踪页面只读取共享镜像,不在请求中直连工作平台库。 + 'jiansun.dbo.ekf_ReturnPickupManagement' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'ekf_ReturnPickupManagement', + 'target' => 'js_ekf_return_pickup_management', + 'keys' => ['Id'], + 'watermark' => 'updateTime', + 'columns' => [ + 'Id', 'orderId', 'urgencyLevel', 'expectedPickupTime', 'orderStatus', 'returnExpressNo', + 'paymentMethod', 'pickupType', 'shopName', 'transactionNo', 'senderName', 'senderPhone', + 'province', 'city', 'district', 'street', 'address', 'note', 'issueType', 'issueDescription', + 'expressFollowStatus', 'expressFollowResult', 'expressFollowDescription', + 'expressOrderTime', 'expressPickupTime', 'creator', 'createTime', 'updateTime', 'guid', + 'totalReturnQuantity', 'express_company', 'extend', 'canceler', 'sourceFrom', + ], + 'indexes' => [ + ['orderId', 'Id'], + ['createTime', 'Id'], + ['updateTime', 'Id'], + ['express_company', 'createTime', 'Id'], + ['transactionNo', 'Id'], + ], + ], + 'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'ekf_ReturnPickupManagement_Item', + 'target' => 'js_ekf_return_pickup_management_item', + 'keys' => ['id'], + 'watermark' => 'updatedTime', + 'columns' => [ + 'id', 'mainTableId', 'returnProcode', 'returnQuantity', 'barcode', 'platformProductId', + 'platformSkuId', 'warehouse', 'receiverName', 'receiverPhone', 'receiverAddress', + 'actualReturnOrderNo', 'actualReturnQuantity', 'unverifiedQuantity', 'returnProgress', + 'productName', 'length', 'width', 'height', 'volume', 'grossWeight', 'estimatedFreight', + 'updatedTime', 'actualReturnProcode', + ], + 'indexes' => [ + ['mainTableId', 'id'], + ['barcode', 'id'], + ['returnProcode', 'id'], + ['updatedTime', 'id'], + ], + ], + 'jiansun.dbo.ekf_ReturnPickupManagement_TruthReExpressNumber' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'ekf_ReturnPickupManagement_TruthReExpressNumber', + 'target' => 'js_ekf_return_pickup_truth_express', + 'keys' => ['Id'], + 'watermark' => 'createTime', + 'columns' => ['Id', 'mId', 'truthExpressNumber', 'createTime'], + 'indexes' => [ + ['mId', 'Id'], + ['truthExpressNumber', 'Id'], + ['createTime', 'Id'], + ], + ], + // 工作平台仓库资料:退货取件明细的「发货仓」同时存在工作平台短码 + // (wp_warehouse.code / wp_warehouseConfig.whCode,如 2852)和聚水潭 + // wms_co_id(如 15038426)。短码名称只从工作平台仓库表解析;这两张表 + // 都很小,页面与导出经共享镜像读取,不直连上游。 + 'jiansun.dbo.wp_warehouse' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'wp_warehouse', + 'target' => 'js_wp_warehouse', + 'keys' => ['id'], + 'watermark' => 'modified', + 'columns' => ['id', 'code', 'name', 'status', 'modified'], + 'indexes' => [ + ['code', 'id'], + ], + ], + // wp_warehouseConfig 没有更新时间列,按主键追加并依靠周期全量校准。 + 'jiansun.dbo.wp_warehouseConfig' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'wp_warehouseConfig', + 'target' => 'js_wp_warehouse_config', + 'keys' => ['Id'], + 'columns' => ['Id', 'moduleId', 'whCode', 'whName'], + 'indexes' => [ + ['whCode', 'Id'], + ], + ], ], ]; diff --git a/config/view.php b/config/view.php index 22b8a18d..76dca230 100644 --- a/config/view.php +++ b/config/view.php @@ -33,4 +33,20 @@ return [ realpath(storage_path('framework/views')) ), + /* + |-------------------------------------------------------------------------- + | Compiled View Cache + |-------------------------------------------------------------------------- + | + | Blade still needs a writable path to generate PHP for each request, but + | local development must not trust an existing compiled template. Setting + | the compiler cache flag to false makes Laravel recompile every view and + | leaves production's normal compiled-view behavior unchanged. + |-------------------------------------------------------------------------- + */ + + 'cache' => env('APP_ENV', 'production') === 'local' + ? false + : env('VIEW_CACHE', true), + ]; diff --git a/database/migrations/2026_08_21_120000_create_product_purchase_price_mirror_tables.php b/database/migrations/2026_08_21_120000_create_product_purchase_price_mirror_tables.php index ae3d3164..a00395f1 100644 --- a/database/migrations/2026_08_21_120000_create_product_purchase_price_mirror_tables.php +++ b/database/migrations/2026_08_21_120000_create_product_purchase_price_mirror_tables.php @@ -27,6 +27,7 @@ return new class extends Migration $table->string('source_object', 191); $table->string('status', 24)->default('pending'); $table->string('run_mode', 24)->nullable(); + $table->unsignedTinyInteger('projection_version')->default(2); $table->uuid('generation')->nullable(); $table->dateTime('window_started_at', 6)->nullable(); $table->dateTime('window_ends_at', 6)->nullable(); @@ -47,11 +48,15 @@ return new class extends Migration $schema->create('product_purchase_price_mirror_rows', function (Blueprint $table): void { $table->unsignedBigInteger('item_id')->primary(); $table->unsignedBigInteger('purchase_order_id')->index(); + $table->unsignedBigInteger('source_order_no')->nullable()->index(); + $table->string('supplier_name', 255)->nullable(); $table->string('sku_id', 255)->nullable()->index(); $table->string('style_id', 255)->nullable()->index(); + $table->decimal('quantity', 20, 4)->nullable(); $table->decimal('unit_price', 20, 4)->nullable(); $table->string('document_status', 50)->nullable()->index(); $table->text('labels')->nullable(); + $table->dateTime('document_created_at', 6)->nullable()->index(); $table->dateTime('finished_at', 6)->nullable()->index(); $table->dateTime('purchase_updated_at', 6)->index(); $table->uuid('_mirror_generation')->nullable()->index(); @@ -63,6 +68,10 @@ return new class extends Migration ['document_status', 'sku_id', 'finished_at'], 'product_purchase_price_latest_lookup', ); + $table->index( + ['document_status', 'document_created_at', 'item_id'], + 'product_purchase_online_daifa_lookup', + ); }); } } diff --git a/database/migrations/2026_09_11_143000_create_third_party_warehouse_storage_mirror_tables.php b/database/migrations/2026_09_11_143000_create_third_party_warehouse_storage_mirror_tables.php index 9713eaa8..3447a3c2 100644 --- a/database/migrations/2026_09_11_143000_create_third_party_warehouse_storage_mirror_tables.php +++ b/database/migrations/2026_09_11_143000_create_third_party_warehouse_storage_mirror_tables.php @@ -18,6 +18,7 @@ return new class extends Migration if (! $schema->hasTable('third_party_warehouse_sync_states')) { $schema->create('third_party_warehouse_sync_states', function (Blueprint $table): void { $table->string('dataset_key', 100)->primary(); + $table->unsignedTinyInteger('scope_version')->default(1); $table->string('status', 32)->default('pending'); $table->string('run_mode', 24)->nullable(); $table->string('sync_phase', 24)->nullable(); @@ -78,6 +79,7 @@ return new class extends Migration $table->unsignedBigInteger('id'); $table->unsignedBigInteger('io_id'); $table->unsignedBigInteger('wms_co_id'); + $table->unsignedBigInteger('wh_id')->default(0); $table->string('status', 32)->nullable(); $table->string('io_type', 64)->nullable(); $table->dateTime('occurred_at', 3)->nullable(); @@ -90,6 +92,10 @@ return new class extends Migration ['generation', 'status', 'occurred_at', 'io_type'], 'tpw_headers_report_index', ); + $table->index( + ['generation', 'wms_co_id', 'occurred_at', 'io_type'], + 'tpw_headers_warehouse_report_index', + ); }); } diff --git a/database/migrations/2026_09_16_000000_create_product_price_override_tables.php b/database/migrations/2026_09_16_000000_create_product_price_override_tables.php new file mode 100644 index 00000000..1013a8dc --- /dev/null +++ b/database/migrations/2026_09_16_000000_create_product_price_override_tables.php @@ -0,0 +1,78 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('product_price_overrides')) { + $schema->create('product_price_overrides', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedInteger('company_id'); + $table->char('upstream_key', 64); + $table->string('barcode', 191); + $table->string('spu', 191)->nullable(); + $table->text('product_name')->nullable(); + $table->string('category', 255)->nullable(); + $table->string('production_status', 120)->nullable(); + $table->decimal('minimum_price', 20, 4)->nullable(); + $table->decimal('price_limit', 20, 4)->nullable(); + $table->decimal('purchase_price', 20, 4)->nullable(); + $table->decimal('shipping_fee', 20, 4)->nullable(); + $table->decimal('jingxi_limit_price', 20, 4)->nullable(); + $table->string('source', 24); + $table->unsignedInteger('created_by')->nullable(); + $table->unsignedInteger('updated_by')->nullable(); + $table->timestamps(); + + $table->unique(['company_id', 'upstream_key'], 'product_price_overrides_company_key_unique'); + $table->index(['company_id', 'barcode'], 'product_price_overrides_company_barcode'); + }); + } + + if (! $schema->hasTable('product_price_override_events')) { + $schema->create('product_price_override_events', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedInteger('company_id'); + $table->char('upstream_key', 64); + $table->string('source', 24); + $table->json('before_values')->nullable(); + $table->json('after_values'); + $table->unsignedInteger('user_id')->nullable(); + $table->timestamp('created_at')->useCurrent(); + + $table->index( + ['company_id', 'upstream_key', 'created_at'], + 'product_price_override_events_lookup' + ); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('product_price_override_events'); + $schema->dropIfExists('product_price_overrides'); + } +}; diff --git a/database/migrations/2026_09_17_000000_create_supplier_payable_override_tables.php b/database/migrations/2026_09_17_000000_create_supplier_payable_override_tables.php new file mode 100644 index 00000000..22fc7ad5 --- /dev/null +++ b/database/migrations/2026_09_17_000000_create_supplier_payable_override_tables.php @@ -0,0 +1,50 @@ +hasTable('supplier_payable_overrides')) { + $schema->create('supplier_payable_overrides', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedInteger('company_id'); + $table->string('dataset', 64); + $table->string('record_key', 191); + $table->json('values'); + $table->unsignedInteger('created_by')->nullable(); + $table->unsignedInteger('updated_by')->nullable(); + $table->timestamps(); + $table->unique(['company_id', 'dataset', 'record_key'], 'supplier_payable_override_unique'); + $table->index(['company_id', 'dataset'], 'supplier_payable_override_dataset'); + }); + } + + if (! $schema->hasTable('supplier_payable_override_events')) { + $schema->create('supplier_payable_override_events', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedInteger('company_id'); + $table->string('dataset', 64); + $table->string('record_key', 191); + $table->string('source', 24); + $table->json('before_values')->nullable(); + $table->json('after_values'); + $table->unsignedInteger('user_id')->nullable(); + $table->timestamp('created_at')->useCurrent(); + $table->index(['company_id', 'dataset', 'record_key'], 'supplier_payable_override_event_lookup'); + }); + } + } + + public function down(): void + { + $schema = Schema::connection(config('database.supplier_payable_maintenance_connection')); + $schema->dropIfExists('supplier_payable_override_events'); + $schema->dropIfExists('supplier_payable_overrides'); + } +}; diff --git a/database/migrations/2026_09_18_140000_create_jd_daily_bill_mirror_tables.php b/database/migrations/2026_09_18_140000_create_jd_daily_bill_mirror_tables.php new file mode 100644 index 00000000..453ad034 --- /dev/null +++ b/database/migrations/2026_09_18_140000_create_jd_daily_bill_mirror_tables.php @@ -0,0 +1,51 @@ +hasTable('jd_daily_bill_periods')) { + $schema->create('jd_daily_bill_periods', function (Blueprint $t): void { + $t->date('period_start')->primary(); + $t->date('period_end'); + $t->uuid('active_generation'); + $t->string('source_filename'); + $t->char('source_sha256', 64); + $t->unsignedInteger('row_count'); + $t->decimal('income', 20, 2); + $t->decimal('expense', 20, 2); + $t->dateTime('imported_at'); + }); + } + if (! $schema->hasTable('jd_daily_bill_rows')) { + $schema->create('jd_daily_bill_rows', function (Blueprint $t): void { + $t->uuid('generation'); + $t->string('record_code', 64); + $t->string('store_name'); + $t->string('bill_item'); + $t->string('order_no', 64)->nullable(); + $t->dateTime('occurred_at'); + $t->decimal('income', 20, 2); + $t->decimal('expense', 20, 2); + $t->json('row_data'); + $t->primary(['generation', 'record_code'], 'jd_daily_pk'); + $t->index(['generation', 'occurred_at', 'record_code'], 'jd_daily_time'); + $t->index(['generation', 'occurred_at', 'income', 'expense'], 'jd_daily_summary'); + $t->index(['generation', 'store_name', 'occurred_at'], 'jd_daily_shop'); + $t->index(['generation', 'bill_item', 'occurred_at'], 'jd_daily_item'); + }); + } + } + + public function down(): void + { + $schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror')); + $schema->dropIfExists('jd_daily_bill_rows'); + $schema->dropIfExists('jd_daily_bill_periods'); + } +}; diff --git a/database/migrations/2026_09_18_160000_create_jd_wallet_bill_mirror_tables.php b/database/migrations/2026_09_18_160000_create_jd_wallet_bill_mirror_tables.php new file mode 100644 index 00000000..43c36389 --- /dev/null +++ b/database/migrations/2026_09_18_160000_create_jd_wallet_bill_mirror_tables.php @@ -0,0 +1,53 @@ +hasTable('jd_wallet_bill_periods')) { + $schema->create('jd_wallet_bill_periods', function (Blueprint $t): void { + $t->date('period_start')->primary(); + $t->date('period_end'); + $t->uuid('active_generation'); + $t->string('source_filename'); + $t->char('source_sha256', 64); + $t->unsignedInteger('row_count'); + $t->decimal('income', 20, 2); + $t->decimal('expense', 20, 2); + $t->dateTime('imported_at'); + }); + } + if (! $schema->hasTable('jd_wallet_bill_rows')) { + $schema->create('jd_wallet_bill_rows', function (Blueprint $t): void { + $t->uuid('generation'); + $t->string('record_code', 64); + $t->string('store_name'); + $t->string('bill_item'); + $t->string('order_no', 64)->nullable(); + $t->dateTime('occurred_at'); + $t->decimal('income', 20, 2); + $t->decimal('expense', 20, 2); + $t->json('row_data'); + $t->decimal('balance', 20, 2); + $t->string('account_name'); + $t->primary(['generation', 'record_code'], 'jd_wallet_pk'); + $t->index(['generation', 'occurred_at', 'record_code'], 'jd_wallet_time'); + $t->index(['generation', 'occurred_at', 'income', 'expense'], 'jd_wallet_summary'); + $t->index(['generation', 'store_name', 'occurred_at'], 'jd_wallet_shop'); + $t->index(['generation', 'bill_item', 'occurred_at'], 'jd_wallet_item'); + }); + } + } + + public function down(): void + { + $schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror')); + $schema->dropIfExists('jd_wallet_bill_rows'); + $schema->dropIfExists('jd_wallet_bill_periods'); + } +}; diff --git a/database/migrations/2026_09_20_150000_expand_inventory_flow_mirror_to_all_warehouses.php b/database/migrations/2026_09_20_150000_expand_inventory_flow_mirror_to_all_warehouses.php new file mode 100644 index 00000000..34415125 --- /dev/null +++ b/database/migrations/2026_09_20_150000_expand_inventory_flow_mirror_to_all_warehouses.php @@ -0,0 +1,41 @@ +connection()); + + if ($schema->hasTable('third_party_warehouse_inout_headers') + && ! $schema->hasColumn('third_party_warehouse_inout_headers', 'wh_id')) { + $schema->table('third_party_warehouse_inout_headers', function (Blueprint $table): void { + $table->unsignedBigInteger('wh_id')->default(0)->after('wms_co_id'); + $table->index( + ['generation', 'wms_co_id', 'occurred_at', 'io_type'], + 'tpw_headers_warehouse_report_index', + ); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if ($schema->hasTable('third_party_warehouse_inout_headers') + && $schema->hasColumn('third_party_warehouse_inout_headers', 'wh_id')) { + $schema->table('third_party_warehouse_inout_headers', function (Blueprint $table): void { + $table->dropIndex('tpw_headers_warehouse_report_index'); + $table->dropColumn('wh_id'); + }); + } + } +}; diff --git a/database/migrations/2026_09_20_151000_add_scope_version_to_inventory_flow_state.php b/database/migrations/2026_09_20_151000_add_scope_version_to_inventory_flow_state.php new file mode 100644 index 00000000..5c33bdd8 --- /dev/null +++ b/database/migrations/2026_09_20_151000_add_scope_version_to_inventory_flow_state.php @@ -0,0 +1,35 @@ +connection()); + if ($schema->hasTable('third_party_warehouse_sync_states') + && ! $schema->hasColumn('third_party_warehouse_sync_states', 'scope_version')) { + $schema->table('third_party_warehouse_sync_states', function (Blueprint $table): void { + $table->unsignedTinyInteger('scope_version')->default(1)->after('dataset_key'); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if ($schema->hasTable('third_party_warehouse_sync_states') + && $schema->hasColumn('third_party_warehouse_sync_states', 'scope_version')) { + $schema->table('third_party_warehouse_sync_states', function (Blueprint $table): void { + $table->dropColumn('scope_version'); + }); + } + } +}; diff --git a/database/migrations/2026_09_20_181000_create_inventory_subwarehouse_snapshots.php b/database/migrations/2026_09_20_181000_create_inventory_subwarehouse_snapshots.php new file mode 100644 index 00000000..ebaf23be --- /dev/null +++ b/database/migrations/2026_09_20_181000_create_inventory_subwarehouse_snapshots.php @@ -0,0 +1,61 @@ +connection()); + if ($schema->hasTable('third_party_warehouse_inventory_subwarehouse_snapshots')) { + return; + } + + $schema->create('third_party_warehouse_inventory_subwarehouse_snapshots', function (Blueprint $table): void { + $table->bigIncrements('_mirror_id'); + $table->uuid('generation'); + $table->string('source_key', 64)->default('jiansun'); + $table->unsignedBigInteger('id'); + $table->unsignedBigInteger('wms_co_id'); + $table->unsignedSmallInteger('wh_id'); + $table->string('sku_code', 191); + $table->decimal('qty', 20, 4)->default(0); + $table->dateTime('source_modified_at', 3)->nullable(); + $table->dateTime('captured_at', 6); + $table->string('row_hash', 64); + $table->dateTime('synced_at', 6); + $table->unique(['generation', 'id', 'wh_id'], 'tpw_subinventory_generation_id_wh_unique'); + $table->index( + ['generation', 'wms_co_id', 'wh_id', 'sku_code'], + 'tpw_subinventory_report_index', + ); + $table->index(['generation', 'sku_code'], 'tpw_subinventory_sku_index'); + }); + + $connection = DB::connection($this->connection()); + $connection->table('third_party_warehouse_inventory_subwarehouse_snapshots')->insertUsing( + [ + 'generation', 'source_key', 'id', 'wms_co_id', 'wh_id', 'sku_code', 'qty', + 'source_modified_at', 'captured_at', 'row_hash', 'synced_at', + ], + $connection->table('third_party_warehouse_inventory_snapshots')->select([ + 'generation', 'source_key', 'id', 'wms_co_id', DB::raw('1'), 'sku_code', 'qty', + 'source_modified_at', 'captured_at', 'row_hash', 'synced_at', + ]), + ); + } + + public function down(): void + { + Schema::connection($this->connection()) + ->dropIfExists('third_party_warehouse_inventory_subwarehouse_snapshots'); + } +}; diff --git a/database/migrations/2026_09_21_000000_create_courier_surcharge_audit_logs_table.php b/database/migrations/2026_09_21_000000_create_courier_surcharge_audit_logs_table.php new file mode 100644 index 00000000..33f5a91e --- /dev/null +++ b/database/migrations/2026_09_21_000000_create_courier_surcharge_audit_logs_table.php @@ -0,0 +1,36 @@ +increments('id'); + $table->unsignedInteger('company_id'); + $table->unsignedInteger('actor_id')->nullable(); + $table->string('action', 32); + $table->string('target_type', 32); + $table->unsignedInteger('target_id')->nullable(); + $table->string('target_label', 191); + $table->text('changes')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->index(['company_id', 'created_at'], 'courier_surcharge_audit_company_created_index'); + $table->index(['company_id', 'target_type', 'target_id'], 'courier_surcharge_audit_target_index'); + }); + } + + public function down(): void + { + Schema::dropIfExists('business_courier_surcharge_audit_logs'); + } +}; diff --git a/database/migrations/2026_09_21_010000_create_inventory_report_authoritative_tables.php b/database/migrations/2026_09_21_010000_create_inventory_report_authoritative_tables.php new file mode 100644 index 00000000..8d2e48f9 --- /dev/null +++ b/database/migrations/2026_09_21_010000_create_inventory_report_authoritative_tables.php @@ -0,0 +1,75 @@ +connection()); + + if (! $schema->hasTable('inventory_report_authoritative_states')) { + $schema->create('inventory_report_authoritative_states', function (Blueprint $table): void { + $table->string('dataset_key', 120)->primary(); + $table->string('status', 24)->default('pending'); + $table->uuid('active_generation')->nullable(); + $table->uuid('pending_generation')->nullable(); + $table->string('source_filename', 255)->nullable(); + $table->char('source_sha256', 64)->nullable(); + $table->date('source_month')->nullable(); + $table->unsignedBigInteger('source_row_count')->default(0); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->string('last_error_code', 120)->nullable(); + $table->timestamps(); + }); + } + + if (! $schema->hasTable('inventory_report_authoritative_rows')) { + $schema->create('inventory_report_authoritative_rows', function (Blueprint $table): void { + $table->uuid('generation'); + $table->char('row_key', 64); + $table->date('report_month'); + $table->string('owner', 191); + $table->string('warehouse_provider', 191); + $table->string('warehouse', 191); + $table->string('product_code', 191); + $table->string('category', 191)->nullable(); + $table->decimal('opening_quantity', 20, 4); + $table->decimal('closing_quantity', 20, 4); + foreach ([ + 'processing_in', 'processing_out', 'purchase_in', 'purchase_return', + 'other_in', 'other_return', 'sales_out', 'sales_return', 'stocktake', + 'transfer_out', 'transfer_in', 'opening', 'other_out', + ] as $column) { + $table->decimal($column, 20, 4)->default(0); + } + $table->dateTime('imported_at'); + + $table->primary(['generation', 'row_key'], 'inventory_report_authoritative_rows_primary'); + $table->index( + ['generation', 'report_month', 'product_code'], + 'inventory_report_authoritative_product_index', + ); + $table->index( + ['generation', 'report_month'], + 'inventory_report_authoritative_month_index', + ); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('inventory_report_authoritative_rows'); + $schema->dropIfExists('inventory_report_authoritative_states'); + } +}; diff --git a/database/migrations/2026_09_21_100000_add_inventory_report_roll_forward_index.php b/database/migrations/2026_09_21_100000_add_inventory_report_roll_forward_index.php new file mode 100644 index 00000000..34a519fb --- /dev/null +++ b/database/migrations/2026_09_21_100000_add_inventory_report_roll_forward_index.php @@ -0,0 +1,40 @@ +connection()); + if (! $schema->hasTable('inventory_report_authoritative_rows')) { + return; + } + + $schema->table('inventory_report_authoritative_rows', function (Blueprint $table): void { + $table->index( + ['generation', 'report_month', 'warehouse_provider', 'warehouse', 'product_code'], + 'inventory_report_authoritative_roll_forward_index', + ); + }); + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('inventory_report_authoritative_rows')) { + return; + } + + $schema->table('inventory_report_authoritative_rows', function (Blueprint $table): void { + $table->dropIndex('inventory_report_authoritative_roll_forward_index'); + }); + } +}; diff --git a/database/migrations/2026_09_22_000000_create_pinduoduo_settlement_bill_tables.php b/database/migrations/2026_09_22_000000_create_pinduoduo_settlement_bill_tables.php new file mode 100644 index 00000000..3d1f0fb9 --- /dev/null +++ b/database/migrations/2026_09_22_000000_create_pinduoduo_settlement_bill_tables.php @@ -0,0 +1,110 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('pdd_settlement_bill_imports')) { + $schema->create('pdd_settlement_bill_imports', function (Blueprint $table): void { + $table->uuid('generation')->primary(); + $table->string('source_filename'); + $table->char('source_sha256', 64)->unique(); + $table->date('period_start'); + $table->date('period_end'); + $table->string('status', 32)->default('running'); + $table->unsignedBigInteger('expected_row_count'); + $table->decimal('expected_income_total', 20, 2); + $table->decimal('expected_expense_total', 20, 2); + $table->unsignedBigInteger('row_count')->default(0); + $table->unsignedBigInteger('excluded_account_rows')->default(0); + $table->unsignedInteger('store_count')->default(0); + $table->unsignedInteger('bill_item_count')->default(0); + $table->json('account_type_counts')->nullable(); + $table->decimal('income_total', 20, 2)->default(0); + $table->decimal('expense_total', 20, 2)->default(0); + $table->decimal('net_total', 20, 2)->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->timestamps(); + + $table->index(['status', 'period_start', 'period_end'], 'pdd_bill_import_period_idx'); + }); + } + + if (! $schema->hasTable('pdd_settlement_bill_staging')) { + $schema->create('pdd_settlement_bill_staging', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->uuid('generation'); + $this->billColumns($table); + $table->unique(['generation', 'record_code'], 'pdd_bill_stage_generation_record_uq'); + $table->index(['generation', 'occurred_at'], 'pdd_bill_stage_generation_time_idx'); + }); + } + + if (! $schema->hasTable('pdd_settlement_bill_rows')) { + $schema->create('pdd_settlement_bill_rows', function (Blueprint $table): void { + $table->string('record_code', 191)->primary(); + $this->billColumns($table, false); + $table->uuid('source_generation'); + $table->char('source_sha256', 64); + $table->timestamp('imported_at'); + + $table->index(['occurred_at', 'record_code'], 'pdd_bill_time_record_idx'); + $table->index(['store_name', 'occurred_at'], 'pdd_bill_store_time_idx'); + $table->index(['bill_item', 'occurred_at'], 'pdd_bill_item_time_idx'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('pdd_settlement_bill_rows'); + $schema->dropIfExists('pdd_settlement_bill_staging'); + $schema->dropIfExists('pdd_settlement_bill_imports'); + } + + private function billColumns(Blueprint $table, bool $includeRecordCode = true): void + { + if ($includeRecordCode) { + $table->string('record_code', 191); + } + $table->string('store_name')->nullable(); + $table->string('custom_remark')->nullable(); + $table->string('bill_item')->nullable(); + $table->string('merchant_order_no', 191)->nullable(); + $table->string('online_order_no', 191)->nullable(); + $table->string('business_type')->nullable(); + $table->string('business_description', 1000)->nullable(); + $table->string('account_name')->nullable(); + $table->dateTime('occurred_at'); + $table->decimal('income_amount', 20, 2)->default(0); + $table->decimal('expense_amount', 20, 2)->default(0); + $table->decimal('signed_amount', 20, 2)->default(0); + $table->string('remark', 1000)->nullable(); + $table->dateTime('source_updated_at')->nullable(); + $table->string('source_modified_by')->nullable(); + $table->unsignedBigInteger('source_row_number'); + } +}; diff --git a/database/migrations/2026_09_22_010000_add_supplier_to_courier_surcharge_quotes_table.php b/database/migrations/2026_09_22_010000_add_supplier_to_courier_surcharge_quotes_table.php new file mode 100644 index 00000000..0ba54e23 --- /dev/null +++ b/database/migrations/2026_09_22_010000_add_supplier_to_courier_surcharge_quotes_table.php @@ -0,0 +1,32 @@ +string('supplier', 191)->nullable()->after('reconciler'); + }); + } + + public function down(): void + { + if (! Schema::hasTable('business_courier_surcharge_quotes') + || ! Schema::hasColumn('business_courier_surcharge_quotes', 'supplier')) { + return; + } + + Schema::table('business_courier_surcharge_quotes', function (Blueprint $table): void { + $table->dropColumn('supplier'); + }); + } +}; diff --git a/database/migrations/2026_09_22_010000_create_dewu_settlement_bill_tables.php b/database/migrations/2026_09_22_010000_create_dewu_settlement_bill_tables.php new file mode 100644 index 00000000..adc15393 --- /dev/null +++ b/database/migrations/2026_09_22_010000_create_dewu_settlement_bill_tables.php @@ -0,0 +1,119 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('dewu_settlement_bill_imports')) { + $schema->create('dewu_settlement_bill_imports', function (Blueprint $table): void { + $table->uuid('generation')->primary(); + $table->string('source_filename'); + $table->char('source_sha256', 64)->unique(); + $table->date('period_start'); + $table->date('period_end'); + $table->string('status', 32)->default('running'); + $table->unsignedBigInteger('expected_row_count'); + $table->decimal('expected_income_total', 20, 2); + $table->decimal('expected_expense_total', 20, 2); + $table->unsignedBigInteger('row_count')->default(0); + $table->unsignedBigInteger('excluded_rows')->default(0); + $table->unsignedInteger('store_count')->default(0); + $table->unsignedInteger('bill_item_count')->default(0); + $table->json('channel_counts')->nullable(); + $table->decimal('income_total', 20, 2)->default(0); + $table->decimal('expense_total', 20, 2)->default(0); + $table->decimal('net_total', 20, 2)->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->timestamps(); + + $table->index(['status', 'period_start', 'period_end'], 'dewu_bill_import_period_idx'); + }); + } + + if (! $schema->hasTable('dewu_settlement_bill_staging')) { + $schema->create('dewu_settlement_bill_staging', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->uuid('generation'); + $this->billColumns($table); + $table->unique(['generation', 'record_code'], 'dewu_bill_stage_generation_record_uq'); + $table->index(['generation', 'bill_date'], 'dewu_bill_stage_generation_time_idx'); + }); + } + + if (! $schema->hasTable('dewu_settlement_bill_rows')) { + $schema->create('dewu_settlement_bill_rows', function (Blueprint $table): void { + $table->string('record_code', 191)->primary(); + $this->billColumns($table, false); + $table->uuid('source_generation'); + $table->char('source_sha256', 64); + $table->timestamp('imported_at'); + + $table->index(['bill_date', 'record_code'], 'dewu_bill_time_record_idx'); + $table->index(['store_name', 'bill_date'], 'dewu_bill_store_time_idx'); + $table->index(['bill_item', 'bill_date'], 'dewu_bill_item_time_idx'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('dewu_settlement_bill_rows'); + $schema->dropIfExists('dewu_settlement_bill_staging'); + $schema->dropIfExists('dewu_settlement_bill_imports'); + } + + private function billColumns(Blueprint $table, bool $includeRecordCode = true): void + { + if ($includeRecordCode) { + $table->string('record_code', 191); + } + $table->string('order_no', 191)->nullable(); + $table->string('online_order_no', 191)->nullable(); + $table->string('custom_remark')->nullable(); + $table->string('bill_item')->nullable(); + $table->string('store_name')->nullable(); + $table->string('order_type')->nullable(); + $table->string('goods_name', 1000)->nullable(); + $table->string('goods_no', 191)->nullable(); + $table->string('quantity', 64)->nullable(); + $table->string('channel')->nullable(); + $table->string('business_type')->nullable(); + $table->decimal('income_amount', 20, 2)->default(0); + $table->decimal('expense_amount', 20, 2)->default(0); + $table->decimal('signed_amount', 20, 2)->default(0); + $table->string('online_real_store')->nullable(); + $table->dateTime('order_created_at')->nullable(); + $table->dateTime('paid_refunded_at')->nullable(); + $table->dateTime('ship_return_at')->nullable(); + $table->dateTime('bill_date'); + $table->string('settle_status')->nullable(); + $table->string('pay_period')->nullable(); + $table->dateTime('pulled_at')->nullable(); + $table->dateTime('source_updated_at')->nullable(); + $table->string('source_modified_by')->nullable(); + $table->unsignedBigInteger('source_row_number'); + } +}; diff --git a/database/migrations/2026_09_22_100000_extend_product_purchase_price_mirror_for_online_daifa.php b/database/migrations/2026_09_22_100000_extend_product_purchase_price_mirror_for_online_daifa.php new file mode 100644 index 00000000..306c95f2 --- /dev/null +++ b/database/migrations/2026_09_22_100000_extend_product_purchase_price_mirror_for_online_daifa.php @@ -0,0 +1,94 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if ($schema->hasTable('product_purchase_price_sync_states') + && ! $schema->hasColumn('product_purchase_price_sync_states', 'projection_version')) { + $schema->table('product_purchase_price_sync_states', function (Blueprint $table): void { + // Existing rows use projection 1 and must complete a fresh full pass + // before purchase-management rows are exposed on the page. + $table->unsignedTinyInteger('projection_version')->default(1)->after('run_mode'); + }); + } + + if (! $schema->hasTable('product_purchase_price_mirror_rows')) { + return; + } + + $missing = array_filter([ + 'source_order_no' => ! $schema->hasColumn('product_purchase_price_mirror_rows', 'source_order_no'), + 'supplier_name' => ! $schema->hasColumn('product_purchase_price_mirror_rows', 'supplier_name'), + 'quantity' => ! $schema->hasColumn('product_purchase_price_mirror_rows', 'quantity'), + 'document_created_at' => ! $schema->hasColumn('product_purchase_price_mirror_rows', 'document_created_at'), + ]); + + if ($missing === []) { + return; + } + + $schema->table('product_purchase_price_mirror_rows', function (Blueprint $table) use ($missing): void { + if (isset($missing['source_order_no'])) { + $table->unsignedBigInteger('source_order_no')->nullable()->after('purchase_order_id'); + } + if (isset($missing['supplier_name'])) { + $table->string('supplier_name', 255)->nullable()->after('source_order_no'); + } + if (isset($missing['quantity'])) { + $table->decimal('quantity', 20, 4)->nullable()->after('style_id'); + } + if (isset($missing['document_created_at'])) { + $table->dateTime('document_created_at', 6)->nullable()->after('labels'); + } + }); + + $schema->table('product_purchase_price_mirror_rows', function (Blueprint $table): void { + $table->index('source_order_no', 'product_purchase_source_order_index'); + $table->index( + ['document_status', 'document_created_at', 'item_id'], + 'product_purchase_online_daifa_lookup', + ); + }); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if ($schema->hasTable('product_purchase_price_mirror_rows')) { + $schema->table('product_purchase_price_mirror_rows', function (Blueprint $table): void { + $table->dropIndex('product_purchase_source_order_index'); + $table->dropIndex('product_purchase_online_daifa_lookup'); + $table->dropColumn(['source_order_no', 'supplier_name', 'quantity', 'document_created_at']); + }); + } + + if ($schema->hasTable('product_purchase_price_sync_states')) { + $schema->table('product_purchase_price_sync_states', function (Blueprint $table): void { + $table->dropColumn('projection_version'); + }); + } + } +}; diff --git a/database/migrations/2026_09_24_000000_create_taobao_wechat_bill_tables.php b/database/migrations/2026_09_24_000000_create_taobao_wechat_bill_tables.php new file mode 100644 index 00000000..a8563cd9 --- /dev/null +++ b/database/migrations/2026_09_24_000000_create_taobao_wechat_bill_tables.php @@ -0,0 +1,110 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('taobao_wechat_bill_imports')) { + $schema->create('taobao_wechat_bill_imports', function (Blueprint $table): void { + $table->uuid('generation')->primary(); + $table->string('source_filename'); + $table->char('source_sha256', 64)->unique(); + $table->date('period_start'); + $table->date('period_end'); + $table->string('status', 32)->default('running'); + $table->unsignedBigInteger('expected_row_count'); + $table->decimal('expected_income_total', 20, 2); + $table->decimal('expected_expense_total', 20, 2); + $table->unsignedBigInteger('row_count')->default(0); + $table->unsignedBigInteger('excluded_rows')->default(0); + $table->unsignedInteger('store_count')->default(0); + $table->unsignedInteger('bill_item_count')->default(0); + $table->json('entry_type_counts')->nullable(); + $table->decimal('income_total', 20, 2)->default(0); + $table->decimal('expense_total', 20, 2)->default(0); + $table->decimal('net_total', 20, 2)->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->timestamps(); + + $table->index(['status', 'period_start', 'period_end'], 'taobao_wechat_bill_import_period_idx'); + }); + } + + if (! $schema->hasTable('taobao_wechat_bill_staging')) { + $schema->create('taobao_wechat_bill_staging', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->uuid('generation'); + $this->billColumns($table); + $table->unique(['generation', 'record_code'], 'taobao_wechat_bill_stage_generation_record_uq'); + $table->index(['generation', 'occurred_at'], 'taobao_wechat_bill_stage_generation_time_idx'); + }); + } + + if (! $schema->hasTable('taobao_wechat_bill_rows')) { + $schema->create('taobao_wechat_bill_rows', function (Blueprint $table): void { + $table->string('record_code', 191)->primary(); + $this->billColumns($table, false); + $table->uuid('source_generation'); + $table->char('source_sha256', 64); + $table->timestamp('imported_at'); + + $table->index(['occurred_at', 'record_code'], 'taobao_wechat_bill_time_record_idx'); + $table->index(['store_name', 'occurred_at'], 'taobao_wechat_bill_store_time_idx'); + $table->index(['bill_item', 'occurred_at'], 'taobao_wechat_bill_item_time_idx'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('taobao_wechat_bill_rows'); + $schema->dropIfExists('taobao_wechat_bill_staging'); + $schema->dropIfExists('taobao_wechat_bill_imports'); + } + + private function billColumns(Blueprint $table, bool $includeRecordCode = true): void + { + if ($includeRecordCode) { + $table->string('record_code', 191); + } + $table->string('store_name')->nullable(); + $table->string('custom_remark')->nullable(); + $table->string('bill_item')->nullable(); + $table->string('taobao_order_no', 191)->nullable(); + $table->string('online_order_no', 191)->nullable(); + $table->string('pay_serial_no')->nullable(); + $table->string('business_description', 1000)->nullable(); + $table->string('entry_type')->nullable(); + $table->dateTime('occurred_at'); + $table->decimal('income_amount', 20, 2)->default(0); + $table->decimal('expense_amount', 20, 2)->default(0); + $table->decimal('signed_amount', 20, 2)->default(0); + $table->string('remark', 1000)->nullable(); + $table->dateTime('jst_pulled_at')->nullable(); + $table->string('source_modified_by')->nullable(); + $table->unsignedBigInteger('source_row_number'); + } +}; diff --git a/database/migrations/2026_09_26_010000_create_inventory_report_authoritative_months.php b/database/migrations/2026_09_26_010000_create_inventory_report_authoritative_months.php new file mode 100644 index 00000000..5814a698 --- /dev/null +++ b/database/migrations/2026_09_26_010000_create_inventory_report_authoritative_months.php @@ -0,0 +1,70 @@ +connection(); + $schema = Schema::connection($connection); + + if (! $schema->hasTable('inventory_report_authoritative_months')) { + $schema->create('inventory_report_authoritative_months', function (Blueprint $table): void { + $table->string('dataset_key', 120); + $table->date('source_month'); + $table->string('status', 24)->default('succeeded'); + $table->uuid('active_generation')->nullable(); + $table->string('source_filename', 255)->nullable(); + $table->char('source_sha256', 64)->nullable(); + $table->unsignedBigInteger('source_row_count')->default(0); + $table->dateTime('last_succeeded_at')->nullable(); + $table->timestamps(); + + $table->primary(['dataset_key', 'source_month']); + $table->index( + ['dataset_key', 'source_month', 'active_generation'], + 'inventory_report_authoritative_month_lookup', + ); + }); + } + + // Preserve the already imported single-month snapshot when upgrading + // from the original one-row state table. + if ($schema->hasTable('inventory_report_authoritative_states')) { + $legacy = DB::connection($connection) + ->table('inventory_report_authoritative_states') + ->where('dataset_key', 'jiansun.inventory-report.authoritative-month') + ->whereNotNull('source_month') + ->whereNotNull('active_generation') + ->first(); + if ($legacy !== null) { + DB::connection($connection)->table('inventory_report_authoritative_months')->insertOrIgnore([ + 'dataset_key' => (string) $legacy->dataset_key, + 'source_month' => $legacy->source_month, + 'status' => (string) ($legacy->status ?: 'succeeded'), + 'active_generation' => $legacy->active_generation, + 'source_filename' => $legacy->source_filename, + 'source_sha256' => $legacy->source_sha256, + 'source_row_count' => (int) ($legacy->source_row_count ?? 0), + 'last_succeeded_at' => $legacy->last_succeeded_at, + 'created_at' => $legacy->created_at, + 'updated_at' => $legacy->updated_at, + ]); + } + } + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists('inventory_report_authoritative_months'); + } +}; diff --git a/database/migrations/2026_09_27_000000_create_inventory_warehouse_name_mappings.php b/database/migrations/2026_09_27_000000_create_inventory_warehouse_name_mappings.php new file mode 100644 index 00000000..a5ba9a9d --- /dev/null +++ b/database/migrations/2026_09_27_000000_create_inventory_warehouse_name_mappings.php @@ -0,0 +1,41 @@ +increments('id'); + $table->unsignedInteger('company_id')->default(1); + $table->string('warehouse_provider', 191)->comment('仓储方'); + $table->string('warehouse', 191)->comment('仓库'); + $table->string('warehouse_short_name', 191)->comment('仓库简称'); + $table->unsignedInteger('created_by')->nullable(); + $table->unsignedInteger('updated_by')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->unique( + ['company_id', 'warehouse_provider', 'warehouse'], + 'inventory_warehouse_mapping_identity', + ); + $table->index( + ['company_id', 'warehouse_short_name'], + 'inventory_warehouse_mapping_short_name_index', + ); + }); + } + + public function down(): void + { + Schema::dropIfExists('business_inventory_warehouse_name_mappings'); + } +}; diff --git a/database/migrations/2026_09_27_000000_create_taobao_alipay_settlement_bill_tables.php b/database/migrations/2026_09_27_000000_create_taobao_alipay_settlement_bill_tables.php new file mode 100644 index 00000000..d484ff4f --- /dev/null +++ b/database/migrations/2026_09_27_000000_create_taobao_alipay_settlement_bill_tables.php @@ -0,0 +1,118 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('taobao_alipay_bill_imports')) { + $schema->create('taobao_alipay_bill_imports', function (Blueprint $table): void { + $table->uuid('generation')->primary(); + $table->string('source_filename'); + $table->char('source_sha256', 64)->unique(); + $table->date('period_start'); + $table->date('period_end'); + $table->string('status', 32)->default('running'); + $table->unsignedBigInteger('expected_row_count'); + $table->decimal('expected_income_total', 20, 2); + $table->decimal('expected_expense_total', 20, 2); + $table->unsignedBigInteger('row_count')->default(0); + $table->unsignedInteger('store_count')->default(0); + $table->unsignedInteger('bill_item_count')->default(0); + $table->json('business_type_counts')->nullable(); + $table->decimal('income_total', 20, 2)->default(0); + $table->decimal('expense_total', 20, 2)->default(0); + $table->decimal('net_total', 20, 2)->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->timestamps(); + + $table->index(['status', 'period_start', 'period_end'], 'taobao_alipay_bill_import_period_idx'); + }); + } + + if (! $schema->hasTable('taobao_alipay_bill_staging')) { + $schema->create('taobao_alipay_bill_staging', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->uuid('generation'); + $this->billColumns($table); + $table->unique(['generation', 'record_code'], 'taobao_alipay_bill_stage_generation_record_uq'); + $table->index(['generation', 'occurred_at'], 'taobao_alipay_bill_stage_generation_time_idx'); + }); + } + + if (! $schema->hasTable('taobao_alipay_bill_rows')) { + $schema->create('taobao_alipay_bill_rows', function (Blueprint $table): void { + $table->string('record_code', 191)->primary(); + $this->billColumns($table, false); + $table->uuid('source_generation'); + $table->char('source_sha256', 64); + $table->timestamp('imported_at'); + + $table->index(['occurred_at', 'record_code'], 'taobao_alipay_bill_time_record_idx'); + $table->index(['store_name', 'occurred_at'], 'taobao_alipay_bill_store_time_idx'); + $table->index(['bill_item', 'occurred_at'], 'taobao_alipay_bill_item_time_idx'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('taobao_alipay_bill_rows'); + $schema->dropIfExists('taobao_alipay_bill_staging'); + $schema->dropIfExists('taobao_alipay_bill_imports'); + } + + private function billColumns(Blueprint $table, bool $includeRecordCode = true): void + { + if ($includeRecordCode) { + $table->string('record_code', 191); + } + $table->string('store_name')->nullable(); + $table->string('custom_remark')->nullable(); + $table->string('bill_item')->nullable(); + $table->string('alipay_account')->nullable(); + $table->string('account_order_no', 191)->nullable(); + $table->string('business_serial_no', 191)->nullable(); + $table->string('merchant_order_no', 191)->nullable(); + $table->string('business_base_order_no', 191)->nullable(); + $table->string('goods_name', 1000)->nullable(); + $table->string('counterparty_account', 255)->nullable(); + $table->dateTime('occurred_at'); + $table->decimal('income_amount', 20, 6)->default(0); + $table->decimal('expense_amount', 20, 6)->default(0); + $table->decimal('balance_amount', 20, 6)->default(0); + $table->string('business_type')->nullable(); + $table->string('remark', 1000)->nullable(); + $table->string('online_order_no', 191)->nullable(); + $table->string('online_real_store')->nullable(); + $table->string('business_description', 1000)->nullable(); + $table->string('business_bill_source', 255)->nullable(); + $table->string('business_order_no', 191)->nullable(); + $table->dateTime('source_created_at')->nullable(); + $table->dateTime('source_updated_at')->nullable(); + $table->string('source_modified_by')->nullable(); + $table->unsignedBigInteger('source_row_number'); + } +}; diff --git a/database/migrations/2026_09_29_160000_create_product_monthly_weighted_average_tables.php b/database/migrations/2026_09_29_160000_create_product_monthly_weighted_average_tables.php new file mode 100644 index 00000000..c8b692b9 --- /dev/null +++ b/database/migrations/2026_09_29_160000_create_product_monthly_weighted_average_tables.php @@ -0,0 +1,69 @@ +connection()); + + if (! $schema->hasTable('product_monthly_weighted_average_rows')) { + $schema->create('product_monthly_weighted_average_rows', function (Blueprint $table): void { + $table->date('report_month'); + $table->char('row_key', 64); + $table->string('barcode_warehouse', 191); + $table->string('warehouse_short_name', 191); + $table->string('supplier', 191)->nullable(); + $table->string('product_code', 191); + $table->string('product_name', 191)->nullable(); + $table->decimal('opening_quantity', 20, 4)->nullable(); + $table->decimal('opening_unit_price', 20, 4)->nullable(); + $table->decimal('opening_original_amount', 20, 4)->nullable(); + $table->decimal('adjusted_unit_price', 20, 4)->nullable(); + $table->decimal('opening_amount', 20, 4)->nullable(); + $table->decimal('purchase_quantity', 20, 4)->nullable(); + $table->decimal('purchase_unit_price', 20, 4)->nullable(); + $table->decimal('purchase_amount', 20, 4)->nullable(); + $table->decimal('weighted_average_unit_price', 20, 4)->nullable(); + $table->string('pricing_status', 64)->nullable(); + $table->string('base_source', 16)->default('base'); + $table->dateTime('imported_at'); + $table->dateTime('computed_at')->nullable(); + + $table->primary(['report_month', 'row_key'], 'product_monthly_weighted_rows_primary'); + $table->index(['report_month', 'warehouse_short_name'], 'product_monthly_weighted_rows_warehouse_index'); + $table->index(['report_month', 'product_code'], 'product_monthly_weighted_rows_product_index'); + }); + } + + if (! $schema->hasTable('product_monthly_weighted_average_states')) { + $schema->create('product_monthly_weighted_average_states', function (Blueprint $table): void { + $table->date('report_month')->primary(); + $table->string('status', 24)->default('pending'); + $table->string('base_filename', 255)->nullable(); + $table->unsignedInteger('base_rows')->default(0); + $table->unsignedInteger('delivery_rows')->default(0); + $table->unsignedInteger('matched_rows')->default(0); + $table->unsignedInteger('computed_rows')->default(0); + $table->dateTime('last_computed_at')->nullable(); + $table->string('last_error', 255)->nullable(); + $table->timestamps(); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('product_monthly_weighted_average_rows'); + $schema->dropIfExists('product_monthly_weighted_average_states'); + } +}; diff --git a/database/migrations/2026_09_29_170000_add_previous_pricing_status_to_product_monthly_weighted_rows.php b/database/migrations/2026_09_29_170000_add_previous_pricing_status_to_product_monthly_weighted_rows.php new file mode 100644 index 00000000..959660c9 --- /dev/null +++ b/database/migrations/2026_09_29_170000_add_previous_pricing_status_to_product_monthly_weighted_rows.php @@ -0,0 +1,31 @@ +hasTable('product_monthly_weighted_average_rows') + || $schema->hasColumn('product_monthly_weighted_average_rows', 'previous_pricing_status')) { + return; + } + + $schema->table('product_monthly_weighted_average_rows', function (Blueprint $table): void { + $table->string('previous_pricing_status', 64)->nullable()->after('opening_unit_price'); + }); + } + + public function down(): void + { + $schema = Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + if ($schema->hasColumn('product_monthly_weighted_average_rows', 'previous_pricing_status')) { + $schema->table('product_monthly_weighted_average_rows', function (Blueprint $table): void { + $table->dropColumn('previous_pricing_status'); + }); + } + } +}; diff --git a/database/migrations/2026_09_30_100000_create_inventory_inbound_detail_rows.php b/database/migrations/2026_09_30_100000_create_inventory_inbound_detail_rows.php new file mode 100644 index 00000000..52086da2 --- /dev/null +++ b/database/migrations/2026_09_30_100000_create_inventory_inbound_detail_rows.php @@ -0,0 +1,53 @@ +hasTable('inventory_inbound_detail_rows')) { + return; + } + + $schema->create('inventory_inbound_detail_rows', function (Blueprint $table): void { + $table->date('report_month'); + $table->char('row_key', 64); + $table->string('source_no', 64)->nullable(); + $table->string('document_no', 64)->nullable(); + $table->string('created_serial', 32)->nullable(); + $table->string('supplier', 191)->nullable(); + $table->string('item_no', 191)->nullable(); + $table->string('barcode', 191)->nullable(); + $table->string('spec_name', 255)->nullable(); + $table->decimal('quantity', 20, 4)->nullable(); + $table->decimal('unit_price', 20, 4)->nullable(); + $table->decimal('amount', 20, 4)->nullable(); + $table->decimal('estimated_unit_price', 20, 4)->nullable(); + $table->decimal('estimated_amount', 20, 4)->nullable(); + $table->string('supplier_barcode', 191)->nullable(); + $table->string('remark', 255)->nullable(); + $table->string('warehouse', 191)->nullable(); + $table->string('warehouse_short_name', 191)->nullable(); + $table->dateTime('created_at_raw')->nullable(); + $table->string('express_name', 191)->nullable(); + $table->string('express_no', 191)->nullable(); + $table->string('not_sent', 64)->nullable(); + $table->string('owner_name', 191)->nullable(); + $table->dateTime('imported_at'); + + $table->primary(['report_month', 'row_key'], 'inventory_inbound_detail_primary'); + $table->index(['report_month', 'warehouse_short_name'], 'inventory_inbound_detail_warehouse_index'); + $table->index(['report_month', 'barcode'], 'inventory_inbound_detail_barcode_index'); + }); + } + + public function down(): void + { + Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->dropIfExists('inventory_inbound_detail_rows'); + } +}; diff --git a/database/migrations/2026_09_30_120000_create_planting_details_table.php b/database/migrations/2026_09_30_120000_create_planting_details_table.php new file mode 100644 index 00000000..9131d90e --- /dev/null +++ b/database/migrations/2026_09_30_120000_create_planting_details_table.php @@ -0,0 +1,58 @@ +increments('id'); + $table->unsignedInteger('company_id'); + $table->date('bill_date')->comment('日期'); + $table->string('order_no', 100)->nullable()->comment('订单编号'); + $table->decimal('finance_selling_price', 18, 4)->default(0)->comment('财务售价'); + $table->decimal('finance_freight', 18, 4)->default(0)->comment('财务运费'); + $table->decimal('finance_commission', 18, 4)->default(0)->comment('财务佣金'); + $table->decimal('jingxi_price_diff', 18, 4)->default(0)->comment('京喜差价'); + $table->decimal('deduction', 18, 4)->default(0)->comment('扣款'); + $table->decimal('finance_empty_package_fee', 18, 4)->default(0)->comment('财务空包费'); + $table->decimal('finance_payment_amount', 18, 4)->default(0)->comment('财务打款金额'); + $table->integer('pieces')->default(0)->comment('笔数'); + $table->text('remark')->nullable()->comment('备注'); + $table->string('store', 191)->nullable()->comment('正确店铺'); + $table->string('owner', 191)->nullable()->comment('负责人'); + $table->string('account', 191)->nullable()->comment('账户'); + $table->string('type', 191)->nullable()->comment('类型'); + $table->string('creator', 191)->nullable()->comment('创建人'); + $table->string('tag', 191)->nullable()->comment('标签'); + $table->string('profit_center', 191)->nullable()->comment('所属利润中心'); + $table->string('responsible_platform', 191)->nullable()->comment('负责平台'); + $table->string('external_id', 100)->nullable()->comment('ID'); + $table->string('created_from', 100)->nullable(); + $table->unsignedInteger('created_by')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->index(['company_id', 'bill_date']); + $table->index(['company_id', 'store']); + $table->index(['company_id', 'owner']); + $table->index(['company_id', 'type']); + $table->index(['company_id', 'tag']); + $table->index('order_no'); + }); + } + + public function down(): void + { + Schema::dropIfExists('planting_details'); + } +}; diff --git a/database/migrations/2026_09_30_130000_widen_planting_details_external_id.php b/database/migrations/2026_09_30_130000_widen_planting_details_external_id.php new file mode 100644 index 00000000..72621696 --- /dev/null +++ b/database/migrations/2026_09_30_130000_widen_planting_details_external_id.php @@ -0,0 +1,26 @@ +text('external_id')->nullable()->change(); + }); + } + + public function down(): void + { + Schema::table('planting_details', function (Blueprint $table) { + $table->string('external_id', 100)->nullable()->change(); + }); + } +}; diff --git a/database/migrations/2026_09_30_160000_create_jst_order_labels_table.php b/database/migrations/2026_09_30_160000_create_jst_order_labels_table.php new file mode 100644 index 00000000..e963d8d3 --- /dev/null +++ b/database/migrations/2026_09_30_160000_create_jst_order_labels_table.php @@ -0,0 +1,40 @@ +bigIncrements('id'); + $table->unsignedInteger('company_id'); + $table->string('order_no', 100)->comment('线上订单号'); + $table->string('shop_name', 191)->nullable()->comment('店铺名称'); + $table->dateTime('ordered_at')->comment('下单时间'); + $table->string('label', 191)->comment('标签(单个)'); + $table->string('created_from', 100)->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->index(['company_id', 'ordered_at'], 'jst_order_labels_company_time'); + $table->index(['company_id', 'label'], 'jst_order_labels_company_label'); + $table->index(['company_id', 'shop_name'], 'jst_order_labels_company_shop'); + $table->index('order_no', 'jst_order_labels_order_no'); + }); + } + + public function down(): void + { + Schema::dropIfExists('jst_order_labels'); + } +}; diff --git a/database/migrations/2026_10_03_000100_create_store_report_shop_period_changes_table.php b/database/migrations/2026_10_03_000100_create_store_report_shop_period_changes_table.php new file mode 100644 index 00000000..960c948f --- /dev/null +++ b/database/migrations/2026_10_03_000100_create_store_report_shop_period_changes_table.php @@ -0,0 +1,38 @@ +connection()); + + if (! $schema->hasTable('store_report_shop_period_changes')) { + $schema->create('store_report_shop_period_changes', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('erp_store_name', 191); + $table->string('company_name', 191)->nullable(); + $table->string('unified_social_credit_code', 64)->nullable(); + $table->date('observed_on'); + $table->string('source', 32)->default('crawl_shop_company'); + $table->string('business_key', 64); + $table->timestamps(); + $table->unique('business_key', 'store_report_period_changes_key_unique'); + $table->index(['erp_store_name', 'observed_on'], 'store_report_period_changes_store_time_index'); + }); + } + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists('store_report_shop_period_changes'); + } +}; diff --git a/database/migrations/2026_10_03_000200_cleanup_legacy_logic_setting_keys.php b/database/migrations/2026_10_03_000200_cleanup_legacy_logic_setting_keys.php new file mode 100644 index 00000000..13807832 --- /dev/null +++ b/database/migrations/2026_10_03_000200_cleanup_legacy_logic_setting_keys.php @@ -0,0 +1,33 @@ +whereIn('key', [ + 'business_data_logic.entity_trademark', + 'store_report.initial_periods', + 'store_report.initial_periods.shops', + ]) + ->orWhere('key', 'like', 'store_report.initial_periods.shops.%') + ->delete(); + } + + public function down(): void + { + // 清理动作不可逆,也不影响现有数据。 + } +}; diff --git a/database/migrations/2026_10_05_000000_create_business_internal_flow_records_table.php b/database/migrations/2026_10_05_000000_create_business_internal_flow_records_table.php new file mode 100644 index 00000000..c3a2a150 --- /dev/null +++ b/database/migrations/2026_10_05_000000_create_business_internal_flow_records_table.php @@ -0,0 +1,53 @@ +connection()); + + if ($schema->hasTable('business_internal_flow_records')) { + return; + } + + $schema->create('business_internal_flow_records', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedInteger('sort_order')->default(0)->comment('源表行序,用于保持页面默认顺序'); + $table->string('company_name', 191)->comment('抬头'); + $table->string('tag', 32)->nullable()->comment('标签'); + $table->decimal('projected_sales', 20, 6)->nullable()->comment('预计9月销量'); + $table->decimal('invoiced_to_buyer', 20, 6)->nullable()->comment('开票-给买家开票'); + $table->decimal('internal_invoiced', 20, 6)->nullable()->comment('开票-内部开票'); + $table->decimal('required_input_cost', 20, 6)->nullable()->comment('所需进项成本'); + $table->decimal('receipt_from_supplier', 20, 6)->nullable()->comment('收票-供应商'); + $table->decimal('receipt_from_suofeiya', 20, 6)->nullable()->comment('收票-索菲亚'); + $table->decimal('receipt_from_gujia', 20, 6)->nullable()->comment('收票-顾家'); + $table->decimal('internal_transfer_1', 20, 6)->nullable()->comment('收票-内部流转(来源)1'); + $table->decimal('internal_transfer_2', 20, 6)->nullable()->comment('收票-内部流转(来源)2'); + $table->decimal('internal_transfer_3', 20, 6)->nullable()->comment('收票-内部流转(来源)3'); + $table->decimal('receipt_total', 20, 6)->nullable()->comment('收票-合计'); + $table->decimal('remaining_gap', 20, 6)->nullable()->comment('剩余缺口'); + $table->string('invoicing_ratio', 32)->nullable()->comment('开票比例,源表存在 “/” 原样保留'); + $table->string('source_file', 191)->nullable()->comment('导入文件名'); + $table->timestamp('imported_at')->nullable()->comment('导入时间'); + $table->timestamps(); + + $table->index('sort_order', 'business_internal_flow_records_sort_index'); + $table->index('company_name', 'business_internal_flow_records_company_index'); + }); + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists('business_internal_flow_records'); + } +}; diff --git a/database/migrations/2026_10_05_100000_widen_product_monthly_weighted_average_precision.php b/database/migrations/2026_10_05_100000_widen_product_monthly_weighted_average_precision.php new file mode 100644 index 00000000..f4eb407c --- /dev/null +++ b/database/migrations/2026_10_05_100000_widen_product_monthly_weighted_average_precision.php @@ -0,0 +1,38 @@ +hasTable('product_monthly_weighted_average_rows')) { + return; + } + + // 精度改写语句只在 MySQL 上有效;测试环境用 sqlite 内存库,保持原状。 + if (DB::connection($connection)->getDriverName() !== 'mysql') { + return; + } + + foreach (self::COLUMNS as $column) { + DB::connection($connection)->statement( + "alter table `product_monthly_weighted_average_rows` modify `{$column}` decimal(24,8) null", + ); + } + } + + public function down(): void + { + // 缩放回 4 位会丢失精度,这里保持不回退。 + } +}; diff --git a/database/migrations/2026_10_06_100000_create_store_receipt_order_match_rows.php b/database/migrations/2026_10_06_100000_create_store_receipt_order_match_rows.php new file mode 100644 index 00000000..f1fb7539 --- /dev/null +++ b/database/migrations/2026_10_06_100000_create_store_receipt_order_match_rows.php @@ -0,0 +1,43 @@ +hasTable('store_receipt_order_match_rows')) { + return; + } + + $schema->create('store_receipt_order_match_rows', function (Blueprint $table): void { + $table->date('report_month'); + $table->char('row_key', 64); + $table->date('occurred_date')->nullable(); + $table->string('store_name', 191)->nullable(); + $table->string('online_order_no', 64)->nullable(); + $table->unsignedInteger('payment_count')->default(0); + $table->decimal('income_amount', 20, 4)->default(0); + $table->string('warehouse', 191)->nullable(); + $table->string('product_code', 191)->nullable(); + $table->decimal('quantity', 20, 4)->nullable(); + $table->decimal('product_amount', 20, 4)->nullable(); + $table->string('match_status', 32)->nullable(); + $table->dateTime('imported_at'); + + $table->primary(['report_month', 'row_key'], 'store_receipt_order_match_primary'); + $table->index(['report_month', 'store_name'], 'store_receipt_order_match_store_index'); + $table->index(['report_month', 'online_order_no'], 'store_receipt_order_match_order_index'); + $table->index(['report_month', 'match_status'], 'store_receipt_order_match_status_index'); + }); + } + + public function down(): void + { + Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->dropIfExists('store_receipt_order_match_rows'); + } +}; diff --git a/database/migrations/2026_10_06_120000_reshape_store_receipt_order_match_rows.php b/database/migrations/2026_10_06_120000_reshape_store_receipt_order_match_rows.php new file mode 100644 index 00000000..44de6b85 --- /dev/null +++ b/database/migrations/2026_10_06_120000_reshape_store_receipt_order_match_rows.php @@ -0,0 +1,64 @@ +connection()); + if (! $schema->hasTable('store_receipt_order_match_rows')) { + return; + } + + $schema->table('store_receipt_order_match_rows', function (Blueprint $table): void { + if (! Schema::connection($this->connection())->hasColumn('store_receipt_order_match_rows', 'order_core_no')) { + $table->string('order_core_no', 64)->nullable()->after('online_order_no'); + } + if (! Schema::connection($this->connection())->hasColumn('store_receipt_order_match_rows', 'difference')) { + $table->decimal('difference', 20, 4)->nullable()->after('product_amount'); + } + if (! Schema::connection($this->connection())->hasColumn('store_receipt_order_match_rows', 'remark')) { + $table->string('remark', 64)->nullable()->after('match_status'); + } + }); + + // warehouse/product_code/quantity 已不在输出列;order_product_amount 是 + // 旧的「明细行 + 订单级商品金额」方案遗留列,新口径下由 product_amount 直接承载。 + $columns = ['warehouse', 'product_code', 'quantity', 'order_product_amount']; + $existing = array_filter($columns, fn (string $column): bool => Schema::connection($this->connection()) + ->hasColumn('store_receipt_order_match_rows', $column)); + + if ($existing !== []) { + $schema->table('store_receipt_order_match_rows', function (Blueprint $table) use ($existing): void { + $table->dropColumn(array_values($existing)); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('store_receipt_order_match_rows')) { + return; + } + + $schema->table('store_receipt_order_match_rows', function (Blueprint $table): void { + $table->string('warehouse', 191)->nullable(); + $table->string('product_code', 191)->nullable(); + $table->decimal('quantity', 20, 4)->nullable(); + $table->dropColumn(['order_core_no', 'difference', 'remark']); + }); + } +}; diff --git a/database/migrations/2026_10_06_180000_create_store_violation_records_table.php b/database/migrations/2026_10_06_180000_create_store_violation_records_table.php new file mode 100644 index 00000000..083789dd --- /dev/null +++ b/database/migrations/2026_10_06_180000_create_store_violation_records_table.php @@ -0,0 +1,53 @@ +connection()); + + if ($schema->hasTable('store_violation_records')) { + return; + } + + $schema->create('store_violation_records', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('platform', 32); + $table->string('shop_name', 191)->default(''); + $table->string('violation_type', 500)->nullable(); + $table->string('violation_category', 64)->nullable(); + $table->string('violation_no', 100); + $table->date('violation_date')->nullable(); + $table->decimal('points_deducted', 10, 2)->nullable(); + $table->string('status', 64)->nullable(); + $table->date('penalty_date')->nullable(); + $table->date('appeal_deadline')->nullable(); + $table->string('handling_status', 32)->default('未处理'); + $table->string('source', 16)->default('crawl'); + $table->string('window_name', 191)->nullable(); + $table->date('crawl_date')->nullable(); + $table->dateTime('synced_at')->nullable(); + $table->timestamps(); + + $table->unique(['platform', 'violation_no'], 'store_violations_platform_no_unique'); + $table->index(['platform', 'violation_date'], 'store_violations_platform_date_index'); + $table->index(['platform', 'shop_name'], 'store_violations_platform_shop_index'); + $table->index(['platform', 'status'], 'store_violations_platform_status_index'); + $table->index(['platform', 'handling_status'], 'store_violations_platform_handling_index'); + }); + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists('store_violation_records'); + } +}; diff --git a/deploy/Dockerfile b/deploy/Dockerfile index 02cc6fe6..3efe271f 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -35,7 +35,7 @@ RUN apt-get -o Acquire::Retries=3 update \ && a2enmod expires headers rewrite \ && rm -rf /var/lib/apt/lists/* -FROM composer:2.8@sha256:5248900ab8b5f7f880c2d62180e40960cd87f60149ec9a1abfd62ac72a02577c AS composer-bin +FROM m.daocloud.io/docker.io/library/composer:2.8@sha256:5248900ab8b5f7f880c2d62180e40960cd87f60149ec9a1abfd62ac72a02577c AS composer-bin FROM php-base AS vendor @@ -45,8 +45,17 @@ WORKDIR /build COPY composer.json composer.lock ./ +## 可选:Composer 下载源(留空使用官方源)。 +## 国内网络访问 GitHub 受限时,发布脚本会传入镜像源,例如 https://mirrors.cloud.tencent.com/composer/。 +ARG COMPOSER_REPO_PACKAGIST="" + RUN --mount=type=cache,target=/tmp/composer-cache \ set -eu; \ + if [ -n "${COMPOSER_REPO_PACKAGIST:-}" ]; then \ + export COMPOSER_REPO_PACKAGIST; \ + else \ + unset COMPOSER_REPO_PACKAGIST; \ + fi; \ attempt=1; \ while true; do \ if COMPOSER_CACHE_DIR=/tmp/composer-cache \ @@ -78,11 +87,16 @@ RUN apt-get -o Acquire::Retries=3 update \ ARG VCS_REF=unknown ARG BUILD_DATE=unknown +ARG APP_VERSION=3.1.15 LABEL com.caiwu.project="CaiWuXiTong" \ org.opencontainers.image.revision="$VCS_REF" \ org.opencontainers.image.created="$BUILD_DATE" +ENV CAIWU_APP_VERSION="$APP_VERSION" \ + CAIWU_BUILD_COMMIT="$VCS_REF" \ + CAIWU_BUILD_TIME="$BUILD_DATE" + WORKDIR /var/www/html COPY --from=vendor /build/vendor /var/www/html/vendor diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index b467f70b..d9b7e7e3 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -140,7 +140,7 @@ fi healthy=0 attempt=1 while [ "$attempt" -le 30 ]; do - if curl -fsS -o /dev/null http://127.0.0.1:18088/; then + if curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then healthy=1 break fi @@ -164,7 +164,7 @@ if ! docker exec -u www-data caiwu_app php artisan storage:business-files:sync - exit 1 fi -if ! curl -fsS -o /dev/null http://127.0.0.1:18088/; then +if ! curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then restore_previous_image echo "Release failed after business storage activation; previous image was restored when available" >&2 exit 1 @@ -178,11 +178,17 @@ mv "$REMOTE_DIR/.deployed-sha.tmp" "$REMOTE_DIR/.deployed-sha" # 普通商品优先高频增量,并在配置的每周低峰窗口自动继续全量校准。 cat > /etc/cron.d/caiwu-jiansun-snapshots <<'EOF' CRON_TZ=Asia/Shanghai -* * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-catalog --quiet; /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-store-report --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan upstream:snapshots:refresh-all --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables --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-third-party-warehouse-storage --max-batches=0 --quiet >/dev/null 2>&1 +* * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-catalog --quiet; /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 upstream:snapshots:refresh-all --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables --quiet' >/dev/null 2>&1 +# 店铺经营报表按 15 分钟刷新;单轮覆盖 50000 行回看窗口,避免空闲时持续重读千万级账单。 +7,22,37,52 * * * * root /usr/bin/flock -w 600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-store-report --max-batches=12 --quiet >/dev/null 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:sync-third-party-warehouse-storage --max-batches=0 --quiet && /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 +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 */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 28 1 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan jushuitan:sync-shipping --days=3 >/dev/null 2>&1 +# 头条放心购(店铺收款账户账单 › 抖音账户)资金流水:每天 09:30 定点把该渠道所用 +# 原始账单镜像追平一次,保证上班前当日/前一日流水已进系统,而不是等每分钟轮转慢慢走。 +30 9 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_originalBillInfo --max-batches=20 --quiet >/dev/null 2>&1 EOF chmod 644 /etc/cron.d/caiwu-jiansun-snapshots diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index a3df1591..241950e2 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -144,7 +144,7 @@ fi healthy=0 attempt=1 while [ "$attempt" -le 30 ]; do - if curl -fsS -o /dev/null http://127.0.0.1:18088/; then + if curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then healthy=1 break fi @@ -168,7 +168,7 @@ if ! docker exec -u www-data caiwu_app php artisan storage:business-files:sync - exit 1 fi -if ! curl -fsS -o /dev/null http://127.0.0.1:18088/; then +if ! curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then restore_previous_image echo "Release failed after business storage activation; previous image was restored when available" >&2 exit 1 @@ -182,11 +182,17 @@ mv "$REMOTE_DIR/.deployed-sha.tmp" "$REMOTE_DIR/.deployed-sha" # 普通商品优先高频增量,并在配置的每周低峰窗口自动继续全量校准。 cat > /etc/cron.d/caiwu-jiansun-snapshots <<'EOF' CRON_TZ=Asia/Shanghai -* * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-catalog --quiet; /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-store-report --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan upstream:snapshots:refresh-all --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables --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-third-party-warehouse-storage --max-batches=0 --quiet >/dev/null 2>&1 +* * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-catalog --quiet; /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 upstream:snapshots:refresh-all --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables --quiet' >/dev/null 2>&1 +# 店铺经营报表按 15 分钟刷新;单轮覆盖 50000 行回看窗口,避免空闲时持续重读千万级账单。 +7,22,37,52 * * * * root /usr/bin/flock -w 600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-store-report --max-batches=12 --quiet >/dev/null 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:sync-third-party-warehouse-storage --max-batches=0 --quiet && /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 +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 */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 28 1 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan jushuitan:sync-shipping --days=3 >/dev/null 2>&1 +# 头条放心购(店铺收款账户账单 › 抖音账户)资金流水:每天 09:30 定点把该渠道所用 +# 原始账单镜像追平一次,保证上班前当日/前一日流水已进系统,而不是等每分钟轮转慢慢走。 +30 9 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_originalBillInfo --max-batches=20 --quiet >/dev/null 2>&1 EOF chmod 644 /etc/cron.d/caiwu-jiansun-snapshots diff --git a/deploy/entrypoint.sh b/deploy/entrypoint.sh index c4b2ace2..422e0dd2 100644 --- a/deploy/entrypoint.sh +++ b/deploy/entrypoint.sh @@ -37,6 +37,11 @@ run_artisan_as_web() { runuser -u www-data -- php artisan "$@" } +app_environment="" +if [ -f .env ]; then + app_environment="$(sed -n 's/^APP_ENV=//p' .env | tail -n 1 | tr -d '\r' | sed 's/^"//; s/"$//; s/^'\''//; s/'\''$//')" +fi + if [ "${1:-}" = "apache2-foreground" ]; then sed -ri 's/^Listen 80$/Listen 18088/' /etc/apache2/ports.conf assert_web_writable @@ -53,8 +58,17 @@ if [ "${1:-}" = "apache2-foreground" ]; then run_artisan_as_web migrate --force fi - run_artisan_as_web config:cache - run_artisan_as_web view:cache + if [ "$app_environment" = "local" ]; then + # Keep development source live: optimize:clear above removes any + # stale bootstrap/view artifacts, while view.cache=false makes + # Blade recompile templates on every request without a restart. + run_artisan_as_web optimize:clear + else + # Production keeps the existing immutable config and compiled + # Blade caches for startup and request performance. + run_artisan_as_web config:cache + run_artisan_as_web view:cache + fi fi fi diff --git a/deploy/local-healthcheck.sh b/deploy/local-healthcheck.sh index 3e11222c..d6015b8d 100644 --- a/deploy/local-healthcheck.sh +++ b/deploy/local-healthcheck.sh @@ -17,5 +17,5 @@ runuser -u www-data -- php artisan app:ready --quiet # Artisan 能先于 Apache 启动完成;必须同时确认真实 HTTP 入口已经响应, # 防止初始化脚本在容器“看似健康”时过早访问并得到空响应。 curl --fail --silent --show-error --max-time 5 \ - http://127.0.0.1:18088/auth/login \ + http://127.0.0.1:18088/serviceworker.js \ >/dev/null diff --git a/deploy/local-init.sh b/deploy/local-init.sh index 6dfa66b8..79f8b978 100644 --- a/deploy/local-init.sh +++ b/deploy/local-init.sh @@ -81,6 +81,7 @@ calculate_local_image_fingerprint() { deploy/Dockerfile.local \ deploy/apache-vhost.conf \ deploy/php.ini \ + deploy/php-local.ini \ deploy/entrypoint.sh \ deploy/local-healthcheck.sh @@ -342,7 +343,7 @@ fi db_host="$(read_env_value DB_HOST)" app_installed="$(read_env_value APP_INSTALLED | tr '[:upper:]' '[:lower:]')" -docker compose -f "$compose_file" up -d --no-build app +docker compose -f "$compose_file" up -d --no-build app frontend # 容器可能已经存在而没有重新执行 entrypoint。显式复用同一权限初始化逻辑, # 修复历史 root CLI 遗留目录;该命令本身不运行 Artisan。 @@ -384,6 +385,11 @@ fi echo "==> 自动检查本机临时引导库结构..." docker compose -f "$compose_file" exec -T -u www-data app php artisan optimize:clear >/dev/null +echo "==> 自动检查供应商应付本地维护库结构..." +docker compose -f "$compose_file" exec -T -u www-data app \ + php artisan migrate --database=supplier_payable_maintenance \ + --path=database/migrations/2026_09_17_000000_create_supplier_payable_override_tables.php \ + --force --no-ansi docker compose -f "$compose_file" exec -T -u www-data app \ php artisan local-bootstrap:update --no-ansi diff --git a/deploy/php-local.ini b/deploy/php-local.ini new file mode 100644 index 00000000..812a4875 --- /dev/null +++ b/deploy/php-local.ini @@ -0,0 +1,6 @@ +; Local development serves bind-mounted PHP/Blade source directly. Disable +; opcode caching so a browser refresh always executes the current source. +opcache.enable=0 +opcache.enable_cli=0 +opcache.validate_timestamps=1 +opcache.revalidate_freq=0 diff --git a/docker-compose.local.yml b/docker-compose.local.yml index 45276cf0..17891e12 100644 --- a/docker-compose.local.yml +++ b/docker-compose.local.yml @@ -20,12 +20,26 @@ services: depends_on: mysql: condition: service_healthy + environment: + # Local test data entry uses PATCH requests; do not let the global + # firewall heuristics block the maintenance-only test environment. + FIREWALL_ENABLED: "false" + SUPPLIER_PAYABLE_MAINTENANCE_DB_CONNECTION: supplier_payable_maintenance + SUPPLIER_PAYABLE_MAINTENANCE_DB_DRIVER: mysql + SUPPLIER_PAYABLE_MAINTENANCE_DB_HOST: mysql + SUPPLIER_PAYABLE_MAINTENANCE_DB_PORT: 3306 + SUPPLIER_PAYABLE_MAINTENANCE_DB_DATABASE: akaunting + SUPPLIER_PAYABLE_MAINTENANCE_DB_USERNAME: akaunting + SUPPLIER_PAYABLE_MAINTENANCE_DB_PASSWORD: akaunting123 + SUPPLIER_PAYABLE_MAINTENANCE_DB_PREFIX: ak_ ports: - "127.0.0.1:18088:18088" volumes: - ./runtime/.env:/var/www/html/.env - ./runtime/bills.sqlite:/var/www/html/runtime/bills.sqlite:ro + - ./deploy/php-local.ini:/usr/local/etc/php/conf.d/zz-local-dev.ini:ro - jiangling_storage:/var/www/html/storage + - jiangling_public:/var/www/html/public - ./app:/var/www/html/app - ./config:/var/www/html/config - ./database:/var/www/html/database @@ -44,6 +58,23 @@ services: retries: 10 start_period: 60s + # Laravel Mix watcher for local frontend development. The generated assets + # live in a shared volume so Apache serves the latest build immediately. + frontend: + image: jiangling_akaunting:local + container_name: jiangling_frontend + restart: unless-stopped + user: "www-data" + working_dir: /var/www/html + command: ["npm", "run", "watch-poll"] + environment: + NPM_CONFIG_UPDATE_NOTIFIER: "false" + volumes: + - jiangling_public:/var/www/html/public + - ./resources:/var/www/html/resources + networks: + - jiangling_net + mysql: image: mysql:8.0 container_name: jiangling_mysql @@ -108,6 +139,8 @@ volumes: name: jiangling_mysql jiangling_clickhouse: name: jiangling_clickhouse + jiangling_public: + name: jiangling_public networks: jiangling_net: diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 8d1e95fc..55625e3b 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -12,10 +12,11 @@ | --- | --- | | 已完成 | `operations_replica/rpt.Bulk_Price_Limit` 已进入类型化表 `product_price_mirror_rows`,商品价格页面已读取镜像并支持完整分页。 | | 已完成 | `operations_replica/rpt.jst_sku` 已进入 `ops_jst_sku`,普通商品资料页面固定读取 `sku_type = normal` 的共享镜像,并支持稳定分页和业务筛选。 | -| 本次接入 | 聚水潭进销存“商品 + 按天”数据固定读取 `jiansun/dbo.jst_inoutWater + dbo.jst_inoutWaterItem + dbo.jst_inventoryInfo` 中仓库 `三方-南昌樵舍仓`(`wms_co_id = 15045364`),进入专用流水、明细、库存快照及同步状态镜像。页面位于“快递应付 / 三方仓进销存”,仅展示 2026-08-01 起的数据;按月或单日选择后均输出“日期 + 商品”明细,并支持分页、筛选、数量汇总和导出。 | +| 本次接入 | 聚水潭进销存共享镜像读取 `jiansun/dbo.jst_inoutWater + dbo.jst_inoutWaterItem + dbo.jst_inventoryInfo` 的全部仓库,保留 2026-08-01 起的已确认流水与库存锚点。“快递应付 / 三方仓进销存”在查询层继续固定 `wms_co_id = 15045364`;“商品价格管理 / 进销存报表”按所有仓库、商品和月份汇总。 | | 已接入校准 | 聚水潭“普通商品资料”完整 XLSX 导出通过 `product-catalog:import-authoritative-export` 流式导入;导出中不存在的经营分析副本历史行写入 `product_catalog_exclusions`,页面与导出统一排除,但不删除 `ops_jst_sku` 原始镜像行。 | -| 本次接入 | `jiansun/dbo.jst_purchase + dbo.jst_purchaseItem` 通过固定联表查询进入 `product_purchase_price_mirror_rows`;普通商品资料只读取 `Finished` 且带“1688一键代发”标签的最近采购单价,并与原商品采购价分别标注来源。 | +| 本次接入 | `jiansun/dbo.jst_purchase + dbo.jst_purchaseItem` 通过固定联表查询进入 `product_purchase_price_mirror_rows`;普通商品资料只读取 `Finished` 且带“1688一键代发”标签的最近采购单价。线上代发价格页面另读取 `Confirmed` / `Finished` 采购明细,以 `source_o_id` 关联 `ops_jst_orders.o_id`,展示线上单号、店铺、供应商、商品编码、数量、单价并标记“采购单管理”;页面请求不直连上游。 | | 本次接入 | 工作平台快递资料页面读取 `wp_express` 主表,并预留网点 `wp_express_expNet`、打款账户 `wp_express_account` 标签;三张表均登记为独立镜像数据集,首次同步完成前页面明确显示同步状态。 | +| 本次接入 | 工作平台“客服系统 → 退款数据 → 退货取件管理”读取 `jiansun/dbo.ekf_ReturnPickupManagement`(主表)、`dbo.ekf_ReturnPickupManagement_Item`(明细分录)与 `dbo.ekf_ReturnPickupManagement_TruthReExpressNumber`(实退快递单号映射),分别镜像为 `js_ekf_return_pickup_management`、`js_ekf_return_pickup_management_item`、`js_ekf_return_pickup_truth_express`;主表按 `Id` + `updateTime`、明细按 `id` + `updatedTime`、映射按 `Id` + `createTime` 增量,逆向物流运费核算与退件跟踪只读共享镜像,不在页面请求中直连工作平台。2026-10-02 已完成首次全量(296,707 / 378,705 / 173,346 行)。 明细 `warehouse` 是混合编码:4 位工作平台仓码(`dbo.wp_warehouse.code` / `dbo.wp_warehouseConfig.whCode`)镜像为 `js_wp_warehouse`(992 行,`id` + `modified`)与 `js_wp_warehouse_config`(132 行,无更新时间按主键全量校准),8 位聚水潭 `wms_co_id` 继续读 `ops_jst_warehouse_info`;页面与导出按名称展示,未命中时保留原始编码。 | | 本次接入 | 聚水潭聚工单协同工单登记 `work_order_main`、`work_order_sub`、`work_order_form_config`、`work_order_form_value` 四张表;工单 API 固定筛选类型“仓内未发”,首次同步完成前返回同步未完成状态。 | | 待首次同步 | 聚水潭聚工单“小额打款”读取 `jiansun.dbo.jst_workOrderInfo` 与已解析映射 `dbo.jst_small_payment_order_map`;财务经营报表的小额打款页面固定筛选工单类型 `82D94F5C54544EE3833CD8A3AB8B9F73`,页面只读共享镜像,首次同步完成前明确显示待同步状态。 | | 本次建立 | `config/upstream_mirrors.php` 中登记全部当前代码引用的原表;通用表级同步框架负责建表、稳定游标、断点续传、增量重叠和全量校准。 | @@ -25,10 +26,13 @@ | 页面已切换 | 店铺收款账单的淘系支付宝账户读取 `operations_replica.rpt.jst_originalBillInfo`,并关联 `rpt.jst_shopInfo` 展示店铺;分页、筛选、汇总和导出统一读取共享业务镜像。 | | 抖音按月校准 | 抖音账户对已核对的完整月份读取 `douyin_authoritative_bills` 中胜算原始明细,`douyin_authoritative_periods` 原子选择有效版本;该月份不再叠加聚水潭拆分行。未校准月份继续读取原始账单镜像。导入命令为 `business-mirror:import-douyin-authoritative --count=<核对笔数> --income=<收入> --expense=<支出>`,只接受完整月份和精确核对值,保留旧版本、文件摘要及原镜像供回滚。生产执行前备份状态与受影响月份镜像,并使用 `/run/caiwu-upstream-sync.lock`。实际财务数据只放私有目录,不进入 Git。 | | 已接入待首次同步 | 店铺收款账单的拼多多账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel = PinduoduoImport` 的独立切片镜像 `js_jst_pdd_receiving_bill_rows`;不使用慢一天的 `operations_replica` 副本或营销账户 `pdd_spread_bills`。 | -| 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX 及多平台“平台资金账户余额”导出,进入 `jushuitan_shop_balance_snapshots`;已导入 2026-09-11 的淘系、拼多多和抖音共 164 条余额。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | +| 已接入待首次导入 | 店铺收款账单的得物账户读取聚胜算权威 XLSX 经受控导入生成的 `dewu_settlement_bill_rows`;保留得物、退货退款订单和扣减其他费用明细三类渠道,不再回退 `jst_originalBillInfo` 辅助镜像。 | +| 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX、多平台“平台资金账户余额”导出及“京东商城 → 京东钱包”流水,进入 `jushuitan_shop_balance_snapshots`。京东钱包按前一天作为截止日,每个店铺取最新费用结算时间的最后一笔账户余额,同一时间以最大记录编码消歧;每天 05:00 原子覆盖各来源范围,异常或空数据保留上一快照。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | -| 本次接入 | 普通商品成本价变更读取聚水潭开放平台“商品及库存管理”的商品操作日志接口 `/open/webapi/itemapi/itemsku/queryitemskuopshistory`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;审计历史按 `operation_id` 只追加或更新,全量回补不删除旧记录;页面按商品编码分别展示聚水潭成本价记录和工作平台价格记录,不混用来源。 | +| 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 | + +抖音月中校准可在上述导入命令追加 `--through=YYYY-MM-DD`,文件必须包含该月 1 日至截止日(含当天)的全部店铺和流水。系统仅替换这一日期范围,截止日之后继续读取原始账单镜像;省略参数仍表示完整月份。截止日期不得早于同月已校准范围。每天更新时重新导出月初至昨日的完整结果并核对笔数、收支总额,以覆盖迟到及修改记录,不能把单日增量当作月初至截止日的完整结果导入。 ## 经营分析副本库(operations_replica) @@ -63,7 +67,8 @@ | 营销账户 | `dbo.tmall_spread_bills`、`dbo.pdd_spread_bills`、`dbo.alibaba_bill`、`dbo.jd_spreadBills`、`dbo.jd_costBills` | | 供应商应付 | `dbo.finance_purchaseReturn`、`dbo.finance_invoiceDeduction`、`dbo.fys_supplierPaymentSummary`、`dbo.finance_advanceLoans`、`dbo.pm_unOrderDetails`、`dbo.finance_sampleDeduction`、`dbo.fys_express_courier_settlement` | | 快递运费对账明细 | `dbo.jst_order_express_details`、`dbo.Jst_SendData_View_extension`、`dbo.jst_salesOutboundInfo` | -| 三方仓进销存 | `dbo.jst_inoutWater`、`dbo.jst_inoutWaterItem`、`dbo.jst_inventoryInfo`(仅 `wms_co_id = 15045364`、`io_date >= 2026-08-01`;专用稳定游标与完整代次镜像) | +| 工作平台退货取件管理 | `dbo.ekf_ReturnPickupManagement`、`dbo.ekf_ReturnPickupManagement_Item`、`dbo.ekf_ReturnPickupManagement_TruthReExpressNumber`、发货仓名称 `dbo.wp_warehouse`、`dbo.wp_warehouseConfig` | +| 聚水潭进销存 | `dbo.jst_inoutWater`、`dbo.jst_inoutWaterItem`、`dbo.jst_inventoryInfo`(全部仓库、`io_date >= 2026-08-01`;专用稳定游标与完整代次镜像。三方仓页面仍固定 `wms_co_id = 15045364`,商品价格管理的进销存报表读取全仓库) | | 安装明细 | `dbo.fys_Ticketing_install_view`、`dbo.fys_Ticketing_install_item` | | 板材 | `dbo.finance_boardDeduction`、`dbo.pm_plainPlateData`、`dbo.pm_boardPurchasePrice`、`dbo.pm_boardPriceChangeImport`、`dbo.pm_boardApplyDetail` | | 封边条 | `dbo.pm_edgeBandData`、`dbo.pm_edgeBandApplyDetail`、`dbo.pm_edgeBandProfitInfo`、`dbo.finance_edgeBandDeductio`、`dbo.pm_averageUnitPrice` | @@ -73,6 +78,7 @@ | 快递资料 | `dbo.wp_express`、`dbo.wp_express_expNet`、`dbo.wp_express_account`、`dbo.wp_express_extension` | | 聚水潭小额打款工单 | `dbo.jst_workOrderInfo`(稳定键 `Id`、增量字段 `updateTime`)与 `dbo.jst_small_payment_order_map`(稳定键 `woNo`、增量字段 `updated_at`) | | 拼多多货款账户账单 | `dbo.jst_originalBillInfo`(固定 `channel = PinduoduoImport`,镜像 `js_jst_pdd_receiving_bill_rows`) | +| 得物完整账户账单 | 聚胜算平台原始账单(新)XLSX(受控导入 `dewu_settlement_bill_rows`;保留得物、退货退款订单、扣减其他费用明细) | ## JSDataMiddlePlatform 中台库(js_data_middle_platform) @@ -90,13 +96,14 @@ 4. 普通商品在最近完整校准超过 168 小时后,于周日 02:00-08:00 低峰窗口启动全量校准;一旦启动,后续每分钟从稳定游标继续,直至完整结束。首次全量由 Codex 备份后自主执行,定时任务保持既有初始化开关。 5. 除专用数据集外,通用任务每轮默认只处理 1 个数据集、每个数据集 2 批,每批 500 行,避免同时压迫两个旧系统。 6. 页面切换必须以“总记录数、第一页、第二页、末页、筛选、汇总、空数据和更新时间”作为验收,不能只看首页有数据。 -7. 普通商品的采购单价同步以采购主表 `updateTime` 加明细 `Id` 作为稳定游标;页面按商品编码选择最近完成的 1688 一键代发价格。同步保存全部状态,使完成单后续取消时也能撤回旧价格;首次全量前只显示普通商品自身采购价。 +7. 普通商品的采购单同步以采购主表 `updateTime` 加明细 `Id` 作为稳定游标;镜像保存来源单号、供应商、数量、单价和全部状态。普通商品页面按商品编码选择最近完成的 1688 一键代发价格;线上代发价格页面只展示 `Confirmed` / `Finished`,并在共享镜像内关联订单。完成单后续取消时可撤回旧价格;新增投影字段完成新一轮全量前不展示采购单管理数据。 8. 聚水潭官方接口尚未接入时,普通商品历史残留排除由负责人提供的最新完整 XLSX 导出刷新。只排除“导出生成前已创建、但导出中缺失”的镜像行,导出生成后的新增商品保持可见。导入使用新同步代次,只有完整解析成功才原子替换排除表;中断或错误保留上一版。后续接入聚水潭官方“普通商品资料查询”及删除/恢复记录后,由官方接口取代人工导出校准。 -9. 店铺维度报表是已批准的中央专用数据集:生产节点按 `Id` 断点推进并回看最近 50000 行;原始账单同步后增量维护按店铺/日期汇总的 `store_report_daily_rows`,页面不得现场扫描千万级原始账单。开发机不运行刷新 worker。 +9. 店铺维度报表是已批准的中央专用数据集:生产节点每 15 分钟按 `Id` 断点推进并回看最近 50000 行,一轮最多处理 60000 行;同步批次按受影响主键精确维护行数,不得在完成阶段对千万级原始表执行 `COUNT(*)`。原始账单同步后增量维护按店铺/日期汇总的 `store_report_daily_rows`,页面不得现场扫描千万级原始账单。开发机不运行刷新 worker。 10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步由 Codex 备份后自主安排在生产同步节点低峰期分批续传,无需另行授权;页面请求和普通开发机不启动刷新 worker。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。 淘系支付宝账户账单当前仍读取此 MariaDB 镜像,统一调度须持续增量,不因 ClickHouse 尚未启用而暂停。账单冲减则复用“订单数据 → 原始数据 → 订单售后费用明细”,不按该表费用名称推断 500112。 11. 拼多多货款账户账单使用 `jiansun.dbo.jst_originalBillInfo.pinduoduo_receiving` 数据集。同步器必须以参数绑定固定 `channel = PinduoduoImport`,只复制该渠道切片;页面 Repository 只读 `js_jst_pdd_receiving_bill_rows`。首次全量按 `Id` 断点推进,后续按 `updateTime` 保留重叠窗口,不得切回落后一天的 `operations_replica` 副本。 -12. 三方仓进销存首次全量按头表 `Id` 区间小批断点续传,头表只保存 `io_date >= 2026-08-01` 的目标仓数据,不激活半份数据;日常增量以头表 `(modified, Id)` 作稳定游标并保留 48 小时时间重叠,由命中头单驱动整单明细替换。全量和增量都先写待发布代次,库存抓取完成后再把流水追平到库存抓取之后的固定源时间边界,三部分成功后才一次切换;运行中或失败时页面始终读取上一成功代次。增量扫描不先限定仓库或业务日期,确保单据移出目标仓或日期改到起始日前时可从镜像撤回,重载当前版本时再固定仓库和起始日期。页面只统计 `Confirmed` 的 12 类进销存流水,数量按上游 `qty * qty_type` 保留符号。库存同时保存上游 `source_modified_at` 和实际 `captured_at`,历史余额以每个 SKU 的抓取时间为回推锚点;页面始终按“日期 + 商品”输出,日期区间固定为 `[当天 00:00, 次日 00:00)`。每天 `00:00` 执行增量同步,失败时继续展示上一成功代次。 -13. 聚水潭商品操作日志按最多 30 天的固定时间窗和接口页码稳定断点同步,首次全量从 `2000-01-01` 起扫描;只保留操作内容含“采购价”的记录,并从“采购价:旧值->新值”解析前后价格和差额。日常同步回看 48 小时,按操作日志 `autoid` 幂等更新;接口失败时保留上一版镜像。页面不得把这些聚水潭记录与 `jiansun.dbo.pm_priceAdjustment` 的工作平台价格记录混为同一来源。 +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` 的工作平台价格记录混为同一来源。 工作平台采购价格首次全量需在备份和负责人授权后单独执行: diff --git a/docs/京东日账单接入.md b/docs/京东日账单接入.md new file mode 100644 index 00000000..276f37ba --- /dev/null +++ b/docs/京东日账单接入.md @@ -0,0 +1,29 @@ +# 京东日账单 + +店铺收款账户账单的“京东流水”展示胜算“平台原始账单(新)→ 京东商城 → 京东日账单”,以费用结算时间筛选。保留原始记录编码、单据编号、商品、费用发生时间和费用结算时间;日账单没有账户余额,页面第三项汇总为收支净额。 + +当前来源是胜算完整月份原始导出,尚未接入自动增量接口。页面标明已接入月份与导入时间,不将未导入月份解释为源端无数据。旧库 `jd_billFromShop2024` 尚未通过完整性核对,不作为正式来源。 + +## 平台口径:京东账单与京喜账单 + +同一份日账单同时支撑「京东账单」和「京喜账单」两个页签,共用取数逻辑、列定义、筛选、排序、分页与导出,只按平台口径拆分数据。日账单导出没有平台字段:单据类型(订单/取消退款单/售后服务单/非销售单)两边都有,费用项、账户代码、京东门店编码、品牌门店编号、门店名称均为空,账单项目只有「直营服务费」单独属于京喜;实测全量 699,447 笔中只有店铺维度可靠区分(京喜 213 个店铺 488,464 笔与京东 46 个店铺 210,983 笔互不重叠,店铺号也不跨两边)。 + +口径集中定义在 `config/jd_bill_platform.php`(京喜店铺名关键字、口径切换起始日期),由 `Modules\EcommerceFinance\JdBillPlatform` 读取,`JdDailyBillRepository::forPlatform()` 在查询层收窄:京东账单排除京喜店铺,京喜账单只取京喜店铺。两个口径互补,笔数与金额之和恒等于拆分前,底层镜像数据不修改、不删除。 + +`scope_start_date` 默认 `null`(全量历史);改为某个 `Y-m-d` 后,该记账日期起的京喜行归入京喜账单,之前的京喜行仍留在京东账单,总数保持守恒。新增第三个小平台时,在同一配置与 `JdBillPlatform` 中扩展口径即可,不要在各处散写 if-else。 + +## 同步及回滚 + +1. 在胜算按费用结算时间查询完整月份,记录笔数及收入、支出合计;下载该查询的全部异步导出分片。 +2. 将原始明细无损转为 UTF-8 CSV,长编号保持文本,金额保持两位小数。原件、CSV、核对证据仅存放私有目录。 +3. 备份 `jd_daily_bill_periods` 和受影响月份旧版本;首次接入记录两表原先不存在。生产同步节点持有 `/run/caiwu-upstream-sync.lock` 后运行: + +```bash +php artisan business-mirror:import-jd-daily --count=<笔数> --income=<收入> --expense=<支出> +``` + +导入分批写入共享业务镜像 `jd_daily_bill_rows`,精确核对笔数、金额、月份、币种、时间格式及记录编码唯一性。全部成功后才原子更新 `jd_daily_bill_periods` 的有效版本;失败清理本次未启用版本,保留旧数据。状态保存源文件 SHA256 和导入时间。重复导入不会叠加流水。 + +回滚时在同一互斥锁下恢复备份的月份状态(`active_generation`),旧版本行保留。首次接入回滚只撤销该月份状态,保留原始文件和镜像用于核查。代码回滚沿用发布脚本保留的上一版本镜像。 + +验收核对源端和镜像笔数、收支,验证真实页面首页、翻页、店铺和月份筛选、全量导出及耗时。后续自动同步只能在确认完整官方来源及稳定游标后接入,不能拿部分旧表填补未导入期间。 diff --git a/docs/京东钱包接入.md b/docs/京东钱包接入.md new file mode 100644 index 00000000..9398ff1c --- /dev/null +++ b/docs/京东钱包接入.md @@ -0,0 +1,17 @@ +# 京东钱包流水 + +“京东网银钱包账户”读取胜算“平台原始账单(新)→ 京东商城 → 京东钱包”的完整月份原始明细。费用结算时间决定月份,保留流水号、交易订单号、账户名称、商户订单号、交易类型、账户余额、记账请求号等原始字段,与京东日账单独立存储。 + +当前通过完整月份原始导出校准,不代表自动增量接口已经接通。页面显示已接入月份和导入时间。镜像为 `jd_wallet_bill_rows`,月份有效版本及来源摘要为 `jd_wallet_bill_periods`。 + +生产节点在 `/run/caiwu-upstream-sync.lock` 内执行: + +```bash +php artisan business-mirror:import-jd-wallet --count=<核对笔数> --income=<核对收入> --expense=<核对支出> +``` + +导入前备份受影响镜像与月份状态;首次建表记录原表不存在。原件及无损 CSV 仅放私有目录,编号保存为文本。按批写入待启用版本,验证完整月份、笔数、收支、币种、重复编号和日期后原子启用,保留上一版本供回滚。失败不会启用部分数据。 + +每条“账户余额”保持原始值,可为负数。汇总“账户余额合计(最新)”取当前筛选结果中每个“店铺 + 账户名称”的最新流水,按费用结算时间、数值记录编码消歧后求和;不把流水余额逐笔相加,也不把全表最后一笔当所有账户余额。此口径不补齐筛选范围内没有流水的账户。 + +回滚时使用同一锁恢复旧月份状态的 `active_generation`,原镜像行保留。首次接入可撤销该月份启用状态;不删除上游或其他业务数据。上线核对实际页面、首页/次页/末页、店铺与日期筛选、收支及全量导出。 diff --git a/docs/开发与部署SOP.md b/docs/开发与部署SOP.md index 94088872..9ea96b65 100644 --- a/docs/开发与部署SOP.md +++ b/docs/开发与部署SOP.md @@ -39,7 +39,7 @@ 2. 在 Docker Desktop 的 `Settings -> Resources -> Advanced` 中: - Docker 虚拟磁盘上限建议 60GB; - Windows 磁盘至少保留 15GB 可用空间。 -3. 首次部署仅需在本机密码窗口输入一次服务器密码,之后 Codex 自动复用本机加密保存的登录信息;不要求新人生成、配置或管理私钥。密码使用 Windows 当前用户绑定的 DPAPI 加密,保存在 `%LOCALAPPDATA%\CaiWuXiTong\deploy-credentials`,不进入仓库或日志。已有私钥的机器仍可选传 `-KeyPath`。 +3. 首次部署仅需在本机密码窗口输入一次服务器密码,之后 Codex 自动复用本机加密保存的登录信息;不要求新人生成、配置或管理私钥。Windows 上密码使用当前用户绑定的 DPAPI 加密,保存在 `%LOCALAPPDATA%\CaiWuXiTong\deploy-credentials`;macOS 上保存在系统钥匙串(服务名 `CaiWuXiTong-deploy`)。两者都不进入仓库或日志。已有私钥的机器仍可选传 `-KeyPath`(macOS 为 `--key`)。 4. 只使用仓库里的发布脚本。不要自行执行 `docker system prune -a`,也不要重置 Docker Desktop。 Codex 已有用户提供的密码时可通过 `-Password` 的 `SecureString` 参数直接使用并保存,无需用户再输入;不要把明文写进命令参数或日志。密码变更时由 Codex 使用 `-UpdatePassword` 更新本机登录信息。部署结束保留加密凭据,下次自动使用。 @@ -76,6 +76,12 @@ Codex 已有用户提供的密码时可通过 `-Password` 的 `SecureString` 参 -BootstrapServer ``` +macOS 开发机使用同一套流程的脚本: + +```bash +bash scripts/deploy-from-mac.sh --bootstrap-server +``` + 初始化脚本会: - 使用服务器现有 Ubuntu 安全更新源安装并启动 Docker 与 Compose; @@ -102,6 +108,15 @@ git pull --ff-only .\scripts\deploy-from-workstation.ps1 ``` +macOS 开发机使用同一套流程的脚本: + +```bash +git switch main +git pull --ff-only + +bash scripts/deploy-from-mac.sh +``` + 脚本自动完成: 1. 检查分支和未提交改动; @@ -119,7 +134,15 @@ git pull --ff-only 13. 开发机、服务器 Docker 和服务器 Registry 均仅保留当前和上一个本项目版本; 14. 清理 7 天前的本项目构建缓存,并将总量压到最多 3GB。 -### 5.1 程序资源与业务文件的固定边界 +### 5.1 安全软件拦截 regctl 时的降级 + +第 6 步默认用项目专用 `regctl`(未签名)把 BuildKit 原生 OCI 分层包推入服务器本机 Registry。少数开发机的 360 安全卫士、金山毒霸等安全软件会拦截未签名程序,表现为 `regctl-v0.11.5.exe` 启动即报“拒绝访问”。 + +- 脚本会自动降级:regctl 无法运行或连续上传失败时,改用 `docker save` 全量包经 `scp` 上传,在服务器上 `docker load`、推入本机 Registry,再执行同一个 `activate-incremental-release.sh`(回滚、健康检查、双版本保留和旧层回收逻辑不变)。降级只增加传输量,功能与发布结果一致。 +- 也可以在受拦截的开发机上显式跳过 regctl:`.\scripts\deploy-from-workstation.ps1 -SkipRegctl`(macOS 为 `bash scripts/deploy-from-mac.sh --skip-regctl`)。 +- 建议在这类开发机上把 `%LOCALAPPDATA%\CaiWuXiTong\tools` 加入安全软件信任区,以恢复只上传变化层的增量方式。 + +### 5.2 程序资源与业务文件的固定边界 - 程序资源:JavaScript、CSS、字体、PWA 图标和仓库图片。它们只随 Git 提交和应用镜像发布,浏览器从当前应用域名加载。 - 业务文件:用户上传的图片、票据、PDF、表格和附件。生产环境统一写入项目唯一的私有七牛桶,本地开发默认仍写入本机 `storage/app/uploads`。 @@ -140,6 +163,12 @@ Codex 先核对全部待执行迁移,并准备受影响数据的备份与回 -AllowMigrations ``` +macOS 上对应命令: + +```bash +bash scripts/deploy-from-mac.sh --allow-migrations +``` + 应用镜像回滚不能自动撤销数据库结构变更;Codex 必须为本次迁移保留对应的数据备份和恢复路径。 ## 7. 测试分支发布 @@ -150,6 +179,8 @@ Codex 先核对全部待执行迁移,并准备受影响数据的备份与回 -AllowNonMain ``` +macOS 上对应参数为 `--allow-non-main`。 + 测试完成后仍要回到 `main` 再正式发布,不能把测试分支当长期生产版本。 ## 8. 多上游财务数据库同步 diff --git a/docs/得物完整账单取数方案留档.md b/docs/得物完整账单取数方案留档.md new file mode 100644 index 00000000..3ff73fbc --- /dev/null +++ b/docs/得物完整账单取数方案留档.md @@ -0,0 +1,59 @@ +# 得物完整账单取数方案留档 + +## 目标 + +财务平台“账单流水数据 / 店铺收款账户账单 / 得物账户”以聚胜算导出的平台原始账单为权威来源,不再回退到 `rpt.jst_originalBillInfo` 或其得物辅助镜像。 + +页面现有表头和列顺序保持不变,完整保留以下渠道: + +- 得物 +- 退货退款订单 +- 扣减其他费用明细 + +`Dewubzj` 保证金不属于本账单文件,不混入得物收支账单。 + +## 权威文件 + +来源固定为聚胜算“处理 / 平台原始账单(新) / 得物”导出的 XLSX。导入要求标准表头完整存在: + +`记录编码、订单号、线上单号、自定义备注、账单项目、店铺、订单类型、商品名称、商品货号、数量、渠道、业务类型、收入金额、支出金额、线上单号对应实际店铺、订单创建时间、支付/退款时间、发货/退货时间、结算状态、收款账期、拉取时间、修改时间、修改人`。 + +得物文件没有单独“金额”列,系统以 `收入金额 - 支出金额` 计算净额。账期以“发货/退货时间”为主;该字段为空时才使用“支付/退款时间”。两个原始时间字段均单独保存,页面不会伪造支付/退款时间。 + +## 数据表 + +共享业务镜像库保存三张专用表: + +- `dewu_settlement_bill_imports`:源文件名、SHA-256、账期、预期和实际控制数、渠道计数、状态。 +- `dewu_settlement_bill_staging`:当前导入代次的暂存数据。 +- `dewu_settlement_bill_rows`:页面和导出读取的权威正式数据。 + +页面 Repository 只读 `dewu_settlement_bill_rows`。尚未成功导入时返回明确的 503,不回退旧镜像。 + +## 导入控制 + +导入前必须同时提供账期、行数、收入和支出控制数: + +```bash +php artisan dewu-bills:import-authoritative /protected/path/dewu.xlsx \ + --from=2026-08-01 \ + --to=2026-08-31 \ + --expected-count=68449 \ + --expected-income=1236493.96 \ + --expected-expense=634104.33 +``` + +导入必须满足: + +1. 文件为可读 XLSX,标准表头完整。 +2. 记录编码非空且在同一文件中唯一。 +3. 每行渠道非空,账单时间非空且位于指定账期。 +4. 实际行数、收入、支出与权威控制数完全一致。 +5. 同一 SHA-256 已成功导入时幂等跳过;同一文件使用不同账期或控制数时拒绝。 +6. 先写暂存表并完成核验,再在事务内替换指定账期;任何失败均保留上一版正式数据。 + +## 每日运行 + +每日北京时间 08:00 处理前一自然日已生成的得物完整账单,不处理当天数据。自动任务必须先归档源文件并记录 SHA-256 与控制数,再调用受控导入命令。源文件未生成、下载失败、会话失效、控制数不一致、生产连接不可用或迁移未完成时停止,不使用旧镜像补数。 + +上线前需单独完成生产备份、迁移授权、发布以及首次导入授权。回滚时使用已归档的上一版源文件及其控制数重新导入相同账期。 diff --git a/docs/税金预测表需求说明.md b/docs/税金预测表需求说明.md new file mode 100644 index 00000000..6a9313a3 --- /dev/null +++ b/docs/税金预测表需求说明.md @@ -0,0 +1,62 @@ +# 税金预测表需求说明 + +## 1. 文档状态 + +- 状态:页面和字段结构已建立;取数公式为初稿,税率口径和两个新增数据源待负责人确认。 +- 页面:经营报表 → 税金预测表。 +- 路由标识:`company-management/tax-forecast`。 +- 适用对象:小微企业主体(小规模纳税人、小型微利企业、个体工商户、个人独资企业、合伙企业等)。 +- 本文之外不自行扩展业务规则;正式口径以负责人和主管税务机关确认为准。 + +## 2. 展示粒度 + +一行 = 一个公司主体 × 一个预测月份。 + +先看“公司税务类型 + 工商类型 + 征收方式”三列确定算法口径,再看税种明细列; +不是同一个口径的主体不放在同一组做横向比较。 + +## 3. 字段顺序与取数公式 + +序号由目录表自动生成,不占数据字段。 + +| 顺序 | 字段 | 取数 / 公式 | +| ---: | --- | --- | +| 1 | 公司名称 | 公司基础信息镜像 `rpt.fys_companyInfo.businessLicenseName` | +| 2 | 公司税务类型 | 公司基础信息镜像 `taxCategoryAndType`:一般纳税人 / 小规模纳税人 / 个体工商户 / 无税务登记 | +| 3 | 工商类型 | **新增数据源**:工商登记类型(有限责任公司、有限责任公司(自然人独资)、个人独资企业、合伙企业、个体工商户)。用于区分经营所得个税与企业所得税 | +| 4 | 征收方式 | **新增数据源**:查账征收 / 核定征收 / 定期定额。核定户按核定通知书取数 | +| 5 | 核定应税所得率(%) | 核定征收时按主管税务机关核定通知书维护;定期定额户按核定定额折算 | +| 6 | 预测月份 | 页面参数,默认当月 | +| 7 | 当月含税收入预测 | 主体维度经营报表同口径:`bills.income` 按主体生效/失效期间归集到当月;当月未出账时取上月实际值或公司成本安排页的“当月收入预测” | +| 8 | 当月不含税收入 | 小规模:含税收入 ÷ (1 + 征收率);一般纳税人:按适用税率(6%/9%/13%)分别换算后合计 | +| 9 | 季度累计销售额(不含税) | 本季度 3 个月不含税销售额之和,作为小规模免征增值税的判断基数 | +| 10 | 当月成本费用预测 | 公司成本安排页:供应商成本安排 + 快递成本安排 + 人工成本预测 + 其他费用预测 | +| 11 | 预计应纳税所得额 | 查账征收:不含税收入 − 成本 − 费用 − 税金及附加;核定征收:不含税收入 × 核定应税所得率 | +| 12 | 增值税征收率/税率 | 小规模 1%(3% 减按 1%);一般纳税人按业务适用 6%/9%/13% | +| 13 | 预计增值税 | 小规模:季度销售额 > 30 万元时 = 不含税销售额 × 1%,≤ 30 万元 = 0;一般纳税人:销项税额 − 进项税额;个体工商户、个人独资企业同小规模口径 | +| 14 | 城建税 | 预计增值税 × 7%(市区)/ 5%(县城、镇)/ 1%(其他)× 50%(六税两费减半) | +| 15 | 教育费附加 | 预计增值税 × 3% × 50% | +| 16 | 地方教育附加 | 预计增值税 × 2% × 50% | +| 17 | 印花税 | 购销合同金额 × 0.03% × 50%(小规模、小微减半) | +| 18 | 企业所得税/经营所得个税 | 有限公司(小型微利):应纳税所得额 × 25% × 20%,年 ≤ 300 万元部分实际税负 5%;个人独资/合伙/个体户:经营所得五级超额累进(5%~35%),核定户按 收入 × 核定应税所得率 计算,个体工商户 200 万元以内减半 | +| 19 | 税金合计 | 增值税 + 城建税 + 教育费附加 + 地方教育附加 + 印花税 + 所得税 | +| 20 | 综合税负率(%) | 税金合计 ÷ 当月不含税收入 × 100% | +| 21 | 备注 | 数据来源、核定依据、需人工确认项;工资薪金个税、分红个税按实际发生单独测算,不并入本表 | + +## 4. 政策口径(2026 年 10 月初稿,待财务确认) + +以下按现行小微企业通用政策整理,执行期限和适用条件以最新公告为准: + +- 小规模纳税人月销售额 10 万元以下(季度 30 万元以下)免征增值税;3% 征收率减按 1% 征收。 +- 增值税小规模纳税人、小型微利企业和个体工商户“六税两费”减半征收(含城建税、教育费附加、地方教育附加、印花税等)。 +- 小型微利企业年应纳税所得额不超过 300 万元部分,减按 25% 计入应纳税所得额,按 20% 税率缴纳企业所得税(实际税负 5%)。 +- 个体工商户年应纳税所得额不超过 200 万元部分,经营所得个人所得税减半征收。 + +## 5. 数据缺口与前置条件 + +1. **工商类型**:现有共享镜像只有 `businessLicenseType`(内部管理分类,如“店铺-普通公司”“个体户”),无法区分个人独资企业、合伙企业、有限责任公司。需要确认来源:工商公示/企查查爬虫接入,或维护在公司档案中。 +2. **征收方式与核定应税所得率**:属于税务登记信息,现有镜像没有。需要确认来源:电子税务局取数,或由财务在系统内维护。 +3. **收入预测**:沿用主体维度经营报表的主体收入口径(`bills.income` + 店铺主体生命周期)。 +4. **成本费用预测**:等待公司成本安排页接入供应商、快递、人工和其他费用数据。 + +以上 1、2 两项确认前,页面保持“字段已定义、数据待接入”,不显示推测数据。 diff --git a/modules/EcommerceFinance/AccountBillColumns.php b/modules/EcommerceFinance/AccountBillColumns.php index 9c4ef75d..12cf9a58 100644 --- a/modules/EcommerceFinance/AccountBillColumns.php +++ b/modules/EcommerceFinance/AccountBillColumns.php @@ -18,16 +18,106 @@ namespace Modules\EcommerceFinance; */ class AccountBillColumns { + /** + * 京东账单 / 京喜账单共用列定义(顺序、字段名、导出口径完全一致,只按平台拆分数据)。 + * + * @var array + */ + private const JD_BILL_COLUMNS = [ + ['记录编码', 'record_code', 'num'], + ['店铺', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], + ['自定义备注', 'custom_remark', 'text'], + ['账单项目', 'bill_item', 'tag'], + ['线上单号', 'payload.online_order_no', 'num'], + ['单据编号', 'payload.document_no', 'num'], + ['订单编号', 'order_no', 'num'], + ['商户订单号', 'payload.merchant_order_no', 'num'], + ['单据类型', 'payload.document_type', 'text'], + ['商品编码', 'payload.product_id', 'num'], + ['商品名称', 'payload.product_name', 'text'], + ['费用结算时间', 'occurred_at', 'date'], + ['费用发生时间', 'payload.cost_happened_at', 'date'], + ['费用项', 'payload.cost_name', 'text'], + ['收入金额', 'income', 'money_in'], + ['支出金额', 'expense', 'money_out'], + ['币种', 'payload.currency', 'text'], + ['钱包结算备注', 'payload.settle_remark', 'text'], + ['备注', 'remark', 'text'], + ['店铺号', 'payload.shop_no', 'num'], + ['京东门店编码', 'payload.jd_shop_no', 'num'], + ['品牌门店编号', 'payload.brand_shop_no', 'num'], + ['门店名称', 'payload.shop_name', 'text'], + ['账户代码', 'payload.account_code', 'text'], + ['修改时间', 'updated_at', 'date'], + ['修改人', 'modifier', 'text'], + ]; + /** * @return array,columns:array}> */ public static function map(): array { return [ + 'vipshop' => [ + 'title' => '唯品会MP账户', + 'columns' => [ + ['全局ID', 'record_code', 'num'], + ['店铺ID', 'payload.shop_id', 'num'], + ['店铺名称', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], + ['订单签收或退款时间', 'occurred_at', 'date'], + ['订单结算时间', 'payload.settle_period', 'date'], + ['订单类型名称', 'bill_item', 'text'], + ['行类型名称', 'payload.vip_5', 'text'], + ['售后类型名称', 'payload.vip_6', 'text'], + ['售后单号', 'payload.vip_7', 'text'], + ['订单编号', 'order_no', 'num'], + ['SKU', 'payload.vip_9', 'num'], + ['商品款号', 'payload.vip_10', 'num'], + ['商品SKU', 'payload.vip_11', 'num'], + ['商品描述', 'payload.vip_12', 'text'], + ['店铺协议编号', 'payload.vip_13', 'text'], + ['二级类目', 'payload.vip_14', 'text'], + ['三级类目', 'payload.vip_15', 'text'], + ['商品单价', 'payload.vip_16', 'money'], + ['商品数量', 'payload.vip_17', 'num'], + ['商品金额(A)', 'payload.vip_18', 'money'], + ['商家优惠(B)', 'payload.vip_19', 'money'], + ['调整金额(C)', 'payload.vip_20', 'money'], + ['无需退款金额(D)', 'payload.vip_21', 'money'], + ['总金额(E=A-B-C-D)', 'payload.vip_22', 'money'], + ['扣点', 'payload.vip_23', 'text'], + ['技术服务费(F)', 'payload.vip_24', 'money'], + ['海淘综合税(G)', 'payload.vip_25', 'money'], + ['分享金扣点', 'payload.vip_26', 'text'], + ['唯品仓分享金', 'payload.vip_27', 'money'], + ['商家应收(G=E-F-G)', 'balance', 'money'], + ], + ], + + // 唯品会JX(JITX 入仓/经销)账单只有 5 列原始字段(店铺/类型/二次备注/销售订单号/含税金额), + // 没有日期列;订单日期由销售订单号前 6 位(YYMMDD)还原,其余列由金额正负拆出收/支。 + 'vipshop-jx' => [ + 'title' => '唯品会JX账户', + 'columns' => [ + ['记录编码', 'record_code', 'num'], + ['店铺', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], + ['类型', 'bill_item', 'tag'], + ['二次备注', 'payload.second_remark', 'text'], + ['销售订单号', 'order_no', 'num'], + ['订单结算时间', 'payload.settle_period', 'date'], + ['订单日期(按订单号)', 'occurred_at', 'date'], + ['含税金额', 'amount', 'money'], + ['收入金额', 'income', 'money_in'], + ['支出金额', 'expense', 'money_out'], + ], + ], 'taobao-wechat' => [ 'title' => '淘系微信账户', 'groups' => [ - ['基础信息', 7], + ['基础信息', 8], ['账户与交易', 5], ['金额', 2], ['业务关联', 2], @@ -36,6 +126,7 @@ class AccountBillColumns 'columns' => [ ['记录编码', 'record_code', 'num'], ['店铺', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], ['财务备注', 'finance_remark', 'text'], ['订单号', 'order_no', 'num'], ['金额', 'amount', 'money'], @@ -60,6 +151,7 @@ class AccountBillColumns 'columns' => [ ['记录编码', 'record_code', 'num'], ['店铺', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], ['财务备注', 'finance_remark', 'text'], ['订单', 'order_no', 'num'], ['金额', 'amount', 'money'], @@ -83,49 +175,12 @@ class AccountBillColumns 'columns' => [ ['记录编码', 'record_code', 'num'], ['店铺', 'store_name', 'text'], - ['财务备注', 'finance_remark', 'text'], - ['订单', 'order_no', 'num'], - ['金额', 'amount', 'money'], - ['自定义备注', 'custom_remark', 'text'], - ['账单项目', 'bill_item', 'tag'], - ['线上单号', 'payload.online_order_no', 'num'], - ['单据编号', 'payload.doc_no', 'num'], - ['订单编号', 'payload.order_no_2', 'num'], - ['商户订单号', 'payload.merchant_order_no', 'num'], - ['单据类型', 'payload.doc_type', 'text'], - ['商品编码', 'payload.goods_code', 'num'], - ['商品名称', 'payload.goods_name', 'text'], - ['费用结算时间', 'occurred_at', 'date'], - ['费用发生时间', 'payload.fee_occurred_at', 'date'], - ['费用项', 'payload.fee_item', 'text'], - ['收入金额', 'income', 'money_in'], - ['支出金额', 'expense', 'money_out'], - ['币种', 'payload.currency', 'text'], - ['钱包结算备注', 'payload.wallet_remark', 'text'], - ['备注', 'remark', 'text'], - ['店铺号', 'payload.store_no', 'num'], - ['京东门店编码', 'payload.jd_store_code', 'num'], - ['品牌门店编号', 'payload.brand_store_no', 'num'], - ['门店名称', 'payload.store_name_2', 'text'], - ['账户代码', 'payload.account_code', 'num'], - ['修改时间', 'updated_at', 'date'], - ['修改人', 'modifier', 'text'], - ], - ], - - 'jd-transactions' => [ - 'title' => '京东流水', - 'columns' => [ - ['记录编码', 'record_code', 'num'], - ['店铺', 'store_name', 'text'], - ['财务备注', 'finance_remark', 'text'], - ['订单', 'order_no', 'num'], - ['金额', 'amount', 'money'], + ['总账备注', 'payload.ledger_remark', 'text'], ['自定义备注', 'custom_remark', 'text'], ['账单项目', 'bill_item', 'tag'], ['线上单号', 'payload.online_order_no', 'num'], ['流水号', 'payload.serial_no', 'num'], - ['交易订单号', 'payload.tx_order_no', 'num'], + ['交易订单号', 'order_no', 'num'], ['账户名称', 'payload.account_name', 'text'], ['费用结算时间', 'occurred_at', 'date'], ['账单日期', 'payload.bill_date', 'date'], @@ -143,11 +198,23 @@ class AccountBillColumns ], ], + // 京喜账单与京东账单共用同一份列定义,只按平台口径拆分数据。 + 'jd-transactions' => [ + 'title' => '京东账单', + 'columns' => self::JD_BILL_COLUMNS, + ], + + 'jingxi' => [ + 'title' => '京喜账单', + 'columns' => self::JD_BILL_COLUMNS, + ], + 'douyin' => [ 'title' => '抖音账户', 'columns' => [ ['记录编码', 'record_code', 'num'], ['店铺', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], ['财务备注', 'finance_remark', 'text'], ['订单', 'order_no', 'num'], ['金额', 'amount', 'money'], @@ -182,6 +249,7 @@ class AccountBillColumns 'columns' => [ ['记录编码', 'record_code', 'num'], ['店铺', 'store_name', 'text'], + ['总账备注', 'payload.ledger_remark', 'text'], ['财务备注', 'finance_remark', 'text'], ['金额', 'amount', 'money'], ['订单号', 'order_no', 'num'], @@ -194,6 +262,7 @@ class AccountBillColumns ['商品货号', 'payload.goods_no', 'num'], ['数量', 'payload.quantity', 'num'], ['渠道', 'payload.channel', 'text'], + ['源渠道代码', 'payload.source_channel', 'text'], ['业务类型', 'payload.business_type', 'text'], ['收入金额', 'income', 'money_in'], ['支出金额', 'expense', 'money_out'], diff --git a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php index 021124d4..bf7853c9 100644 --- a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php +++ b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php @@ -17,7 +17,8 @@ use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer; */ class SyncJushuitanShipping extends Command { - protected $signature = 'jushuitan:sync-shipping {--from=} {--to=} {--days=} {--limit=2000}'; + protected $signature = 'jushuitan:sync-shipping {--from=} {--to=} {--days=} {--limit=2000} + {--skip-freight : 仅补发货数量;保留已有运费,新记录运费留空并标记部分完成}'; protected $description = '从经营分析副本库直读聚水潭发货明细,清洗写入 caiwu 发货数据表'; @@ -35,6 +36,12 @@ class SyncJushuitanShipping extends Command $to = now()->startOfDay()->addDay(); } + $skipFreight = (bool) $this->option('skip-freight'); + if ($skipFreight && (! $from || ! $to)) { + $this->error('--skip-freight 需要指定 --from 和 --to,或使用 --days。'); + return self::FAILURE; + } + $limit = (int) ($this->option('limit') ?: 2000); $range = ($from && $to) ? $from->toDateString() . ' ~ ' . $to->toDateString() : '最近 ' . $limit . ' 条'; @@ -46,13 +53,47 @@ class SyncJushuitanShipping extends Command } }; try { - $result = ShippingReplicaSynchronizer::make()->sync($from, $to, $limit, $progress); + $result = ShippingReplicaSynchronizer::make()->sync($from, $to, $limit, $progress, $skipFreight); } catch (\Throwable $e) { $this->error('同步失败:' . $e->getMessage()); return self::FAILURE; } - $this->info('完成:写入 ' . ($result['processed'] ?? 0) . ' 条发货明细。'); + $expressRows = (int) ($result['processed'] ?? 0); + $autoRows = (int) ($result['autoship'] ?? 0); + $summary = sprintf('发货明细 %d 条,代发仓 %d 条,合计处理 %d 条明细', $expressRows, $autoRows, $expressRows + $autoRows); + $packageSummary = isset($result['unique_packages']) + ? sprintf('唯一包裹源键 %d 个,包裹记录处理 %d 次;', $result['unique_packages'], $result['packages'] ?? 0) + : ''; + if (isset($result['outbound']) || isset($result['purchase_out'])) { + $this->info(sprintf( + ' 出库单兜底补出 %d 条明细,采购退货出库 %d 条明细(对齐工作平台发货数据口径)。', + (int) ($result['outbound'] ?? 0), + (int) ($result['purchase_out'] ?? 0), + )); + } + if ($result['freight_incomplete'] ?? false) { + $this->warn('本次窗口' . $packageSummary . $summary . ';新记录运费与结算重量待补齐,空白不代表 0。'); + } else { + $this->info('完成:' . $packageSummary . $summary . '。'); + } + if (($result['packages_without_items'] ?? 0) > 0 || ($result['dws_failed_days'] ?? []) !== []) { + $this->warn(sprintf( + '商品或金额待核对:%d 个包裹未匹配商品,DWS 预载失败 %d 天;页面包裹数不等于商品明细完整性。', + $result['packages_without_items'] ?? 0, + count($result['dws_failed_days'] ?? []), + )); + } + if (($result['packages_retained_for_missing_items'] ?? 0) > 0) { + $this->warn('其中 ' . $result['packages_retained_for_missing_items'] . ' 个包裹因新商品明细缺失而保留原有商品及金额,本次未完成这些包裹的更新。'); + } + if (($result['packages_retained_for_unmatched_amount'] ?? 0) > 0) { + $this->warn('其中 ' . $result['packages_retained_for_unmatched_amount'] . ' 个包裹因商品金额无法安全匹配而保留原记录,金额待核对。'); + } + if (($result['stale_mirror_packages'] ?? 0) > 0) { + $this->error('本窗口仍有 ' . $result['stale_mirror_packages'] . ' 个镜像包裹未在上游扫描中出现;已保留原记录,需按源键核对后才能认定数量完整。'); + return self::FAILURE; + } return self::SUCCESS; } } diff --git a/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php b/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php index 77ca082c..de3b1fb2 100644 --- a/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php +++ b/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php @@ -19,7 +19,7 @@ interface BusinessMirrorDataset public function watermarkColumn(): ?string; - /** @return array */ + /** @return array> */ public function fixedFilters(): array; /** @return list> */ diff --git a/modules/EcommerceFinance/Database/Migrations/2026_10_06_120000_create_ec_account_ledger_remarks_table.php b/modules/EcommerceFinance/Database/Migrations/2026_10_06_120000_create_ec_account_ledger_remarks_table.php new file mode 100644 index 00000000..3a9d7db8 --- /dev/null +++ b/modules/EcommerceFinance/Database/Migrations/2026_10_06_120000_create_ec_account_ledger_remarks_table.php @@ -0,0 +1,31 @@ +id(); + $table->string('platform', 32); + $table->string('bill_item', 191); + $table->string('ledger_remark', 191); + $table->timestamps(); + + $table->unique(['platform', 'bill_item'], 'ec_account_ledger_remarks_unique'); + }); + } + + public function down(): void + { + Schema::dropIfExists('ec_account_ledger_remarks'); + } +}; diff --git a/modules/EcommerceFinance/Http/Concerns/DecoratesLedgerRemarks.php b/modules/EcommerceFinance/Http/Concerns/DecoratesLedgerRemarks.php new file mode 100644 index 00000000..6e8cfd90 --- /dev/null +++ b/modules/EcommerceFinance/Http/Concerns/DecoratesLedgerRemarks.php @@ -0,0 +1,85 @@ + $filters + * @return array + */ + protected function withLedgerRemarkFilter(array $filters, string $tab): array + { + $remark = trim((string) ($filters['ledger_remark'] ?? '')); + if ($remark === '') { + return $filters; + } + + $groups = $this->ledgerRemarkMap()->billItemGroupsForTab($tab, $remark); + $filters['bill_item_groups'] = $groups; + + $items = []; + foreach ($groups as $group) { + foreach ($group['items'] as $item) { + $items[$item] = true; + } + } + $filters['bill_items'] = array_keys($items); + if ($filters['bill_items'] === []) { + $filters['bill_items'] = [self::LEDGER_REMARK_NO_MATCH_ITEM]; + } + + return $filters; + } + + /** + * 分页结果(含 data 行数组)补总账备注。 + * + * @param array $data + * @return array + */ + protected function withLedgerRemarks(array $data, string $tab): array + { + if (! empty($data['data']) && is_array($data['data'])) { + $map = $this->ledgerRemarkMap(); + $data['data'] = array_map( + static fn (mixed $row): mixed => is_array($row) ? $map->decorate($row, $tab) : $row, + $data['data'], + ); + } + + return $data; + } + + /** + * 导出/流式行补总账备注。 + * + * @param iterable> $rows + * @return iterable> + */ + protected function ledgerRemarkRows(iterable $rows, string $tab): iterable + { + return $this->ledgerRemarkMap()->decorateAll($rows, $tab); + } +} diff --git a/modules/EcommerceFinance/Http/Controllers/AccountBills.php b/modules/EcommerceFinance/Http/Controllers/AccountBills.php index d7067d5f..234df561 100644 --- a/modules/EcommerceFinance/Http/Controllers/AccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AccountBills.php @@ -3,16 +3,25 @@ namespace Modules\EcommerceFinance\Http\Controllers; use App\Utilities\SidebarPermissions; +use Modules\EcommerceFinance\Http\Concerns\DecoratesLedgerRemarks; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Modules\EcommerceFinance\AccountBillColumns; +use Modules\EcommerceFinance\JdBillPlatform; use Modules\EcommerceFinance\Models\AccountBill; +use Modules\EcommerceFinance\Repositories\JdDailyBillRepository; +use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; +use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository; use RuntimeException; class AccountBills extends Controller { + use DecoratesLedgerRemarks; + /** 走共享业务镜像的账户类型(其余类型读本系统账单表 ec_account_bills)。 */ + private const MIRROR_TABS = ['douyin', 'pinduoduo', 'dewu', 'jd-transactions', 'jingxi', 'jd-wallet']; + /** * 通用账单列表(店铺收款账户账单 › 各账户类型 tab)。 * 经 admin 路由组(web 会话)暴露,前端带 CSRF 调用。 @@ -28,7 +37,7 @@ class AccountBills extends Controller abort(404, '未知的账户类型。'); } - if (in_array($billType, ['douyin', 'pinduoduo'], true)) { + if (in_array($billType, self::MIRROR_TABS, true)) { return $request->boolean('export') ? $this->export($request, $billType) : $this->mirrorIndex($request, $billType); @@ -36,6 +45,7 @@ class AccountBills extends Controller $request->validate([ 'store_name' => ['nullable', 'string', 'max:255'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], 'bill_item' => ['nullable', 'string', 'max:255'], 'start' => ['nullable', 'date_format:Y-m-d'], 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], @@ -45,35 +55,8 @@ class AccountBills extends Controller 'columns.*' => ['string', 'max:128'], ]); - $query = AccountBill::query() - ->where('company_id', company_id()) - ->where('bill_type', $billType); - - if ($store = $request->get('store_name')) { - $query->where('store_name', $store); - } - - if ($item = $request->get('bill_item')) { - $query->where('bill_item', $item); - } - - if ($start = $request->get('start')) { - $query->where('occurred_at', '>=', $start); - } - - if ($end = $request->get('end')) { - $query->where('occurred_at', '<=', $end . ' 23:59:59'); - } - - if ($keyword = $request->get('keyword')) { - $query->where(function ($q) use ($keyword) { - $like = '%' . $keyword . '%'; - $q->where('record_code', 'like', $like) - ->orWhere('order_no', 'like', $like) - ->orWhere('remark', 'like', $like) - ->orWhere('bill_item', 'like', $like); - }); - } + // 与导出共用同一份筛选(含「总账备注」翻译出的账单项目集合)。 + $query = $this->filteredQuery($request, $billType); $sortable = ['occurred_at', 'income', 'expense', 'balance', 'record_code']; $sort = in_array($request->get('sort'), $sortable, true) ? $request->get('sort') : 'occurred_at'; @@ -100,15 +83,23 @@ class AccountBills extends Controller ->value('balance'); $data = $rows->toArray(); + $data['data'] = collect($rows->items()) + ->map(fn (AccountBill $bill): array => $this->billRow($bill)) + ->all(); + $income = (float) ($summaryRow->income ?? 0); + $expense = (float) ($summaryRow->expense ?? 0); $data['summary'] = [ - 'income' => (float) ($summaryRow->income ?? 0), - 'expense' => (float) ($summaryRow->expense ?? 0), + 'income' => $income, + 'expense' => $expense, 'count' => (int) ($summaryRow->count ?? 0), - 'balance' => $latestBalance !== null ? (float) $latestBalance : 0, + // 唯品会JX账单没有账户余额列,该页签以收支净额作为汇总口径。 + 'balance' => $billType === 'vipshop-jx' + ? round($income - $expense, 2) + : ($latestBalance !== null ? (float) $latestBalance : 0), ]; $data['columns'] = AccountBillColumns::for($billType); - return response()->json($data); + return response()->json($this->withLedgerRemarks($data, $billType)); } public function export(Request $request, string $bill_type) @@ -117,12 +108,13 @@ class AccountBills extends Controller abort_unless(AccountBillColumns::has($bill_type), 404, '未知的账户类型。'); - if (in_array($bill_type, ['douyin', 'pinduoduo'], true)) { + if (in_array($bill_type, self::MIRROR_TABS, true)) { return $this->exportMirror($request, $bill_type); } $filters = $request->validate([ 'store_name' => ['nullable', 'string', 'max:255'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], 'bill_item' => ['nullable', 'string', 'max:255'], 'start' => ['nullable', 'date_format:Y-m-d'], 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], @@ -141,27 +133,65 @@ class AccountBills extends Controller { $this->authorizeStoreReceivingBills(); - abort_unless(in_array($bill_type, ['douyin', 'pinduoduo'], true), 404, '该账户类型没有可用的筛选选项。'); + $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab($bill_type); + + if (in_array($bill_type, ['vipshop', 'vipshop-jx'], true)) { + $query = AccountBill::query() + ->where('company_id', company_id()) + ->where('bill_type', $bill_type); + + return response()->json([ + 'shops' => (clone $query)->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name')->all(), + 'bill_items' => (clone $query)->whereNotNull('bill_item')->where('bill_item', '<>', '') + ->distinct()->orderBy('bill_item')->pluck('bill_item')->all(), + 'ledger_remarks' => $ledgerRemarks, + ]); + } + + abort_unless(in_array($bill_type, self::MIRROR_TABS, true), 404, '该账户类型没有可用的筛选选项。'); $label = $this->mirrorLabel($bill_type); try { return response()->json( - $this->mirrorRepository($bill_type)->filterOptions() + $this->mirrorRepository($bill_type)->filterOptions() + ['ledger_remarks' => $ledgerRemarks] ); } catch (RuntimeException $exception) { - if ($exception->getMessage() !== 'store_receiving_alipay_bill_mirror_not_ready') { + if (! in_array($exception->getMessage(), [ + 'store_receiving_alipay_bill_mirror_not_ready', + 'store_receiving_bill_filter_options_busy', + 'jd_daily_bill_mirror_not_ready', + 'jd_wallet_bill_mirror_not_ready', + ], true)) { throw $exception; } return response()->json([ - 'message' => $label . '账户账单共享业务镜像正在首次同步,筛选选项稍后可用。', + 'message' => $exception->getMessage() === 'store_receiving_bill_filter_options_busy' + ? $label . '账户账单筛选选项正在生成,请稍后重试。' + : $label . '账户账单共享业务镜像正在首次同步,筛选选项稍后可用。', 'shops' => [], 'bill_items' => [], + 'ledger_remarks' => $ledgerRemarks, ], 503); } } + /** 账单表格按 Y-m-d H:i:s 展示日期,避免 Eloquent 默认序列化成 ISO8601(UTC)。 */ + private function billRow(AccountBill $bill): array + { + return collect($bill->toArray()) + ->map(function (mixed $value, string $field) use ($bill): mixed { + $attribute = $bill->getAttribute($field); + + return $attribute instanceof \DateTimeInterface + ? $attribute->format('Y-m-d H:i:s') + : $value; + }) + ->all(); + } + private function exportQuery(Request $request, $query, string $billType) { $definition = AccountBillColumns::for($billType); @@ -173,9 +203,14 @@ class AccountBills extends Controller if (! is_array($requested)) { $requested = []; } + if ($requested !== []) { + $requested = collect($requested)->unique()->values(); + $invalid = $requested->reject(fn (string $field): bool => $available->has($field)); + abort_if($invalid->isNotEmpty(), 422, '包含不可导出的字段:' . $invalid->implode('、')); + } $columns = $requested === [] ? $available->values() - : collect($requested)->unique()->map(fn (string $field) => $available->get($field))->filter()->values(); + : $requested->map(fn (string $field) => $available->get($field))->values(); abort_if($columns->isEmpty(), 422, '至少选择一个可导出的字段。'); @@ -227,6 +262,14 @@ class AccountBills extends Controller $query->where('store_name', $store); } + $ledgerFilters = $this->withLedgerRemarkFilter( + ['ledger_remark' => $request->get('ledger_remark')], + $billType, + ); + if (($ledgerFilters['bill_items'] ?? []) !== []) { + $query->whereIn('bill_item', $ledgerFilters['bill_items']); + } + if ($item = $request->get('bill_item')) { $query->where('bill_item', $item); } @@ -254,7 +297,7 @@ class AccountBills extends Controller private function mirrorIndex(Request $request, string $billType) { - $filters = $this->mirrorFilters($request); + $filters = $this->mirrorFilters($request, $billType); $sort = $this->sort($request); $direction = $this->direction($request); $page = max((int) $request->get('page', 1), 1); @@ -270,7 +313,7 @@ class AccountBills extends Controller $perPage, ); } catch (RuntimeException $exception) { - if ($exception->getMessage() !== 'store_receiving_alipay_bill_mirror_not_ready') { + if (! in_array($exception->getMessage(), ['store_receiving_alipay_bill_mirror_not_ready', 'jd_daily_bill_mirror_not_ready', 'jd_wallet_bill_mirror_not_ready'], true)) { throw $exception; } @@ -288,12 +331,12 @@ class AccountBills extends Controller $data['columns'] = AccountBillColumns::for($billType); - return response()->json($data); + return response()->json($this->withLedgerRemarks($data, $billType)); } private function exportMirror(Request $request, string $billType) { - $filters = $this->mirrorFilters($request); + $filters = $this->mirrorFilters($request, $billType); $definition = AccountBillColumns::for($billType); $columns = collect($definition['columns'] ?? []); $requested = $request->query('columns', []); @@ -308,10 +351,9 @@ class AccountBills extends Controller $selected = $columns; } else { $columnsByField = $columns->keyBy('field'); - $selected = $requested - ->map(static fn (string $field) => $columnsByField->get($field)) - ->filter(static fn ($column): bool => is_array($column)) - ->values(); + $invalid = $requested->reject(static fn (string $field): bool => $columnsByField->has($field)); + abort_if($invalid->isNotEmpty(), 422, '包含不可导出的字段:' . $invalid->implode('、')); + $selected = $requested->map(static fn (string $field) => $columnsByField->get($field))->values(); abort_if($selected->isEmpty(), 422, '未选择有效的导出字段。'); } @@ -321,7 +363,7 @@ class AccountBills extends Controller $rows = $this->mirrorRepository($billType) ->exportRows($filters, $sort, $direction); } catch (RuntimeException $exception) { - if ($exception->getMessage() !== 'store_receiving_alipay_bill_mirror_not_ready') { + if (! in_array($exception->getMessage(), ['store_receiving_alipay_bill_mirror_not_ready', 'jd_daily_bill_mirror_not_ready', 'jd_wallet_bill_mirror_not_ready'], true)) { throw $exception; } @@ -330,6 +372,8 @@ class AccountBills extends Controller $headers = $selected->pluck('label')->all(); + $rows = $this->ledgerRemarkRows($rows, $billType); + return response()->streamDownload(function () use ($rows, $selected, $headers): void { $csv = fopen('php://output', 'w'); fputs($csv, "\xEF\xBB\xBF"); @@ -347,29 +391,49 @@ class AccountBills extends Controller } /** @return array */ - private function mirrorFilters(Request $request): array + private function mirrorFilters(Request $request, string $billType): array { $filters = $request->validate([ 'store_name' => ['nullable', 'string', 'max:255'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], 'bill_item' => ['nullable', 'string', 'max:255'], 'start' => ['nullable', 'date_format:Y-m-d'], 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], 'keyword' => ['nullable', 'string', 'max:255'], + 'keyword_match' => ['nullable', 'in:contains,exact-record'], ]); - return array_map(static fn (mixed $value): string => trim((string) $value), $filters); + $filters = array_map(static fn (mixed $value): string => trim((string) $value), $filters); + + return $this->withLedgerRemarkFilter($filters, $billType); } private function mirrorRepository(string $billType): object { - return $billType === 'pinduoduo' - ? app(StoreReceivingPinduoduoBillMirrorRepository::class) - : app(StoreReceivingDouyinBillMirrorRepository::class); + if (JdBillPlatform::isJdBillTab($billType)) { + // 京东账单与京喜账单共用同一个京东日账单仓库,只用平台口径区分数据。 + return app(JdDailyBillRepository::class) + ->forPlatform(JdBillPlatform::platformForBillType($billType)); + } + + return match ($billType) { + 'jd-wallet' => app(StoreReceivingJdWalletBillRepository::class), + 'pinduoduo' => app(StoreReceivingPinduoduoBillMirrorRepository::class), + 'dewu' => app(StoreReceivingDewuBillMirrorRepository::class), + default => app(StoreReceivingDouyinBillMirrorRepository::class), + }; } private function mirrorLabel(string $billType): string { - return $billType === 'pinduoduo' ? '拼多多' : '抖音'; + return match ($billType) { + 'jd-transactions' => '京东账单', + 'jingxi' => '京喜账单', + 'jd-wallet' => '京东钱包', + 'pinduoduo' => '拼多多', + 'dewu' => '得物', + default => '抖音', + }; } private function sort(Request $request): string diff --git a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php index 34520ed5..258c422d 100644 --- a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php @@ -3,6 +3,7 @@ namespace Modules\EcommerceFinance\Http\Controllers; use App\Utilities\SidebarPermissions; +use Modules\EcommerceFinance\Http\Concerns\DecoratesLedgerRemarks; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Modules\EcommerceFinance\Models\AlipayBill; @@ -11,22 +12,24 @@ use RuntimeException; class AlipayBills extends Controller { + use DecoratesLedgerRemarks; private const EXPORT_COLUMNS = [ 'record_code' => '记录编码', 'store_name' => '原始店铺', + 'ledger_remark' => '总账备注', 'custom_remark' => '自定义备注', 'bill_item' => '账单项目', - 'alipay_account' => '平台渠道', + 'alipay_account' => '支付宝账号', 'account_order_no' => '账务订单号', 'business_serial_no' => '业务流水号', 'merchant_order_no' => '商户订单号', 'business_base_order_no' => '业务基础订单号', - 'goods_name' => '商品编码', + 'goods_name' => '商品名称', 'counterparty_account' => '对方账号', 'occurred_at' => '发生时间', 'income' => '收入', 'expense' => '支出', - 'balance' => '收支净额', + 'balance' => '余额', 'business_type' => '业务类型', 'remark' => '备注', 'online_order_no' => '线上单号', @@ -52,21 +55,29 @@ class AlipayBills extends Controller $dir = $request->get('dir') === 'asc' ? 'asc' : 'desc'; $filters = $request->validate([ 'store_name' => ['nullable', 'string', 'max:255'], - 'alipay_account' => ['nullable', 'string', 'max:128'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], + 'source_channel' => ['nullable', 'string', 'max:128'], 'bill_item' => ['nullable', 'string', 'max:255'], 'business_type' => ['nullable', 'string', 'max:255'], 'start' => ['nullable', 'date_format:Y-m-d'], 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], 'keyword' => ['nullable', 'string', 'max:255'], ]); + $filters = $this->withLedgerRemarkFilter( + array_map(static fn (mixed $value): string => trim((string) $value), $filters), + 'taobao-alipay', + ); try { - return response()->json($repository->paginate( - array_map(static fn (mixed $value): string => trim((string) $value), $filters), - $sort, - $dir, - max((int) $request->get('page', 1), 1), - min(max((int) $request->get('limit', 10), 1), 100), + return response()->json($this->withLedgerRemarks( + $repository->paginate( + $filters, + $sort, + $dir, + max((int) $request->get('page', 1), 1), + min(max((int) $request->get('limit', 10), 1), 100), + ), + 'taobao-alipay', )); } catch (RuntimeException $exception) { if ($exception->getMessage() !== 'store_receiving_alipay_bill_mirror_not_ready') { @@ -85,12 +96,42 @@ class AlipayBills extends Controller } } + public function filterOptions(StoreReceivingAlipayBillMirrorRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab('taobao-alipay'); + + try { + return response()->json($repository->filterOptionsForChannel( + 'alipayCSV', StoreReceivingAlipayBillMirrorRepository::DATASET, true + ) + ['ledger_remarks' => $ledgerRemarks]); + } catch (RuntimeException $exception) { + if (! in_array($exception->getMessage(), [ + 'store_receiving_alipay_bill_mirror_not_ready', + 'store_receiving_bill_filter_options_busy', + ], true)) { + throw $exception; + } + + return response()->json([ + 'message' => $exception->getMessage() === 'store_receiving_bill_filter_options_busy' + ? '淘系支付宝筛选选项正在生成,请稍后重试。' + : '淘系支付宝账单共享业务镜像正在首次同步,筛选选项稍后可用。', + 'shops' => [], + 'bill_items' => [], + 'ledger_remarks' => $ledgerRemarks, + ], 503); + } + } + public function export(Request $request, StoreReceivingAlipayBillMirrorRepository $repository) { $this->authorizeStoreReceivingBills(); $filters = $request->validate([ 'store_name' => ['nullable', 'string', 'max:255'], - 'alipay_account' => ['nullable', 'string', 'max:128'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], + 'source_channel' => ['nullable', 'string', 'max:128'], 'bill_item' => ['nullable', 'string', 'max:255'], 'business_type' => ['nullable', 'string', 'max:255'], 'start' => ['nullable', 'date_format:Y-m-d'], @@ -102,16 +143,16 @@ class AlipayBills extends Controller $columns = $this->requestedExportColumns($filters['columns'] ?? []); unset($filters['columns']); + $filters = $this->withLedgerRemarkFilter( + array_map(static fn (mixed $value): string => trim((string) $value), $filters), + 'taobao-alipay', + ); try { $sortable = ['record_code', 'occurred_at', 'income', 'expense', 'balance']; $sort = in_array($request->get('sort'), $sortable, true) ? $request->get('sort') : 'occurred_at'; $dir = $request->get('dir') === 'asc' ? 'asc' : 'desc'; - $rows = $repository->exportRows( - array_map(static fn (mixed $value): string => trim((string) $value), $filters), - $sort, - $dir, - ); + $rows = $repository->exportRows($filters, $sort, $dir); } catch (RuntimeException $exception) { if ($exception->getMessage() !== 'store_receiving_alipay_bill_mirror_not_ready') { throw $exception; @@ -120,6 +161,8 @@ class AlipayBills extends Controller return response()->json(['message' => '淘系支付宝账单共享业务镜像正在首次同步,完成后将自动显示。'], 503); } + $rows = $this->ledgerRemarkRows($rows, 'taobao-alipay'); + return response()->streamDownload(function () use ($rows, $columns): void { $csv = fopen('php://output', 'w'); fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); diff --git a/modules/EcommerceFinance/Http/Controllers/Api/GoodsReconciliations.php b/modules/EcommerceFinance/Http/Controllers/Api/GoodsReconciliations.php index dfa53775..9cc94795 100644 --- a/modules/EcommerceFinance/Http/Controllers/Api/GoodsReconciliations.php +++ b/modules/EcommerceFinance/Http/Controllers/Api/GoodsReconciliations.php @@ -5,6 +5,7 @@ namespace Modules\EcommerceFinance\Http\Controllers\Api; use App\Abstracts\Http\ApiController; use Modules\EcommerceFinance\Repositories\GoodsReconciliationRepository; use Modules\EcommerceFinance\Services\JianSunQueryCache; +use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; /** * 货款对账 API @@ -20,7 +21,7 @@ class GoodsReconciliations extends ApiController private JianSunQueryCache $cache; - public function __construct(GoodsReconciliationRepository $repo, JianSunQueryCache $cache) + public function __construct(GoodsReconciliationRepository $repo, JianSunQueryCache $cache, private readonly SupplierPayableOverrideStore $overrides) { $this->repo = $repo; $this->cache = $cache; @@ -41,6 +42,8 @@ class GoodsReconciliations extends ApiController fn () => $this->repo->list($filters, $page, $limit) ); + $result['data'] = $this->overrides->decorate('payment-reconciliation', $result['data'] ?? [], (int) (company_id() ?: 1)); + return $this->snapshotResponse([ 'data' => $result['data'], 'total' => $result['total'], diff --git a/modules/EcommerceFinance/Http/Controllers/Api/SupplierPayables.php b/modules/EcommerceFinance/Http/Controllers/Api/SupplierPayables.php index c8401e4d..8d84c164 100644 --- a/modules/EcommerceFinance/Http/Controllers/Api/SupplierPayables.php +++ b/modules/EcommerceFinance/Http/Controllers/Api/SupplierPayables.php @@ -6,6 +6,7 @@ use App\Abstracts\Http\ApiController; use Closure; use Modules\EcommerceFinance\Repositories\SupplierPayableRepository; use Modules\EcommerceFinance\Services\JianSunQueryCache; +use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; /** * 供应商应付 - 子功能页面 API @@ -23,7 +24,7 @@ class SupplierPayables extends ApiController private JianSunQueryCache $cache; - public function __construct(SupplierPayableRepository $repo, JianSunQueryCache $cache) + public function __construct(SupplierPayableRepository $repo, JianSunQueryCache $cache, private readonly SupplierPayableOverrideStore $overrides) { $this->repo = $repo; $this->cache = $cache; @@ -333,12 +334,18 @@ class SupplierPayables extends ApiController { $page = $this->page(); $limit = $this->limit(); + $cacheParameters = ['filters' => $filters, 'page' => $page, 'limit' => $limit]; + if ($scope === 'other-adjustments') { + $cacheParameters['format_version'] = 2; + } $result = $this->cache->remember( $scope . '.list', - ['filters' => $filters, 'page' => $page, 'limit' => $limit], + $cacheParameters, fn () => $resolver($page, $limit) ); + $result['data'] = $this->overrides->decorate($scope, $result['data'] ?? [], (int) (company_id() ?: 1)); + return $this->snapshotResponse([ 'data' => $result['data'], 'total' => $result['total'], diff --git a/modules/EcommerceFinance/Http/Controllers/DewuAccountBills.php b/modules/EcommerceFinance/Http/Controllers/DewuAccountBills.php new file mode 100644 index 00000000..625f2145 --- /dev/null +++ b/modules/EcommerceFinance/Http/Controllers/DewuAccountBills.php @@ -0,0 +1,188 @@ +authorizeStoreReceivingBills(); + + if ($request->boolean('export')) { + return $this->exportResponse($request, $repository); + } + + $validated = $request->validate($this->filterRules() + [ + 'sort' => ['nullable', 'in:occurred_at,income,expense,record_code'], + 'dir' => ['nullable', 'in:asc,desc'], + 'page' => ['nullable', 'integer', 'min:1'], + 'limit' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + $filters = collect($validated)->only(array_keys($this->filterRules()))->all(); + $filters = $this->withLedgerRemarkFilter($filters, 'dewu'); + + try { + $data = $repository->paginateAccountBills( + $filters, + (string) ($validated['sort'] ?? 'occurred_at'), + (string) ($validated['dir'] ?? 'desc'), + (int) ($validated['page'] ?? 1), + (int) ($validated['limit'] ?? 10), + ); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'dewu_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json([ + 'message' => '得物完整账单尚未完成首次导入,当前不会回退到不完整的聚水潭辅助表。', + 'data' => [], + 'total' => 0, + 'current_page' => 1, + 'last_page' => 1, + 'per_page' => (int) ($validated['limit'] ?? 10), + 'summary' => ['income' => 0, 'expense' => 0, 'balance' => 0, 'count' => 0], + 'columns' => AccountBillColumns::for('dewu'), + ], 503); + } + + $data['columns'] = AccountBillColumns::for('dewu'); + + return response()->json($this->withLedgerRemarks($data, 'dewu')); + } + + public function filterOptions(DewuSettlementBillRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab('dewu'); + + try { + return response()->json($repository->accountBillFilterOptions() + ['ledger_remarks' => $ledgerRemarks]); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'dewu_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json([ + 'message' => '得物完整账单尚未完成首次导入。', + 'shops' => [], + 'bill_items' => [], + 'ledger_remarks' => $ledgerRemarks, + ], 503); + } + } + + public function export(Request $request, DewuSettlementBillRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + return $this->exportResponse($request, $repository); + } + + private function exportResponse(Request $request, DewuSettlementBillRepository $repository) + { + $validated = $request->validate($this->filterRules() + [ + 'sort' => ['nullable', 'in:occurred_at,income,expense,record_code'], + 'dir' => ['nullable', 'in:asc,desc'], + ]); + $filters = collect($validated)->only(array_keys($this->filterRules()))->all(); + $filters = $this->withLedgerRemarkFilter($filters, 'dewu'); + $definition = AccountBillColumns::for('dewu'); + $available = collect($definition['columns'] ?? [])->keyBy('field'); + $requested = $request->query('columns', []); + if (is_string($requested)) { + $requested = array_filter(array_map('trim', explode(',', $requested))); + } + if (! is_array($requested) || count($requested) > 40) { + $requested = []; + } + $requested = collect($requested) + ->filter(static fn (mixed $value): bool => is_scalar($value)) + ->map(static fn (mixed $value): string => mb_substr(trim((string) $value), 0, 128)) + ->filter() + ->unique(); + $columns = $requested->isEmpty() + ? $available->values() + : $requested->map(fn (string $field) => $available->get($field))->filter()->values(); + abort_if($columns->isEmpty(), 422, '至少选择一个可导出的字段。'); + + try { + $rows = $repository->exportAccountBills( + $filters, + (string) ($validated['sort'] ?? 'occurred_at'), + (string) ($validated['dir'] ?? 'asc'), + ); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'dewu_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json(['message' => '得物完整账单尚未完成首次导入。'], 503); + } + + $rows = $this->ledgerRemarkRows($rows, 'dewu'); + + return response()->streamDownload(function () use ($rows, $columns): void { + $csv = fopen('php://output', 'w'); + fputs($csv, "\xEF\xBB\xBF"); + fputcsv($csv, $columns->pluck('label')->all()); + foreach ($rows as $row) { + fputcsv($csv, $columns->map( + fn (array $column): string => $this->exportValue($row, $column) + )->all()); + } + fclose($csv); + }, 'dewu_account_bills.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return array> */ + private function filterRules(): array + { + return [ + 'store_name' => ['nullable', 'string', 'max:255'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], + 'bill_item' => ['nullable', 'string', 'max:255'], + 'start' => ['nullable', 'date_format:Y-m-d'], + 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], + 'keyword' => ['nullable', 'string', 'max:255'], + ]; + } + + /** @param array $row */ + private function exportValue(array $row, array $column): string + { + $field = (string) ($column['field'] ?? ''); + $value = str_starts_with($field, 'payload.') + ? data_get($row['payload'] ?? [], substr($field, 8)) + : data_get($row, $field); + $text = (string) ($value ?? ''); + if (preg_match('/^\d{12,}$/', $text) === 1) { + return '="' . $text . '"'; + } + + return preg_match('/^[=+\-@]/u', $text) === 1 ? "'" . $text : $text; + } + + private function authorizeStoreReceivingBills(): void + { + $section = collect(SidebarPermissions::navigationFor(user())) + ->firstWhere('slug', 'billing-transactions'); + $page = collect($section['pages'] ?? []) + ->firstWhere('slug', 'store-receiving-bills'); + + abort_if(empty($page), 403, '当前账号没有店铺收款账户账单权限。'); + } +} diff --git a/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php b/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php new file mode 100644 index 00000000..c0324508 --- /dev/null +++ b/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php @@ -0,0 +1,188 @@ +authorizeStoreReceivingBills(); + + if ($request->boolean('export')) { + return $this->exportResponse($request, $repository); + } + + $validated = $request->validate($this->filterRules() + [ + 'sort' => ['nullable', 'in:occurred_at,income,expense,record_code'], + 'dir' => ['nullable', 'in:asc,desc'], + 'page' => ['nullable', 'integer', 'min:1'], + 'limit' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + $filters = collect($validated)->only(array_keys($this->filterRules()))->all(); + $filters = $this->withLedgerRemarkFilter($filters, 'pinduoduo'); + + try { + $data = $repository->paginateAccountBills( + $filters, + (string) ($validated['sort'] ?? 'occurred_at'), + (string) ($validated['dir'] ?? 'desc'), + (int) ($validated['page'] ?? 1), + (int) ($validated['limit'] ?? 10), + ); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'pinduoduo_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json([ + 'message' => '拼多多完整货款账单尚未完成首次导入,当前不会回退到不完整的聚水潭辅助表。', + 'data' => [], + 'total' => 0, + 'current_page' => 1, + 'last_page' => 1, + 'per_page' => (int) ($validated['limit'] ?? 10), + 'summary' => ['income' => 0, 'expense' => 0, 'balance' => 0, 'count' => 0], + 'columns' => AccountBillColumns::for('pinduoduo'), + ], 503); + } + + $data['columns'] = AccountBillColumns::for('pinduoduo'); + + return response()->json($this->withLedgerRemarks($data, 'pinduoduo')); + } + + public function filterOptions(PinduoduoSettlementBillRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab('pinduoduo'); + + try { + return response()->json($repository->accountBillFilterOptions() + ['ledger_remarks' => $ledgerRemarks]); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'pinduoduo_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json([ + 'message' => '拼多多完整货款账单尚未完成首次导入。', + 'shops' => [], + 'bill_items' => [], + 'ledger_remarks' => $ledgerRemarks, + ], 503); + } + } + + public function export(Request $request, PinduoduoSettlementBillRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + return $this->exportResponse($request, $repository); + } + + private function exportResponse(Request $request, PinduoduoSettlementBillRepository $repository) + { + $validated = $request->validate($this->filterRules() + [ + 'sort' => ['nullable', 'in:occurred_at,income,expense,record_code'], + 'dir' => ['nullable', 'in:asc,desc'], + ]); + $filters = collect($validated)->only(array_keys($this->filterRules()))->all(); + $filters = $this->withLedgerRemarkFilter($filters, 'pinduoduo'); + $definition = AccountBillColumns::for('pinduoduo'); + $available = collect($definition['columns'] ?? [])->keyBy('field'); + $requested = $request->query('columns', []); + if (is_string($requested)) { + $requested = array_filter(array_map('trim', explode(',', $requested))); + } + if (! is_array($requested) || count($requested) > 40) { + $requested = []; + } + $requested = collect($requested) + ->filter(static fn (mixed $value): bool => is_scalar($value)) + ->map(static fn (mixed $value): string => mb_substr(trim((string) $value), 0, 128)) + ->filter() + ->unique(); + $columns = $requested->isEmpty() + ? $available->values() + : $requested->map(fn (string $field) => $available->get($field))->filter()->values(); + abort_if($columns->isEmpty(), 422, '至少选择一个可导出的字段。'); + + try { + $rows = $repository->exportAccountBills( + $filters, + (string) ($validated['sort'] ?? 'occurred_at'), + (string) ($validated['dir'] ?? 'asc'), + ); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'pinduoduo_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json(['message' => '拼多多完整货款账单尚未完成首次导入。'], 503); + } + + $rows = $this->ledgerRemarkRows($rows, 'pinduoduo'); + + return response()->streamDownload(function () use ($rows, $columns): void { + $csv = fopen('php://output', 'w'); + fputs($csv, "\xEF\xBB\xBF"); + fputcsv($csv, $columns->pluck('label')->all()); + foreach ($rows as $row) { + fputcsv($csv, $columns->map( + fn (array $column): string => $this->exportValue($row, $column) + )->all()); + } + fclose($csv); + }, 'pinduoduo_account_bills.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return array> */ + private function filterRules(): array + { + return [ + 'store_name' => ['nullable', 'string', 'max:255'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], + 'bill_item' => ['nullable', 'string', 'max:255'], + 'start' => ['nullable', 'date_format:Y-m-d'], + 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], + 'keyword' => ['nullable', 'string', 'max:255'], + ]; + } + + /** @param array $row */ + private function exportValue(array $row, array $column): string + { + $field = (string) ($column['field'] ?? ''); + $value = str_starts_with($field, 'payload.') + ? data_get($row['payload'] ?? [], substr($field, 8)) + : data_get($row, $field); + $text = (string) ($value ?? ''); + if (preg_match('/^\d{12,}$/', $text) === 1) { + return '="' . $text . '"'; + } + + return preg_match('/^[=+\-@]/u', $text) === 1 ? "'" . $text : $text; + } + + private function authorizeStoreReceivingBills(): void + { + $section = collect(SidebarPermissions::navigationFor(user())) + ->firstWhere('slug', 'billing-transactions'); + $page = collect($section['pages'] ?? []) + ->firstWhere('slug', 'store-receiving-bills'); + + abort_if(empty($page), 403, '当前账号没有店铺收款账户账单权限。'); + } +} diff --git a/modules/EcommerceFinance/Http/Controllers/TaobaoWechatAccountBills.php b/modules/EcommerceFinance/Http/Controllers/TaobaoWechatAccountBills.php new file mode 100644 index 00000000..a99ea17f --- /dev/null +++ b/modules/EcommerceFinance/Http/Controllers/TaobaoWechatAccountBills.php @@ -0,0 +1,188 @@ +authorizeStoreReceivingBills(); + + if ($request->boolean('export')) { + return $this->exportResponse($request, $repository); + } + + $validated = $request->validate($this->filterRules() + [ + 'sort' => ['nullable', 'in:occurred_at,income,expense,record_code'], + 'dir' => ['nullable', 'in:asc,desc'], + 'page' => ['nullable', 'integer', 'min:1'], + 'limit' => ['nullable', 'integer', 'min:1', 'max:100'], + ]); + $filters = collect($validated)->only(array_keys($this->filterRules()))->all(); + $filters = $this->withLedgerRemarkFilter($filters, 'taobao-wechat'); + + try { + $data = $repository->paginateAccountBills( + $filters, + (string) ($validated['sort'] ?? 'occurred_at'), + (string) ($validated['dir'] ?? 'desc'), + (int) ($validated['page'] ?? 1), + (int) ($validated['limit'] ?? 10), + ); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'taobao_wechat_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json([ + 'message' => '淘系微信完整账单尚未完成首次导入,当前不会回退到不完整的聚水潭辅助表。', + 'data' => [], + 'total' => 0, + 'current_page' => 1, + 'last_page' => 1, + 'per_page' => (int) ($validated['limit'] ?? 10), + 'summary' => ['income' => 0, 'expense' => 0, 'balance' => 0, 'count' => 0], + 'columns' => AccountBillColumns::for('taobao-wechat'), + ], 503); + } + + $data['columns'] = AccountBillColumns::for('taobao-wechat'); + + return response()->json($this->withLedgerRemarks($data, 'taobao-wechat')); + } + + public function filterOptions(TaobaoWechatSettlementBillRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab('taobao-wechat'); + + try { + return response()->json($repository->accountBillFilterOptions() + ['ledger_remarks' => $ledgerRemarks]); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'taobao_wechat_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json([ + 'message' => '淘系微信完整账单尚未完成首次导入。', + 'shops' => [], + 'bill_items' => [], + 'ledger_remarks' => $ledgerRemarks, + ], 503); + } + } + + public function export(Request $request, TaobaoWechatSettlementBillRepository $repository) + { + $this->authorizeStoreReceivingBills(); + + return $this->exportResponse($request, $repository); + } + + private function exportResponse(Request $request, TaobaoWechatSettlementBillRepository $repository) + { + $validated = $request->validate($this->filterRules() + [ + 'sort' => ['nullable', 'in:occurred_at,income,expense,record_code'], + 'dir' => ['nullable', 'in:asc,desc'], + ]); + $filters = collect($validated)->only(array_keys($this->filterRules()))->all(); + $filters = $this->withLedgerRemarkFilter($filters, 'taobao-wechat'); + $definition = AccountBillColumns::for('taobao-wechat'); + $available = collect($definition['columns'] ?? [])->keyBy('field'); + $requested = $request->query('columns', []); + if (is_string($requested)) { + $requested = array_filter(array_map('trim', explode(',', $requested))); + } + if (! is_array($requested) || count($requested) > 40) { + $requested = []; + } + $requested = collect($requested) + ->filter(static fn (mixed $value): bool => is_scalar($value)) + ->map(static fn (mixed $value): string => mb_substr(trim((string) $value), 0, 128)) + ->filter() + ->unique(); + $columns = $requested->isEmpty() + ? $available->values() + : $requested->map(fn (string $field) => $available->get($field))->filter()->values(); + abort_if($columns->isEmpty(), 422, '至少选择一个可导出的字段。'); + + try { + $rows = $repository->exportAccountBills( + $filters, + (string) ($validated['sort'] ?? 'occurred_at'), + (string) ($validated['dir'] ?? 'asc'), + ); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'taobao_wechat_authoritative_bills_not_ready') { + throw $exception; + } + + return response()->json(['message' => '淘系微信完整账单尚未完成首次导入。'], 503); + } + + $rows = $this->ledgerRemarkRows($rows, 'taobao-wechat'); + + return response()->streamDownload(function () use ($rows, $columns): void { + $csv = fopen('php://output', 'w'); + fputs($csv, "\xEF\xBB\xBF"); + fputcsv($csv, $columns->pluck('label')->all()); + foreach ($rows as $row) { + fputcsv($csv, $columns->map( + fn (array $column): string => $this->exportValue($row, $column) + )->all()); + } + fclose($csv); + }, 'taobao-wechat_account_bills.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return array> */ + private function filterRules(): array + { + return [ + 'store_name' => ['nullable', 'string', 'max:255'], + 'ledger_remark' => ['nullable', 'string', 'max:191'], + 'bill_item' => ['nullable', 'string', 'max:255'], + 'start' => ['nullable', 'date_format:Y-m-d'], + 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], + 'keyword' => ['nullable', 'string', 'max:255'], + ]; + } + + /** @param array $row */ + private function exportValue(array $row, array $column): string + { + $field = (string) ($column['field'] ?? ''); + $value = str_starts_with($field, 'payload.') + ? data_get($row['payload'] ?? [], substr($field, 8)) + : data_get($row, $field); + $text = (string) ($value ?? ''); + if (preg_match('/^\d{12,}$/', $text) === 1) { + return '="' . $text . '"'; + } + + return preg_match('/^[=+\-@]/u', $text) === 1 ? "'" . $text : $text; + } + + private function authorizeStoreReceivingBills(): void + { + $section = collect(SidebarPermissions::navigationFor(user())) + ->firstWhere('slug', 'billing-transactions'); + $page = collect($section['pages'] ?? []) + ->firstWhere('slug', 'store-receiving-bills'); + + abort_if(empty($page), 403, '当前账号没有店铺收款账户账单权限。'); + } +} diff --git a/modules/EcommerceFinance/JdBillPlatform.php b/modules/EcommerceFinance/JdBillPlatform.php new file mode 100644 index 00000000..3be97c19 --- /dev/null +++ b/modules/EcommerceFinance/JdBillPlatform.php @@ -0,0 +1,84 @@ + 与京东日账单共用取数与渲染逻辑的页签。 */ + public static function tabs(): array + { + return [self::BILL_TYPE_JD, self::BILL_TYPE_JINGXI]; + } + + public static function isJdBillTab(string $billType): bool + { + return in_array($billType, self::tabs(), true); + } + + /** 页签对应的平台口径:'jingxi'、'jd',非京东系列页签返回 null。 */ + public static function platformForBillType(string $billType): ?string + { + return match ($billType) { + self::BILL_TYPE_JINGXI => 'jingxi', + self::BILL_TYPE_JD => 'jd', + default => null, + }; + } + + /** 京喜店铺名关键字。 */ + public static function storeNameKeyword(): string + { + $keyword = trim((string) config(self::CONFIG_KEY . '.jingxi_store_name_keyword', '京喜')); + + return $keyword === '' ? '京喜' : $keyword; + } + + /** 口径切换起始日期;null = 全量历史。 */ + public static function scopeStartDate(): ?string + { + $start = config(self::CONFIG_KEY . '.scope_start_date'); + + return is_string($start) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $start) === 1 ? $start : null; + } + + /** + * 店铺维度的过滤条件。 + * + * @param 'jingxi'|'jd'|null $platform + * @return array{mode:string,keyword:string,start_date:?string}|null mode: only=只取该平台,exclude=排除该平台 + */ + public static function storeNameScope(?string $platform): ?array + { + if (! in_array($platform, ['jingxi', 'jd'], true)) { + return null; + } + + return [ + 'mode' => $platform === 'jingxi' ? 'only' : 'exclude', + 'keyword' => self::storeNameKeyword(), + 'start_date' => self::scopeStartDate(), + ]; + } +} diff --git a/modules/EcommerceFinance/Repositories/BusinessInformationMirrorRepository.php b/modules/EcommerceFinance/Repositories/BusinessInformationMirrorRepository.php index 0700039e..a315204a 100644 --- a/modules/EcommerceFinance/Repositories/BusinessInformationMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/BusinessInformationMirrorRepository.php @@ -31,7 +31,7 @@ class BusinessInformationMirrorRepository } /** @return array{data: array>, total: int} */ - public function paginate(string $scope, int $page, int $perPage): array + public function paginate(string $scope, int $page, int $perPage, array $filters = []): array { if (! $this->ready($scope)) { throw new RuntimeException('business_mirror_dataset_not_ready'); @@ -41,9 +41,9 @@ class BusinessInformationMirrorRepository $perPage = min(max($perPage, 1), 100); return match ($scope) { - 'company-information.read' => $this->companies($page, $perPage), - 'store-information.read' => $this->stores($page, $perPage), - 'trademark-information.read' => $this->trademarks($page, $perPage), + 'company-information.read' => $this->companies($page, $perPage, $filters), + 'store-information.read' => $this->stores($page, $perPage, $filters), + 'trademark-information.read' => $this->trademarks($page, $perPage, $filters), default => throw new InvalidArgumentException('未知的业务资料镜像范围:' . $scope), }; } @@ -118,7 +118,7 @@ SQL) ] as $key => $column) { $value = trim((string) ($filters[$key] ?? '')); if ($value !== '') { - $query->where($column, '=', $value); + $query->where($column, 'like', '%' . addcslashes($value, '%_\\') . '%'); } } @@ -162,7 +162,7 @@ SQL) } /** @return array{data: array>, total: int} */ - private function companies(int $page, int $perPage): array + private function companies(int $page, int $perPage, array $filters): array { $query = $this->connection->table('ops_fys_company_info') ->selectRaw(<<<'SQL' @@ -184,13 +184,77 @@ taxCategoryAndType AS taxpayer_category, NULL AS shareholders SQL); - return $this->page($query, $page, $perPage, 'Id'); + $this->applyFieldFilters($query, $filters, [ + 'unified_social_credit_code' => 'unifiedSocialCreditCode', 'company_name' => 'businessLicenseName', + 'establishment_date' => 'IncorporationDate', + 'registered_at' => 'IncorporationDate', + 'legal_representative' => 'legalRepresentative', 'registered_address' => 'registeredAddress', + 'city' => 'registeredAddress', + 'business_scope' => 'businessScope', 'subscribed_at' => 'registeredCapitalVaildTime', + 'financial_officer' => 'financialManager', + 'billing_officer' => 'financialManager', + 'supervisor' => 'supervisor', + ], ['subscribed_capital' => 'registeredCapital'], [ + 'company_type' => 'businessLicenseType', + 'taxpayer_type' => 'taxCategoryAndType', + 'taxpayer_category' => 'taxCategoryAndType', + ]); + $companyStatus = trim((string) ($filters['company_status'] ?? '')); + if ($companyStatus !== '') { + $statusCode = ['正常' => '0', '已注销' => '1'][$companyStatus] ?? $companyStatus; + $query->where('companyStatus', '=', $statusCode); + } + $relatedPeople = mb_substr(trim((string) ($filters['related_people'] ?? '')), 0, 191); + if ($relatedPeople !== '') { + $like = '%' . addcslashes($relatedPeople, '%_\\') . '%'; + $query->where(function ($query) use ($like): void { + $query->where('legalRepresentative', 'like', $like) + ->orWhere('supervisor', 'like', $like) + ->orWhere('financialManager', 'like', $like); + }); + } + return $this->page($query, $page, $perPage, 'Id', $filters, [ + 'unified_social_credit_code' => 'unifiedSocialCreditCode', 'company_name' => 'businessLicenseName', + 'taxpayer_type' => 'taxCategoryAndType', 'company_status' => 'companyStatus', + 'subscribed_capital' => 'registeredCapital', 'registered_at' => 'IncorporationDate', + 'legal_representative' => 'legalRepresentative', 'supervisor' => 'supervisor', + 'billing_officer' => 'financialManager', 'registered_address' => 'registeredAddress', + 'city' => 'registeredAddress', 'business_scope' => 'businessScope', + 'basic_deposit_account' => 'accountSerialNumber', 'subscribed_at' => 'registeredCapitalVaildTime', + ]); } /** @return array{data: array>, total: int} */ - private function stores(int $page, int $perPage): array + private function stores(int $page, int $perPage, array $filters): array { - return $this->page($this->storeQuery(), $page, $perPage, 's.Id'); + $query = $this->storeQuery(); + $this->applyFieldFilters($query, $filters, [ + 'store_id' => 's.sotreId', 'store_name' => 's.erpShopName', 'store_entity' => 'c.businessLicenseName', + 'trademark' => 't.trademarkName', 'trademark_number' => 's.trademarkNumber', + 'business_department' => 's.responsibleDepartment', 'store_manager' => 's.shopHead', + 'department_manager' => 's.customerDeptManager', 'opened_at' => 's.openTime', 'renewed_at' => 's.renewalTime', + ], [], ['platform' => 's.platform']); + $storeStatus = trim((string) ($filters['store_status'] ?? '')); + if ($storeStatus !== '') { + $statusCode = ['正常' => '0', '关闭中' => '3', '已关闭' => '6'][$storeStatus] ?? $storeStatus; + $query->where('s.shopState', '=', $statusCode); + } + $withdrawalAccount = trim((string) ($filters['withdrawal_account'] ?? '')); + if ($withdrawalAccount === '已配置') { + $query->whereNotNull('s.shopBankAccount')->where('s.shopBankAccount', '<>', ''); + } elseif ($withdrawalAccount === '未配置') { + $query->where(function ($query): void { + $query->whereNull('s.shopBankAccount')->orWhere('s.shopBankAccount', '=', ''); + }); + } + return $this->page($query, $page, $perPage, 's.Id', $filters, [ + 'platform' => 's.platform', 'store_id' => 's.sotreId', 'store_name' => 's.erpShopName', + 'store_entity' => 'c.businessLicenseName', 'store_status' => 's.shopState', + 'trademark' => 't.trademarkName', 'trademark_number' => 's.trademarkNumber', + 'business_department' => 's.responsibleDepartment', 'store_manager' => 's.shopHead', + 'department_manager' => 's.customerDeptManager', 'opened_at' => 's.openTime', + 'renewed_at' => 's.renewalTime', 'withdrawal_account' => 's.shopBankAccount', + ]); } private function storeQuery() @@ -245,7 +309,7 @@ SQL); } /** @return array{data: array>, total: int} */ - private function trademarks(int $page, int $perPage): array + private function trademarks(int $page, int $perPage, array $filters): array { $query = $this->connection->table('ops_fys_trademark_info') ->where('isDelete', 0) @@ -264,14 +328,69 @@ custodyDepartment AS custody_department, remark AS notes SQL); - return $this->page($query, $page, $perPage, 'Id'); + $this->applyFieldFilters($query, $filters, [ + 'trademark_number' => 'trademarkNumber', 'trademark_name' => 'trademarkName', + 'registration_date' => 'registrationDate', + 'expiry_date' => 'termOfValidity', 'international_classification' => 'internationalClassification', + 'approved_goods' => 'approvedCommodities', 'final_holder' => 'transferenceUser', + 'registered_address' => 'registrationAddress', 'custody_department' => 'custodyDepartment', + ]); + $status = trim((string) ($filters['trademark_status'] ?? '')); + if ($status !== '') { + $statusCode = ['未启用' => '0', '有效' => '1'][$status] ?? $status; + $query->where('trademarkStatus', '=', $statusCode); + } + return $this->page($query, $page, $perPage, 'Id', $filters, [ + 'trademark_name' => 'trademarkName', 'trademark_number' => 'trademarkNumber', + 'trademark_status' => 'trademarkStatus', 'registration_date' => 'registrationDate', + 'expiry_date' => 'termOfValidity', 'international_classification' => 'internationalClassification', + 'approved_goods' => 'approvedCommodities', 'final_holder' => 'transferenceUser', + 'registered_address' => 'registrationAddress', 'custody_department' => 'custodyDepartment', + ]); + } + + /** @param array $textColumns @param array $exactColumns @param array $enumColumns */ + private function applyFieldFilters($query, array $filters, array $textColumns, array $exactColumns = [], array $enumColumns = []): void + { + foreach ($textColumns as $key => $column) { + $value = mb_substr(trim((string) ($filters[$key] ?? '')), 0, 191); + if ($value !== '') { + $query->where($column, 'like', '%' . addcslashes($value, '%_\\') . '%'); + } + } + foreach ($exactColumns as $key => $column) { + $value = trim((string) ($filters[$key] ?? '')); + if ($value !== '') { + $query->where($column, '=', $value); + } + } + foreach ($enumColumns as $key => $column) { + $value = trim((string) ($filters[$key] ?? '')); + if ($value !== '') { + $query->where($column, '=', $value); + } + } + foreach (['opened_at' => 's.openTime', 'renewed_at' => 's.renewalTime', 'registration_date' => 'registrationDate', 'expiry_date' => 'termOfValidity'] as $key => $column) { + if (! array_key_exists($key, $textColumns)) continue; + foreach (['_from' => '>=', '_to' => '<='] as $suffix => $operator) { + $date = trim((string) ($filters[$key . $suffix] ?? '')); + if (preg_match('/^\\d{4}-\\d{2}-\\d{2}$/D', $date)) $query->where($column, $operator, $date); + } + } } /** @return array{data: array>, total: int} */ - private function page($query, int $page, int $perPage, string $orderColumn): array + private function page($query, int $page, int $perPage, string $orderColumn, array $filters = [], array $sortColumns = []): array { $total = (clone $query)->count(); - $rows = $query->orderByDesc($orderColumn) + $sortColumn = $sortColumns[$filters['_sort'] ?? ''] ?? null; + $direction = ($filters['_direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc'; + if ($sortColumn !== null) { + $query->orderBy($sortColumn, $direction)->orderByDesc($orderColumn); + } else { + $query->orderByDesc($orderColumn); + } + $rows = $query ->forPage($page, $perPage) ->get() ->map(static fn (object $row): array => (array) $row) diff --git a/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php b/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php index 068afcf2..4d14024b 100644 --- a/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php @@ -112,6 +112,30 @@ class CourierInformationMirrorRepository return ['data' => $rows, 'total' => $total]; } + /** + * 快递资料中的去重快递公司名称,按资料 Id 的首次出现顺序返回。 + * + * @return list + */ + public function names(): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + return $this->connection + ->table($this->dataset()->targetTable()) + ->select(['Id', 'expname']) + ->whereNotNull('expname') + ->orderBy('Id') + ->get() + ->map(static fn ($row): string => trim((string) ($row->expname ?? ''))) + ->filter(static fn (string $name): bool => $name !== '') + ->unique() + ->values() + ->all(); + } + /** * @param array $filters * @return \Generator diff --git a/modules/EcommerceFinance/Repositories/DewuSettlementBillRepository.php b/modules/EcommerceFinance/Repositories/DewuSettlementBillRepository.php new file mode 100644 index 00000000..25608e0e --- /dev/null +++ b/modules/EcommerceFinance/Repositories/DewuSettlementBillRepository.php @@ -0,0 +1,344 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::IMPORT_TABLE) || ! $schema->hasTable(self::ROW_TABLE)) { + return false; + } + + return $this->connection->table(self::IMPORT_TABLE)->where('status', 'succeeded')->exists(); + } + + /** @return string[] */ + public function storeOptions(): array + { + return $this->query()->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name')->map('strval')->all(); + } + + /** @return array{shops:list,bill_items:list} */ + public function accountBillFilterOptions(): array + { + $shops = $this->query()->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name') + ->map(static fn (mixed $value): string => (string) $value)->all(); + $billItems = $this->query()->whereNotNull('bill_item')->where('bill_item', '<>', '') + ->distinct()->orderBy('bill_item')->pluck('bill_item') + ->map(static fn (mixed $value): string => (string) $value)->all(); + + return ['shops' => $shops, 'bill_items' => $billItems]; + } + + /** @return array{rows:list>,total:int} */ + public function paginate( + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + int $page, + int $pageSize, + ): array { + $page = max(1, $page); + $pageSize = min(max(1, $pageSize), 500); + $query = $this->query(); + $this->applyFilters($query, $storeName, $fromDate, $toDate, $flowType); + $total = (clone $query)->count(); + + $rows = $query->orderByDesc('bill_date')->orderByDesc('record_code') + ->forPage($page, $pageSize)->get()->map(function (object $row): array { + $signed = (float) $row->signed_amount; + $income = (float) $row->income_amount; + $expense = (float) $row->expense_amount; + $flowType = $income > 0 ? 1 : ($expense > 0 ? 2 : 0); + + return [ + 'id' => $row->record_code, + 'shopName' => (string) ($row->store_name ?? ''), + 'amount' => abs($signed), + 'balance' => null, + 'summary' => (string) ($row->bill_item ?? ''), + 'flowType' => $flowType, + 'toAdvertiserFundType' => null, + 'createTime' => (string) $row->bill_date, + 'source_primary_key' => (string) ($row->order_no ?? ''), + 'source_record_code' => (string) $row->record_code, + 'source_channel' => 'DewuSettlementBill', + ]; + })->all(); + + return ['rows' => $rows, 'total' => $total]; + } + + /** @return array{income_total:float,expense_total:float,cnt:int} */ + public function summarize( + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + ): array { + $query = $this->query(); + $this->applyFilters($query, $storeName, $fromDate, $toDate, $flowType); + $row = $query->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS cnt' + )->first(); + + return [ + 'income_total' => (float) ($row->income_total ?? 0), + 'expense_total' => (float) ($row->expense_total ?? 0), + 'cnt' => (int) ($row->cnt ?? 0), + ]; + } + + /** @return array */ + public function paginateAccountBills( + array $filters, + string $sort, + string $direction, + int $page, + int $perPage, + ): array { + $page = max(1, $page); + $perPage = min(max(1, $perPage), 100); + $query = $this->query(); + $this->applyAccountBillFilters($query, $filters); + + $summary = (clone $query)->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS row_count' + )->first(); + $total = (int) ($summary->row_count ?? 0); + $income = (float) ($summary->income_total ?? 0); + $expense = (float) ($summary->expense_total ?? 0); + + $sortColumn = $this->accountBillSortColumn($sort); + $direction = $direction === 'asc' ? 'asc' : 'desc'; + + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') { + $query->orderBy('record_code', $direction); + } + + $rows = $query->forPage($page, $perPage)->get() + ->map(fn (object $row): array => $this->mapAccountBillRow($row))->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'current_page' => $page, + 'last_page' => max(1, (int) ceil($total / $perPage)), + 'per_page' => $perPage, + 'from' => $total === 0 ? null : (($page - 1) * $perPage) + 1, + 'to' => $total === 0 ? null : min($page * $perPage, $total), + 'summary' => [ + 'income' => $income, + 'expense' => $expense, + 'balance' => round($income - $expense, 2), + 'count' => $total, + ], + ]; + } + + /** @return iterable> */ + public function exportAccountBills(array $filters, string $sort, string $direction): iterable + { + $query = $this->query(); + $this->applyAccountBillFilters($query, $filters); + $sortColumn = $this->accountBillSortColumn($sort); + $direction = $direction === 'desc' ? 'desc' : 'asc'; + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') { + $query->orderBy('record_code', $direction); + } + + return $query->cursor()->map(fn (object $row): array => $this->mapAccountBillRow($row)); + } + + private function query(): Builder + { + if (! $this->ready()) { + throw new RuntimeException('dewu_authoritative_bills_not_ready'); + } + + return $this->connection->table(self::ROW_TABLE); + } + + private function applyFilters( + Builder $query, + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + ): void { + if ($storeName !== null && $storeName !== '') { + $query->where('store_name', $storeName); + } + $from = $this->date($fromDate); + if ($from !== null) { + $query->where('bill_date', '>=', $from->format('Y-m-d') . ' 00:00:00'); + } + $to = $this->date($toDate); + if ($to !== null) { + $query->where('bill_date', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + } + if ($flowType === 'income') { + $query->where('income_amount', '>', 0); + } elseif ($flowType === 'expense') { + $query->where('expense_amount', '>', 0); + } +} + /** @param array $filters */ + private function applyAccountBillFilters(Builder $query, array $filters): void + { + $storeName = trim((string) ($filters['store_name'] ?? '')); + if ($storeName !== '') { + $query->where('store_name', $storeName); + } + + $billItem = trim((string) ($filters['bill_item'] ?? '')); + if ($billItem !== '') { + $query->where('bill_item', $billItem); + } + + $this->applyLedgerRemarkFilter($query, $filters); + + $from = $this->date(isset($filters['start']) ? (string) $filters['start'] : null); + if ($from !== null) { + $query->where('bill_date', '>=', $from->format('Y-m-d') . ' 00:00:00'); + } + + $to = $this->date(isset($filters['end']) ? (string) $filters['end'] : null); + if ($to !== null) { + $query->where('bill_date', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + } + + $keyword = trim((string) ($filters['keyword'] ?? '')); + if ($keyword !== '') { + $query->where(function (Builder $nested) use ($keyword): void { + $like = '%' . $keyword . '%'; + $nested->where('record_code', 'like', $like) + ->orWhere('order_no', 'like', $like) + ->orWhere('online_order_no', 'like', $like) + ->orWhere('custom_remark', 'like', $like) + ->orWhere('goods_name', 'like', $like) + ->orWhere('goods_no', 'like', $like) + ->orWhere('channel', 'like', $like) + ->orWhere('bill_item', 'like', $like); + }); + } + } + + /** 「总账备注」筛选:翻译成账单项目集合(得物单平台)。 */ + private function applyLedgerRemarkFilter(Builder $query, array $filters): void + { + $groups = is_array($filters['bill_item_groups'] ?? null) ? $filters['bill_item_groups'] : []; + if ($groups !== []) { + LedgerRemarkFilter::applyGroups( + $query, + $groups, + 'bill_item', + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'like', $prefix . '%'), + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'not like', $prefix . '%'), + ); + + return; + } + + LedgerRemarkFilter::itemsWhereIn($query, (array) ($filters['bill_items'] ?? []), 'bill_item'); + } + + private function accountBillSortColumn(string $sort): string + { + return [ + 'occurred_at' => 'bill_date', + 'income' => 'income_amount', + 'expense' => 'expense_amount', + 'record_code' => 'record_code', + ][$sort] ?? 'bill_date'; + } + + /** @return array */ + private function mapAccountBillRow(object $row): array + { + $signedAmount = (float) $row->signed_amount; + + return [ + 'id' => (string) $row->record_code, + 'record_code' => (string) $row->record_code, + 'store_name' => (string) ($row->store_name ?? ''), + 'finance_remark' => '', + 'order_no' => (string) ($row->order_no ?? ''), + 'amount' => abs($signedAmount), + 'custom_remark' => (string) ($row->custom_remark ?? ''), + 'bill_item' => (string) ($row->bill_item ?? ''), + 'occurred_at' => $row->paid_refunded_at !== null + ? (string) $row->paid_refunded_at + : null, + 'income' => (float) $row->income_amount, + 'expense' => (float) $row->expense_amount, + 'balance' => $signedAmount, + 'remark' => '', + 'updated_at' => $row->source_updated_at !== null + ? (string) $row->source_updated_at + : null, + 'modifier' => (string) ($row->source_modified_by ?? ''), + 'payload' => [ + 'online_order_no' => (string) ($row->online_order_no ?? ''), + 'store_2' => (string) ($row->store_name ?? ''), + 'order_type' => (string) ($row->order_type ?? ''), + 'goods_name' => (string) ($row->goods_name ?? ''), + 'goods_no' => (string) ($row->goods_no ?? ''), + 'quantity' => (string) ($row->quantity ?? ''), + 'channel' => (string) ($row->channel ?? ''), + 'source_channel' => match ((string) ($row->channel ?? '')) { + '得物' => 'Dewu', + '退货退款订单' => 'DewuTK', + '扣减其他费用明细' => 'DewuKJ', + default => (string) ($row->channel ?? ''), + }, + 'business_type' => (string) ($row->business_type ?? ''), + 'online_real_store' => (string) ($row->online_real_store ?? ''), + 'order_created_at' => $row->order_created_at !== null ? (string) $row->order_created_at : null, + 'ship_return_at' => $row->ship_return_at !== null ? (string) $row->ship_return_at : null, + 'settle_status' => (string) ($row->settle_status ?? ''), + 'pay_period' => (string) ($row->pay_period ?? ''), + 'pulled_at' => $row->pulled_at !== null ? (string) $row->pulled_at : null, + ], + ]; + } + + private function date(?string $value): ?DateTimeImmutable + { + if ($value === null || preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value); + + return $date !== false && $date->format('Y-m-d') === $value ? $date : null; + } +} diff --git a/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php index 33a6f88c..c06ab03a 100644 --- a/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php @@ -4,16 +4,17 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\DingPayableWorkflowStatus; use RuntimeException; /** - * 线上代发业务报销流程的共享镜像读取与按商品ID关联。 + * 线上代发价格的统一镜像查询。 * - * 数据由 DingPayableWorkflowMirrorSynchronizer(ding_online_daifa_price 配置) - * 从钉钉 OA 审批同步到 ding_online_daifa_price_mirror 宽表。本仓库只在镜像库 - * 读取,并依据 商品ID(product_id)关联共享业务镜像的商品目录,页面不直连上游。 + * 钉钉线上代发审批和聚水潭采购单先分别同步到共享业务镜像,再在这里合并。 + * 页面请求只读共享镜像,不跨来源实时查询上游。 */ class DingOnlineDaifaPriceMirrorRepository { @@ -21,8 +22,13 @@ class DingOnlineDaifaPriceMirrorRepository public const TARGET_TABLE = 'ding_online_daifa_price_mirror'; + private const ORDER_DATASET_KEY = 'operations_replica.rpt.jst_Orders'; + private readonly ConnectionInterface $connection; + /** @var array>|null */ + private ?array $sourceStatusCache = null; + public function __construct(GenericBusinessMirrorRepository $mirror) { $this->connection = $mirror->connection(); @@ -30,18 +36,12 @@ class DingOnlineDaifaPriceMirrorRepository public function ready(): bool { - $schema = Schema::connection($this->connection->getName()); - if (! $schema->hasTable(self::TARGET_TABLE) || ! $schema->hasTable('business_mirror_table_states')) { - return false; - } - - $state = $this->connection->table('business_mirror_table_states') - ->where('dataset_key', self::DATASET_KEY)->first(); - - return $state !== null && $state->initial_completed_at !== null; + return collect($this->sourceStatuses())->contains( + static fn (array $source): bool => (bool) ($source['ready'] ?? false), + ); } - /** @return array{data:list>,total:int,status:string,last_synced_at:?string,summary:array} */ + /** @return array{data:list>,total:int,status:string,last_synced_at:?string,summary:array,source_statuses:array>} */ public function paginate(array $filters, int $page, int $perPage): array { if (! $this->ready()) { @@ -50,38 +50,37 @@ class DingOnlineDaifaPriceMirrorRepository $page = max($page, 1); $perPage = min(max($perPage, 1), 100); - $state = $this->connection->table('business_mirror_table_states')->where('dataset_key', self::DATASET_KEY)->first(); - - // The synchronized dataset normally contains one configured status, so - // count, totals, and paging can stay in SQL instead of loading all rows. - $onlyStatus = strtoupper(trim((string) config('upstream_mirrors.ding_online_daifa_price.only_status', ''))); - $statusFilter = strtoupper(trim((string) ($filters['status'] ?? ''))); - $statusMismatch = $statusFilter !== '' && $onlyStatus !== '' && $statusFilter !== $onlyStatus; - - $total = $statusMismatch ? 0 : (int) $this->filteredQuery($filters)->count(); + $total = (int) $this->filteredQuery($filters)->count(); $summary = [ 'count' => 0, 'matched_count' => 0, + 'matchable_count' => 0, + 'purchase_count' => 0, 'daifa_amount' => 0.0, 'paid_amount' => 0.0, 'price_diff' => 0.0, ]; $pageRows = []; - if (! $statusMismatch) { + if ($total > 0) { $aggregate = $this->filteredQuery($filters) ->selectRaw( 'COUNT(*) AS row_count, ' - . "SUM(CASE WHEN product_id IS NOT NULL AND product_id <> '' AND product_name IS NOT NULL AND product_name <> '' THEN 1 ELSE 0 END) AS matched_count, " - . 'COALESCE(SUM(daifa_amount), 0) AS daifa_amount, ' - . 'COALESCE(SUM(paid_amount), 0) AS paid_amount, ' - . 'COALESCE(SUM(price_diff), 0) AS price_diff' + . "SUM(CASE WHEN source_type = 'purchase' THEN 1 ELSE 0 END) AS purchase_count, " + . "SUM(CASE WHEN source_type = 'ding' THEN 1 ELSE 0 END) AS matchable_count, " + . "SUM(CASE WHEN source_type = 'ding' AND product_id IS NOT NULL AND product_id <> '' " + . "AND product_name IS NOT NULL AND product_name <> '' THEN 1 ELSE 0 END) AS matched_count, " + . "COALESCE(SUM(CASE WHEN source_type = 'ding' THEN daifa_amount ELSE 0 END), 0) AS daifa_amount, " + . "COALESCE(SUM(CASE WHEN source_type = 'ding' THEN paid_amount ELSE 0 END), 0) AS paid_amount, " + . "COALESCE(SUM(CASE WHEN source_type = 'ding' THEN price_diff ELSE 0 END), 0) AS price_diff" ) ->first(); $summary = [ 'count' => (int) ($aggregate->row_count ?? 0), 'matched_count' => (int) ($aggregate->matched_count ?? 0), + 'matchable_count' => (int) ($aggregate->matchable_count ?? 0), + 'purchase_count' => (int) ($aggregate->purchase_count ?? 0), 'daifa_amount' => round((float) ($aggregate->daifa_amount ?? 0), 2), 'paid_amount' => round((float) ($aggregate->paid_amount ?? 0), 2), 'price_diff' => round((float) ($aggregate->price_diff ?? 0), 2), @@ -97,16 +96,22 @@ class DingOnlineDaifaPriceMirrorRepository $data = []; foreach ($pageRows as $row) { - $workflow = $this->decode((string) $row->workflow_payload, []); - $data[] = $this->presentRow($row, $workflow); + $data[] = $this->presentRow($row); } + $sources = $this->sourceStatuses(); + $readySources = array_filter($sources, static fn (array $source): bool => (bool) ($source['ready'] ?? false)); + $synced = array_values(array_filter(array_column($readySources, 'last_synced_at'))); + return [ 'data' => $data, 'total' => $total, - 'status' => (string) ($state->status ?? 'unknown'), - 'last_synced_at' => $state->last_succeeded_at ? (string) $state->last_succeeded_at : null, + 'status' => count($readySources) > 1 + ? 'available' + : (string) (reset($readySources)['status'] ?? 'unknown'), + 'last_synced_at' => $synced === [] ? null : max($synced), 'summary' => $summary, + 'source_statuses' => $sources, ]; } @@ -117,7 +122,6 @@ class DingOnlineDaifaPriceMirrorRepository throw new RuntimeException('business_mirror_dataset_not_ready'); } - $statusFilter = strtoupper(trim((string) ($filters['status'] ?? ''))); $rows = $this->filteredQuery($filters) ->orderByDesc('workflow_created_at') ->orderByDesc('process_instance_id') @@ -125,18 +129,13 @@ class DingOnlineDaifaPriceMirrorRepository ->cursor(); foreach ($rows as $row) { - $workflow = $this->decode((string) $row->workflow_payload, []); - if (! $this->matchesStatus($workflow, $statusFilter)) { - continue; - } - - yield $this->presentRow($row, $workflow); + yield $this->presentRow($row); } } private function filteredQuery(array $filters): Builder { - $query = $this->connection->table(self::TARGET_TABLE); + $query = $this->combinedQuery(); if (($filters['product_id'] ?? '') !== '') { $query->where('product_id', (string) $filters['product_id']); @@ -155,58 +154,236 @@ class DingOnlineDaifaPriceMirrorRepository $query->where(function ($q) use ($keyword): void { $q->where('process_instance_id', 'like', '%' . $keyword . '%') ->orWhere('daifa_trade_no', 'like', '%' . $keyword . '%') - ->orWhere('shop_trade_no', 'like', '%' . $keyword . '%'); + ->orWhere('shop_trade_no', 'like', '%' . $keyword . '%') + ->orWhere('source_order_no', 'like', '%' . $keyword . '%'); }); } + if (($filters['status'] ?? '') !== '') { + $query->where('status_key', strtoupper((string) $filters['status'])); + } if (($filters['created_from'] ?? '') !== '') { $query->where('workflow_created_at', '>=', (string) $filters['created_from']); } if (($filters['created_to'] ?? '') !== '') { - $query->where('workflow_created_at', '<', \Illuminate\Support\Carbon::parse((string) $filters['created_to'])->addDay()->startOfDay()->format('Y-m-d H:i:s')); + $query->where( + 'workflow_created_at', + '<', + Carbon::parse((string) $filters['created_to'])->addDay()->startOfDay()->format('Y-m-d H:i:s'), + ); } return $query; } - private function matchesStatus(array $workflow, string $statusFilter): bool + private function combinedQuery(): Builder { - return $statusFilter === '' || DingPayableWorkflowStatus::key($workflow) === $statusFilter; + $statuses = $this->sourceStatuses(); + $queries = []; + + if ((bool) ($statuses['ding']['ready'] ?? false)) { + $queries[] = $this->dingQuery(); + } + if ((bool) ($statuses['purchase']['ready'] ?? false)) { + $queries[] = $this->purchaseQuery(); + } + + if ($queries === []) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $union = array_shift($queries); + foreach ($queries as $query) { + $union->unionAll($query); + } + + return $this->connection->query()->fromSub($union, 'online_daifa_rows'); + } + + private function dingQuery(): Builder + { + $status = strtoupper(trim((string) config( + 'upstream_mirrors.ding_online_daifa_price.only_status', + 'COMPLETED', + ))) ?: 'COMPLETED'; + + return $this->connection->table(self::TARGET_TABLE . ' as d')->select([ + DB::raw("'ding' AS source_type"), + 'd.process_instance_id', + 'd.detail_index', + DB::raw('NULL AS purchase_order_id'), + DB::raw('NULL AS source_order_no'), + 'd.product_id', + 'd.product_name', + 'd.daifa_trade_no', + 'd.shop_trade_no', + 'd.shop_name', + 'd.payee_name', + DB::raw("CASE WHEN d.payee_name = '宁波顾家望业家居有限公司' THEN '刘萧代发' ELSE '1688代发' END AS tag"), + 'd.supplier_name', + 'd.material_no', + 'd.ship_qty', + 'd.paid_amount', + 'd.daifa_amount', + 'd.price_diff', + 'd.workflow_payload', + 'd.scheme_payload', + 'd.task_payload', + DB::raw("'" . $status . "' AS status_key"), + 'd.workflow_created_at', + ]); + } + + private function purchaseQuery(): Builder + { + return $this->connection->table('product_purchase_price_mirror_rows as p') + ->leftJoin('ops_jst_orders as o', 'o.o_id', '=', 'p.source_order_no') + ->whereIn('p.document_status', ['Confirmed', 'Finished']) + ->select([ + DB::raw("'purchase' AS source_type"), + 'p.purchase_order_id as process_instance_id', + 'p.item_id as detail_index', + 'p.purchase_order_id', + 'p.source_order_no', + DB::raw("'' AS product_id"), + DB::raw('NULL AS product_name'), + DB::raw("'' AS daifa_trade_no"), + 'o.so_id as shop_trade_no', + 'o.shop_name', + DB::raw("'' AS payee_name"), + DB::raw("'采购单管理' AS tag"), + 'p.supplier_name', + 'p.sku_id as material_no', + 'p.quantity as ship_qty', + DB::raw('NULL AS paid_amount'), + 'p.unit_price as daifa_amount', + DB::raw('NULL AS price_diff'), + DB::raw('NULL AS workflow_payload'), + DB::raw('NULL AS scheme_payload'), + DB::raw('NULL AS task_payload'), + DB::raw('UPPER(p.document_status) AS status_key'), + DB::raw('COALESCE(p.document_created_at, p.purchase_updated_at) AS workflow_created_at'), + ]); + } + + /** @return array> */ + private function sourceStatuses(): array + { + if ($this->sourceStatusCache !== null) { + return $this->sourceStatusCache; + } + + $schema = Schema::connection($this->connection->getName()); + $dingState = null; + if ($schema->hasTable(self::TARGET_TABLE) && $schema->hasTable('business_mirror_table_states')) { + $dingState = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', self::DATASET_KEY) + ->first(); + } + $dingReady = $dingState !== null && $dingState->initial_completed_at !== null; + + $purchaseState = null; + $orderState = null; + $requiredPurchaseColumns = [ + 'source_order_no', 'supplier_name', 'quantity', 'document_created_at', + ]; + $purchaseSchemaReady = $schema->hasTable('product_purchase_price_mirror_rows') + && $schema->hasTable('product_purchase_price_sync_states') + && $schema->hasTable('ops_jst_orders') + && $schema->hasColumns('product_purchase_price_mirror_rows', $requiredPurchaseColumns); + + if ($purchaseSchemaReady) { + $purchaseState = $this->connection->table('product_purchase_price_sync_states') + ->where('dataset_key', ProductPurchasePriceMirrorRepository::DATASET_KEY) + ->first(); + $orderState = $schema->hasTable('business_mirror_table_states') + ? $this->connection->table('business_mirror_table_states') + ->where('dataset_key', self::ORDER_DATASET_KEY) + ->first() + : null; + } + + $purchaseReady = $purchaseState !== null + && $purchaseState->initial_completed_at !== null + && (int) ($purchaseState->projection_version ?? 1) + >= ProductPurchasePriceMirrorRepository::CURRENT_PROJECTION_VERSION + && $orderState !== null + && $orderState->initial_completed_at !== null; + + return $this->sourceStatusCache = [ + 'ding' => [ + 'label' => '钉钉线上代发审批', + 'ready' => $dingReady, + 'status' => $dingState === null ? 'pending' : (string) $dingState->status, + 'last_synced_at' => $dingState?->last_succeeded_at === null + ? null + : (string) $dingState->last_succeeded_at, + ], + 'purchase' => [ + 'label' => '聚水潭采购单管理', + 'ready' => $purchaseReady, + 'status' => $purchaseReady + ? (string) $purchaseState->status + : ($purchaseSchemaReady ? 'requires_full_sync' : 'pending'), + 'last_synced_at' => $purchaseState?->last_succeeded_at === null + ? null + : (string) $purchaseState->last_succeeded_at, + ], + ]; } /** @return array */ - private function presentRow(object $row, array $workflow): array + private function presentRow(object $row): array { + $sourceType = (string) ($row->source_type ?? 'ding'); + $purchase = $sourceType === 'purchase'; + $workflow = $purchase + ? [ + 'businessId' => (string) ($row->purchase_order_id ?? ''), + 'title' => '采购单管理', + 'status' => (string) ($row->status_key ?? ''), + ] + : $this->decode((string) ($row->workflow_payload ?? ''), []); $productId = (string) ($row->product_id ?? ''); - // 商品名称已在同步阶段按 商品ID 关联商品目录并写入镜像宽表 product_name 列, - // 页面直接读取,避免对 2500 万行的 ops_jst_sku_map 做临时 JOIN 导致超时。 $resolvedName = $this->cleanName($row->product_name ?? null); - $product = $productId !== '' && $resolvedName !== null + $product = ! $purchase && $productId !== '' && $resolvedName !== null ? ['matched' => true, 'name' => $resolvedName, 'sku_id' => null, 'i_id' => null] : ['matched' => false, 'name' => null, 'sku_id' => null, 'i_id' => null]; + $statusKey = $purchase + ? strtoupper((string) ($row->status_key ?? '')) + : DingPayableWorkflowStatus::key($workflow); return [ + 'source_type' => $sourceType, 'process_instance_id' => (string) $row->process_instance_id, 'detail_index' => (int) $row->detail_index, + 'purchase_order_id' => $row->purchase_order_id === null ? null : (int) $row->purchase_order_id, + 'source_order_no' => $row->source_order_no === null ? null : (string) $row->source_order_no, 'product_id' => $productId, 'daifa_trade_no' => (string) ($row->daifa_trade_no ?? ''), 'shop_trade_no' => (string) ($row->shop_trade_no ?? ''), 'shop_name' => (string) ($row->shop_name ?? ''), 'payee_name' => (string) ($row->payee_name ?? ''), - 'tag' => ((string) ($row->payee_name ?? '')) === '宁波顾家望业家居有限公司' - ? '刘萧代发' - : '1688代发', + 'tag' => (string) ($row->tag ?? ''), 'supplier_name' => (string) ($row->supplier_name ?? ''), 'material_no' => (string) ($row->material_no ?? ''), - 'ship_qty' => $row->ship_qty === null ? null : (int) $row->ship_qty, + 'ship_qty' => $row->ship_qty === null ? null : (float) $row->ship_qty, 'paid_amount' => $row->paid_amount === null ? null : (float) $row->paid_amount, 'daifa_amount' => $row->daifa_amount === null ? null : (float) $row->daifa_amount, 'price_diff' => $row->price_diff === null ? null : (float) $row->price_diff, 'workflow' => $workflow, - 'scheme' => $this->decode((string) ($row->scheme_payload ?? '[]'), []), - 'tasks' => $this->decode((string) ($row->task_payload ?? '[]'), []), - 'status_key' => DingPayableWorkflowStatus::key($workflow), - 'status_label' => DingPayableWorkflowStatus::label($workflow), + 'scheme' => $purchase ? [] : $this->decode((string) ($row->scheme_payload ?? ''), []), + 'tasks' => $purchase ? [] : $this->decode((string) ($row->task_payload ?? ''), []), + 'status_key' => $statusKey, + 'status_label' => $purchase + ? match ($statusKey) { + 'CONFIRMED' => '已确认', + 'FINISHED' => '已完成', + default => $statusKey, + } + : DingPayableWorkflowStatus::label($workflow), 'matched_product' => $product, + 'order_matched' => ! $purchase + || ((string) ($row->shop_trade_no ?? '') !== '' && (string) ($row->shop_name ?? '') !== ''), 'workflow_created_at' => (string) ($row->workflow_created_at ?? ''), ]; } @@ -222,6 +399,7 @@ class DingOnlineDaifaPriceMirrorRepository return null; } $name = trim((string) $value); + return $name === '' ? null : $name; } @@ -231,6 +409,7 @@ class DingOnlineDaifaPriceMirrorRepository return $fallback; } $decoded = json_decode($json, true); + return is_array($decoded) ? $decoded : $fallback; } } diff --git a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php index b75b6a85..f141b144 100644 --- a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php +++ b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php @@ -5,6 +5,7 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\DatabaseManager; use Illuminate\Database\Query\Builder; use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry; +use Modules\EcommerceFinance\Services\LedgerRemarkFilter; use RuntimeException; class DouyinAuthoritativeBillRepository @@ -121,9 +122,19 @@ class DouyinAuthoritativeBillRepository } } if (($filters['bill_item'] ?? '') !== '') $query->where($item, 'like', '%' . $this->escape($filters['bill_item']) . '%'); + LedgerRemarkFilter::itemsWhereIn($query, (array) ($filters['bill_items'] ?? []), $item); if (($filters['start'] ?? '') !== '') $query->where($date, '>=', $filters['start'] . ' 00:00:00'); if (($filters['end'] ?? '') !== '') $query->where($date, '<', date('Y-m-d', strtotime($filters['end'] . ' +1 day')) . ' 00:00:00'); if (($filters['keyword'] ?? '') !== '') { + if (($filters['keyword_match'] ?? '') === 'exact-record') { + $keyword = (string) $filters['keyword']; + if ($legacy && (! preg_match('/^(0|[1-9]\d{0,9})$/', $keyword) || (float) $keyword > 2147483647)) { + $query->whereRaw('1 = 0'); + } else { + $query->where($legacy ? 'b.Id' : 'record_code', $keyword); + } + return; + } $value = '%' . $this->escape($filters['keyword']) . '%'; $columns = $legacy ? ['b.Id', 'b.auto_id', 'b.fee_name', 'b.primary_key', 'b.p_auto_id', 'b.so_id', 'b.sku_id', 'b.shop_sku_id', 'b.shop_i_id', 'b.channel'] : ['record_code', 'order_no', 'bill_item', 'row_data']; diff --git a/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php b/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php new file mode 100644 index 00000000..3435f0f1 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/InternalFlowReportRepository.php @@ -0,0 +1,89 @@ +connection = $mirror->connection(); + } + + public function ready(): bool + { + return $this->connection->getSchemaBuilder()->hasTable(self::TABLE); + } + + /** + * @param array{company_name?:string,tag?:string} $filters + * @return array{data: list>, total: int} + */ + public function paginate(int $page, int $perPage, array $filters = [], ?string $sort = null, string $direction = 'asc'): array + { + if (! $this->ready()) { + return ['data' => [], 'total' => 0]; + } + + $query = $this->connection->table(self::TABLE); + + $companyName = trim((string) ($filters['company_name'] ?? '')); + if ($companyName !== '') { + $query->where('company_name', 'like', '%' . addcslashes($companyName, '%_\\') . '%'); + } + + $tag = trim((string) ($filters['tag'] ?? '')); + if ($tag !== '') { + $query->where('tag', '=', $tag); + } + + $total = (clone $query)->count(); + + $column = in_array($sort, self::SORTABLE, true) ? $sort : null; + $direction = strtolower($direction) === 'desc' ? 'desc' : 'asc'; + + if ($column !== null) { + $query->orderBy($column, $direction)->orderBy('sort_order'); + } else { + $query->orderBy('sort_order')->orderBy('id'); + } + + $rows = $query + ->forPage(max($page, 1), min(max($perPage, 1), 100)) + ->get() + ->map(static fn (object $row): array => (array) $row) + ->all(); + + return ['data' => $rows, 'total' => $total]; + } +} diff --git a/modules/EcommerceFinance/Repositories/JdDailyBillRepository.php b/modules/EcommerceFinance/Repositories/JdDailyBillRepository.php new file mode 100644 index 00000000..37f4a8ee --- /dev/null +++ b/modules/EcommerceFinance/Repositories/JdDailyBillRepository.php @@ -0,0 +1,135 @@ +platform = $platform; + + return $clone; + } + + public function paginate(array $filters, string $sort, string $direction, int $page, int $perPage): array + { + $periods = $this->periods(); + $query = $this->query($filters, $periods); + $summary = (clone $query)->selectRaw('COUNT(*) AS count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')->first(); + $total = (int) $summary->count; + $page = max(1, $page); + $perPage = min(100, max(1, $perPage)); + // Skip deep pages using narrow indexed keys, then load JSON only for the visible rows. + $keys = $this->ordered($query, $sort, $direction)->forPage($page, $perPage)->get(['generation', 'record_code']); + $rows = []; + foreach ($keys->groupBy('generation') as $generation => $group) { + $records = $this->db()->table('jd_daily_bill_rows')->where('generation', $generation) + ->whereIn('record_code', $group->pluck('record_code')->all())->get(['record_code', 'row_data']); + foreach ($records as $record) $rows[$generation . ':' . $record->record_code] = json_decode($record->row_data, true, 512, JSON_THROW_ON_ERROR); + } + return [ + 'data' => $keys->map(fn ($key) => $rows[$key->generation . ':' . $key->record_code])->all(), + 'total' => $total, 'current_page' => $page, 'last_page' => max(1, (int) ceil($total / $perPage)), 'per_page' => $perPage, + 'summary' => ['count' => $total, 'income' => round((float) $summary->income, 2), 'expense' => round((float) $summary->expense, 2), + 'balance' => round((float) $summary->income - (float) $summary->expense, 2)], + 'sync' => ['status' => 'imported', 'source' => '胜算原始导出', + 'last_succeeded_at' => $periods->max('imported_at'), + 'periods' => $periods->map(fn ($p) => substr($p->period_start, 0, 7))->values()->all()], + ]; + } + + public function exportRows(array $filters, string $sort, string $direction): iterable + { + $query = $this->ordered($this->query($filters, $this->periods()), $sort, $direction); + return $this->stream($query); + } + + private function stream(Builder $query): iterable + { + foreach ($query->select('row_data')->cursor() as $row) yield json_decode($row->row_data, true, 512, JSON_THROW_ON_ERROR); + } + + public function filterOptions(): array + { + $q = $this->query([], $this->periods()); + return [ + 'shops' => (clone $q)->distinct()->orderBy('store_name')->pluck('store_name')->all(), + 'bill_items' => (clone $q)->distinct()->orderBy('bill_item')->pluck('bill_item')->all(), + ]; + } + + private function periods(): \Illuminate\Support\Collection + { + if (! $this->db()->getSchemaBuilder()->hasTable('jd_daily_bill_periods')) throw new RuntimeException('jd_daily_bill_mirror_not_ready'); + $periods = $this->db()->table('jd_daily_bill_periods')->orderBy('period_start')->get(); + if ($periods->isEmpty()) throw new RuntimeException('jd_daily_bill_mirror_not_ready'); + return $periods; + } + + private function query(array $filters, \Illuminate\Support\Collection $periods): Builder + { + $q = $this->db()->table('jd_daily_bill_rows')->whereIn('generation', $periods->pluck('active_generation')->all()); + $this->applyPlatformScope($q); + foreach (['store_name', 'bill_item'] as $field) { + if (($filters[$field] ?? '') !== '') $q->where($field, $filters[$field]); + } + LedgerRemarkFilter::itemsWhereIn($q, (array) ($filters['bill_items'] ?? []), 'bill_item'); + if (($filters['start'] ?? '') !== '') $q->where('occurred_at', '>=', $filters['start'] . ' 00:00:00'); + if (($filters['end'] ?? '') !== '') $q->where('occurred_at', '<', date('Y-m-d', strtotime($filters['end'] . ' +1 day')) . ' 00:00:00'); + if (($filters['keyword'] ?? '') !== '') { + $like = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['keyword']) . '%'; + $q->where(fn (Builder $sub) => $sub->where('record_code', 'like', $like)->orWhere('order_no', 'like', $like)->orWhere('row_data', 'like', $like)); + } + return $q; + } + + /** 按平台口径收窄数据;两个口径互补,笔数与金额之和恒等于拆分前。 */ + private function applyPlatformScope(Builder $query): void + { + $scope = JdBillPlatform::storeNameScope($this->platform); + if ($scope === null) { + return; + } + + $like = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $scope['keyword']) . '%'; + $start = $scope['start_date']; + + if ($scope['mode'] === 'only') { + $query->where('store_name', 'like', $like); + if ($start !== null) $query->where('occurred_at', '>=', $start . ' 00:00:00'); + + return; + } + + // 起始日期之前取到的京喜行仍留在京东账单,保证两边相加等于拆分前。 + $query->where(function (Builder $sub) use ($like, $start): void { + $sub->where('store_name', 'not like', $like); + if ($start !== null) $sub->orWhere('occurred_at', '<', $start . ' 00:00:00'); + }); + } + + private function ordered(Builder $q, string $sort, string $direction): Builder + { + $sort = in_array($sort, ['occurred_at', 'record_code', 'income', 'expense'], true) ? $sort : 'occurred_at'; + $direction = $direction === 'asc' ? 'asc' : 'desc'; + return $q->orderBy($sort, $direction)->orderBy('record_code', $direction); + } + + private function db(): \Illuminate\Database\Connection + { + return $this->databases->connection(config('upstream_mirrors.connection', 'business_mirror')); + } +} diff --git a/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php b/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php index 4046fcdb..eec7cb07 100644 --- a/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php +++ b/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php @@ -112,7 +112,7 @@ class JushuitanShopBalanceRepository { $value = trim(str_replace(['-', '—', '–'], '-', $value)); $value = preg_replace( - '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-_::]+/u', + '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|京喜小店|京喜|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-_::]+/u', '', $value, ) ?? $value; @@ -124,7 +124,7 @@ class JushuitanShopBalanceRepository public static function sourcePlatform(string $storeName): ?string { if (preg_match( - '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-—–_::]+/u', + '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|京喜小店|京喜|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-—–_::]+/u', trim($storeName), $matches, ) === 1) { diff --git a/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php b/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php new file mode 100644 index 00000000..55ad3aa5 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php @@ -0,0 +1,326 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::IMPORT_TABLE) || ! $schema->hasTable(self::ROW_TABLE)) { + return false; + } + + return $this->connection->table(self::IMPORT_TABLE)->where('status', 'succeeded')->exists(); + } + + /** @return string[] */ + public function storeOptions(): array + { + return $this->query()->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name')->map('strval')->all(); + } + + /** @return array{shops:list,bill_items:list} */ + public function accountBillFilterOptions(): array + { + $shops = $this->query()->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name') + ->map(static fn (mixed $value): string => (string) $value)->all(); + $billItems = $this->query()->whereNotNull('bill_item')->where('bill_item', '<>', '') + ->distinct()->orderBy('bill_item')->pluck('bill_item') + ->map(static fn (mixed $value): string => (string) $value)->all(); + + return ['shops' => $shops, 'bill_items' => $billItems]; + } + + /** @return array{rows:list>,total:int} */ + public function paginate( + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + int $page, + int $pageSize, + ): array { + $page = max(1, $page); + $pageSize = min(max(1, $pageSize), 500); + $query = $this->query(); + $this->applyFilters($query, $storeName, $fromDate, $toDate, $flowType); + $total = (clone $query)->count(); + + $rows = $query->orderByDesc('occurred_at')->orderByDesc('record_code') + ->forPage($page, $pageSize)->get()->map(function (object $row): array { + $signed = (float) $row->signed_amount; + $income = (float) $row->income_amount; + $expense = (float) $row->expense_amount; + $flowType = $income > 0 ? 1 : ($expense > 0 ? 2 : 0); + + return [ + 'id' => $row->record_code, + 'shopName' => (string) ($row->store_name ?? ''), + 'amount' => abs($signed), + 'balance' => null, + 'summary' => (string) ($row->bill_item ?? ''), + 'flowType' => $flowType, + 'toAdvertiserFundType' => null, + 'createTime' => (string) $row->occurred_at, + 'source_primary_key' => (string) ($row->merchant_order_no ?? ''), + 'source_record_code' => (string) $row->record_code, + 'source_channel' => 'PinduoduoSettlementBill', + ]; + })->all(); + + return ['rows' => $rows, 'total' => $total]; + } + + /** @return array{income_total:float,expense_total:float,cnt:int} */ + public function summarize( + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + ): array { + $query = $this->query(); + $this->applyFilters($query, $storeName, $fromDate, $toDate, $flowType); + $row = $query->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS cnt' + )->first(); + + return [ + 'income_total' => (float) ($row->income_total ?? 0), + 'expense_total' => (float) ($row->expense_total ?? 0), + 'cnt' => (int) ($row->cnt ?? 0), + ]; + } + + /** @return array */ + public function paginateAccountBills( + array $filters, + string $sort, + string $direction, + int $page, + int $perPage, + ): array { + $page = max(1, $page); + $perPage = min(max(1, $perPage), 100); + $query = $this->query(); + $this->applyAccountBillFilters($query, $filters); + + $summary = (clone $query)->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS row_count' + )->first(); + $total = (int) ($summary->row_count ?? 0); + $income = (float) ($summary->income_total ?? 0); + $expense = (float) ($summary->expense_total ?? 0); + + $sortColumn = $this->accountBillSortColumn($sort); + $direction = $direction === 'asc' ? 'asc' : 'desc'; + + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') { + $query->orderBy('record_code', $direction); + } + + $rows = $query->forPage($page, $perPage)->get() + ->map(fn (object $row): array => $this->mapAccountBillRow($row))->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'current_page' => $page, + 'last_page' => max(1, (int) ceil($total / $perPage)), + 'per_page' => $perPage, + 'from' => $total === 0 ? null : (($page - 1) * $perPage) + 1, + 'to' => $total === 0 ? null : min($page * $perPage, $total), + 'summary' => [ + 'income' => $income, + 'expense' => $expense, + 'balance' => round($income - $expense, 2), + 'count' => $total, + ], + ]; + } + + /** @return iterable> */ + public function exportAccountBills(array $filters, string $sort, string $direction): iterable + { + $query = $this->query(); + $this->applyAccountBillFilters($query, $filters); + $sortColumn = $this->accountBillSortColumn($sort); + $direction = $direction === 'desc' ? 'desc' : 'asc'; + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') { + $query->orderBy('record_code', $direction); + } + + return $query->cursor()->map(fn (object $row): array => $this->mapAccountBillRow($row)); + } + + private function query(): Builder + { + if (! $this->ready()) { + throw new RuntimeException('pinduoduo_authoritative_bills_not_ready'); + } + + return $this->connection->table(self::ROW_TABLE); + } + + private function applyFilters( + Builder $query, + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + ): void { + if ($storeName !== null && $storeName !== '') { + $query->where('store_name', $storeName); + } + $from = $this->date($fromDate); + if ($from !== null) { + $query->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00'); + } + $to = $this->date($toDate); + if ($to !== null) { + $query->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + } + if ($flowType === 'income') { + $query->where('income_amount', '>', 0); + } elseif ($flowType === 'expense') { + $query->where('expense_amount', '>', 0); + } +} + /** @param array $filters */ + private function applyAccountBillFilters(Builder $query, array $filters): void + { + $storeName = trim((string) ($filters['store_name'] ?? '')); + if ($storeName !== '') { + $query->where('store_name', $storeName); + } + + $billItem = trim((string) ($filters['bill_item'] ?? '')); + if ($billItem !== '') { + $query->where('bill_item', $billItem); + } + + $this->applyLedgerRemarkFilter($query, $filters); + + $from = $this->date(isset($filters['start']) ? (string) $filters['start'] : null); + if ($from !== null) { + $query->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00'); + } + + $to = $this->date(isset($filters['end']) ? (string) $filters['end'] : null); + if ($to !== null) { + $query->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + } + + $keyword = trim((string) ($filters['keyword'] ?? '')); + if ($keyword !== '') { + $query->where(function (Builder $nested) use ($keyword): void { + $like = '%' . $keyword . '%'; + $nested->where('record_code', 'like', $like) + ->orWhere('merchant_order_no', 'like', $like) + ->orWhere('online_order_no', 'like', $like) + ->orWhere('remark', 'like', $like) + ->orWhere('custom_remark', 'like', $like) + ->orWhere('business_description', 'like', $like) + ->orWhere('bill_item', 'like', $like); + }); + } + } + + /** 「总账备注」筛选:翻译成账单项目集合(拼多多单平台)。 */ + private function applyLedgerRemarkFilter(Builder $query, array $filters): void + { + $groups = is_array($filters['bill_item_groups'] ?? null) ? $filters['bill_item_groups'] : []; + if ($groups !== []) { + LedgerRemarkFilter::applyGroups( + $query, + $groups, + 'bill_item', + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'like', $prefix . '%'), + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'not like', $prefix . '%'), + ); + + return; + } + + LedgerRemarkFilter::itemsWhereIn($query, (array) ($filters['bill_items'] ?? []), 'bill_item'); + } + + private function accountBillSortColumn(string $sort): string + { + return [ + 'occurred_at' => 'occurred_at', + 'income' => 'income_amount', + 'expense' => 'expense_amount', + 'record_code' => 'record_code', + ][$sort] ?? 'occurred_at'; + } + + /** @return array */ + private function mapAccountBillRow(object $row): array + { + $signedAmount = (float) $row->signed_amount; + + return [ + 'id' => (string) $row->record_code, + 'record_code' => (string) $row->record_code, + 'store_name' => (string) ($row->store_name ?? ''), + 'finance_remark' => (string) ($row->business_description ?? ''), + 'order_no' => (string) ($row->merchant_order_no ?? ''), + 'amount' => abs($signedAmount), + 'custom_remark' => (string) ($row->custom_remark ?? ''), + 'bill_item' => (string) ($row->bill_item ?? ''), + 'occurred_at' => (string) $row->occurred_at, + 'income' => (float) $row->income_amount, + 'expense' => (float) $row->expense_amount, + 'balance' => $signedAmount, + 'remark' => (string) ($row->remark ?? ''), + 'updated_at' => $row->source_updated_at !== null + ? (string) $row->source_updated_at + : null, + 'modifier' => (string) ($row->source_modified_by ?? ''), + 'payload' => [ + 'merchant_order_no' => (string) ($row->merchant_order_no ?? ''), + 'online_order_no' => (string) ($row->online_order_no ?? ''), + 'finance_type' => (string) ($row->business_type ?? ''), + 'business_description' => (string) ($row->business_description ?? ''), + 'type' => (string) ($row->account_name ?? ''), + ], + ]; + } + + private function date(?string $value): ?DateTimeImmutable + { + if ($value === null || preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value); + + return $date !== false && $date->format('Y-m-d') === $value ? $date : null; + } +} diff --git a/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php b/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php index 2d3e147d..0f49c1aa 100644 --- a/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php @@ -112,7 +112,8 @@ class ProductCatalogMirrorRepository * total:int, * purchase_price_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string}, * price_change_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string}, - * work_platform_price_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string} + * work_platform_price_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string}, + * jushuitan_cost_price_history_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string} * } */ public function paginate(array $filters, int $page, int $perPage): array @@ -147,6 +148,7 @@ class ProductCatalogMirrorRepository 'purchase_price_sync_status' => $purchasePriceSyncStatus, 'price_change_sync_status' => $priceChangeSyncStatus, 'work_platform_price_sync_status' => $workPlatformPriceSyncStatus, + 'jushuitan_cost_price_history_sync_status' => $jushuitanCostPriceHistorySyncStatus, ]; } diff --git a/modules/EcommerceFinance/Repositories/ProductPriceMirrorRepository.php b/modules/EcommerceFinance/Repositories/ProductPriceMirrorRepository.php index 39bda7ee..7b95b18a 100644 --- a/modules/EcommerceFinance/Repositories/ProductPriceMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductPriceMirrorRepository.php @@ -4,14 +4,30 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; +use Illuminate\Database\Query\Builder; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use RuntimeException; class ProductPriceMirrorRepository { public const DATASET_KEY = 'supplier-payables.product-prices'; + public const EDITABLE_FIELDS = [ + 'barcode', + 'spu', + 'product_name', + 'category', + 'production_status', + 'minimum_price', + 'price_limit', + 'purchase_price', + 'shipping_fee', + 'jingxi_limit_price', + ]; + private readonly ConnectionInterface $connection; public function __construct(DatabaseManager $database) @@ -36,6 +52,14 @@ class ProductPriceMirrorRepository return is_array($state) && ($state['initial_completed_at'] ?? null) !== null; } + public function maintenanceReady(): bool + { + $schema = Schema::connection($this->connection->getName()); + + return $schema->hasTable('product_price_overrides') + && $schema->hasTable('product_price_override_events'); + } + /** @return array|null */ public function state(): ?array { @@ -46,34 +70,113 @@ class ProductPriceMirrorRepository return $row === null ? null : (array) $row; } - public function paginate(array $filters, int $page, int $limit): LengthAwarePaginator + public function paginate(array $filters, int $page, int $limit, ?int $companyId = null): LengthAwarePaginator { $page = max($page, 1); $limit = min(max($limit, 1), 100); - $query = $this->connection->table('product_price_mirror_rows'); + [$query, $withOverrides] = $this->effectiveQuery($companyId ?? (int) (company_id() ?: 1)); + $this->applyFilters($query, $filters, $withOverrides); + $this->applySelect($query, $withOverrides); - if (($filters['barcode'] ?? '') !== '') { - $query->whereRaw("barcode LIKE ? ESCAPE '!'", [$this->contains((string) $filters['barcode'])]); + return $this->applyOrder($query, $withOverrides) + ->paginate($limit, ['*'], 'page', $page); + } + + public function exportRows(array $filters, ?int $companyId = null): iterable + { + [$query, $withOverrides] = $this->effectiveQuery($companyId ?? (int) (company_id() ?: 1)); + $this->applyFilters($query, $filters, $withOverrides); + $this->applySelect($query, $withOverrides); + + return $this->applyOrder($query, $withOverrides)->cursor(); + } + + /** + * @param array> $records keyed by upstream key + * @return array{created:int,updated:int} + */ + public function applyOverrides( + array $records, + int $companyId, + ?int $userId, + string $source, + ): array { + if (! $this->maintenanceReady()) { + throw new RuntimeException('product_price_maintenance_schema_missing'); } - if (($filters['completed_from'] ?? '') !== '') { - $query->where('completed_at', '>=', (string) $filters['completed_from'] . ' 00:00:00'); + if ($records === []) { + return ['created' => 0, 'updated' => 0]; } - if (($filters['completed_to'] ?? '') !== '') { - $query->where('completed_at', '<', Carbon::parse((string) $filters['completed_to'])->addDay()->startOfDay()); - } + $keys = array_values(array_unique(array_keys($records))); - return $query - ->orderByDesc('completed_at') - ->orderByDesc('business_id') - ->orderBy('barcode') - ->paginate($limit, [ - 'barcode', 'spu', 'product_name', 'category', 'production_status', - 'minimum_price', 'price_limit', 'purchase_price', 'shipping_fee', - 'jingxi_limit_price', 'approval_status', 'approval_result', - 'workflow_title', 'completed_at', - ], 'page', $page); + return $this->connection->transaction(function () use ( + $records, + $keys, + $companyId, + $userId, + $source, + ): array { + [$effective, $withOverrides] = $this->effectiveQuery($companyId); + $this->applySelect($effective, $withOverrides); + $current = $effective->whereIn('r.upstream_key', $keys)->get()->keyBy('upstream_key'); + + if ($current->count() !== count($keys)) { + $missing = collect($keys)->first(fn (string $key): bool => ! $current->has($key)); + throw new RuntimeException('product_price_record_not_found:' . $missing); + } + + $existing = $this->connection->table('product_price_overrides') + ->where('company_id', $companyId) + ->whereIn('upstream_key', $keys) + ->pluck('upstream_key') + ->flip(); + $created = 0; + $updated = 0; + $now = now(); + + foreach ($records as $upstreamKey => $changes) { + $row = (array) $current->get($upstreamKey); + $before = $this->editableValues($row); + $provided = array_intersect_key($changes, array_flip(self::EDITABLE_FIELDS)); + $after = array_replace($before, $provided); + + if (trim((string) ($after['barcode'] ?? '')) === '') { + throw new RuntimeException('product_price_barcode_required:' . $upstreamKey); + } + + $identity = ['company_id' => $companyId, 'upstream_key' => $upstreamKey]; + $values = $after + [ + 'source' => $source, + 'updated_by' => $userId, + 'updated_at' => $now, + ]; + + if ($existing->has($upstreamKey)) { + $this->connection->table('product_price_overrides')->where($identity)->update($values); + $updated++; + } else { + $this->connection->table('product_price_overrides')->insert($identity + $values + [ + 'created_by' => $userId, + 'created_at' => $now, + ]); + $created++; + } + + $this->connection->table('product_price_override_events')->insert([ + 'company_id' => $companyId, + 'upstream_key' => $upstreamKey, + 'source' => $source, + 'before_values' => json_encode($before, JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION), + 'after_values' => json_encode($after, JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION), + 'user_id' => $userId, + 'created_at' => $now, + ]); + } + + return compact('created', 'updated'); + }); } public function startRun(string $mode, Carbon $since, Carbon $until, bool $resume): array @@ -213,4 +316,91 @@ class ProductPriceMirrorRepository { return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%'; } + + /** @return array{0:Builder,1:bool} */ + private function effectiveQuery(int $companyId): array + { + $query = $this->connection->table('product_price_mirror_rows as r'); + $withOverrides = $this->maintenanceReady(); + + if ($withOverrides) { + $query->leftJoin('product_price_overrides as o', function ($join) use ($companyId): void { + $join->on('o.upstream_key', '=', 'r.upstream_key') + ->where('o.company_id', '=', $companyId); + }); + } + + return [$query, $withOverrides]; + } + + private function applyFilters(Builder $query, array $filters, bool $withOverrides): void + { + if (($filters['barcode'] ?? '') !== '') { + $query->whereRaw( + $this->effectiveColumn('barcode', $withOverrides) . " LIKE ? ESCAPE '!'", + [$this->contains((string) $filters['barcode'])], + ); + } + + if (($filters['completed_from'] ?? '') !== '') { + $query->where('r.completed_at', '>=', (string) $filters['completed_from'] . ' 00:00:00'); + } + + if (($filters['completed_to'] ?? '') !== '') { + $query->where('r.completed_at', '<', Carbon::parse((string) $filters['completed_to'])->addDay()->startOfDay()); + } + } + + private function applySelect(Builder $query, bool $withOverrides): void + { + $query->select([ + 'r.id', + 'r.upstream_key', + 'r.business_id', + 'r.approval_status', + 'r.approval_result', + 'r.workflow_title', + 'r.completed_at', + ]); + + foreach (self::EDITABLE_FIELDS as $field) { + $query->addSelect(DB::raw($this->effectiveColumn($field, $withOverrides) . ' AS ' . $field)); + } + + if ($withOverrides) { + $query->addSelect([ + DB::raw('CASE WHEN o.id IS NULL THEN 0 ELSE 1 END AS is_overridden'), + 'o.updated_at as override_updated_at', + ]); + } else { + $query->addSelect([ + DB::raw('0 AS is_overridden'), + DB::raw('NULL AS override_updated_at'), + ]); + } + } + + private function applyOrder(Builder $query, bool $withOverrides): Builder + { + return $query + ->orderByDesc('r.completed_at') + ->orderByDesc('r.business_id') + ->orderByRaw($this->effectiveColumn('barcode', $withOverrides) . ' ASC'); + } + + private function effectiveColumn(string $field, bool $withOverrides): string + { + return $withOverrides + ? "CASE WHEN o.id IS NULL THEN r.{$field} ELSE o.{$field} END" + : "r.{$field}"; + } + + /** @return array */ + private function editableValues(array $row): array + { + return array_combine( + self::EDITABLE_FIELDS, + array_map(static fn (string $field): mixed => $row[$field] ?? null, self::EDITABLE_FIELDS), + ); + } } diff --git a/modules/EcommerceFinance/Repositories/ProductPurchasePriceMirrorRepository.php b/modules/EcommerceFinance/Repositories/ProductPurchasePriceMirrorRepository.php index 1c5ff984..fc73ff97 100644 --- a/modules/EcommerceFinance/Repositories/ProductPurchasePriceMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductPurchasePriceMirrorRepository.php @@ -12,6 +12,8 @@ class ProductPurchasePriceMirrorRepository { public const DATASET_KEY = 'product-inventory.purchase-order-prices'; + public const CURRENT_PROJECTION_VERSION = 2; + private readonly ConnectionInterface $connection; public function __construct(DatabaseManager $database) @@ -33,7 +35,9 @@ class ProductPurchasePriceMirrorRepository { $state = $this->state(); - return is_array($state) && ($state['initial_completed_at'] ?? null) !== null; + return is_array($state) + && ($state['initial_completed_at'] ?? null) !== null + && (int) ($state['projection_version'] ?? 1) >= self::CURRENT_PROJECTION_VERSION; } /** @return array|null */ @@ -67,6 +71,7 @@ class ProductPurchasePriceMirrorRepository 'status' => 'running', 'run_mode' => $mode, 'generation' => $generation, + 'projection_version' => self::CURRENT_PROJECTION_VERSION, 'last_attempted_at' => $now, 'last_error_code' => null, 'updated_at' => $now, @@ -104,11 +109,15 @@ class ProductPurchasePriceMirrorRepository $values = [ 'item_id' => (int) $row['item_id'], 'purchase_order_id' => (int) $row['purchase_order_id'], + 'source_order_no' => $this->nullablePositiveInteger($row['source_order_no'] ?? null), + 'supplier_name' => $this->nullableString($row['supplier_name'] ?? null), 'sku_id' => $this->nullableString($row['sku_id'] ?? null), 'style_id' => $this->nullableString($row['style_id'] ?? null), + 'quantity' => $row['quantity'] ?? null, 'unit_price' => $row['unit_price'] ?? null, 'document_status' => $this->nullableString($row['document_status'] ?? null), 'labels' => $this->nullableString($row['labels'] ?? null), + 'document_created_at' => $row['document_created_at'] ?? null, 'finished_at' => $row['finished_at'] ?? null, 'purchase_updated_at' => $row['purchase_updated_at'], ]; @@ -130,8 +139,9 @@ class ProductPurchasePriceMirrorRepository $mapped, ['item_id'], [ - 'purchase_order_id', 'sku_id', 'style_id', 'unit_price', - 'document_status', 'labels', 'finished_at', 'purchase_updated_at', + 'purchase_order_id', 'source_order_no', 'supplier_name', + 'sku_id', 'style_id', 'quantity', 'unit_price', + 'document_status', 'labels', 'document_created_at', 'finished_at', 'purchase_updated_at', '_mirror_generation', 'row_hash', '_mirror_synced_at', 'updated_at', ], ); @@ -211,4 +221,15 @@ class ProductPurchasePriceMirrorRepository return $value === '' ? null : $value; } + + private function nullablePositiveInteger(mixed $value): ?int + { + if ($value === null || $value === '' || ! is_numeric($value)) { + return null; + } + + $value = (int) $value; + + return $value > 0 ? $value : null; + } } diff --git a/modules/EcommerceFinance/Repositories/ProductPurchasePriceRepository.php b/modules/EcommerceFinance/Repositories/ProductPurchasePriceRepository.php index 713674d6..b297a5a7 100644 --- a/modules/EcommerceFinance/Repositories/ProductPurchasePriceRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductPurchasePriceRepository.php @@ -34,8 +34,11 @@ class ProductPurchasePriceRepository $sql = 'SELECT TOP (' . $limit . ') ' . 'i.[Id] AS item_id, p.[po_id] AS purchase_order_id, ' - . 'i.[sku_id] AS sku_id, i.[i_id] AS style_id, i.[price] AS unit_price, ' + . 'CONVERT(varchar(64), CONVERT(decimal(38, 0), p.[source_o_id])) AS source_order_no, ' + . 'p.[seller] AS supplier_name, ' + . 'i.[sku_id] AS sku_id, i.[i_id] AS style_id, i.[qty] AS quantity, i.[price] AS unit_price, ' . 'p.[status] AS document_status, p.[labels] AS labels, ' + . 'CONVERT(varchar(27), p.[createTime], 126) AS document_created_at, ' . 'CONVERT(varchar(27), p.[finish_time], 126) AS finished_at, ' . 'CONVERT(varchar(27), p.[updateTime], 126) AS purchase_updated_at ' . 'FROM [dbo].[jst_purchase] p ' diff --git a/modules/EcommerceFinance/Repositories/ReturnPickupManagementMirrorRepository.php b/modules/EcommerceFinance/Repositories/ReturnPickupManagementMirrorRepository.php new file mode 100644 index 00000000..cf04aef5 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/ReturnPickupManagementMirrorRepository.php @@ -0,0 +1,406 @@ +connection = $mirror->connection(); + } + + public function available(): bool + { + $schema = Schema::connection($this->connection->getName()); + + return $schema->hasTable('business_mirror_table_states') + && $schema->hasTable($this->dataset()->targetTable()); + } + + public function ready(): bool + { + return $this->mirror->ready($this->dataset()); + } + + /** @return array|null */ + public function state(): ?array + { + return $this->mirror->state($this->dataset()); + } + + /** + * @param array|null $state + * @return array{code:string,lag_minutes:?int} + */ + public function syncStatus(?array $state = null, ?CarbonInterface $at = null): array + { + $state ??= $this->state(); + + if (! is_array($state)) { + return ['code' => 'unavailable', 'lag_minutes' => null]; + } + + $lastSucceeded = $this->timestamp($state['last_succeeded_at'] ?? null); + $lagMinutes = $lastSucceeded === null + ? null + : (int) ceil(max(0, ($at ?? now())->getTimestamp() - $lastSucceeded) / 60); + $status = (string) ($state['status'] ?? 'pending'); + + if (($state['initial_completed_at'] ?? null) === null) { + $code = $status === 'failed' + ? 'initial_failed' + : ($status === 'running' ? 'initializing' : 'pending'); + } elseif ($status === 'failed') { + $code = 'failed'; + } elseif ($status === 'running') { + $code = ($state['run_mode'] ?? null) === 'full' ? 'reconciling' : 'syncing'; + } elseif ($lagMinutes === null + || $lagMinutes > max((int) config('upstream_mirrors.return_pickup.stale_after_minutes', 180), 1)) { + $code = 'delayed'; + } else { + $code = 'healthy'; + } + + return ['code' => $code, 'lag_minutes' => $lagMinutes]; + } + + /** + * @param array $filters + * @return array{data:list,total:int} + */ + public function paginate(array $filters, int $page, int $perPage): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $query = $this->filteredQuery($filters); + $total = (clone $query)->count(); + $rows = $query + ->orderByDesc('createTime') + ->orderByDesc('Id') + ->forPage($page, $perPage) + ->get() + ->all(); + + return ['data' => $rows, 'total' => $total]; + } + + /** + * 全部去重快递公司(对应镜像中的 express_company)。 + * + * @return list + */ + public function carriers(): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + return $this->connection->table($this->dataset()->targetTable()) + ->whereNotNull('express_company') + ->distinct() + ->orderBy('express_company') + ->pluck('express_company') + ->map(static fn ($value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => $value !== '') + ->values() + ->all(); + } + + /** + * 全部去重订单状态(对应镜像中的 orderStatus)。 + * + * @return list + */ + public function statuses(): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + return $this->connection->table($this->dataset()->targetTable()) + ->whereNotNull('orderStatus') + ->distinct() + ->orderBy('orderStatus') + ->pluck('orderStatus') + ->map(static fn ($value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => $value !== '') + ->values() + ->all(); + } + + /** + * 单张退货取件单的完整明细:主表 + 明细分录 + 实退快递单号映射。 + * + * @return array{main:object,items:list,truth_numbers:list}|null + */ + public function detail(int $id): ?array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $main = $this->connection->table($this->dataset()->targetTable()) + ->where('Id', $id) + ->first(); + + if ($main === null) { + return null; + } + + $items = $this->connection->table($this->itemDataset()->targetTable()) + ->where('mainTableId', $id) + ->orderBy('id') + ->get() + ->all(); + + $truthNumbers = $this->connection->table($this->truthDataset()->targetTable()) + ->where('mId', $id) + ->orderBy('Id') + ->pluck('truthExpressNumber') + ->map(static fn ($value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => $value !== '') + ->values() + ->all(); + + return ['main' => $main, 'items' => $items, 'truth_numbers' => $truthNumbers]; + } + + /** + * 发货仓编码 → 名称目录。 + * + * 明细里的 warehouse 可能是工作平台短码(wp_warehouse.code 或 + * wp_warehouseConfig.whCode,如 2852)或聚水潭 wms_co_id(如 + * 15038426)。短码优先取工作平台仓库资料,长码回退聚水潭仓库镜像; + * 未命中的编码由调用方保留原始值展示,不猜测名称。 + * + * @return array + */ + public function warehouseDirectory(): array + { + $schema = Schema::connection($this->connection->getName()); + $directory = []; + + foreach ([ + ['js_wp_warehouse', 'code', 'name'], + ['js_wp_warehouse_config', 'whCode', 'whName'], + ] as [$table, $codeColumn, $nameColumn]) { + if (! $schema->hasTable($table)) { + continue; + } + + try { + $rows = $this->connection->table($table)->get([$codeColumn, $nameColumn]); + } catch (Throwable) { + continue; + } + + foreach ($rows as $row) { + $code = trim((string) ($row->{$codeColumn} ?? '')); + $name = trim((string) ($row->{$nameColumn} ?? '')); + + if ($code !== '' && $name !== '' && ! isset($directory[$code])) { + $directory[$code] = $name; + } + } + } + + if ($schema->hasTable('ops_jst_warehouse_info')) { + try { + $rows = $this->connection->table('ops_jst_warehouse_info')->get(['Id', 'wms_co_id', 'name']); + } catch (Throwable) { + $rows = []; + } + + foreach ($rows as $row) { + $name = trim((string) ($row->name ?? '')); + + if ($name === '') { + continue; + } + + foreach ([$row->wms_co_id ?? null, $row->Id ?? null] as $value) { + $code = trim((string) $value); + + if ($code !== '' && $code !== '0' && ! isset($directory[$code])) { + $directory[$code] = $name; + } + } + } + } + + return $directory; + } + + /** + * 导出用明细流:按取件单 Id 倒序断点遍历,逐条输出「主表 + 明细」, + * 由调用方按同一份快照计算实际运费与差异。 + * + * @param array $filters + * @return \Generator + */ + public function exportRows(array $filters, int $maxRows = 50000, int $batchSize = 300): \Generator + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $mainTable = $this->dataset()->targetTable(); + $itemTable = $this->itemDataset()->targetTable(); + $batchSize = min(max($batchSize, 1), 1000); + $yielded = 0; + $lastId = null; + + while ($yielded < $maxRows) { + $mains = $this->filteredQuery($filters); + + if ($lastId !== null) { + $mains->where('Id', '<', $lastId); + } + + $ids = $mains->orderByDesc('Id')->limit($batchSize)->pluck('Id')->all(); + + if ($ids === []) { + return; + } + + $lastId = (int) min($ids); + + $rows = $this->connection->table($mainTable . ' AS m') + ->join($itemTable . ' AS i', 'i.mainTableId', '=', 'm.Id') + ->whereIn('m.Id', $ids) + ->orderByDesc('m.Id') + ->orderBy('i.id') + ->select([ + 'm.Id AS mainId', 'm.orderId', 'm.express_company', 'm.orderStatus', 'm.urgencyLevel', + 'm.shopName', 'm.transactionNo', 'm.province', 'm.city', 'm.senderName', 'm.senderPhone', + 'm.returnExpressNo', 'm.createTime', 'm.updateTime', 'm.expectedPickupTime', 'm.paymentMethod', + 'm.pickupType', 'm.totalReturnQuantity', 'm.note', 'm.issueType', 'm.issueDescription', + 'm.expressFollowStatus', 'm.expressFollowResult', 'm.expressFollowDescription', + 'm.expressOrderTime', 'm.expressPickupTime', 'm.creator', 'm.canceler', + 'i.id AS itemId', 'i.returnProcode', 'i.actualReturnProcode', 'i.barcode', 'i.productName', + 'i.platformProductId', 'i.platformSkuId', 'i.returnQuantity', 'i.actualReturnQuantity', + 'i.unverifiedQuantity', 'i.returnProgress', 'i.warehouse', + 'i.receiverName', 'i.receiverPhone', 'i.receiverAddress', 'i.actualReturnOrderNo', + 'i.grossWeight', 'i.length', 'i.width', 'i.height', 'i.estimatedFreight', + ]) + ->get(); + + foreach ($rows as $row) { + yield $row; + $yielded++; + + if ($yielded >= $maxRows) { + return; + } + } + } + } + + /** @param array $filters */ + private function filteredQuery(array $filters): Builder + { + $query = $this->connection->table($this->dataset()->targetTable()); + + if (($filters['created_from'] ?? '') !== '') { + $query->where('createTime', '>=', $filters['created_from'] . ' 00:00:00'); + } + + if (($filters['created_to'] ?? '') !== '') { + $query->where('createTime', '<', Carbon::parse($filters['created_to'])->addDay()->toDateString()); + } + + if (($filters['carrier'] ?? '') !== '') { + $query->where('express_company', $filters['carrier']); + } + + if (($filters['status'] ?? '') !== '') { + $query->where('orderStatus', $filters['status']); + } + + if (($filters['shop'] ?? '') !== '') { + $query->whereRaw("shopName LIKE ? ESCAPE '!'", [$this->contains($filters['shop'])]); + } + + $keyword = trim((string) ($filters['keyword'] ?? '')); + + if ($keyword !== '') { + $pattern = $this->contains($keyword); + $query->where(static function (Builder $inner) use ($pattern): void { + $inner->whereRaw("orderId LIKE ? ESCAPE '!'", [$pattern]) + ->orWhereRaw("transactionNo LIKE ? ESCAPE '!'", [$pattern]) + ->orWhereRaw("returnExpressNo LIKE ? ESCAPE '!'", [$pattern]) + ->orWhereRaw("senderName LIKE ? ESCAPE '!'", [$pattern]) + ->orWhereRaw("senderPhone LIKE ? ESCAPE '!'", [$pattern]); + }); + } + + return $query; + } + + private function contains(string $value): string + { + return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%'; + } + + private function timestamp(mixed $value): ?int + { + if (! is_string($value) || $value === '') { + return null; + } + + try { + return Carbon::parse($value)->getTimestamp(); + } catch (Throwable) { + return null; + } + } + + private function dataset(): BusinessMirrorDataset + { + return $this->datasets->get(self::DATASET_KEY); + } + + private function itemDataset(): BusinessMirrorDataset + { + return $this->datasets->get(self::ITEM_DATASET_KEY); + } + + private function truthDataset(): BusinessMirrorDataset + { + return $this->datasets->get(self::TRUTH_DATASET_KEY); + } +} diff --git a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php index 4149b9d1..91915fb3 100644 --- a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php +++ b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php @@ -295,9 +295,21 @@ class ShippingOrderRepository return ['code' => 'unavailable', 'last_succeeded_at' => null]; } + $freightPending = $this->db->table('jst_sync_state') + ->where('dataset_key', 'like', 'jst.sctrade.freight.%')->where('status', '!=', 'succeeded')->count(); + $itemsPending = $this->db->table('jst_sync_state') + ->where('dataset_key', 'like', 'jst.sctrade.items.%')->where('status', '!=', 'succeeded')->count(); + $code = (string) ($row->status ?? 'unavailable'); + return [ - 'code' => (string) ($row->status ?? 'unavailable'), + 'code' => ($freightPending || $itemsPending) && $code === 'succeeded' ? 'partial' : $code, 'last_succeeded_at' => $row->last_succeeded_at ?? null, + 'freight_pending' => (bool) $freightPending, + 'warning' => implode(' ', array_filter([ + $code === 'partial' ? '部分包裹尚需与上游源键核对,原有镜像记录已保留。' : null, + $freightPending ? "{$freightPending} 个日期窗口的运费和结算重量待补,空白不代表 0。" : null, + $itemsPending ? "{$itemsPending} 个日期窗口的商品或金额待核对。" : null, + ])), ]; } catch (\Throwable) { return ['code' => 'unavailable', 'last_succeeded_at' => null]; diff --git a/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php b/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php index 74a6dd21..8ea87399 100644 --- a/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php @@ -3,9 +3,12 @@ namespace Modules\EcommerceFinance\Repositories; use Carbon\CarbonInterface; +use Illuminate\Contracts\Cache\LockTimeoutException; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Query\Builder; use Illuminate\Support\Carbon; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Contracts\BusinessMirrorDataset; use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry; @@ -21,6 +24,16 @@ class SmallPaymentWorkOrderMirrorRepository public const SMALL_PAYMENT_WORK_TYPE_ID = '82D94F5C54544EE3833CD8A3AB8B9F73'; + private const QUERY_TIMEOUT_SECONDS = 30; + + private const SUMMARY_CACHE_SECONDS = 900; + + private const CACHE_LOCK_SECONDS = 180; + + private const CACHE_WAIT_SECONDS = 10; + + private const FILTER_OPTIONS_CACHE_SECONDS = 900; + private const REQUIRED_QUERY_INDEXES = [ self::WORK_ORDER_DATASET => [ ['woTypeId', 'woNo', 'Id'], @@ -40,6 +53,9 @@ class SmallPaymentWorkOrderMirrorRepository private const COMPLETED_WORK_ORDER_STATUSES = ['CONFIRMED', '已完成', '已确认']; + /** 打款金额在 businessFieldList 中的候选字段名(按优先级) */ + private const PAYMENT_AMOUNT_FIELDS = ['打款金额', '付款金额', '小额打款金额', 'amountField']; + private readonly ConnectionInterface $connection; public function __construct( @@ -147,7 +163,7 @@ class SmallPaymentWorkOrderMirrorRepository /** * @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters - * @return array{data:list>,total:int,page_payment_amount:string} + * @return array{data:list>,total:int,page_payment_amount:string,filtered_payment_amount:string} */ public function paginate(array $filters, int $page, int $perPage): array { @@ -158,23 +174,96 @@ class SmallPaymentWorkOrderMirrorRepository $query = $this->baseQuery(); $this->applyFilters($query, $filters); - $total = (clone $query)->count(); - $rows = $query + $summary = $this->filteredSummary($filters); + $rows = $this->boundedGet($query ->select($this->selectColumns()) ->orderByDesc('w.completeTime') ->orderByDesc('p.woNo') - ->forPage($page, $perPage) - ->get() + ->forPage($page, $perPage)) ->map(fn (object $row): array => $this->decorate((array) $row)) ->all(); return [ 'data' => $rows, - 'total' => $total, + 'total' => $summary['count'], 'page_payment_amount' => $this->sumMoney(array_column($rows, 'payment_amount')), + 'filtered_payment_amount' => $summary['payment_amount'], ]; } + /** + * 统计当前筛选条件下全部记录的打款金额合计。 + * + * 只取金额所需字段,按 Id 做键集分块批量读取:不使用逐行游标(本地/远端库时每次取行都是一次网络往返), + * 也不复用导出用的分页排序查询(会为大结果集重复执行连接与排序)。 + * + * @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters + */ + public function filteredPaymentAmount(array $filters, int $chunkSize = 1000): string + { + return $this->filteredSummary($filters, $chunkSize)['payment_amount']; + } + + /** + * @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters + * @return array{count:int,payment_amount:string} + */ + private function filteredSummary(array $filters, int $chunkSize = 1000): array + { + $this->ensureReady(); + + $key = $this->summaryCacheKey($filters); + + return $this->rememberArray( + $key, + self::SUMMARY_CACHE_SECONDS, + fn (): array => $this->calculateFilteredSummary($filters, $chunkSize), + 'small_payment_work_order_summary_busy', + ); + } + + /** + * @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters + * @return array{count:int,payment_amount:string} + */ + private function calculateFilteredSummary(array $filters, int $chunkSize): array + { + $this->ensureReady(); + + $query = $this->baseQuery(); + $this->applyFilters($query, $filters); + + $chunkSize = min(max($chunkSize, 100), 5000); + $cents = 0; + $count = 0; + $lastId = null; + + do { + $chunk = $this->boundedGet((clone $query) + ->select(['w.Id AS source_id', 'w.businessFieldList']) + ->when($lastId !== null, static fn (Builder $q): Builder => $q->where('w.Id', '>', $lastId)) + ->orderBy('w.Id') + ->limit($chunkSize)); + + foreach ($chunk as $row) { + $cents += $this->centsFromMoney($this->paymentAmountOf($row->businessFieldList ?? null)); + } + + $count += $chunk->count(); + $lastId = $chunk->isEmpty() ? null : $chunk->last()->source_id; + } while ($chunk->count() === $chunkSize); + + return ['count' => $count, 'payment_amount' => $this->formatCents($cents)]; + } + + private function paymentAmountOf(mixed $businessFieldList): ?string + { + return $this->money($this->field( + $this->businessFields($businessFieldList), + self::PAYMENT_AMOUNT_FIELDS, + )); + } + /** * @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters * @return iterable> @@ -204,6 +293,72 @@ class SmallPaymentWorkOrderMirrorRepository } while ($rows->count() === $chunkSize); } + /** + * 返回当前小额打款镜像中出现过的店铺名称列表,用于筛选下拉/自动补全。 + * + * @return list + */ + public function shopNames(): array + { + return $this->filterOptions()['shops']; + } + + /** + * 返回当前小额打款镜像中出现过的打款原因列表,用于筛选下拉/自动补全。 + * + * @return list + */ + public function paymentReasons(): array + { + return $this->filterOptions()['payment_reasons']; + } + + /** @return array{shops:list,payment_reasons:list} */ + public function filterOptions(): array + { + if (! $this->available() || ! $this->ready() || ! $this->queryReady()) { + return ['shops' => [], 'payment_reasons' => []]; + } + + $table = $this->dataset(self::PAYMENT_MAP_DATASET)->targetTable(); + + try { + return $this->rememberArray( + 'small-payment-work-orders:filter-options:v1', + self::FILTER_OPTIONS_CACHE_SECONDS, + function () use ($table): array { + $shops = $this->boundedGet($this->connection->table($table) + ->where('woTypeId', self::SMALL_PAYMENT_WORK_TYPE_ID) + ->whereNotNull('shop_name') + ->where('shop_name', '<>', '') + ->distinct() + ->select('shop_name') + ->orderBy('shop_name') + ->limit(1000)) + ->pluck('shop_name') + ->map(static fn (mixed $name): string => (string) $name) + ->all(); + $reasons = $this->boundedGet($this->connection->table($table) + ->where('woTypeId', self::SMALL_PAYMENT_WORK_TYPE_ID) + ->whereNotNull('payment_reason') + ->where('payment_reason', '<>', '') + ->distinct() + ->select('payment_reason') + ->orderBy('payment_reason') + ->limit(200)) + ->pluck('payment_reason') + ->map(static fn (mixed $reason): string => (string) $reason) + ->all(); + + return ['shops' => $shops, 'payment_reasons' => $reasons]; + }, + 'small_payment_work_order_filter_options_busy', + ); + } catch (Throwable) { + return ['shops' => [], 'payment_reasons' => []]; + } + } + private function ensureReady(): void { if (! $this->ready() || ! $this->queryReady()) { @@ -250,8 +405,11 @@ class SmallPaymentWorkOrderMirrorRepository /** @param array $filters */ private function applyFilters(Builder $query, array $filters): void { - $query->where('w.completeTime', '>=', $filters['from'] . ' 00:00:00') - ->where('w.completeTime', '<', Carbon::parse($filters['to'])->addDay()->format('Y-m-d 00:00:00')); + $from = $this->filterDateTime($filters['from'], false); + $to = $this->filterDateTime($filters['to'], true); + + $query->where('w.completeTime', '>=', $from) + ->where('w.completeTime', '<', $to); if ($filters['work_order_no'] !== '') { $query->whereRaw("p.woNo LIKE ? ESCAPE '!'", [$this->contains($filters['work_order_no'])]); @@ -315,9 +473,7 @@ class SmallPaymentWorkOrderMirrorRepository $row['alipay_batch_no'] = $this->field($fields, [ '支付宝批次号', '支付宝打款批次号', '打款批次号', '批次号', 'alipayBatchNo', 'batchNo', ]); - $row['payment_amount'] = $this->money($this->field($fields, [ - '打款金额', '付款金额', '小额打款金额', 'amountField', - ])); + $row['payment_amount'] = $this->money($this->field($fields, self::PAYMENT_AMOUNT_FIELDS)); $row['online_order_no'] = $this->firstFilled( $this->field($fields, ['线上订单号', '线上单号', '订单号', 'orderField']), $row['mapped_online_order_no'] ?? null, @@ -460,14 +616,26 @@ class SmallPaymentWorkOrderMirrorRepository { $cents = 0; foreach ($amounts as $amount) { - if ($amount === null || ! preg_match('/^(-?)(\d+)\.(\d{2})$/', (string) $amount, $matches)) { - continue; - } - - $value = ((int) $matches[2] * 100) + (int) $matches[3]; - $cents += $matches[1] === '-' ? -$value : $value; + $cents += $this->centsFromMoney($amount); } + return $this->formatCents($cents); + } + + /** 将 '123.45' / '-123.45' 形式的金额字符串转成分(无效值计 0)。 */ + private function centsFromMoney(mixed $amount): int + { + if ($amount === null || ! preg_match('/^(-?)(\d+)\.(\d{2})$/', (string) $amount, $matches)) { + return 0; + } + + $value = ((int) $matches[2] * 100) + (int) $matches[3]; + + return $matches[1] === '-' ? -$value : $value; + } + + private function formatCents(int $cents): string + { $sign = $cents < 0 ? '-' : ''; $absolute = abs($cents); @@ -543,6 +711,90 @@ class SmallPaymentWorkOrderMirrorRepository ], static fn (?string $value): bool => $value !== null && $value !== ''))); } + /** @param array $filters */ + private function summaryCacheKey(array $filters): string + { + $normalized = array_map(static fn (mixed $value): string => trim((string) $value), $filters); + ksort($normalized); + + return 'small-payment-work-orders:summary:v1:' . hash( + 'sha256', + (string) json_encode($normalized, JSON_UNESCAPED_UNICODE), + ); + } + + /** @param callable():array $resolver @return array */ + private function rememberArray(string $key, int $seconds, callable $resolver, string $busyMessage): array + { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + try { + return Cache::lock($key . ':lock', self::CACHE_LOCK_SECONDS) + ->block(self::CACHE_WAIT_SECONDS, function () use ($key, $seconds, $resolver): array { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + $resolved = $resolver(); + Cache::put($key, $resolved, $seconds); + + return $resolved; + }); + } catch (LockTimeoutException $exception) { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + throw new RuntimeException($busyMessage, 0, $exception); + } + } + + /** @return Collection */ + private function boundedGet(Builder $query): Collection + { + $connection = $query->getConnection(); + if ($connection->getDriverName() !== 'mysql') { + return $query->get(); + } + + return collect($connection->select( + 'SET STATEMENT max_statement_time=' . self::QUERY_TIMEOUT_SECONDS . ' FOR ' . $query->toSql(), + $query->getBindings(), + )); + } + + /** + * 将前端传来的日期或日期时间字符串统一为 SQL 比较用的日期时间。 + * 仅日期时:from 取 00:00:00,to 取次日 00:00:00(半开区间)。 + * 含分钟时:to 取下一分钟;含秒时:to 取下一秒,完整包含用户选择的最小时间单位。 + */ + private function filterDateTime(string $value, bool $isUpperBound): string + { + $value = trim($value); + $hasTime = str_contains($value, ':') || str_contains($value, 'T'); + + if (! $hasTime) { + return $isUpperBound + ? Carbon::parse($value)->addDay()->format('Y-m-d 00:00:00') + : $value . ' 00:00:00'; + } + + $carbon = Carbon::parse($value); + + if (! $isUpperBound) { + return $carbon->format('Y-m-d H:i:s'); + } + + return preg_match('/:\d{2}:\d{2}$/', str_replace('T', ' ', $value)) === 1 + ? $carbon->clone()->addSecond()->format('Y-m-d H:i:s') + : $carbon->clone()->addMinute()->format('Y-m-d H:i:s'); + } + private function contains(string $value): string { return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value) . '%'; diff --git a/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php index 91ed7d7f..5880ccb0 100644 --- a/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php @@ -15,7 +15,7 @@ class StoreAccountMirrorRepository ) {} /** @return array{data:array>,total:int} */ - public function paginate(int $page, int $perPage): array + public function paginate(int $page, int $perPage, array $filters = []): array { $dataset = $this->datasets->get(self::DATASET); if (! $this->mirror->ready($dataset)) { @@ -25,9 +25,46 @@ class StoreAccountMirrorRepository $page = max($page, 1); $perPage = min(max($perPage, 1), 100); $query = $this->mirror->connection()->table($dataset->targetTable()); + $columns = [ + 'store_name' => 'storeName', 'operation_owner' => 'operationOwner', + 'operation_department_head' => 'operationDepartmentHead', 'operation_director' => 'operationDirector', + 'profit_center' => 'profitCenter', 'account' => 'account', 'bound_phone' => 'boundPhone', + 'verification_contact' => 'verificationContact', 'account_group_name' => 'accountGroupName', + ]; + foreach ($columns as $key => $column) { + $value = mb_substr(trim((string) ($filters[$key] ?? '')), 0, 191); + if ($value !== '') $query->where($column, 'like', '%' . addcslashes($value, '%_\\') . '%'); + } + $accountType = trim((string) ($filters['account_type'] ?? '')); + if ($accountType !== '') $query->where('accountType', '=', $accountType === '主账号' ? 'MAIN' : ($accountType === '子账号' ? 'SUB' : $accountType)); + $passwordState = trim((string) ($filters['password_configured'] ?? '')); + if (in_array($passwordState, ['已设置', '未设置', '状态未同步'], true)) { + if ($passwordState === '状态未同步') $query->whereNull('passwordConfigured'); + else $query->where('passwordConfigured', $passwordState === '已设置'); + } + foreach (['created_at' => 'createdAt', 'updated_at' => 'updatedAt'] as $key => $column) { + foreach (['_from' => '>=', '_to' => '<='] as $suffix => $operator) { + $date = trim((string) ($filters[$key . $suffix] ?? '')); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date)) $query->whereDate($column, $operator, $date); + } + } $total = (clone $query)->count(); + $sortColumns = [ + 'store_name' => 'storeName', 'operation_owner' => 'operationOwner', + 'operation_department_head' => 'operationDepartmentHead', 'operation_director' => 'operationDirector', + 'profit_center' => 'profitCenter', 'account_type' => 'accountType', 'account' => 'account', + 'password_configured' => 'passwordConfigured', 'bound_phone' => 'boundPhone', + 'verification_contact' => 'verificationContact', 'account_group_name' => 'accountGroupName', + 'created_at' => 'createdAt', 'updated_at' => 'updatedAt', + ]; + $sortColumn = $sortColumns[$filters['_sort'] ?? ''] ?? null; + $direction = ($filters['_direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc'; + if ($sortColumn !== null) { + $query->orderBy($sortColumn, $direction)->orderByDesc('id'); + } else { + $query->orderByDesc('id'); + } $rows = $query - ->orderByDesc('id') ->forPage($page, $perPage) ->get() ->map(fn (object $row): array => [ diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php index 1080b831..59e99cd8 100644 --- a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php @@ -2,14 +2,29 @@ namespace Modules\EcommerceFinance\Repositories; +use Illuminate\Contracts\Cache\LockTimeoutException; use Illuminate\Database\Query\Builder; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry; +use Modules\EcommerceFinance\Services\LedgerRemarkFilter; use RuntimeException; /** 店铺收款账单·淘系支付宝账户只读经营分析副本镜像。 */ class StoreReceivingAlipayBillMirrorRepository { + private const PAGE_QUERY_TIMEOUT_SECONDS = 30; + + private const AGGREGATE_CACHE_SECONDS = 900; + + private const AGGREGATE_CACHE_LOCK_SECONDS = 45; + + private const AGGREGATE_CACHE_WAIT_SECONDS = 35; + + private const FILTER_OPTIONS_CACHE_SECONDS = 900; + /** 淘系支付宝页面不展示其他平台店铺;头条放心购是镜像中的抖音平台名称。 */ private const EXCLUDED_TAOBAO_SHOP_SITE_PREFIXES = [ '拼多多', '京东', '抖音', '头条放心购', '得物', '唯品会', @@ -17,6 +32,9 @@ class StoreReceivingAlipayBillMirrorRepository public const DATASET = 'operations_replica.rpt.jst_originalBillInfo'; public const SHOP_DATASET = 'operations_replica.rpt.jst_shopInfo'; + public const SKU_DATASET = 'operations_replica.rpt.jst_sku'; + + private ?TaobaoAlipaySettlementBillRepository $authoritative = null; public function __construct( private readonly BusinessMirrorDatasetRegistry $datasets, @@ -26,6 +44,10 @@ class StoreReceivingAlipayBillMirrorRepository /** @return array{data:array>,total:int,current_page:int,last_page:int,per_page:int,summary:array{income:float,expense:float,balance:float,count:int},sync:array} */ public function paginate(array $filters, string $sort, string $direction, int $page, int $perPage): array { + if ($this->authoritative()->ready()) { + return $this->authoritative()->paginate($filters, $sort, $direction, $page, $perPage); + } + return $this->paginateChannel($filters, $sort, $direction, $page, $perPage, 'alipayCSV', 'taobao', self::DATASET, true); } @@ -42,7 +64,7 @@ class StoreReceivingAlipayBillMirrorRepository string $direction, int $page, int $perPage, - ?string $channel, + string|array|null $channel, string $mapping = 'taobao', string $datasetKey = self::DATASET, bool $excludeNonTaobaoPlatforms = false, @@ -58,7 +80,7 @@ class StoreReceivingAlipayBillMirrorRepository $perPage = min(max($perPage, 1), 100); $direction = $direction === 'asc' ? 'asc' : 'desc'; $sortColumn = [ - 'record_code' => $mapping === 'pinduoduo' ? 'b.auto_id' : 'b.Id', + 'record_code' => in_array($mapping, ['pinduoduo', 'dewu'], true) ? 'b.auto_id' : ($mapping === 'taobao' ? 'b.p_auto_id' : 'b.Id'), 'occurred_at' => 'b.fee_time', 'income' => 'b.amount', 'expense' => 'b.amount', @@ -81,15 +103,27 @@ class StoreReceivingAlipayBillMirrorRepository && $this->channelCoversDataset($channel, $dataset->fixedFilters()) && ! $hasFilters && (($state['status'] ?? null) === 'succeeded' || (bool) ($state['mirror_row_count_is_exact'] ?? false)) && $recordedCount !== null && ctype_digit((string) $recordedCount); - $total = $useRecordedCount ? (int) $recordedCount : (clone $query)->count(); - $summary = $this->summary($query, $filters, $channel); + $summary = $this->rememberAggregateSummary( + $this->aggregateCacheKey( + $datasetKey, + $filters, + $channel, + $excludeNonTaobaoPlatforms, + ), + fn (): array => $this->summary($query, $filters, $channel, ! $useRecordedCount), + ); + $total = $useRecordedCount + ? (int) $recordedCount + : ($summary['count'] ?? $this->boundedCount(clone $query)); $billRows = $this->pageRows( $query, $sortColumn, $direction, $page, $perPage, $filters, $channel, $targetTable, ); $shopNames = $this->shopNames($billRows); + $productNames = $mapping === 'taobao' ? $this->productNames($billRows) : []; + $importedRows = $mapping === 'taobao' ? $this->importedRows($billRows) : []; $rows = collect($billRows) - ->map(fn (object $row): array => $this->mapRowFor($row, $shopNames[(string) $row->shop_id] ?? null, $mapping)) + ->map(fn (object $row): array => $this->mapRowFor($row, $shopNames[(string) $row->shop_id] ?? null, $mapping, $productNames, $importedRows)) ->all(); $income = $summary['income']; $expense = $summary['expense']; @@ -103,7 +137,7 @@ class StoreReceivingAlipayBillMirrorRepository 'summary' => [ 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'count' => $total, ], 'sync' => [ @@ -116,6 +150,10 @@ class StoreReceivingAlipayBillMirrorRepository /** @return iterable> */ public function exportRows(array $filters, string $sort = 'occurred_at', string $direction = 'asc'): iterable { + if ($this->authoritative()->ready()) { + return $this->authoritative()->exportRows($filters, $sort, $direction); + } + return $this->exportChannelRows($filters, $sort, $direction, 'alipayCSV', 'taobao', self::DATASET, true); } @@ -124,7 +162,7 @@ class StoreReceivingAlipayBillMirrorRepository array $filters, string $sort = 'occurred_at', string $direction = 'asc', - ?string $channel = null, + string|array|null $channel = null, string $mapping = 'taobao', string $datasetKey = self::DATASET, bool $excludeNonTaobaoPlatforms = false, @@ -146,7 +184,7 @@ class StoreReceivingAlipayBillMirrorRepository $shopNames = $this->allShopNames(); $direction = $direction === 'desc' ? 'desc' : 'asc'; $sortColumn = [ - 'record_code' => $mapping === 'pinduoduo' ? 'b.auto_id' : 'b.Id', + 'record_code' => in_array($mapping, ['pinduoduo', 'dewu'], true) ? 'b.auto_id' : ($mapping === 'taobao' ? 'b.p_auto_id' : 'b.Id'), 'occurred_at' => 'b.fee_time', 'income' => 'b.amount', 'expense' => 'b.amount', @@ -157,51 +195,63 @@ class StoreReceivingAlipayBillMirrorRepository } /** @return array{shops:array,bill_items:array} */ - public function filterOptionsForChannel(string $channel, string $datasetKey = self::DATASET): array + public function filterOptionsForChannel(string|array $channel, string $datasetKey = self::DATASET, bool $excludeNonTaobaoPlatforms = false): array { + if ($channel === 'alipayCSV' && $datasetKey === self::DATASET && $excludeNonTaobaoPlatforms && $this->authoritative()->ready()) { + return $this->authoritative()->accountBillFilterOptions(); + } + $dataset = $this->datasets->get($datasetKey); if (! $this->mirror->ready($dataset) || ! $this->mirror->ready($this->datasets->get(self::SHOP_DATASET))) { throw new RuntimeException('store_receiving_alipay_bill_mirror_not_ready'); } - $channelQuery = $this->billQuery($dataset->targetTable()); - $this->applyChannel($channelQuery, $channel, $dataset->fixedFilters()); + return $this->rememberFilterOptions( + $this->filterOptionsCacheKey($datasetKey, $channel, $excludeNonTaobaoPlatforms), + function () use ($dataset, $channel, $excludeNonTaobaoPlatforms): array { + $channelQuery = $this->billQuery($dataset->targetTable()); + $this->applyChannel($channelQuery, $channel, $dataset->fixedFilters()); + if ($excludeNonTaobaoPlatforms) { + $this->applyTaobaoPlatformScope($channelQuery); + } - $shopIds = (clone $channelQuery) - ->whereNotNull('b.shop_id') - ->distinct() - ->pluck('b.shop_id') - ->filter(static fn (mixed $value): bool => $value !== null && $value !== '') - ->all(); + $shopIds = (clone $channelQuery) + ->whereNotNull('b.shop_id') + ->distinct() + ->pluck('b.shop_id') + ->filter(static fn (mixed $value): bool => $value !== null && $value !== '') + ->all(); - $shops = $shopIds === [] - ? collect() - : $this->mirror->connection()->table('ops_jst_shop_info') - ->whereIn('shop_id', $shopIds) - ->whereNotNull('shop_name') - ->orderBy('shop_name') - ->pluck('shop_name'); + $shops = $shopIds === [] + ? collect() + : $this->mirror->connection()->table('ops_jst_shop_info') + ->whereIn('shop_id', $shopIds) + ->whereNotNull('shop_name') + ->orderBy('shop_name') + ->pluck('shop_name'); - $billItems = (clone $channelQuery) - ->whereNotNull('b.fee_name') - ->where('b.fee_name', '<>', '') - ->select('b.fee_name') - ->distinct() - ->orderBy('b.fee_name') - ->pluck('b.fee_name'); + $billItems = (clone $channelQuery) + ->whereNotNull('b.fee_name') + ->where('b.fee_name', '<>', '') + ->select('b.fee_name') + ->distinct() + ->orderBy('b.fee_name') + ->pluck('b.fee_name'); - $normalize = static fn ($values): array => collect($values) - ->map(static fn (mixed $value): string => trim((string) $value)) - ->filter() - ->unique() - ->values() - ->all(); + $normalize = static fn ($values): array => collect($values) + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter() + ->unique() + ->values() + ->all(); - return [ - 'shops' => $normalize($shops), - 'bill_items' => $normalize($billItems), - ]; + return [ + 'shops' => $normalize($shops), + 'bill_items' => $normalize($billItems), + ]; + }, + ); } /** Read bounded pages so a full export does not sort/buffer millions of rows at once. */ @@ -238,8 +288,10 @@ class StoreReceivingAlipayBillMirrorRepository } $rows = $batch->select('b.*')->orderBy($sortColumn, $direction) ->orderBy('b.Id', $direction)->limit(1000)->get(); + $productNames = $mapping === 'taobao' ? $this->productNames($rows->all()) : []; + $importedRows = $mapping === 'taobao' ? $this->importedRows($rows->all()) : []; foreach ($rows as $row) { - yield $this->mapRowFor($row, $shopNames[(string) $row->shop_id] ?? null, $mapping); + yield $this->mapRowFor($row, $shopNames[(string) $row->shop_id] ?? null, $mapping, $productNames, $importedRows); } $last = $rows->last(); } while ($rows->count() === 1000); @@ -250,6 +302,11 @@ class StoreReceivingAlipayBillMirrorRepository return $this->mirror->connection()->table($targetTable . ' as b'); } + private function authoritative(): TaobaoAlipaySettlementBillRepository + { + return $this->authoritative ??= app(TaobaoAlipaySettlementBillRepository::class); + } + /** @return array */ private function pageRows( Builder $query, @@ -258,33 +315,36 @@ class StoreReceivingAlipayBillMirrorRepository int $page, int $perPage, array $filters, - ?string $channel, + string|array|null $channel, string $targetTable, ): array { if ($channel === null || ($filters['bill_item'] ?? '') === '') { - return $query->select('b.*') + $pageQuery = $query->select('b.*') ->orderBy($sortColumn, $direction) ->orderBy('b.Id', $direction) - ->forPage($page, $perPage) - ->get() - ->all(); + ->forPage($page, $perPage); + + return $this->boundedGet($pageQuery)->all(); } $idQuery = clone $query; if ($targetTable === 'ops_jst_original_bill_info' && $idQuery->getConnection()->getDriverName() === 'mysql') { $idQuery->forceIndex('idx_original_bill_channel_shop'); } - $ids = $idQuery->select('b.Id') + $idQuery->select('b.Id') ->orderBy($sortColumn, $direction) ->orderBy('b.Id', $direction) - ->forPage($page, $perPage) - ->pluck('b.Id') + ->forPage($page, $perPage); + $ids = $this->boundedGet($idQuery) + ->pluck('Id') ->all(); if ($ids === []) { return []; } - $rowsById = $this->billQuery($targetTable)->whereIn('b.Id', $ids)->select('b.*')->get() + $rowsById = $this->boundedGet( + $this->billQuery($targetTable)->whereIn('b.Id', $ids)->select('b.*'), + ) ->keyBy(static fn (object $row): string => (string) $row->Id); return collect($ids) @@ -294,34 +354,38 @@ class StoreReceivingAlipayBillMirrorRepository ->all(); } - /** @return array{income:float,expense:float} */ + /** @return array{income:float,expense:float,count:?int} */ private function summary( Builder $billQuery, array $filters, - ?string $channel = null, + string|array|null $channel = null, + bool $includeCount = true, ): array { if ($channel === null && $this->dailySummarySupports($filters)) { $summary = $this->dailySummary($filters); if ($summary !== null) { - return $summary; + return $summary + ['count' => null]; } } - $row = (clone $billQuery)->selectRaw( - "COALESCE(SUM(CASE WHEN b.inout_type = '1' THEN ABS(COALESCE(b.amount, 0)) ELSE 0 END), 0) AS income, " + $aggregate = (clone $billQuery)->selectRaw( + ($includeCount ? 'COUNT(*) AS aggregate_count, ' : '') + . "COALESCE(SUM(CASE WHEN b.inout_type = '1' THEN ABS(COALESCE(b.amount, 0)) ELSE 0 END), 0) AS income, " . "COALESCE(SUM(CASE WHEN b.inout_type = '-1' THEN ABS(COALESCE(b.amount, 0)) ELSE 0 END), 0) AS expense" - )->first(); + ); + $row = $this->boundedGet($aggregate)->first(); return [ 'income' => round((float) ($row->income ?? 0), 2), 'expense' => round((float) ($row->expense ?? 0), 2), + 'count' => $includeCount ? (int) ($row->aggregate_count ?? 0) : null, ]; } private function dailySummarySupports(array $filters): bool { - return ($filters['alipay_account'] ?? '') === '' + return ($filters['source_channel'] ?? '') === '' && ($filters['bill_item'] ?? '') === '' && ($filters['keyword'] ?? '') === ''; } @@ -377,12 +441,25 @@ class StoreReceivingAlipayBillMirrorRepository $query->whereIn('b.shop_id', $shopIds); } } - if (($filters['alipay_account'] ?? '') !== '') { - $query->where('b.channel', 'like', '%' . $this->escapeLike((string) $filters['alipay_account']) . '%'); + if (($filters['source_channel'] ?? '') !== '') { + $query->where('b.channel', 'like', '%' . $this->escapeLike((string) $filters['source_channel']) . '%'); } if (($filters['bill_item'] ?? '') !== '') { $query->where('b.fee_name', 'like', '%' . $this->escapeLike((string) $filters['bill_item']) . '%'); } + // 「总账备注」:共享原始账单镜像只有 shop_id,平台归属用店铺资料表的店铺名前缀判定。 + $groups = is_array($filters['bill_item_groups'] ?? null) ? $filters['bill_item_groups'] : []; + if ($groups !== []) { + LedgerRemarkFilter::applyGroups( + $query, + $groups, + 'b.fee_name', + fn (Builder $sub, string $prefix) => $sub->whereIn('b.shop_id', $this->shopIdsLike($prefix)), + fn (Builder $sub, string $prefix) => $sub->whereNotIn('b.shop_id', $this->shopIdsLike($prefix)), + ); + } else { + LedgerRemarkFilter::itemsWhereIn($query, (array) ($filters['bill_items'] ?? []), 'b.fee_name'); + } if (($filters['business_type'] ?? '') !== '') { $query->where('b.inout_type', $this->directionCode((string) $filters['business_type'])); } @@ -393,6 +470,15 @@ class StoreReceivingAlipayBillMirrorRepository $query->where('b.fee_time', '<', date('Y-m-d', strtotime($filters['end'] . ' +1 day')) . ' 00:00:00'); } if (($filters['keyword'] ?? '') !== '') { + if (($filters['keyword_match'] ?? '') === 'exact-record') { + $keyword = (string) $filters['keyword']; + if (! preg_match('/^(0|[1-9]\d{0,9})$/', $keyword) || (float) $keyword > 2147483647) { + $query->whereRaw('1 = 0'); + } else { + $query->where('b.Id', $keyword); + } + return; + } $value = '%' . $this->escapeLike((string) $filters['keyword']) . '%'; $query->where(function (Builder $query) use ($value): void { foreach (['b.Id', 'b.auto_id', 'b.fee_name', 'b.primary_key', 'b.p_auto_id', 'b.so_id', 'b.sku_id', 'b.shop_sku_id', 'b.shop_i_id', 'b.channel'] as $column) { @@ -402,12 +488,24 @@ class StoreReceivingAlipayBillMirrorRepository } } - /** @param array $fixedFilters */ - private function applyChannel(Builder $query, ?string $channel, array $fixedFilters): void + /** @param array> $fixedFilters */ + private function applyChannel(Builder $query, string|array|null $channel, array $fixedFilters): void { - if ($this->channelCoversDataset($channel, $fixedFilters)) return; + if ($channel === null || $channel === '') return; + if (is_string($channel)) { + if (! $this->channelCoversDataset($channel, $fixedFilters)) { + $query->where('b.channel', $channel); + } + return; + } - $query->where('b.channel', $channel); + $channels = array_values($channel); + if ($channels === []) { + $query->whereRaw('1 = 0'); + return; + } + + $query->whereIn('b.channel', $channels); } private function applyTaobaoPlatformScope(Builder $query): void @@ -423,17 +521,30 @@ class StoreReceivingAlipayBillMirrorRepository $query->whereNotIn('b.shop_id', $excludedShopIds); } - /** @param array $fixedFilters */ - private function channelCoversDataset(?string $channel, array $fixedFilters): bool + /** 店铺名前缀 → shop_id 子查询(共享原始账单镜像按店铺资料表判定平台)。 */ + private function shopIdsLike(string $prefix): Builder + { + return $this->mirror->connection()->table('ops_jst_shop_info') + ->where('shop_name', 'like', $this->escapeLike($prefix) . '%') + ->select('shop_id'); + } + + /** @param array> $fixedFilters */ + private function channelCoversDataset(string|array|null $channel, array $fixedFilters): bool { if ($channel === null || $channel === '') { return true; } foreach ($fixedFilters as $column => $value) { - if (strcasecmp($column, 'channel') === 0 && (string) $value === $channel) { - return true; - } + if (strcasecmp($column, 'channel') !== 0) continue; + + $requested = is_array($channel) ? array_map('strval', $channel) : [(string) $channel]; + $configured = is_array($value) ? array_map('strval', $value) : [(string) $value]; + sort($requested); + sort($configured); + + return $requested === $configured; } return false; @@ -462,6 +573,47 @@ class StoreReceivingAlipayBillMirrorRepository ->all(); } + /** @param array $rows @return array */ + private function productNames(array $rows): array + { + $skuIds = collect($rows)->map(fn (object $row): ?string => $row->sku_id ?: $row->shop_sku_id) + ->filter()->unique()->values()->all(); + if ($skuIds === []) return []; + + try { + $dataset = $this->datasets->get(self::SKU_DATASET); + } catch (\Throwable) { + return []; + } + if (! $this->mirror->ready($dataset) || ! Schema::connection($this->mirror->connection()->getName())->hasTable('ops_jst_sku')) { + return []; + } + + return $this->mirror->connection()->table('ops_jst_sku') + ->whereIn('sku_id', $skuIds)->pluck('name', 'sku_id') + ->mapWithKeys(static fn (mixed $name, mixed $id): array => [(string) $id => (string) $name]) + ->all(); + } + + /** @param array $rows @return array */ + private function importedRows(array $rows): array + { + if (! Schema::hasTable('ec_alipay_bills')) { + return []; + } + + $recordCodes = collect($rows)->pluck('p_auto_id')->filter()->unique()->values()->all(); + if ($recordCodes === []) { + return []; + } + + return DB::table('ec_alipay_bills') + ->where('company_id', (int) (company_id() ?: 1)) + ->whereNull('deleted_at') + ->whereIn('record_code', $recordCodes) + ->get()->keyBy(fn (object $row): string => (string) $row->record_code)->all(); + } + /** @param array $rows */ public function mapDouyinRows(array $rows): array { @@ -469,51 +621,74 @@ class StoreReceivingAlipayBillMirrorRepository return array_map(fn (object $row): array => $this->mapRowFor($row, $shops[(string) $row->shop_id] ?? null, 'douyin'), $rows); } - private function mapRow(object $row, ?string $shopName): array + private function mapRow(object $row, ?string $shopName, array $productNames = [], array $importedRows = []): array { $amount = abs((float) ($row->amount ?? 0)); $income = (string) ($row->inout_type ?? '') === '1' ? $amount : 0.0; $expense = (string) ($row->inout_type ?? '') === '-1' ? $amount : 0.0; - return [ + $mapped = [ 'id' => (string) $row->Id, - 'record_code' => (string) $row->Id, + 'record_code' => (string) ($row->p_auto_id ?: $row->Id), 'store_name' => $shopName, 'custom_remark' => null, 'bill_item' => $row->fee_name, - 'alipay_account' => $row->channel, - 'account_order_no' => $row->primary_key, - 'business_serial_no' => $row->auto_id, - 'merchant_order_no' => $row->p_auto_id, - 'business_base_order_no' => $row->so_id, - 'goods_name' => $row->sku_id ?: $row->shop_sku_id, + 'alipay_account' => null, + 'account_order_no' => null, + 'business_serial_no' => null, + 'merchant_order_no' => null, + 'business_base_order_no' => null, + 'goods_name' => $productNames[(string) ($row->sku_id ?: $row->shop_sku_id)] ?? null, 'counterparty_account' => null, 'occurred_at' => $this->dateTime($row->fee_time), 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, - 'business_type' => $this->directionName($row->inout_type), + 'balance' => null, + 'business_type' => null, 'remark' => null, 'online_order_no' => $row->so_id, 'online_real_store' => $shopName, - 'business_description' => $row->combine_type, - 'business_bill_source' => $row->channel, - 'business_order_no' => $row->p_auto_id, + 'business_description' => null, + 'business_bill_source' => null, + 'business_order_no' => null, 'created_at' => $this->dateTime($row->createTime), 'updated_at' => $this->dateTime($row->updateTime), 'modifier' => '', ]; + + $imported = $importedRows[$mapped['record_code']] ?? null; + if ($imported === null) { + return $mapped; + } + + foreach ([ + 'custom_remark', 'alipay_account', 'account_order_no', 'business_serial_no', + 'merchant_order_no', 'business_base_order_no', 'counterparty_account', 'balance', + 'business_type', 'remark', 'business_description', 'business_bill_source', + 'business_order_no', 'modifier', + ] as $field) { + $mapped[$field] = $imported->{$field} ?? $mapped[$field]; + } + if ($mapped['goods_name'] === null || $mapped['goods_name'] === '') { + $mapped['goods_name'] = $imported->goods_name ?? null; + } + + return $mapped; } /** @return array */ - private function mapRowFor(object $row, ?string $shopName, string $mapping): array + private function mapRowFor(object $row, ?string $shopName, string $mapping, array $productNames = [], array $importedRows = []): array { if ($mapping === 'pinduoduo') { return $this->mapPinduoduoRow($row, $shopName); } + if ($mapping === 'dewu') { + return $this->mapDewuRow($row, $shopName); + } + if ($mapping !== 'douyin') { - return $this->mapRow($row, $shopName); + return $this->mapRow($row, $shopName, $productNames, $importedRows); } $amount = abs((float) ($row->amount ?? 0)); @@ -533,7 +708,7 @@ class StoreReceivingAlipayBillMirrorRepository 'occurred_at' => $this->dateTime($row->fee_time), 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'remark' => null, 'modifier' => '聚水潭', 'created_at' => $this->dateTime($row->createTime), @@ -576,7 +751,7 @@ class StoreReceivingAlipayBillMirrorRepository 'occurred_at' => $this->dateTime($row->fee_time), 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'remark' => null, 'updated_at' => $this->dateTime($row->updateTime), 'modifier' => 'RPA', @@ -589,6 +764,56 @@ class StoreReceivingAlipayBillMirrorRepository ]; } + /** @return array */ + private function mapDewuRow(object $row, ?string $shopName): array + { + $amount = abs((float) ($row->amount ?? 0)); + $income = (string) ($row->inout_type ?? '') === '1' ? $amount : 0.0; + $expense = (string) ($row->inout_type ?? '') === '-1' ? $amount : 0.0; + $orderNo = $row->so_id ?: $row->p_auto_id; + $goodsNo = $row->sku_id ?: $row->shop_sku_id ?: $row->shop_i_id; + + return [ + 'id' => (string) $row->Id, + 'record_code' => (string) ($row->auto_id ?: $row->Id), + 'store_name' => $shopName, + 'finance_remark' => null, + 'order_no' => $orderNo, + 'amount' => $amount, + 'custom_remark' => null, + 'bill_item' => $row->fee_name, + 'occurred_at' => $this->dateTime($row->fee_time), + 'income' => $income, + 'expense' => $expense, + 'balance' => round($income - $expense, 2), + 'remark' => null, + 'updated_at' => $this->dateTime($row->updateTime), + 'modifier' => '聚水潭', + 'payload' => [ + 'online_order_no' => $orderNo, + 'store_2' => $shopName, + 'order_type' => null, + 'goods_name' => null, + 'goods_no' => $goodsNo, + 'quantity' => null, + 'channel' => match ((string) $row->channel) { + 'Dewu' => '得物', + 'DewuTK' => '退货退款订单', + 'DewuKJ' => '扣减其他费用明细', + default => (string) $row->channel, + }, + 'source_channel' => $row->channel, + 'business_type' => $this->directionName($row->inout_type), + 'online_real_store' => $shopName, + 'order_created_at' => null, + 'ship_return_at' => null, + 'settle_status' => null, + 'pay_period' => null, + 'pulled_at' => $this->dateTime($row->createTime), + ], + ]; + } + private function directionCode(string $value): string { return match ($value) { @@ -612,6 +837,136 @@ class StoreReceivingAlipayBillMirrorRepository return $value === null || $value === '' ? '' : date('Y-m-d H:i:s', strtotime((string) $value)); } + /** @return Collection */ + private function boundedGet(Builder $query): Collection + { + $connection = $query->getConnection(); + if ($connection->getDriverName() !== 'mysql') { + return $query->get(); + } + + return collect($connection->select( + 'SET STATEMENT max_statement_time=' . self::PAGE_QUERY_TIMEOUT_SECONDS . ' FOR ' . $query->toSql(), + $query->getBindings(), + )); + } + + private function boundedCount(Builder $query): int + { + $count = $query->getConnection()->query() + ->fromSub($query, 'bounded_count') + ->selectRaw('COUNT(*) AS aggregate'); + + return (int) ($this->boundedGet($count)->first()->aggregate ?? 0); + } + + /** @param array $filters */ + private function aggregateCacheKey( + string $datasetKey, + array $filters, + string|array|null $channel, + bool $excludeNonTaobaoPlatforms, + ): string { + $normalizedFilters = array_filter( + array_map( + static fn (mixed $value): string => trim((string) $value), + $filters, + ), + static fn (string $value): bool => $value !== '', + ); + ksort($normalizedFilters); + $normalizedChannel = is_array($channel) ? array_map('strval', $channel) : $channel; + if (is_array($normalizedChannel)) { + sort($normalizedChannel); + } + + return 'store-receiving-bills:aggregate:v3:' . hash('sha256', (string) json_encode([ + 'dataset' => $datasetKey, + 'filters' => $normalizedFilters, + 'channel' => $normalizedChannel, + 'exclude_non_taobao' => $excludeNonTaobaoPlatforms, + ], JSON_UNESCAPED_UNICODE)); + } + + /** @param callable():array{income:float,expense:float,count:?int} $resolver */ + private function rememberAggregateSummary(string $key, callable $resolver): array + { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + try { + return Cache::lock($key . ':lock', self::AGGREGATE_CACHE_LOCK_SECONDS) + ->block(self::AGGREGATE_CACHE_WAIT_SECONDS, function () use ($key, $resolver): array { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + $resolved = $resolver(); + Cache::put($key, $resolved, self::AGGREGATE_CACHE_SECONDS); + + return $resolved; + }); + } catch (LockTimeoutException $exception) { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + throw new RuntimeException('store_receiving_bill_aggregate_busy', 0, $exception); + } + } + + private function filterOptionsCacheKey( + string $datasetKey, + string|array $channel, + bool $excludeNonTaobaoPlatforms, + ): string { + $normalizedChannel = is_array($channel) ? array_map('strval', $channel) : $channel; + if (is_array($normalizedChannel)) { + sort($normalizedChannel); + } + + return 'store-receiving-bills:filter-options:v1:' . hash('sha256', (string) json_encode([ + 'dataset' => $datasetKey, + 'channel' => $normalizedChannel, + 'exclude_non_taobao' => $excludeNonTaobaoPlatforms, + ], JSON_UNESCAPED_UNICODE)); + } + + /** @param callable():array{shops:array,bill_items:array} $resolver */ + private function rememberFilterOptions(string $key, callable $resolver): array + { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + try { + return Cache::lock($key . ':lock', self::AGGREGATE_CACHE_LOCK_SECONDS) + ->block(self::AGGREGATE_CACHE_WAIT_SECONDS, function () use ($key, $resolver): array { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + $resolved = $resolver(); + Cache::put($key, $resolved, self::FILTER_OPTIONS_CACHE_SECONDS); + + return $resolved; + }); + } catch (LockTimeoutException $exception) { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + throw new RuntimeException('store_receiving_bill_filter_options_busy', 0, $exception); + } + } + private function escapeLike(string $value): string { return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value); diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php new file mode 100644 index 00000000..b1d8aab3 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php @@ -0,0 +1,49 @@ + */ + public function paginate(array $filters, string $sort, string $direction, int $page, int $perPage): array + { + return $this->source->paginateChannel( + $filters, + $sort, + $direction, + $page, + $perPage, + self::SOURCE_CHANNELS, + 'dewu', + self::DATASET, + ); + } + + /** @return iterable> */ + public function exportRows(array $filters, string $sort = 'occurred_at', string $direction = 'asc'): iterable + { + return $this->source->exportChannelRows( + $filters, + $sort, + $direction, + self::SOURCE_CHANNELS, + 'dewu', + self::DATASET, + ); + } + + /** @return array{shops:array,bill_items:array} */ + public function filterOptions(): array + { + return $this->source->filterOptionsForChannel(self::SOURCE_CHANNELS, self::DATASET); + } +} diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingJdWalletBillRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingJdWalletBillRepository.php new file mode 100644 index 00000000..197823b2 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/StoreReceivingJdWalletBillRepository.php @@ -0,0 +1,105 @@ +periods(); + $query = $this->query($filters, $periods); + $summary = (clone $query)->selectRaw('COUNT(*) AS count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')->first(); + $total = (int) $summary->count; + $page = max(1, $page); + $perPage = min(100, max(1, $perPage)); + // Skip deep pages using narrow indexed keys, then load JSON only for the visible rows. + $keys = $this->ordered($query, $sort, $direction)->forPage($page, $perPage)->get(['generation', 'record_code']); + $rows = []; + foreach ($keys->groupBy('generation') as $generation => $group) { + $records = $this->db()->table('jd_wallet_bill_rows')->where('generation', $generation) + ->whereIn('record_code', $group->pluck('record_code')->all())->get(['record_code', 'row_data']); + foreach ($records as $record) $rows[$generation . ':' . $record->record_code] = json_decode($record->row_data, true, 512, JSON_THROW_ON_ERROR); + } + $balance = $this->latestBalanceTotal($filters, $periods); + return [ + 'data' => $keys->map(fn ($key) => $rows[$key->generation . ':' . $key->record_code])->all(), + 'total' => $total, 'current_page' => $page, 'last_page' => max(1, (int) ceil($total / $perPage)), 'per_page' => $perPage, + 'summary' => ['count' => $total, 'income' => round((float) $summary->income, 2), 'expense' => round((float) $summary->expense, 2), + 'balance' => $balance], + 'sync' => ['status' => 'imported', 'source' => '胜算原始导出', + 'last_succeeded_at' => $periods->max('imported_at'), + 'periods' => $periods->map(fn ($p) => substr($p->period_start, 0, 7))->values()->all()], + ]; + } + + public function exportRows(array $filters, string $sort, string $direction): iterable + { + $query = $this->ordered($this->query($filters, $this->periods()), $sort, $direction); + return $this->stream($query); + } + + private function stream(Builder $query): iterable + { + foreach ($query->select('row_data')->cursor() as $row) yield json_decode($row->row_data, true, 512, JSON_THROW_ON_ERROR); + } + + public function filterOptions(): array + { + $q = $this->query([], $this->periods()); + return [ + 'shops' => (clone $q)->distinct()->orderBy('store_name')->pluck('store_name')->all(), + 'bill_items' => (clone $q)->distinct()->orderBy('bill_item')->pluck('bill_item')->all(), + ]; + } + + private function periods(): \Illuminate\Support\Collection + { + if (! $this->db()->getSchemaBuilder()->hasTable('jd_wallet_bill_periods')) throw new RuntimeException('jd_wallet_bill_mirror_not_ready'); + $periods = $this->db()->table('jd_wallet_bill_periods')->orderBy('period_start')->get(); + if ($periods->isEmpty()) throw new RuntimeException('jd_wallet_bill_mirror_not_ready'); + return $periods; + } + + private function query(array $filters, \Illuminate\Support\Collection $periods): Builder + { + $q = $this->db()->table('jd_wallet_bill_rows')->whereIn('generation', $periods->pluck('active_generation')->all()); + foreach (['store_name', 'bill_item'] as $field) { + if (($filters[$field] ?? '') !== '') $q->where($field, $filters[$field]); + } + LedgerRemarkFilter::itemsWhereIn($q, (array) ($filters['bill_items'] ?? []), 'bill_item'); + if (($filters['start'] ?? '') !== '') $q->where('occurred_at', '>=', $filters['start'] . ' 00:00:00'); + if (($filters['end'] ?? '') !== '') $q->where('occurred_at', '<', date('Y-m-d', strtotime($filters['end'] . ' +1 day')) . ' 00:00:00'); + if (($filters['keyword'] ?? '') !== '') { + $like = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['keyword']) . '%'; + $q->where(fn (Builder $sub) => $sub->where('record_code', 'like', $like)->orWhere('order_no', 'like', $like)->orWhere('row_data', 'like', $like)); + } + return $q; + } + + private function ordered(Builder $q, string $sort, string $direction): Builder + { + $sort = in_array($sort, ['occurred_at', 'record_code', 'income', 'expense', 'balance'], true) ? $sort : 'occurred_at'; + $direction = $direction === 'asc' ? 'asc' : 'desc'; + return $q->orderBy($sort, $direction)->orderBy('record_code', $direction); + } + + private function latestBalanceTotal(array $filters, \Illuminate\Support\Collection $periods): float + { + // Balances are snapshots: sum only the latest row per shop/account within the selected results. + $ranked = $this->query($filters, $periods)->select('balance') + ->selectRaw('ROW_NUMBER() OVER (PARTITION BY store_name, account_name ORDER BY occurred_at DESC, LENGTH(record_code) DESC, record_code DESC) AS balance_rank'); + return round((float) $this->db()->query()->fromSub($ranked, 'latest')->where('balance_rank', 1)->sum('balance'), 2); + } + + private function db(): \Illuminate\Database\Connection + { + return $this->databases->connection(config('upstream_mirrors.connection', 'business_mirror')); + } +} diff --git a/modules/EcommerceFinance/Repositories/StoreReportRepository.php b/modules/EcommerceFinance/Repositories/StoreReportRepository.php index 3da15e78..db0ed977 100644 --- a/modules/EcommerceFinance/Repositories/StoreReportRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReportRepository.php @@ -5,13 +5,15 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; use Illuminate\Support\Facades\Schema; +use Modules\EcommerceFinance\Services\StoreReportPeriodBuilder; use RuntimeException; /** - * 将经营分析副本库中的店铺资料与共享日汇总组合为店铺维度报表。 + * 将店铺主体期间与共享日汇总组合为店铺维度报表。 * * 页面不扫描千万级原始账单,也不依赖开发机或镜像中不存在的 SQLite。 - * 生命周期区间统一使用 [effective_at, expires_at),避免主体切换日重复统计。 + * 期间由 StoreReportPeriodBuilder 按期初数据和爬虫变更生成:变更店铺的老主体 + * 失效时间为变更日前一天、新主体从变更日当天生效,收入按实际日期归集,不重复统计。 */ class StoreReportRepository { @@ -26,12 +28,14 @@ class StoreReportRepository /** 主表 rpt.fys_shopinfo 中这些平台不支持变更主体(能否变更=否),其余平台均为是。 */ public const UNCHANGEABLE_PLATFORMS = ['唯品会MP', '淘工厂']; private readonly ConnectionInterface $connection; + private readonly StoreReportPeriodBuilder $periods; public function __construct(DatabaseManager $database) { $this->connection = $database->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), ); + $this->periods = new StoreReportPeriodBuilder($database); } /** @@ -52,15 +56,32 @@ class StoreReportRepository foreach (['erp_store_name', 'store_name', 'store_id', 'profit_center', 'store_manager', 'department_manager', 'entity', 'company_type'] as $key) { $rules[$key] = ['nullable', 'string', 'max:191']; } + foreach (['period_sales', ...array_map(static fn (int $month): string => sprintf('sales_%02d', $month), range(1, 12))] as $key) { + $rules[$key] = ['nullable', 'string', 'max:64']; + } $rules['status'] = ['nullable', 'string', 'in:0,3,6']; $rules['can_change'] = ['nullable', 'string', 'in:是,否']; + $sortFields = [ + 'erp_store_name', 'store_name', 'store_id', 'profit_center', 'store_manager', 'department_manager', + 'opened_at', 'status', 'can_change', 'entity', 'company_type', 'effective_at', + 'invalid_at', 'period_sales', ...array_map(static fn (int $month): string => sprintf('sales_%02d', $month), range(1, 12)), + ]; + $rules['sort'] = ['nullable', 'string', 'in:' . implode(',', $sortFields)]; + $rules['direction'] = ['nullable', 'string', 'in:asc,desc']; - return validator(request()->only(array_keys($rules)), $rules)->validate(); + $filters = validator(request()->only(array_keys($rules)), $rules)->validate(); + if (! empty($filters['sort'])) { + $filters['_sort'] = $filters['sort']; + $filters['_direction'] = ($filters['direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc'; + } + unset($filters['sort'], $filters['direction']); + + return $filters; } /** * @param array> $stores - * @param array $filters 未覆盖字段已在上游 allStores 过滤;这里过滤主体、生命周期区间及归属覆盖字段。 + * @param array $filters 未覆盖字段已在上游 allStores 过滤;这里过滤主体、主体期间及归属覆盖字段。 * @return array> */ public function rows(array $stores, ?int $reportYear = null, array $filters = []): array @@ -70,17 +91,19 @@ class StoreReportRepository } $dailyGeneration = $this->activeGeneration(self::DAILY_DATASET); - $lifecycleGeneration = $this->activeGeneration(self::LIFECYCLES_DATASET); - $names = array_values(array_unique(array_filter(array_map( - static fn (array $row): string => trim((string) ($row['erp_store_name'] ?? '')), - $stores, - )))); - $lifecycles = $this->lifecycles($names, $lifecycleGeneration); - $lifecycleSales = $this->lifecycleSales($names, $lifecycleGeneration, $dailyGeneration); - $fallbackSales = $this->fallbackSales( - array_values(array_diff($names, array_keys($lifecycles))), - $dailyGeneration, - ); + // 期间由期初数据、系统主体和爬虫变更生成,同一店铺不再展开流程历史重复行。 + $periods = $this->periods->build($stores); + $multiPeriod = []; + $singleNames = []; + foreach ($periods as $name => $list) { + if (count($list) > 1) { + $multiPeriod[$name] = $list; + } else { + $singleNames[] = $name; + } + } + $singleSales = $this->singlePeriodSales($singleNames, $dailyGeneration); + $splitSales = $this->periodSales($multiPeriod, $dailyGeneration); $reportYear = $reportYear ?? (int) now()->format('Y'); $currentMonth = now()->startOfMonth(); $rollingMonths = collect(range(12, 1))->map( @@ -94,17 +117,18 @@ class StoreReportRepository continue; } - $periods = $lifecycles[$storeName] ?? [[ + $list = $periods[$storeName] ?? [[ 'company_name' => $store['company_name'] ?? null, 'effective_at' => self::DEFAULT_EFFECTIVE_AT, - 'expires_at' => self::DEFAULT_EXPIRES_AT, - 'lifecycle_id' => null, + 'expires_at' => null, + 'source' => 'fallback', ]]; + $split = count($list) > 1; - foreach ($periods as $period) { - $saleData = $period['lifecycle_id'] === null - ? ($fallbackSales[$storeName] ?? ['period' => 0.0, 'months' => []]) - : ($lifecycleSales[(string) $period['lifecycle_id']] ?? ['period' => 0.0, 'months' => []]); + foreach ($list as $index => $period) { + $saleData = $split + ? ($splitSales[$storeName][$index] ?? ['period' => 0.0, 'months' => []]) + : ($singleSales[$storeName] ?? ['period' => 0.0, 'months' => []]); $monthly = []; $monthlyIncome = []; for ($month = 1; $month <= 12; $month++) { @@ -123,13 +147,18 @@ class StoreReportRepository $effectiveAt = $this->date($period['effective_at'] ?? null, self::DEFAULT_EFFECTIVE_AT); $expiresAt = $this->date($period['expires_at'] ?? null, self::DEFAULT_EXPIRES_AT); + $status = $this->status($store['store_status'] ?? null); + // 关店和其他非正常状态不展示期间日期,避免把已关闭店铺计入在营期间。 + $normal = $status === '开店中'; $row = [ ...$store, - 'status' => $this->status($store['store_status'] ?? null), + 'status' => $status, 'can_change' => $this->canChange($store['platform'] ?? null), 'entity' => $period['company_name'] ?: ($store['company_name'] ?? null), - 'effective_at' => $effectiveAt, - 'invalid_at' => $expiresAt === self::DEFAULT_EXPIRES_AT ? '存续中' : $expiresAt, + 'effective_at' => $normal ? $effectiveAt : '-', + 'invalid_at' => $normal + ? ($expiresAt === self::DEFAULT_EXPIRES_AT ? '存续中' : $expiresAt) + : '-', 'period_sales' => (float) $saleData['period'], 'rolling_12m_income' => array_intersect($rollingMonths, array_keys($saleData['months'])) === [] ? null @@ -138,7 +167,7 @@ class StoreReportRepository ...$monthlyIncome, ]; - if (! $this->matchesFilters($row, $expiresAt, $filters)) { + if (! $this->matchesFilters($row, $effectiveAt, $expiresAt, $filters)) { continue; } @@ -146,82 +175,107 @@ class StoreReportRepository } } + return $this->sortRows($rows, $filters); + } + + /** @param array> $rows @param array $filters */ + private function sortRows(array $rows, array $filters): array + { + $key = (string) ($filters['_sort'] ?? ''); + if ($key === '') { + return $rows; + } + + $allowed = [ + 'erp_store_name' => 'erp_store_name', 'store_name' => 'store_name', 'store_id' => 'store_id', + 'profit_center' => 'profit_center', 'store_manager' => 'store_manager', + 'department_manager' => 'department_manager', 'opened_at' => 'opened_at', + 'status' => 'status', 'can_change' => 'can_change', 'entity' => 'entity', + 'company_type' => 'company_type', 'effective_at' => 'effective_at', + 'invalid_at' => 'invalid_at', 'period_sales' => 'period_sales', + ...array_combine( + array_map(static fn (int $month): string => sprintf('sales_%02d', $month), range(1, 12)), + array_map(static fn (int $month): string => sprintf('sales_%02d', $month), range(1, 12)), + ), + ]; + $column = $allowed[$key] ?? null; + if ($column === null) { + return $rows; + } + + $direction = ($filters['_direction'] ?? 'asc') === 'desc' ? -1 : 1; + usort($rows, static function (array $left, array $right) use ($column, $direction): int { + $leftValue = $left[$column] ?? null; + $rightValue = $right[$column] ?? null; + if (is_numeric($leftValue) && is_numeric($rightValue)) { + $comparison = ((float) $leftValue <=> (float) $rightValue) * $direction; + } else { + $comparison = strcmp((string) ($leftValue ?? ''), (string) ($rightValue ?? '')) * $direction; + } + + return $comparison !== 0 ? $comparison : strcmp((string) ($left['store_id'] ?? ''), (string) ($right['store_id'] ?? '')); + }); + return $rows; } - /** @return array>> */ - private function lifecycles(array $names, string $generation): array + /** + * 多期间店铺按每个期间的主体生效日、失效日(含当天)拆分日汇总收入。 + * + * @param array>> $periodsByStore + * @return array}>> + */ + private function periodSales(array $periodsByStore, string $dailyGeneration): array { - $result = []; - foreach ($this->nameChunks($names) as $chunk) { - $placeholders = implode(',', array_fill(0, count($chunk), '?')); - $rows = $this->select( - "SELECT id, erp_store_name, company_name, effective_at, expires_at - FROM store_report_lifecycle_rows - WHERE generation = ? AND erp_store_name IN ($placeholders) - ORDER BY erp_store_name, effective_at, id", - [$generation, ...$chunk], - ); - - foreach ($rows as $row) { - $result[(string) $row['erp_store_name']][] = [ - 'lifecycle_id' => (int) $row['id'], - 'company_name' => $row['company_name'], - 'effective_at' => $row['effective_at'], - 'expires_at' => $row['expires_at'], + $flat = []; + foreach ($periodsByStore as $name => $list) { + foreach ($list as $index => $period) { + $flat[] = [ + 'key' => $name . "\x1f" . $index, + 'store' => $name, + 'effective_at' => $this->date($period['effective_at'] ?? null, self::DEFAULT_EFFECTIVE_AT), + 'expires_at' => $this->date($period['expires_at'] ?? null, self::DEFAULT_EXPIRES_AT), ]; } } - return $result; - } - - /** @return array}> */ - private function lifecycleSales(array $names, string $lifecycleGeneration, string $dailyGeneration): array - { - if ($names === []) { - return []; - } - $month = $this->connection->getDriverName() === 'sqlite' ? "substr(d.occurred_on, 1, 7)" : "DATE_FORMAT(d.occurred_on, '%Y-%m')"; - $lowerBound = $this->connection->getDriverName() === 'sqlite' - ? 'date(d.occurred_on) >= date(COALESCE(l.effective_at, ?))' - : 'd.occurred_on >= COALESCE(l.effective_at, ?)'; - $upperBound = $this->connection->getDriverName() === 'sqlite' - ? 'date(d.occurred_on) < date(COALESCE(l.expires_at, ?))' - : 'd.occurred_on < COALESCE(l.expires_at, ?)'; - $result = []; - foreach ($this->nameChunks($names) as $chunk) { - $placeholders = implode(',', array_fill(0, count($chunk), '?')); + $collected = []; + foreach (array_chunk($flat, 200) as $chunk) { + $selects = []; + $bindings = []; + foreach ($chunk as $row) { + $selects[] = 'SELECT ? AS period_key, ? AS store_name, ? AS effective_at, ? AS expires_at'; + array_push($bindings, $row['key'], $row['store'], $row['effective_at'], $row['expires_at']); + } $rows = $this->select( - "SELECT l.id AS lifecycle_id, {$month} AS bill_month, + "SELECT p.period_key, {$month} AS bill_month, SUM(COALESCE(d.income, 0)) AS income_total - FROM store_report_lifecycle_rows AS l + FROM (" . implode(' UNION ALL ', $selects) . ") AS p INNER JOIN store_report_daily_rows AS d - ON d.store_name = l.erp_store_name + ON d.store_name = p.store_name AND d.generation = ? - AND {$lowerBound} - AND {$upperBound} - WHERE l.generation = ? AND l.erp_store_name IN ($placeholders) - GROUP BY l.id, {$month}", - [ - $dailyGeneration, - self::DEFAULT_EFFECTIVE_AT, - self::DEFAULT_EXPIRES_AT, - $lifecycleGeneration, - ...$chunk, - ], + AND d.occurred_on >= p.effective_at + AND d.occurred_on <= p.expires_at + GROUP BY p.period_key, {$month}", + [...$bindings, $dailyGeneration], ); - $this->collectSales($result, $rows, 'lifecycle_id'); + $this->collectSales($collected, $rows, 'period_key'); + } + + $result = []; + foreach ($collected as $key => $sales) { + [$store, $index] = explode("\x1f", (string) $key, 2) + [1 => '0']; + $result[$store][(int) $index] = $sales; } return $result; } /** @return array}> */ - private function fallbackSales(array $names, string $dailyGeneration): array + private function singlePeriodSales(array $names, string $dailyGeneration): array { if ($names === []) { return []; @@ -301,24 +355,30 @@ class StoreReportRepository } /** - * 生命周期字段的行级过滤:主体、能否变更、负责人、利润中心精确匹配;生效、失效时间左闭右开。 + * 生命周期字段的行级过滤:主体、负责人和利润中心按关键词匹配,能否变更按原值匹配;生效、失效时间左闭右开。 * * 店铺负责人/部门负责人/利润中心展示店铺账号镜像(PostgreSQL)覆盖后的值, * 与页面筛选保持一致,因此在这里按行值匹配而不是上游镜像 SQL。 * - * @param array $row + * @param array $row 展示行(关店店铺的期间字段已显示为“-”) + * @param string $effectiveAt 期间真实生效日,不受状态展示影响 + * @param string $expiresAt 期间真实失效日,存续中按 2999-01-01 参与过滤 * @param array $filters */ - private function matchesFilters(array $row, string $expiresAt, array $filters): bool + private function matchesFilters(array $row, string $effectiveAt, string $expiresAt, array $filters): bool { - foreach (['entity', 'can_change', 'store_manager', 'department_manager', 'profit_center'] as $key) { + foreach (['entity', 'store_manager', 'department_manager', 'profit_center'] as $key) { $expected = trim((string) ($filters[$key] ?? '')); - if ($expected !== '' && trim((string) ($row[$key] ?? '')) !== $expected) { + if ($expected !== '' && ! str_contains(mb_strtolower(trim((string) ($row[$key] ?? ''))), mb_strtolower($expected))) { return false; } } + $canChange = trim((string) ($filters['can_change'] ?? '')); + if ($canChange !== '' && trim((string) ($row['can_change'] ?? '')) !== $canChange) { + return false; + } - foreach (['effective_at' => (string) $row['effective_at'], 'invalid_at' => $expiresAt] as $key => $value) { + foreach (['effective_at' => $effectiveAt, 'invalid_at' => $expiresAt] as $key => $value) { $from = trim((string) ($filters[$key . '_from'] ?? '')); $to = trim((string) ($filters[$key . '_to'] ?? '')); if ($from !== '' && strcmp($value, $from) < 0) { @@ -329,6 +389,14 @@ class StoreReportRepository } } + foreach (['period_sales', ...array_map(static fn (int $month): string => sprintf('sales_%02d', $month), range(1, 12))] as $key) { + $needle = str_replace(',', '', trim((string) ($filters[$key] ?? ''))); + if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null) + || abs((float) $row[$key] - (float) $needle) > 0.000001)) { + return false; + } + } + return true; } diff --git a/modules/EcommerceFinance/Repositories/StoreViolationRecordRepository.php b/modules/EcommerceFinance/Repositories/StoreViolationRecordRepository.php new file mode 100644 index 00000000..987285ba --- /dev/null +++ b/modules/EcommerceFinance/Repositories/StoreViolationRecordRepository.php @@ -0,0 +1,279 @@ +connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + } + + public function available(): bool + { + return Schema::connection($this->connection->getName())->hasTable(self::TABLE); + } + + public function syncState(): ?object + { + if (! $this->available()) { + return null; + } + + if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) { + return null; + } + + return $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->first(); + } + + public function totalRows(): int + { + return $this->available() ? (int) $this->connection->table(self::TABLE)->count() : 0; + } + + /** @return array{code:string,last_succeeded_at:?string,row_count:int,last_error:?string} */ + public function syncStatus(): array + { + $state = $this->syncState(); + $total = $this->available() ? $this->connection->table(self::TABLE)->count() : 0; + + return [ + 'code' => $total > 0 ? 'ready' : 'pending', + 'last_succeeded_at' => $state->last_succeeded_at ?? null, + 'row_count' => (int) ($state->mirror_row_count ?? $total), + 'last_error' => $state->last_error_code ?? null, + ]; + } + + /** @return array */ + public function platformCounts(): array + { + if (! $this->available()) { + return []; + } + + return $this->connection->table(self::TABLE) + ->selectRaw('platform, COUNT(*) AS aggregate') + ->groupBy('platform') + ->pluck('aggregate', 'platform') + ->map(static fn (mixed $value): int => (int) $value) + ->all(); + } + + /** + * @param array{keyword?:?string,status?:?string,handling_status?:?string,category?:?string,date_from?:?string,date_to?:?string} $filters + * @return array{data:list,total:int} + */ + public function paginate(string $platform, array $filters, int $page, int $limit): array + { + $query = $this->query($platform, $filters); + $total = (clone $query)->count(); + + $rows = $query + ->orderByDesc('violation_date') + ->orderByDesc('id') + ->forPage(max($page, 1), max($limit, 1)) + ->get(); + + return ['data' => $rows->all(), 'total' => $total]; + } + + /** + * @param array{keyword?:?string,status?:?string,handling_status?:?string,category?:?string,date_from?:?string,date_to?:?string} $filters + */ + public function query(string $platform, array $filters): Builder + { + $query = $this->connection->table(self::TABLE)->where('platform', $platform); + + $keyword = trim((string) ($filters['keyword'] ?? '')); + if ($keyword !== '') { + $like = '%' . addcslashes($keyword, '%_\\') . '%'; + $query->where(static function (Builder $inner) use ($like): void { + $inner->where('shop_name', 'like', $like) + ->orWhere('violation_no', 'like', $like) + ->orWhere('violation_type', 'like', $like); + }); + } + + if (($filters['status'] ?? null) !== null && $filters['status'] !== '') { + $query->where('status', $filters['status']); + } + + if (($filters['handling_status'] ?? null) !== null && $filters['handling_status'] !== '') { + $query->where('handling_status', $filters['handling_status']); + } + + if (($filters['category'] ?? null) !== null && $filters['category'] !== '') { + $query->where('violation_category', $filters['category']); + } + + if (($filters['date_from'] ?? null) !== null && $filters['date_from'] !== '') { + $query->whereDate('violation_date', '>=', $filters['date_from']); + } + + if (($filters['date_to'] ?? null) !== null && $filters['date_to'] !== '') { + $query->whereDate('violation_date', '<=', $filters['date_to']); + } + + return $query; + } + + /** @return array{statuses:list,handling_statuses:list,categories:list,shops:list} */ + public function filterOptions(string $platform): array + { + if (! $this->available()) { + return ['statuses' => [], 'handling_statuses' => [], 'categories' => [], 'shops' => []]; + } + + $distinct = fn (string $column): array => $this->connection->table(self::TABLE) + ->where('platform', $platform) + ->whereNotNull($column) + ->where($column, '<>', '') + ->orderBy($column) + ->distinct() + ->pluck($column) + ->map(static fn (mixed $value): string => (string) $value) + ->all(); + + return [ + 'statuses' => $distinct('status'), + 'handling_statuses' => $distinct('handling_status'), + 'categories' => $distinct('violation_category'), + 'shops' => $this->connection->table(self::TABLE) + ->where('platform', $platform) + ->where('shop_name', '<>', '') + ->orderBy('shop_name') + ->distinct() + ->limit(2000) + ->pluck('shop_name') + ->map(static fn (mixed $value): string => (string) $value) + ->all(), + ]; + } + + /** + * 统一表头导出用的行数据(流式读取,避免一次性载入)。 + * + * @param array $filters + * @return \Generator + */ + public function exportRows(string $platform, array $filters): \Generator + { + $query = $this->query($platform, $filters) + ->orderByDesc('violation_date') + ->orderByDesc('id'); + + foreach ($query->cursor() as $row) { + yield $row; + } + } + + /** + * 按 (platform, violation_no) 幂等写入统一表。 + * + * @param list> $rows + * @param list $updateColumns + */ + public function upsertRows(array $rows, array $updateColumns): int + { + if ($rows === []) { + return 0; + } + + $affected = 0; + foreach (array_chunk($rows, 500) as $chunk) { + $affected += $this->connection->table(self::TABLE)->upsert( + $chunk, + ['platform', 'violation_no'], + $updateColumns, + ); + } + + return $affected; + } + + /** + * 记录抓取同步状态(与通用镜像数据集共用 business_mirror_table_states)。 + */ + public function recordSyncState(string $status, int $rowCount, ?string $errorCode = null): void + { + if (! $this->available()) { + return; + } + + if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) { + return; + } + + $now = now(); + $values = [ + 'source_key' => 'operations_replica', + 'source_object' => 'rpt.crawl_shop_violation', + 'target_table' => self::TABLE, + 'status' => $status, + 'last_attempted_at' => $now, + 'mirror_row_count' => $rowCount, + 'last_error_code' => $errorCode, + 'updated_at' => $now, + ]; + + if ($status === 'succeeded') { + $values['last_succeeded_at'] = $now; + $values['initial_completed_at'] = $now; + } + + $exists = $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->exists(); + + if ($exists) { + $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->update($values); + + return; + } + + $this->connection->table(self::STATE_TABLE)->insert($values + [ + 'dataset_key' => self::DATASET_KEY, + 'created_at' => $now, + ]); + } +} diff --git a/modules/EcommerceFinance/Repositories/SupplierPayableRepository.php b/modules/EcommerceFinance/Repositories/SupplierPayableRepository.php index 96dfc4f1..7f3130d4 100644 --- a/modules/EcommerceFinance/Repositories/SupplierPayableRepository.php +++ b/modules/EcommerceFinance/Repositories/SupplierPayableRepository.php @@ -135,6 +135,7 @@ class SupplierPayableRepository $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $sql = "SELECT + id AS id, CONVERT(varchar(10), date, 120) AS send_time, supplierName AS supplier, sku_id AS barcode, @@ -225,6 +226,7 @@ class SupplierPayableRepository $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $sql = "SELECT + id AS id, CONVERT(varchar(7), month, 120) AS month_str, '' AS category, supplier AS payee, @@ -281,6 +283,7 @@ class SupplierPayableRepository $rows = $this->query->select( "SELECT + [id] AS id, [Month] AS month, [supplier] AS supplier, CAST([Totalindemnity] AS decimal(18,2)) AS amount, @@ -369,6 +372,7 @@ class SupplierPayableRepository $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $sql = "SELECT + id AS id, supplier, '' AS contract_name, CAST(price AS decimal(18,2)) AS advance_amount, @@ -454,6 +458,7 @@ class SupplierPayableRepository $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $sql = "SELECT + id AS id, CONVERT(varchar(10), finishTime, 120) AS finish_time, department, creator, @@ -619,6 +624,7 @@ class SupplierPayableRepository $whereSql = 'WHERE ' . implode(' AND ', $where); $sql = "SELECT + id AS id, CONVERT(varchar(10), date, 120) AS send_time, supplierName AS supplier, sku_id AS barcode, @@ -759,7 +765,7 @@ class SupplierPayableRepository $whereSql = 'WHERE ' . implode(' AND ', $where); $sql = "SELECT - '其他扣款补款' AS project, + id AS id, Month AS month_str, supplier, CAST(other AS decimal(18,2)) AS supplement_amount, @@ -770,7 +776,13 @@ class SupplierPayableRepository FROM fys_supplierPaymentSummary $whereSql"; - return $this->runQuery($sql, $params, $page, $pageSize, 'month_str DESC, supplier'); + $result = $this->runQuery($sql, $params, $page, $pageSize, 'month_str DESC, supplier'); + foreach ($result['data'] as &$row) { + $row['project'] = '其他扣款补款'; + } + unset($row); + + return $result; } public function otherAdjustmentsSummary(array $filters): array @@ -825,6 +837,7 @@ class SupplierPayableRepository $whereSql = 'WHERE ' . implode(' AND ', $where); $sql = "SELECT + id AS id, reconciliation_person, month AS month_str, courier_company_name AS supplier, diff --git a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php new file mode 100644 index 00000000..11d04427 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php @@ -0,0 +1,216 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::IMPORT_TABLE) || ! $schema->hasTable(self::ROW_TABLE)) { + return false; + } + + return $this->connection->table(self::IMPORT_TABLE)->where('status', 'succeeded')->exists(); + } + + /** @return array{shops:list,bill_items:list} */ + public function accountBillFilterOptions(): array + { + $query = $this->query(); + + return [ + 'shops' => (clone $query)->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name')->map('strval')->all(), + 'bill_items' => (clone $query)->whereNotNull('bill_item')->where('bill_item', '<>', '') + ->distinct()->orderBy('bill_item')->pluck('bill_item')->map('strval')->all(), + ]; + } + + /** @return array */ + public function paginate(array $filters, string $sort, string $direction, int $page, int $perPage): array + { + $page = max(1, $page); + $perPage = min(max(1, $perPage), 100); + $query = $this->query(); + $this->applyFilters($query, $filters); + $summary = (clone $query)->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS row_count' + )->first(); + $total = (int) ($summary->row_count ?? 0); + $income = (float) ($summary->income_total ?? 0); + $expense = (float) ($summary->expense_total ?? 0); + $sortColumn = $this->sortColumn($sort); + $direction = $direction === 'asc' ? 'asc' : 'desc'; + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') $query->orderBy('record_code', $direction); + + $rows = $query->forPage($page, $perPage)->get() + ->map(fn (object $row): array => $this->mapRow($row))->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'current_page' => $page, + 'last_page' => max(1, (int) ceil($total / $perPage)), + 'per_page' => $perPage, + 'summary' => [ + 'income' => $income, + 'expense' => $expense, + 'balance' => round($income - $expense, 2), + 'count' => $total, + ], + 'sync' => [ + 'status' => 'succeeded', + 'last_succeeded_at' => $this->connection->table(self::IMPORT_TABLE) + ->where('status', 'succeeded')->max('completed_at'), + ], + ]; + } + + /** @return iterable> */ + public function exportRows(array $filters, string $sort = 'occurred_at', string $direction = 'asc'): iterable + { + $query = $this->query(); + $this->applyFilters($query, $filters); + $sortColumn = $this->sortColumn($sort); + $direction = $direction === 'desc' ? 'desc' : 'asc'; + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') $query->orderBy('record_code', $direction); + + return $query->cursor()->map(fn (object $row): array => $this->mapRow($row)); + } + + private function query(): Builder + { + if (! $this->ready()) { + throw new RuntimeException('taobao_alipay_authoritative_bills_not_ready'); + } + + return $this->connection->table(self::ROW_TABLE); + } + + /** @param array $filters */ + private function applyFilters(Builder $query, array $filters): void + { + $store = trim((string) ($filters['store_name'] ?? '')); + if ($store !== '') $query->where('store_name', $store); + $channel = trim((string) ($filters['source_channel'] ?? '')); + if ($channel !== '') $query->where('business_bill_source', 'like', '%' . $this->escapeLike($channel) . '%'); + $item = trim((string) ($filters['bill_item'] ?? '')); + if ($item !== '') $query->where('bill_item', $item); + // 「总账备注」:淘系支付宝页签同页混有天猫/淘宝/阿里巴巴店铺,按店铺名前缀分平台过滤。 + $groups = is_array($filters['bill_item_groups'] ?? null) ? $filters['bill_item_groups'] : []; + if ($groups !== []) { + LedgerRemarkFilter::applyGroups( + $query, + $groups, + 'bill_item', + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'like', $prefix . '%'), + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'not like', $prefix . '%'), + ); + } else { + LedgerRemarkFilter::itemsWhereIn($query, (array) ($filters['bill_items'] ?? []), 'bill_item'); + } + $type = trim((string) ($filters['business_type'] ?? '')); + if ($type === '收入') $query->where('income_amount', '>', 0); + if ($type === '支出') $query->where('expense_amount', '>', 0); + $from = $this->date($filters['start'] ?? null); + if ($from !== null) $query->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00'); + $to = $this->date($filters['end'] ?? null); + if ($to !== null) $query->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + $keyword = trim((string) ($filters['keyword'] ?? '')); + if ($keyword !== '') { + $like = '%' . $this->escapeLike($keyword) . '%'; + $query->where(function (Builder $nested) use ($like): void { + foreach ([ + 'record_code', 'account_order_no', 'business_serial_no', 'merchant_order_no', + 'business_base_order_no', 'online_order_no', 'business_order_no', 'remark', + 'custom_remark', 'business_description', 'bill_item', 'goods_name', + ] as $column) { + $method = $column === 'record_code' ? 'where' : 'orWhere'; + $nested->{$method}($column, 'like', $like); + } + }); + } + } + + private function sortColumn(string $sort): string + { + return [ + 'occurred_at' => 'occurred_at', + 'income' => 'income_amount', + 'expense' => 'expense_amount', + 'balance' => 'balance_amount', + 'record_code' => 'record_code', + ][$sort] ?? 'occurred_at'; + } + + /** @return array */ + private function mapRow(object $row): array + { + return [ + 'id' => (string) $row->record_code, + 'record_code' => (string) $row->record_code, + 'store_name' => (string) ($row->store_name ?? ''), + 'custom_remark' => (string) ($row->custom_remark ?? ''), + 'bill_item' => (string) ($row->bill_item ?? ''), + 'alipay_account' => (string) ($row->alipay_account ?? ''), + 'account_order_no' => (string) ($row->account_order_no ?? ''), + 'business_serial_no' => (string) ($row->business_serial_no ?? ''), + 'merchant_order_no' => (string) ($row->merchant_order_no ?? ''), + 'business_base_order_no' => (string) ($row->business_base_order_no ?? ''), + 'goods_name' => (string) ($row->goods_name ?? ''), + 'counterparty_account' => (string) ($row->counterparty_account ?? ''), + 'occurred_at' => (string) $row->occurred_at, + 'income' => (float) $row->income_amount, + 'expense' => (float) $row->expense_amount, + 'balance' => (float) $row->balance_amount, + 'business_type' => (string) ($row->business_type ?? ''), + 'remark' => (string) ($row->remark ?? ''), + 'online_order_no' => (string) ($row->online_order_no ?? ''), + 'online_real_store' => (string) ($row->online_real_store ?? ''), + 'business_description' => (string) ($row->business_description ?? ''), + 'business_bill_source' => (string) ($row->business_bill_source ?? ''), + 'business_order_no' => (string) ($row->business_order_no ?? ''), + 'created_at' => $row->source_created_at !== null ? (string) $row->source_created_at : null, + 'updated_at' => $row->source_updated_at !== null ? (string) $row->source_updated_at : null, + 'modifier' => (string) ($row->source_modified_by ?? ''), + ]; + } + + private function date(mixed $value): ?DateTimeImmutable + { + $value = trim((string) ($value ?? '')); + if ($value === '' || preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) return null; + $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value); + + return $date !== false && $date->format('Y-m-d') === $value ? $date : null; + } + + private function escapeLike(string $value): string + { + return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value); + } +} diff --git a/modules/EcommerceFinance/Repositories/TaobaoWechatSettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoWechatSettlementBillRepository.php new file mode 100644 index 00000000..f93cb2be --- /dev/null +++ b/modules/EcommerceFinance/Repositories/TaobaoWechatSettlementBillRepository.php @@ -0,0 +1,330 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::IMPORT_TABLE) || ! $schema->hasTable(self::ROW_TABLE)) { + return false; + } + + return $this->connection->table(self::IMPORT_TABLE)->where('status', 'succeeded')->exists(); + } + + /** @return string[] */ + public function storeOptions(): array + { + return $this->query()->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name')->map('strval')->all(); + } + + /** @return array{shops:list,bill_items:list} */ + public function accountBillFilterOptions(): array + { + $shops = $this->query()->whereNotNull('store_name')->where('store_name', '<>', '') + ->distinct()->orderBy('store_name')->pluck('store_name') + ->map(static fn (mixed $value): string => (string) $value)->all(); + $billItems = $this->query()->whereNotNull('bill_item')->where('bill_item', '<>', '') + ->distinct()->orderBy('bill_item')->pluck('bill_item') + ->map(static fn (mixed $value): string => (string) $value)->all(); + + return ['shops' => $shops, 'bill_items' => $billItems]; + } + + /** @return array{rows:list>,total:int} */ + public function paginate( + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + int $page, + int $pageSize, + ): array { + $page = max(1, $page); + $pageSize = min(max(1, $pageSize), 500); + $query = $this->query(); + $this->applyFilters($query, $storeName, $fromDate, $toDate, $flowType); + $total = (clone $query)->count(); + + $rows = $query->orderByDesc('occurred_at')->orderByDesc('record_code') + ->forPage($page, $pageSize)->get()->map(function (object $row): array { + $signed = (float) $row->signed_amount; + $income = (float) $row->income_amount; + $expense = (float) $row->expense_amount; + $flowType = $income > 0 ? 1 : ($expense > 0 ? 2 : 0); + + return [ + 'id' => $row->record_code, + 'shopName' => (string) ($row->store_name ?? ''), + 'amount' => abs($signed), + 'balance' => null, + 'summary' => (string) ($row->bill_item ?? ''), + 'flowType' => $flowType, + 'toAdvertiserFundType' => null, + 'createTime' => (string) $row->occurred_at, + 'source_primary_key' => (string) ($row->taobao_order_no ?? ''), + 'source_record_code' => (string) $row->record_code, + 'source_channel' => 'TaobaoWechatSettlementBill', + ]; + })->all(); + + return ['rows' => $rows, 'total' => $total]; + } + + /** @return array{income_total:float,expense_total:float,cnt:int} */ + public function summarize( + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + ): array { + $query = $this->query(); + $this->applyFilters($query, $storeName, $fromDate, $toDate, $flowType); + $row = $query->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS cnt' + )->first(); + + return [ + 'income_total' => (float) ($row->income_total ?? 0), + 'expense_total' => (float) ($row->expense_total ?? 0), + 'cnt' => (int) ($row->cnt ?? 0), + ]; + } + + /** @return array */ + public function paginateAccountBills( + array $filters, + string $sort, + string $direction, + int $page, + int $perPage, + ): array { + $page = max(1, $page); + $perPage = min(max(1, $perPage), 100); + $query = $this->query(); + $this->applyAccountBillFilters($query, $filters); + + $summary = (clone $query)->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS row_count' + )->first(); + $total = (int) ($summary->row_count ?? 0); + $income = (float) ($summary->income_total ?? 0); + $expense = (float) ($summary->expense_total ?? 0); + + $sortColumn = $this->accountBillSortColumn($sort); + $direction = $direction === 'asc' ? 'asc' : 'desc'; + + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') { + $query->orderBy('record_code', $direction); + } + + $rows = $query->forPage($page, $perPage)->get() + ->map(fn (object $row): array => $this->mapAccountBillRow($row))->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'current_page' => $page, + 'last_page' => max(1, (int) ceil($total / $perPage)), + 'per_page' => $perPage, + 'from' => $total === 0 ? null : (($page - 1) * $perPage) + 1, + 'to' => $total === 0 ? null : min($page * $perPage, $total), + 'summary' => [ + 'income' => $income, + 'expense' => $expense, + 'balance' => round($income - $expense, 2), + 'count' => $total, + ], + ]; + } + + /** @return iterable> */ + public function exportAccountBills(array $filters, string $sort, string $direction): iterable + { + $query = $this->query(); + $this->applyAccountBillFilters($query, $filters); + $sortColumn = $this->accountBillSortColumn($sort); + $direction = $direction === 'desc' ? 'desc' : 'asc'; + $query->orderBy($sortColumn, $direction); + if ($sortColumn !== 'record_code') { + $query->orderBy('record_code', $direction); + } + + return $query->cursor()->map(fn (object $row): array => $this->mapAccountBillRow($row)); + } + + private function query(): Builder + { + if (! $this->ready()) { + throw new RuntimeException('taobao_wechat_authoritative_bills_not_ready'); + } + + return $this->connection->table(self::ROW_TABLE); + } + + private function applyFilters( + Builder $query, + ?string $storeName, + ?string $fromDate, + ?string $toDate, + ?string $flowType, + ): void { + if ($storeName !== null && $storeName !== '') { + $query->where('store_name', $storeName); + } + $from = $this->date($fromDate); + if ($from !== null) { + $query->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00'); + } + $to = $this->date($toDate); + if ($to !== null) { + $query->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + } + if ($flowType === 'income') { + $query->where('income_amount', '>', 0); + } elseif ($flowType === 'expense') { + $query->where('expense_amount', '>', 0); + } +} + /** @param array $filters */ + private function applyAccountBillFilters(Builder $query, array $filters): void + { + $storeName = trim((string) ($filters['store_name'] ?? '')); + if ($storeName !== '') { + $query->where('store_name', $storeName); + } + + $billItem = trim((string) ($filters['bill_item'] ?? '')); + if ($billItem !== '') { + $query->where('bill_item', $billItem); + } + + $this->applyLedgerRemarkFilter($query, $filters); + + $from = $this->date(isset($filters['start']) ? (string) $filters['start'] : null); + if ($from !== null) { + $query->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00'); + } + + $to = $this->date(isset($filters['end']) ? (string) $filters['end'] : null); + if ($to !== null) { + $query->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00'); + } + + $keyword = trim((string) ($filters['keyword'] ?? '')); + if ($keyword !== '') { + $query->where(function (Builder $nested) use ($keyword): void { + $like = '%' . $keyword . '%'; + $nested->where('record_code', 'like', $like) + ->orWhere('taobao_order_no', 'like', $like) + ->orWhere('online_order_no', 'like', $like) + ->orWhere('pay_serial_no', 'like', $like) + ->orWhere('remark', 'like', $like) + ->orWhere('custom_remark', 'like', $like) + ->orWhere('business_description', 'like', $like) + ->orWhere('bill_item', 'like', $like); + }); + } + } + + /** 「总账备注」筛选:淘系微信页签同页混有天猫/淘宝店铺,按店铺名前缀分平台过滤。 */ + private function applyLedgerRemarkFilter(Builder $query, array $filters): void + { + $groups = is_array($filters['bill_item_groups'] ?? null) ? $filters['bill_item_groups'] : []; + if ($groups !== []) { + LedgerRemarkFilter::applyGroups( + $query, + $groups, + 'bill_item', + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'like', $prefix . '%'), + static fn (Builder $sub, string $prefix) => $sub->where('store_name', 'not like', $prefix . '%'), + ); + + return; + } + + LedgerRemarkFilter::itemsWhereIn($query, (array) ($filters['bill_items'] ?? []), 'bill_item'); + } + + private function accountBillSortColumn(string $sort): string + { + return [ + 'occurred_at' => 'occurred_at', + 'income' => 'income_amount', + 'expense' => 'expense_amount', + 'record_code' => 'record_code', + ][$sort] ?? 'occurred_at'; + } + + /** @return array */ + private function mapAccountBillRow(object $row): array + { + $signedAmount = (float) $row->signed_amount; + + return [ + 'id' => (string) $row->record_code, + 'record_code' => (string) $row->record_code, + 'store_name' => (string) ($row->store_name ?? ''), + 'finance_remark' => (string) ($row->business_description ?? ''), + 'order_no' => (string) ($row->taobao_order_no ?? ''), + 'amount' => abs($signedAmount), + 'custom_remark' => (string) ($row->custom_remark ?? ''), + 'bill_item' => (string) ($row->bill_item ?? ''), + 'occurred_at' => (string) $row->occurred_at, + 'income' => (float) $row->income_amount, + 'expense' => (float) $row->expense_amount, + 'balance' => $signedAmount, + 'remark' => (string) ($row->remark ?? ''), + 'updated_at' => $row->jst_pulled_at !== null + ? (string) $row->jst_pulled_at + : null, + 'modifier' => (string) ($row->source_modified_by ?? ''), + 'payload' => [ + 'online_order_no' => (string) ($row->online_order_no ?? ''), + 'taobao_order_no' => (string) ($row->taobao_order_no ?? ''), + 'pay_serial_no' => (string) ($row->pay_serial_no ?? ''), + 'entry_type' => (string) ($row->entry_type ?? ''), + 'business_desc' => (string) ($row->business_description ?? ''), + 'jst_pulled_at' => $row->jst_pulled_at !== null + ? (string) $row->jst_pulled_at + : null, + ], + ]; + } + + private function date(?string $value): ?DateTimeImmutable + { + if ($value === null || preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value); + + return $date !== false && $date->format('Y-m-d') === $value ? $date : null; + } +} diff --git a/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageMirrorRepository.php b/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageMirrorRepository.php index bcf78e80..f75e3500 100644 --- a/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageMirrorRepository.php @@ -4,10 +4,13 @@ namespace Modules\EcommerceFinance\Repositories; use Carbon\CarbonInterface; use Generator; +use Illuminate\Contracts\Cache\LockTimeoutException; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; use Illuminate\Database\Query\Builder; use Illuminate\Support\Carbon; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Schema; use RuntimeException; use Throwable; @@ -20,6 +23,22 @@ use Throwable; */ class ThirdPartyWarehouseStorageMirrorRepository { + private const REPORT_QUERY_TIMEOUT_SECONDS = 30; + + /** Export queries may aggregate a larger batch, but must stay below the web proxy timeout. */ + private const REPORT_EXPORT_QUERY_TIMEOUT_SECONDS = 90; + + /** Shared movement aggregate is executed once per full export. */ + private const REPORT_EXPORT_AGGREGATE_TIMEOUT_SECONDS = 180; + + private const REPORT_EXPORT_BATCH_SIZE = 50000; + + private const REPORT_CACHE_SECONDS = 93600; + + private const REPORT_CACHE_LOCK_SECONDS = 45; + + private const REPORT_CACHE_WAIT_SECONDS = 35; + public const DATASET_KEY = 'jiansun.third-party-warehouse-storage'; public const WAREHOUSE_ID = 15045364; @@ -32,6 +51,8 @@ class ThirdPartyWarehouseStorageMirrorRepository private const INVENTORY_TABLE = 'third_party_warehouse_inventory_snapshots'; + private const SUBWAREHOUSE_INVENTORY_TABLE = 'third_party_warehouse_inventory_subwarehouse_snapshots'; + private const AUTHORITATIVE_STATE_TABLE = 'third_party_warehouse_authoritative_anchor_states'; private const AUTHORITATIVE_ANCHOR_TABLE = 'third_party_warehouse_authoritative_anchors'; @@ -40,14 +61,27 @@ class ThirdPartyWarehouseStorageMirrorRepository private const AUTHORITATIVE_DATASET_KEY = 'jiansun.third-party-warehouse-storage.authoritative-anchor'; + private const INVENTORY_REPORT_AUTHORITATIVE_STATE_TABLE = 'inventory_report_authoritative_states'; + + private const INVENTORY_REPORT_AUTHORITATIVE_ROW_TABLE = 'inventory_report_authoritative_rows'; + + private const INVENTORY_REPORT_AUTHORITATIVE_DATASET_KEY = 'jiansun.inventory-report.authoritative-month'; + private const PRODUCT_TABLE = 'ops_jst_sku'; + private const WAREHOUSE_TABLE = 'ops_jst_warehouse_info'; + private const GENERIC_STATE_TABLE = 'business_mirror_table_states'; private const PRODUCT_DATASET_KEY = 'operations_replica.rpt.jst_sku'; + private const WAREHOUSE_DATASET_KEY = 'operations_replica.rpt.jst_warehouseInfo'; + public const START_DATE = '2026-08-01'; + /** Historical monthly report range can start one month before the flow page. */ + public const INVENTORY_REPORT_START_DATE = '2026-07-01'; + /** @var array */ private const MOVEMENT_COLUMNS = [ 'processing_in' => '加工进仓', @@ -64,6 +98,45 @@ class ThirdPartyWarehouseStorageMirrorRepository 'other_out' => '其它出库', ]; + /** @var array */ + private const SUBWAREHOUSE_SUFFIXES = [ + 1 => '主仓', + 2 => '销退仓', + 3 => '进货仓', + 4 => '次品仓', + 6 => '自定义仓1', + 7 => '自定义仓2', + 8 => '自定义仓3', + ]; + + /** + * 聚水潭“按商品、按仓库、按月”导出中使用的实际子仓名。 + * 其余仓库按“仓储方 + 子仓后缀”生成,不再只显示通用类型名。 + * + * @var array> + */ + private const SPECIAL_SUBWAREHOUSE_NAMES = [ + '常州简尚家居有限公司' => [ + 1 => '配件单仓', + ], + '简尚-横林二仓' => [ + 6 => '客退临时上架仓', + 7 => '数量校验仓', + ], + '简尚-新苏北仓' => [ + 6 => '新苏北客退上架仓', + ], + '简尚-睢宁仓' => [ + 6 => '睢宁客退上架仓', + ], + '简尚-河南洛宁仓' => [ + 6 => '河南洛宁客退上架仓', + ], + '简尚-山东青岗集仓' => [ + 7 => '青岗集客退上架仓', + ], + ]; + /** @var list */ private const OUTPUT_COLUMNS = [ 'owner', 'date', 'sku_code', 'image_url', 'product_name', 'short_name', @@ -123,6 +196,15 @@ class ThirdPartyWarehouseStorageMirrorRepository && $this->dependenciesReady(); } + public function allWarehousesReady(): bool + { + $state = $this->state(); + + return $this->ready() + && (int) ($state['scope_version'] ?? 1) >= 2 + && $this->warehouseDependencyReady(); + } + /** @return array|null */ public function state(): ?array { @@ -218,6 +300,1081 @@ class ThirdPartyWarehouseStorageMirrorRepository ]; } + /** + * 商品价格管理的进销存报表与三方仓共用同一套已确认流水、 + * 库存锚点和业务类型口径,只在这里将日明细再汇总为“商品 + 仓库 + 月”。 + * + * @param array $filters + * @return array{data:list,total:int,state:array,sync:array} + */ + public function paginateMonthlyInventoryReport( + array $filters, + int $page, + int $perPage, + bool $includeTotal = true, + ?array $state = null, + ?array $sourceCounts = null, + ?int $queryTimeoutSeconds = null, + ?Collection $prefetchedMovementRows = null, + bool $refreshSourceCounts = false, + ): array + { + $state ??= $this->requireReadyState(); + if ((int) ($state['scope_version'] ?? 1) < 2) { + throw new RuntimeException('inventory_report_all_warehouses_not_ready'); + } + $page = max($page, 1); + $perPage = min(max($perPage, 1), $prefetchedMovementRows === null ? 5000 : self::REPORT_EXPORT_BATCH_SIZE); + $queryTimeoutSeconds ??= self::REPORT_QUERY_TIMEOUT_SECONDS; + $period = $this->inventoryReportPeriod((string) ($filters['month'] ?? '')); + // 已导入的当前月份是对账基准,直接返回工作簿中的完整月度明细。 + // 这样不会再把同月镜像流水重复叠加到权威的各类进出数量上。 + $currentAuthority = $this->currentMonthlyInventoryAuthority($period); + if ($currentAuthority !== null) { + return $this->paginateCurrentMonthlyInventoryAuthority( + $period, + $filters, + $page, + $perPage, + $includeTotal, + $state, + $queryTimeoutSeconds, + ); + } + + // 没有当前月权威数据时,保留原有的上月期末结转和已确认流水滚算。 + $headerGeneration = $this->generation($state, 'active_header_generation'); + $itemGeneration = $this->generation($state, 'active_item_generation'); + $inventoryGeneration = $this->generation($state, 'active_inventory_generation'); + if ($headerGeneration === null || $itemGeneration === null || $inventoryGeneration === null) { + throw new RuntimeException('inventory_report_mirror_not_ready'); + } + + $authority = $this->previousMonthlyInventoryAuthority($period); + $authorityIsCurrentMonth = false; + $resolveRollForward = fn (): ?array => $authority === null + ? null + : $this->monthlyInventoryRollForward( + $period, + $filters, + $authority, + $headerGeneration, + $itemGeneration, + $inventoryGeneration, + $page, + $perPage, + $includeTotal, + $state, + $authorityIsCurrentMonth, + $sourceCounts, + $queryTimeoutSeconds, + $prefetchedMovementRows, + $refreshSourceCounts, + ); + $rolledForward = $includeTotal && $perPage <= 100 && $authority !== null + ? $this->rememberMonthlyInventoryReport( + $this->monthlyInventoryReportCacheKey( + $period, + $filters, + $authority, + $headerGeneration, + $itemGeneration, + $inventoryGeneration, + $page, + $perPage, + ), + $resolveRollForward, + ) + : $resolveRollForward(); + if ($rolledForward !== null) { + $rolledForward['state'] = $state; + $rolledForward['sync'] = $this->syncStatus($state); + + return $rolledForward; + } + + $anchorAt = $this->stateAnchor($state); + $rangeStart = min($period['start'], $anchorAt); + $rangeEnd = max($period['end'], $anchorAt); + $latestProducts = $this->connection->table(self::PRODUCT_TABLE) + ->where('sku_type', 'normal')->whereNotNull('sku_id')->where('sku_id', '!=', '') + ->groupBy('sku_id')->select('sku_id')->selectRaw('MAX(autoid) AS autoid'); + $latestWarehouses = $this->connection->table(self::WAREHOUSE_TABLE) + ->whereNotNull('wms_co_id')->groupBy('wms_co_id') + ->select('wms_co_id')->selectRaw('MAX(Id) AS Id'); + $inventoryDimensions = $this->connection->table(self::SUBWAREHOUSE_INVENTORY_TABLE) + ->where('generation', $inventoryGeneration) + ->where('qty', '!=', 0) + ->whereNotNull('sku_code')->where('sku_code', '!=', '') + ->select(['wms_co_id', 'wh_id', 'sku_code as inventory_sku_code', 'captured_at']) + ->selectRaw('qty AS snapshot_qty'); + $candidates = $this->connection->query()->fromSub($inventoryDimensions, 'pairs') + ->joinSub($latestProducts, 'latest_product', 'latest_product.sku_id', '=', 'pairs.inventory_sku_code') + ->join(self::PRODUCT_TABLE . ' as s', function ($join): void { + $join->on('s.sku_id', '=', 'latest_product.sku_id') + ->on('s.autoid', '=', 'latest_product.autoid'); + }) + ->select([ + 'pairs.wms_co_id', 'pairs.wh_id', 'pairs.inventory_sku_code', + 's.sku_id as sku_code', 's.category', + ]); + $productCode = trim((string) ($filters['product_code'] ?? '')); + if ($productCode !== '') { + $candidates->where('s.sku_id', $productCode); + } + $warehouseFilter = trim((string) ($filters['warehouse_provider'] ?? '')); + if ($warehouseFilter !== '') { + $warehouseIds = $this->connection->query()->fromSub( + clone $latestWarehouses, + 'filter_latest_warehouse', + )->join(self::WAREHOUSE_TABLE . ' as filter_warehouse', function ($join): void { + $join->on('filter_warehouse.wms_co_id', '=', 'filter_latest_warehouse.wms_co_id') + ->on('filter_warehouse.Id', '=', 'filter_latest_warehouse.Id'); + }); + $this->containsFilter($warehouseIds, 'filter_warehouse.name', $warehouseFilter); + $candidates->whereIn('pairs.wms_co_id', $warehouseIds->select('filter_warehouse.wms_co_id')); + } + $categoryFilter = trim((string) ($filters['category'] ?? '')); + if ($categoryFilter !== '') { + $this->containsFilter($candidates, 's.category', $categoryFilter); + } + + $total = $includeTotal ? $this->boundedCount(clone $candidates, $queryTimeoutSeconds) : 0; + $pagePairs = (clone $candidates) + ->orderBy('pairs.wms_co_id')->orderBy('pairs.wh_id')->orderBy('s.sku_id') + ->forPage($page, $perPage); + $pairRows = $this->boundedGet(clone $pagePairs, $queryTimeoutSeconds); + if ($pairRows->isEmpty()) { + return [ + 'data' => [], + 'total' => $total, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } + + $dimensionedPagePairs = $this->connection->query()->fromSub($pagePairs, 'pairs') + ->leftJoinSub($latestWarehouses, 'latest_warehouse', 'latest_warehouse.wms_co_id', '=', 'pairs.wms_co_id') + ->leftJoin(self::WAREHOUSE_TABLE . ' as w', function ($join): void { + $join->on('w.wms_co_id', '=', 'latest_warehouse.wms_co_id') + ->on('w.Id', '=', 'latest_warehouse.Id'); + }) + ->select([ + 'pairs.wms_co_id', 'pairs.wh_id', 'pairs.inventory_sku_code', + 'pairs.sku_code', 'pairs.category', 'w.name as warehouse_name', + ]); + $anchors = $this->connection->query()->fromSub($dimensionedPagePairs, 'pairs') + ->leftJoinSub(clone $inventoryDimensions, 'inventory', function ($join): void { + $join->on('inventory.wms_co_id', '=', 'pairs.wms_co_id') + ->on('inventory.inventory_sku_code', '=', 'pairs.inventory_sku_code') + ->on('inventory.wh_id', '=', 'pairs.wh_id'); + }) + ->select([ + 'pairs.wms_co_id', 'pairs.wh_id', 'pairs.inventory_sku_code', + 'pairs.sku_code', 'pairs.category', 'pairs.warehouse_name', + ]) + ->selectRaw('COALESCE(inventory.snapshot_qty, 0) AS snapshot_qty') + ->selectRaw('COALESCE(inventory.captured_at, ?) AS snapshot_at', [$anchorAt]); + + $movements = $this->confirmedMovements($headerGeneration, $itemGeneration, null) + ->where('h.occurred_at', '>=', $rangeStart) + ->where('h.occurred_at', '<', $rangeEnd) + ->whereIn('h.wms_co_id', $pairRows->pluck('wms_co_id')->unique()->values()->all()) + ->whereIn('i.sku_code', $pairRows->pluck('inventory_sku_code')->unique()->values()->all()) + ->select([ + 'h.wms_co_id', 'h.io_type', 'h.occurred_at', 'i.sku_code as inventory_sku_code', + 'i.qty as movement_qty', 'i.qty_type as movement_qty_type', + ]) + ->selectRaw('COALESCE(NULLIF(h.wh_id, 0), 1) AS wh_id'); + $signed = '(COALESCE(mv.movement_qty, 0) * COALESCE(mv.movement_qty_type, 0))'; + $balanceAt = static fn (string $target): array => [ + 'a.snapshot_qty + COALESCE(SUM(CASE ' + . 'WHEN a.snapshot_at < ? AND mv.occurred_at >= a.snapshot_at AND mv.occurred_at < ? THEN ' . $signed . ' ' + . 'WHEN a.snapshot_at >= ? AND mv.occurred_at >= ? AND mv.occurred_at < a.snapshot_at THEN -' . $signed . ' ' + . 'ELSE 0 END), 0)', + [$target, $target, $target, $target], + ]; + [$openingSql, $openingBindings] = $balanceAt($period['start']); + [$closingSql, $closingBindings] = $balanceAt($period['end']); + $monthly = $this->connection->query()->fromSub($anchors, 'a') + ->leftJoinSub($movements, 'mv', function ($join): void { + $join->on('mv.wms_co_id', '=', 'a.wms_co_id') + ->on('mv.wh_id', '=', 'a.wh_id') + ->on('mv.inventory_sku_code', '=', 'a.inventory_sku_code'); + }) + ->groupBy([ + 'a.wms_co_id', 'a.wh_id', 'a.inventory_sku_code', 'a.sku_code', + 'a.category', 'a.warehouse_name', + 'a.snapshot_qty', 'a.snapshot_at', + ]) + ->select(['a.wms_co_id', 'a.wh_id', 'a.sku_code', 'a.category', 'a.warehouse_name']) + ->selectRaw($openingSql . ' AS opening_qty', $openingBindings) + ->selectRaw($closingSql . ' AS closing_qty', $closingBindings); + foreach (self::MOVEMENT_COLUMNS as $column => $type) { + $monthly->selectRaw( + 'COALESCE(SUM(CASE WHEN mv.occurred_at >= ? AND mv.occurred_at < ? ' + . 'AND mv.io_type = ? THEN ' . $signed . ' ELSE 0 END), 0) AS ' . $column, + [$period['start'], $period['end'], $type], + ); + } + $monthly->selectRaw('0 AS opening_aux'); + + $monthlyRows = $this->connection->query()->fromSub($monthly, 'm') + ->select('m.*')->orderBy('m.warehouse_name')->orderBy('m.wh_id')->orderBy('m.sku_code'); + $rows = $this->boundedGet($monthlyRows, $queryTimeoutSeconds) + ->map(function (object $row) use ($period): object { + $warehouse = trim((string) ($row->warehouse_name ?? '')); + $subwarehouseId = (int) ($row->wh_id ?? 0); + $subwarehouse = $this->subwarehouseName($warehouse, $subwarehouseId); + + return (object) [ + 'owner' => (string) config( + 'upstream_mirrors.third_party_warehouse_storage.owner_name', + '常州简尚家居有限公司', + ), + 'month' => Carbon::parse($period['start'])->toDateString(), + 'warehouse_provider' => $warehouse, + 'warehouse' => $subwarehouse, + 'product_code' => (string) ($row->sku_code ?? ''), + 'category' => (string) ($row->category ?? ''), + 'opening_quantity' => $row->opening_qty, + 'closing_quantity' => $row->closing_qty, + 'processing_in' => $row->processing_in, + 'processing_out' => $row->processing_out, + 'purchase_in' => $row->purchase_in, + 'purchase_return' => $row->purchase_return, + 'other_in' => $row->other_in, + 'other_return' => $row->other_return, + 'sales_out' => $row->sales_out, + 'sales_return' => $row->sales_return, + 'stocktake' => $row->stocktake, + 'transfer_out' => $row->transfer_out, + 'transfer_in' => $row->transfer_in, + 'opening' => $row->opening_aux, + 'other_out' => $row->other_out, + ]; + })->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } + + /** + * Read one authoritative month without joining the movement mirror. + * The imported workbook already contains the opening balance, every movement + * column and the closing balance at the requested warehouse/SKU grain. + * + * @param array{start:string,end:string} $period + * @param array $filters + * @param array $state + * @return array{data:list,total:int,state:array,sync:array} + */ + private function paginateCurrentMonthlyInventoryAuthority( + array $period, + array $filters, + int $page, + int $perPage, + bool $includeTotal, + array $state, + ?int $queryTimeoutSeconds, + ): array { + $query = $this->monthlyInventoryAuthoritativeQuery($period, $filters); + if ($query === null) { + return [ + 'data' => [], + 'total' => 0, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } + + $total = $includeTotal ? $this->boundedCount(clone $query, $queryTimeoutSeconds) : 0; + $rows = $this->boundedGet( + (clone $query) + ->orderBy('warehouse_provider') + ->orderBy('warehouse') + ->orderBy('product_code') + ->forPage($page, $perPage), + $queryTimeoutSeconds, + )->map(static function (object $row): object { + return (object) [ + 'owner' => (string) $row->owner, + 'month' => Carbon::parse($row->report_month)->toDateString(), + 'warehouse_provider' => (string) $row->warehouse_provider, + 'warehouse' => (string) $row->warehouse, + 'product_code' => (string) $row->product_code, + 'category' => (string) ($row->category ?? ''), + 'opening_quantity' => $row->opening_quantity, + 'closing_quantity' => $row->closing_quantity, + 'processing_in' => $row->processing_in, + 'processing_out' => $row->processing_out, + 'purchase_in' => $row->purchase_in, + 'purchase_return' => $row->purchase_return, + 'other_in' => $row->other_in, + 'other_return' => $row->other_return, + 'sales_out' => $row->sales_out, + 'sales_return' => $row->sales_return, + 'stocktake' => $row->stocktake, + 'transfer_out' => $row->transfer_out, + 'transfer_in' => $row->transfer_in, + 'opening' => $row->opening, + 'other_out' => $row->other_out, + ]; + })->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } + + private function subwarehouseName(string $warehouseProvider, int $subwarehouseId): string + { + $specialName = self::SPECIAL_SUBWAREHOUSE_NAMES[$warehouseProvider][$subwarehouseId] ?? null; + if ($specialName !== null) { + return $specialName; + } + + $suffix = self::SUBWAREHOUSE_SUFFIXES[$subwarehouseId] ?? '其他子仓(' . $subwarehouseId . ')'; + + return $warehouseProvider === '' ? $suffix : $warehouseProvider . $suffix; + } + + /** + * @param array $filters + * @return Generator + */ + public function exportMonthlyInventoryReportRows(array $filters, int $batchSize = self::REPORT_EXPORT_BATCH_SIZE): Generator + { + $batchSize = min(max($batchSize, 1), self::REPORT_EXPORT_BATCH_SIZE); + $page = 1; + $state = $this->requireReadyState(); + $sourceCounts = null; + $prefetchedMovementRows = $this->prefetchMonthlyMovementRows($filters, $state); + $refreshSourceCounts = true; + $exported = 0; + $expectedTotal = null; + + while (true) { + $result = $this->paginateMonthlyInventoryReport( + $filters, + $page, + $batchSize, + false, + $state, + $sourceCounts, + self::REPORT_EXPORT_QUERY_TIMEOUT_SECONDS, + $prefetchedMovementRows, + $refreshSourceCounts, + ); + $refreshSourceCounts = false; + + if (isset($result['source_counts']) && is_array($result['source_counts'])) { + $sourceCounts = $result['source_counts']; + $expectedTotal ??= array_sum(array_map('intval', $sourceCounts)); + } + + $rows = $result['data'] ?? []; + if ($rows === []) { + return; + } + $rowCount = count($rows); + if ($expectedTotal !== null) { + $remaining = $expectedTotal - $exported; + if ($remaining <= 0) { + return; + } + if ($rowCount > $remaining) { + $rows = array_slice($rows, 0, $remaining); + $rowCount = count($rows); + } + } + foreach ($rows as $row) { + yield $row; + } + $exported += $rowCount; + + // Release the previous batch before constructing the next SQL result. + unset($rows, $result); + if ($rowCount < $batchSize || ($expectedTotal !== null && $exported >= $expectedTotal)) { + return; + } + $page++; + } + } + + /** + * 用户确认的聚水潭月报保留了“仓储方 + 子仓 + 商品”维度。 + * 命中同月权威数据时整月直接读取,不再用当前库存倒推历史子仓余额。 + * + * @param array{start:string,end:string} $period + * @param array $filters + */ + private function monthlyInventoryAuthoritativeQuery(array $period, array $filters): ?Builder + { + try { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::INVENTORY_REPORT_AUTHORITATIVE_STATE_TABLE) + || ! $schema->hasTable(self::INVENTORY_REPORT_AUTHORITATIVE_ROW_TABLE)) { + return null; + } + + $month = Carbon::parse($period['start'])->startOfMonth()->toDateString(); + $authority = $this->currentMonthlyInventoryAuthority($period); + if ($authority === null) { + return null; + } + + $query = $this->connection->table(self::INVENTORY_REPORT_AUTHORITATIVE_ROW_TABLE) + ->where('generation', $authority['generation']) + ->where('report_month', $month) + ->select([ + 'owner', 'report_month', 'warehouse_provider', 'warehouse', + 'product_code', 'category', 'opening_quantity', 'closing_quantity', + 'processing_in', 'processing_out', 'purchase_in', 'purchase_return', + 'other_in', 'other_return', 'sales_out', 'sales_return', 'stocktake', + 'transfer_out', 'transfer_in', 'opening', 'other_out', + ]); + + $productCode = trim((string) ($filters['product_code'] ?? '')); + if ($productCode !== '') { + $query->where('product_code', $productCode); + } + $this->containsFilter($query, 'warehouse_provider', $filters['warehouse_provider'] ?? ''); + $this->containsFilter($query, 'category', $filters['category'] ?? ''); + + return $query; + } catch (Throwable) { + return null; + } + } + + /** + * Every later month starts from the latest authoritative month closing quantity and + * rolls confirmed movements forward to the requested month. Current inventory is + * deliberately ignored because it cannot reproduce historical opening balances. + * + * @param array{start:string,end:string} $period + * @param array $filters + * @param array{generation:string,source_month:string} $authority + * @param array $state + * @return array{data:list,total:int,state:array,sync:array}|null + */ + private function monthlyInventoryRollForward( + array $period, + array $filters, + array $authority, + string $headerGeneration, + string $itemGeneration, + string $inventoryGeneration, + int $page, + int $perPage, + bool $includeTotal, + array $state, + bool $authorityIsCurrentMonth = false, + ?array $sourceCounts = null, + ?int $queryTimeoutSeconds = null, + ?Collection $prefetchedMovementRows = null, + bool $refreshSourceCounts = false, + ): ?array { + try { + $queryTimeoutSeconds ??= self::REPORT_QUERY_TIMEOUT_SECONDS; + $latestProducts = $this->connection->table(self::PRODUCT_TABLE) + ->where('sku_type', 'normal')->whereNotNull('sku_id')->where('sku_id', '!=', '') + ->groupBy('sku_id')->select('sku_id')->selectRaw('MAX(autoid) AS autoid'); + $latestWarehouses = $this->connection->table(self::WAREHOUSE_TABLE) + ->whereNotNull('wms_co_id')->groupBy('wms_co_id') + ->select('wms_co_id')->selectRaw('MAX(Id) AS Id'); + + $authorityRows = $this->connection + ->table(self::INVENTORY_REPORT_AUTHORITATIVE_ROW_TABLE . ' as authority') + ->where('authority.generation', $authority['generation']) + ->where('authority.report_month', $authority['source_month']); + $productCode = trim((string) ($filters['product_code'] ?? '')); + if ($productCode !== '') { + $authorityRows->where('authority.product_code', $productCode); + } + $this->containsFilter($authorityRows, 'authority.warehouse_provider', $filters['warehouse_provider'] ?? ''); + $this->containsFilter($authorityRows, 'authority.category', $filters['category'] ?? ''); + [$authorityWarehouseIdSql, $authorityWarehouseIdBindings] = $this->subwarehouseIdSql( + 'authority.warehouse_provider', + 'authority.warehouse', + ); + $authorityOpeningColumn = $authorityIsCurrentMonth + ? 'authority.opening_quantity' + : 'authority.closing_quantity'; + $authorityCandidates = (clone $authorityRows) + ->leftJoin(self::WAREHOUSE_TABLE . ' as authority_warehouse', function ($join): void { + $join->on('authority_warehouse.name', '=', 'authority.warehouse_provider'); + }) + ->leftJoinSub($latestWarehouses, 'authority_latest_warehouse', function ($join): void { + $join->on('authority_latest_warehouse.wms_co_id', '=', 'authority_warehouse.wms_co_id') + ->on('authority_latest_warehouse.Id', '=', 'authority_warehouse.Id'); + })->selectRaw( + 'authority.owner AS owner, authority.warehouse_provider AS warehouse_provider, ' + . 'authority.warehouse AS source_warehouse, authority_warehouse.wms_co_id AS wms_co_id, ' + . $authorityWarehouseIdSql . ' AS wh_id, authority.product_code AS sku_code, ' + . 'authority.category AS category, ' . $authorityOpeningColumn . ' AS opening_qty', + $authorityWarehouseIdBindings, + ); + $inventoryDimensions = $this->connection->table(self::SUBWAREHOUSE_INVENTORY_TABLE . ' as inventory') + ->where('inventory.generation', $inventoryGeneration) + ->where('inventory.qty', '!=', 0) + ->whereNotNull('inventory.sku_code')->where('inventory.sku_code', '!=', '') + ->joinSub($latestProducts, 'latest_product', 'latest_product.sku_id', '=', 'inventory.sku_code') + ->join(self::PRODUCT_TABLE . ' as s', function ($join): void { + $join->on('s.sku_id', '=', 'latest_product.sku_id') + ->on('s.autoid', '=', 'latest_product.autoid'); + }) + ->joinSub($latestWarehouses, 'latest_warehouse', 'latest_warehouse.wms_co_id', '=', 'inventory.wms_co_id') + ->join(self::WAREHOUSE_TABLE . ' as w', function ($join): void { + $join->on('w.wms_co_id', '=', 'latest_warehouse.wms_co_id') + ->on('w.Id', '=', 'latest_warehouse.Id'); + }); + if ($productCode !== '') { + $inventoryDimensions->where('s.sku_id', $productCode); + } + $this->containsFilter($inventoryDimensions, 'w.name', $filters['warehouse_provider'] ?? ''); + $this->containsFilter($inventoryDimensions, 's.category', $filters['category'] ?? ''); + $owner = (string) config( + 'upstream_mirrors.third_party_warehouse_storage.owner_name', + '常州简尚家居有限公司', + ); + [$inventoryWarehouseSql, $inventoryWarehouseBindings] = $this->subwarehouseNameSql( + 'w.name', + 'inventory.wh_id', + ); + $inventoryDimensions->whereNotExists(function (Builder $prior) use ( + $authority, + $inventoryWarehouseSql, + $inventoryWarehouseBindings, + ): void { + $prior->selectRaw('1') + ->from(self::INVENTORY_REPORT_AUTHORITATIVE_ROW_TABLE . ' as prior') + ->where('prior.generation', $authority['generation']) + ->where('prior.report_month', $authority['source_month']) + ->whereColumn('prior.product_code', 'inventory.sku_code') + ->whereColumn('prior.warehouse_provider', 'w.name') + ->whereRaw('prior.warehouse = ' . $inventoryWarehouseSql, $inventoryWarehouseBindings); + }); + $inventoryDimensions->distinct() + ->selectRaw( + '? AS owner, w.name AS warehouse_provider, ' + . $inventoryWarehouseSql . ' AS source_warehouse, ' + . 'inventory.wms_co_id AS wms_co_id, inventory.wh_id AS wh_id, ' + . 'inventory.sku_code AS sku_code, s.category AS category, 0 AS opening_qty', + array_merge([$owner], $inventoryWarehouseBindings), + ); + + $authorityEnd = Carbon::parse($authority['source_month']) + ->addMonth()->startOfMonth()->format('Y-m-d 00:00:00'); + $movementStart = $authorityIsCurrentMonth ? $period['start'] : $authorityEnd; + $movementWarehouseIdSql = 'COALESCE(NULLIF(h.wh_id, 0), 1)'; + $movementPairs = $this->confirmedMovements($headerGeneration, $itemGeneration, null) + ->where('h.occurred_at', '>=', $movementStart) + ->where('h.occurred_at', '<', $period['end']) + ->where('i.qty', '!=', 0) + ->where('i.qty_type', '!=', 0) + ->select('h.wms_co_id', 'i.sku_code') + ->selectRaw($movementWarehouseIdSql . ' AS wh_id') + ->distinct(); + if ($productCode !== '') { + $movementPairs->where('i.sku_code', $productCode); + } + $movementDimensions = $this->connection->query()->fromSub($movementPairs, 'movement_pair') + ->joinSub($latestWarehouses, 'movement_latest_warehouse', 'movement_latest_warehouse.wms_co_id', '=', 'movement_pair.wms_co_id') + ->join(self::WAREHOUSE_TABLE . ' as movement_warehouse', function ($join): void { + $join->on('movement_warehouse.wms_co_id', '=', 'movement_latest_warehouse.wms_co_id') + ->on('movement_warehouse.Id', '=', 'movement_latest_warehouse.Id'); + }); + $this->containsFilter($movementDimensions, 'movement_warehouse.name', $filters['warehouse_provider'] ?? ''); + [$movementWarehouseSql, $movementWarehouseBindings] = $this->subwarehouseNameSql( + 'movement_warehouse.name', + 'movement_pair.wh_id', + ); + $movementDimensions->whereNotExists(function (Builder $prior) use ( + $authority, + $movementWarehouseSql, + $movementWarehouseBindings, + ): void { + $prior->selectRaw('1') + ->from(self::INVENTORY_REPORT_AUTHORITATIVE_ROW_TABLE . ' as prior') + ->where('prior.generation', $authority['generation']) + ->where('prior.report_month', $authority['source_month']) + ->whereColumn('prior.product_code', 'movement_pair.sku_code') + ->whereColumn('prior.warehouse_provider', 'movement_warehouse.name') + ->whereRaw('prior.warehouse = ' . $movementWarehouseSql, $movementWarehouseBindings); + }); + if (! $authorityIsCurrentMonth) { + $movementDimensions->whereNotExists(function (Builder $snapshot) use ($inventoryGeneration): void { + $snapshot->selectRaw('1') + ->from(self::SUBWAREHOUSE_INVENTORY_TABLE . ' as matching_inventory') + ->where('matching_inventory.generation', $inventoryGeneration) + ->where('matching_inventory.qty', '!=', 0) + ->whereColumn('matching_inventory.wms_co_id', 'movement_pair.wms_co_id') + ->whereRaw('COALESCE(NULLIF(matching_inventory.wh_id, 0), 1) = movement_pair.wh_id') + ->whereColumn('matching_inventory.sku_code', 'movement_pair.sku_code'); + }); + } + $movementCount = clone $movementDimensions; + if (trim((string) ($filters['category'] ?? '')) === '') { + $movementCount->whereExists(function (Builder $product): void { + $product->selectRaw('1')->from(self::PRODUCT_TABLE . ' as known_product') + ->where('known_product.sku_type', 'normal') + ->whereColumn('known_product.sku_id', 'movement_pair.sku_code'); + })->selectRaw('1 AS counted'); + } + $movementDimensions->joinSub($latestProducts, 'movement_latest_product', 'movement_latest_product.sku_id', '=', 'movement_pair.sku_code') + ->join(self::PRODUCT_TABLE . ' as movement_product', function ($join): void { + $join->on('movement_product.sku_id', '=', 'movement_latest_product.sku_id') + ->on('movement_product.autoid', '=', 'movement_latest_product.autoid'); + }); + $this->containsFilter($movementDimensions, 'movement_product.category', $filters['category'] ?? ''); + if (trim((string) ($filters['category'] ?? '')) !== '') { + $movementCount = (clone $movementDimensions)->selectRaw('1 AS counted'); + } + $movementDimensions->selectRaw( + '? AS owner, movement_warehouse.name AS warehouse_provider, ' + . $movementWarehouseSql . ' AS source_warehouse, ' + . 'movement_pair.wms_co_id AS wms_co_id, movement_pair.wh_id AS wh_id, ' + . 'movement_pair.sku_code AS sku_code, movement_product.category AS category, 0 AS opening_qty', + array_merge([$owner], $movementWarehouseBindings), + ); + + $sources = $authorityIsCurrentMonth + ? [ + [$authorityCandidates, $authorityCandidates, 'authority.warehouse_provider', 'authority.product_code'], + [$movementDimensions, $movementCount, 'movement_warehouse.name', 'movement_pair.sku_code'], + ] + : [ + [$authorityCandidates, $authorityCandidates, 'authority.warehouse_provider', 'authority.product_code'], + [$inventoryDimensions, $inventoryDimensions, 'w.name', 'inventory.sku_code'], + [$movementDimensions, $movementCount, 'movement_warehouse.name', 'movement_pair.sku_code'], + ]; + $counts = is_array($sourceCounts) ? array_values($sourceCounts) : []; + $total = 0; + $countCacheKey = $this->monthlyInventoryReportCacheKey( + $period, $filters, $authority, $headerGeneration, $itemGeneration, + $inventoryGeneration, 0, 0, + ) . ':source-counts'; + if ($includeTotal || $counts === [] || $refreshSourceCounts) { + $cachedCounts = $refreshSourceCounts ? null : Cache::get($countCacheKey); + if (is_array($cachedCounts) && count($cachedCounts) === count($sources)) { + $counts = array_values($cachedCounts); + } else { + foreach ($sources as $index => [, $countQuery]) { + $counts[$index] = $this->boundedCount(clone $countQuery, $queryTimeoutSeconds); + } + Cache::put($countCacheKey, $counts, self::REPORT_CACHE_SECONDS); + } + } + if ($includeTotal) { + $total = array_sum($counts); + } + $offset = ($page - 1) * $perPage; + $remaining = $perPage; + $candidatePages = []; + foreach ($sources as $index => [$candidates, $countQuery, $warehouseOrder, $productOrder]) { + if ($remaining === 0) { + break; + } + $sourceTotal = $counts[$index] ?? null; + if ($sourceTotal !== null && $offset >= $sourceTotal) { + $offset -= $sourceTotal; + continue; + } + $limit = $sourceTotal === null ? $remaining : min($remaining, $sourceTotal - $offset); + $candidatePages[] = (clone $candidates) + ->orderBy($warehouseOrder) + ->orderBy('wh_id') + ->orderBy($productOrder) + ->offset($offset) + ->limit($limit); + $remaining -= $limit; + $offset = 0; + } + + if ($candidatePages === []) { + return [ + 'data' => [], + 'total' => $total, + 'source_counts' => $counts, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } + + $pageCandidates = array_shift($candidatePages); + foreach ($candidatePages as $candidatePage) { + $pageCandidates->unionAll($candidatePage); + } + $pairRows = $this->boundedGet(clone $pageCandidates, $queryTimeoutSeconds); + if ($pairRows->isEmpty()) { + return [ + 'data' => [], + 'total' => $total, + 'source_counts' => $counts, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } + + $movementPairs = $pairRows->filter( + static fn (object $row): bool => $row->wms_co_id !== null && trim((string) $row->sku_code) !== '', + )->unique(static fn (object $row): string => implode(':', [ + (string) $row->wms_co_id, + (string) $row->wh_id, + (string) $row->sku_code, + ]))->values(); + $movementRows = $prefetchedMovementRows ?? collect(); + if ($movementPairs->isNotEmpty()) { + if ($prefetchedMovementRows === null) { + $movements = $this->aggregateMonthlyMovementQuery( + $period, + $authorityEnd, + $movementStart, + $headerGeneration, + $itemGeneration, + ); + $movementRows = $this->boundedGet($movements, $queryTimeoutSeconds)->keyBy( + static fn (object $row): string => implode(':', [ + (string) $row->wms_co_id, + (string) $row->wh_id, + (string) $row->sku_code, + ]), + ); + } + } + + $rows = $pairRows->map(function (object $row) use ($movementRows, $period): object { + $key = implode(':', [(string) $row->wms_co_id, (string) $row->wh_id, (string) $row->sku_code]); + $movement = $movementRows->get($key); + $sourceWarehouse = trim((string) ($row->source_warehouse ?? '')); + $warehouse = $sourceWarehouse !== '' + ? $sourceWarehouse + : $this->subwarehouseName( + trim((string) $row->warehouse_provider), + (int) $row->wh_id, + ); + $rolledOpening = (float) $row->opening_qty + (float) ($movement->rolled_opening_delta ?? 0); + $closingQuantity = $rolledOpening; + foreach (array_keys(self::MOVEMENT_COLUMNS) as $column) { + $closingQuantity += (float) ($movement->{$column} ?? 0); + } + + return (object) [ + 'owner' => $row->owner, + 'month' => Carbon::parse($period['start'])->toDateString(), + 'warehouse_provider' => $row->warehouse_provider, + 'warehouse' => $warehouse, + 'product_code' => $row->sku_code, + 'category' => $row->category, + 'opening_quantity' => $rolledOpening, + 'closing_quantity' => $closingQuantity, + 'processing_in' => $movement->processing_in ?? 0, + 'processing_out' => $movement->processing_out ?? 0, + 'purchase_in' => $movement->purchase_in ?? 0, + 'purchase_return' => $movement->purchase_return ?? 0, + 'other_in' => $movement->other_in ?? 0, + 'other_return' => $movement->other_return ?? 0, + 'sales_out' => $movement->sales_out ?? 0, + 'sales_return' => $movement->sales_return ?? 0, + 'stocktake' => $movement->stocktake ?? 0, + 'transfer_out' => $movement->transfer_out ?? 0, + 'transfer_in' => $movement->transfer_in ?? 0, + 'opening' => 0, + 'other_out' => $movement->other_out ?? 0, + ]; + })->all(); + + return [ + 'data' => $rows, + 'total' => $total, + 'source_counts' => $counts, + 'state' => $state, + 'sync' => $this->syncStatus($state), + ]; + } catch (Throwable $exception) { + if ($this->isStatementTimeout($exception)) { + throw $exception; + } + report($exception); + + return null; + } + } + + /** + * Aggregate the complete movement range once for a full export. The normal + * page query intentionally limits movements to the current page, but doing + * that for every export batch repeats the same expensive scan thousands of + * times. The result is keyed by warehouse, subwarehouse and SKU so each + * page can perform an O(1) lookup. + * + * @param array $filters + * @param array $state + * @return Collection|null + */ + private function prefetchMonthlyMovementRows(array $filters, array $state): ?Collection + { + $period = $this->inventoryReportPeriod((string) ($filters['month'] ?? '')); + $headerGeneration = $this->generation($state, 'active_header_generation'); + $itemGeneration = $this->generation($state, 'active_item_generation'); + if ($headerGeneration === null || $itemGeneration === null) { + return null; + } + + $currentAuthority = $this->currentMonthlyInventoryAuthority($period); + if ($currentAuthority !== null) { + // The current authoritative month already contains all movement + // columns; exporting it must not scan the mirror movement tables. + return collect(); + } + $authority = $currentAuthority ?? $this->previousMonthlyInventoryAuthority($period); + if ($authority === null) { + return null; + } + + $authorityEnd = Carbon::parse($authority['source_month']) + ->addMonth()->startOfMonth()->format('Y-m-d 00:00:00'); + $movementStart = $currentAuthority !== null ? $period['start'] : $authorityEnd; + $query = $this->aggregateMonthlyMovementQuery( + $period, + $authorityEnd, + $movementStart, + $headerGeneration, + $itemGeneration, + ); + + return $this->boundedGet($query, self::REPORT_EXPORT_AGGREGATE_TIMEOUT_SECONDS)->keyBy( + static fn (object $row): string => implode(':', [ + (string) $row->wms_co_id, + (string) $row->wh_id, + (string) $row->sku_code, + ]), + ); + } + + /** + * @param array{start:string,end:string} $period + */ + private function aggregateMonthlyMovementQuery( + array $period, + string $authorityEnd, + string $movementStart, + string $headerGeneration, + string $itemGeneration, + ): Builder { + $movements = $this->confirmedMovements($headerGeneration, $itemGeneration, null) + ->where('h.occurred_at', '>=', $movementStart) + ->where('h.occurred_at', '<', $period['end']) + ->groupBy(['h.wms_co_id', 'i.sku_code']) + ->groupByRaw('COALESCE(NULLIF(h.wh_id, 0), 1)') + ->select(['h.wms_co_id', 'i.sku_code']) + ->selectRaw('COALESCE(NULLIF(h.wh_id, 0), 1) AS wh_id'); + $signed = '(COALESCE(i.qty, 0) * COALESCE(i.qty_type, 0))'; + $movements->selectRaw( + 'COALESCE(SUM(CASE WHEN h.occurred_at >= ? AND h.occurred_at < ? ' + . 'THEN ' . $signed . ' ELSE 0 END), 0) AS rolled_opening_delta', + [$authorityEnd, $period['start']], + ); + foreach (self::MOVEMENT_COLUMNS as $column => $type) { + $expression = 'COALESCE(SUM(CASE WHEN h.occurred_at >= ? AND h.occurred_at < ? ' + . 'AND h.io_type = ? THEN ' . $signed . ' ELSE 0 END), 0)'; + $movements->selectRaw($expression . ' AS ' . $column, [$period['start'], $period['end'], $type]); + } + + return $movements; + } + + /** + * @param array{start:string,end:string} $period + * @param array $filters + * @param array{generation:string,source_month:string} $authority + */ + private function monthlyInventoryReportCacheKey( + array $period, + array $filters, + array $authority, + string $headerGeneration, + string $itemGeneration, + string $inventoryGeneration, + int $page, + int $perPage, + ): string { + $normalizedFilters = [ + 'product_code' => trim((string) ($filters['product_code'] ?? '')), + 'warehouse_provider' => trim((string) ($filters['warehouse_provider'] ?? '')), + 'category' => trim((string) ($filters['category'] ?? '')), + ]; + + return 'inventory-report:monthly-page:v10:' . hash('sha256', (string) json_encode([ + 'period' => $period, + 'filters' => $normalizedFilters, + 'authority' => $authority, + 'header_generation' => $headerGeneration, + 'item_generation' => $itemGeneration, + 'inventory_generation' => $inventoryGeneration, + 'page' => $page, + 'per_page' => $perPage, + ], JSON_UNESCAPED_UNICODE)); + } + + /** @param callable():?array $resolver */ + private function rememberMonthlyInventoryReport(string $key, callable $resolver): ?array + { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + try { + return Cache::lock($key . ':lock', self::REPORT_CACHE_LOCK_SECONDS) + ->block(self::REPORT_CACHE_WAIT_SECONDS, function () use ($key, $resolver): ?array { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + $resolved = $resolver(); + if (is_array($resolved)) { + Cache::put($key, $resolved, self::REPORT_CACHE_SECONDS); + } + + return $resolved; + }); + } catch (LockTimeoutException $exception) { + $cached = Cache::get($key); + if (is_array($cached)) { + return $cached; + } + + throw new RuntimeException('inventory_report_generation_busy', 0, $exception); + } + } + + /** @param array{start:string,end:string} $period */ + private function currentMonthlyInventoryAuthority(array $period): ?array + { + $month = Carbon::parse($period['start'])->startOfMonth(); + $state = $this->monthlyAuthorityStateQuery() + ?->whereDate('source_month', '=', $month->toDateString()) + ->first(); + if ($state === null) { + $state = $this->connection->table(self::INVENTORY_REPORT_AUTHORITATIVE_STATE_TABLE) + ->where('dataset_key', self::INVENTORY_REPORT_AUTHORITATIVE_DATASET_KEY) + ->whereNotNull('active_generation') + ->whereDate('source_month', '=', $month->toDateString()) + ->first(); + } + if ($state === null || trim((string) $state->active_generation) === '') { + return null; + } + + return [ + 'generation' => (string) $state->active_generation, + 'source_month' => $month->toDateString(), + ]; + } + + /** @param array{start:string,end:string} $period */ + private function previousMonthlyInventoryAuthority(array $period): ?array + { + $month = Carbon::parse($period['start'])->startOfMonth(); + $state = $this->monthlyAuthorityStateQuery() + ?->whereDate('source_month', '<', $month) + ->orderByDesc('source_month') + ->first(); + if ($state === null) { + $state = $this->connection->table(self::INVENTORY_REPORT_AUTHORITATIVE_STATE_TABLE) + ->where('dataset_key', self::INVENTORY_REPORT_AUTHORITATIVE_DATASET_KEY) + ->whereNotNull('active_generation') + ->whereDate('source_month', '<', $month) + ->orderByDesc('source_month') + ->first(); + } + if ($state === null || trim((string) $state->active_generation) === '') { + return null; + } + + return [ + 'generation' => (string) $state->active_generation, + 'source_month' => Carbon::parse($state->source_month)->startOfMonth()->toDateString(), + ]; + } + + private function monthlyAuthorityStateQuery(): ?Builder + { + try { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable('inventory_report_authoritative_months')) { + return null; + } + + return $this->connection->table('inventory_report_authoritative_months') + ->where('dataset_key', self::INVENTORY_REPORT_AUTHORITATIVE_DATASET_KEY) + ->where('status', 'succeeded') + ->whereNotNull('active_generation'); + } catch (Throwable) { + return null; + } + } + + /** @return array{0:string,1:list} */ + private function subwarehouseIdSql(string $providerColumn, string $warehouseColumn): array + { + $cases = []; + $bindings = []; + foreach (self::SPECIAL_SUBWAREHOUSE_NAMES as $provider => $names) { + foreach ($names as $id => $name) { + $cases[] = "WHEN {$providerColumn} = ? AND {$warehouseColumn} = ? THEN {$id}"; + array_push($bindings, $provider, $name); + } + } + foreach (self::SUBWAREHOUSE_SUFFIXES as $id => $suffix) { + $cases[] = 'WHEN ' . $warehouseColumn . ' = ' + . $this->concatSql([$providerColumn, '?']) . " THEN {$id}"; + $bindings[] = $suffix; + } + + return ['CASE ' . implode(' ', $cases) . ' ELSE -1 END', $bindings]; + } + + /** @return array{0:string,1:list} */ + private function subwarehouseNameSql(string $providerColumn, string $subwarehouseColumn): array + { + $cases = []; + $bindings = []; + foreach (self::SPECIAL_SUBWAREHOUSE_NAMES as $provider => $names) { + foreach ($names as $id => $name) { + $cases[] = "WHEN {$providerColumn} = ? AND {$subwarehouseColumn} = {$id} THEN ?"; + array_push($bindings, $provider, $name); + } + } + foreach (self::SUBWAREHOUSE_SUFFIXES as $id => $suffix) { + $cases[] = "WHEN {$subwarehouseColumn} = {$id} THEN " . $this->concatSql([$providerColumn, '?']); + $bindings[] = $suffix; + } + + $fallback = $this->concatSql([$providerColumn, "'其他子仓('", $subwarehouseColumn, "')'"]); + + return ['CASE ' . implode(' ', $cases) . ' ELSE ' . $fallback . ' END', $bindings]; + } + + /** @param list $parts */ + private function concatSql(array $parts): string + { + return $this->connection->getDriverName() === 'sqlite' + ? '(' . implode(' || ', $parts) . ')' + : 'CONCAT(' . implode(', ', $parts) . ')'; + } + /** * @param array $filters * @return array{count:int,opening_qty:float,closing_qty:float} @@ -536,15 +1693,22 @@ class ThirdPartyWarehouseStorageMirrorRepository return $dates; } - private function confirmedMovements(string $headerGeneration, string $itemGeneration): Builder + private function confirmedMovements( + string $headerGeneration, + string $itemGeneration, + ?int $warehouseId = self::WAREHOUSE_ID, + ): Builder { - return $this->connection->table(self::ITEM_TABLE . ' as i') - ->join(self::HEADER_TABLE . ' as h', function ($join) use ($headerGeneration): void { - $join->on('h.io_id', '=', 'i.io_id') - ->where('h.generation', '=', $headerGeneration); - }) - ->where('i.generation', $itemGeneration) - ->where('h.wms_co_id', self::WAREHOUSE_ID) + $query = $this->connection->table(self::HEADER_TABLE . ' as h'); + // MariaDB otherwise scans every historical header for the all-warehouse roll-forward. + if ($warehouseId === null && $this->connection->getDriverName() === 'mysql') { + $query->forceIndex('tpw_headers_report_index'); + } + $query->join(self::ITEM_TABLE . ' as i', function ($join) use ($itemGeneration): void { + $join->on('i.io_id', '=', 'h.io_id') + ->where('i.generation', '=', $itemGeneration); + }) + ->where('h.generation', $headerGeneration) ->where('h.status', 'Confirmed') ->whereIn('h.io_type', array_values(self::MOVEMENT_COLUMNS)) ->whereNotExists(function (Builder $newer) use ($headerGeneration): void { @@ -554,6 +1718,12 @@ class ThirdPartyWarehouseStorageMirrorRepository ->whereColumn('newer.id', '>', 'h.id'); }) ->whereNotNull('i.sku_code')->where('i.sku_code', '!=', ''); + + if ($warehouseId !== null) { + $query->where('h.wms_co_id', $warehouseId); + } + + return $query; } /** @@ -613,6 +1783,31 @@ class ThirdPartyWarehouseStorageMirrorRepository ]; } + /** @return array{dimension:string,value:string,start:string,end:string,days:int} */ + private function inventoryReportPeriod(string $month): array + { + try { + $start = preg_match('/^\d{4}-\d{2}$/', trim($month)) === 1 + ? Carbon::createFromFormat('!Y-m', trim($month))->startOfMonth() + : now()->startOfMonth(); + } catch (Throwable) { + $start = now()->startOfMonth(); + } + + $minimum = Carbon::parse(self::INVENTORY_REPORT_START_DATE)->startOfMonth(); + if ($start->lt($minimum)) { + $start = $minimum; + } + + return [ + 'dimension' => 'month', + 'value' => $start->format('Y-m'), + 'start' => $start->format('Y-m-d 00:00:00'), + 'end' => $start->copy()->addMonth()->format('Y-m-d 00:00:00'), + 'days' => $start->daysInMonth, + ]; + } + /** @param array $state */ private function stateAnchor(array $state): string { @@ -775,6 +1970,23 @@ class ThirdPartyWarehouseStorageMirrorRepository } } + private function warehouseDependencyReady(): bool + { + try { + if (! $this->connection->getSchemaBuilder()->hasTable(self::WAREHOUSE_TABLE)) { + return false; + } + + return $this->connection->table(self::GENERIC_STATE_TABLE) + ->where('dataset_key', self::WAREHOUSE_DATASET_KEY) + ->whereNotNull('initial_completed_at') + ->whereIn('status', ['succeeded', 'running', 'failed']) + ->exists(); + } catch (Throwable) { + return false; + } + } + /** @param array $state */ private function generation(array $state, string $key): ?string { @@ -856,4 +2068,36 @@ class ThirdPartyWarehouseStorageMirrorRepository { return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value) . '%'; } + + /** @return Collection */ + private function boundedGet(Builder $query, ?int $timeoutSeconds = null): Collection + { + if ($this->connection->getDriverName() !== 'mysql') { + return $query->get(); + } + + $timeoutSeconds = max(1, $timeoutSeconds ?? self::REPORT_QUERY_TIMEOUT_SECONDS); + + return collect($this->connection->select( + 'SET STATEMENT max_statement_time=' . $timeoutSeconds . ' FOR ' . $query->toSql(), + $query->getBindings(), + )); + } + + private function boundedCount(Builder $query, ?int $timeoutSeconds = null): int + { + $count = $this->connection->query() + ->fromSub($query, 'bounded_count') + ->selectRaw('COUNT(*) AS aggregate'); + + return (int) ($this->boundedGet($count, $timeoutSeconds)->first()->aggregate ?? 0); + } + + private function isStatementTimeout(Throwable $exception): bool + { + $message = strtolower($exception->getMessage()); + + return str_contains($message, 'max_statement_time') + || str_contains($message, 'query execution was interrupted'); + } } diff --git a/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageUpstreamRepository.php b/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageUpstreamRepository.php index a128dfac..d80c3e97 100644 --- a/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageUpstreamRepository.php +++ b/modules/EcommerceFinance/Repositories/ThirdPartyWarehouseStorageUpstreamRepository.php @@ -9,9 +9,10 @@ class ThirdPartyWarehouseStorageUpstreamRepository { public const SOURCE_KEY = 'jiansun'; + /** 三方仓页面仍固定读取该仓;共享流水镜像覆盖全部仓库。 */ public const WAREHOUSE_ID = 15045364; - public const START_DATE = '2026-08-01'; + public const START_DATE = '2026-07-01'; private ?UpstreamReadOnlyQuery $query = null; @@ -22,8 +23,7 @@ class ThirdPartyWarehouseStorageUpstreamRepository public function headerHighWatermark(): int { return (int) $this->query()->scalar( - 'SELECT COALESCE(MAX([Id]), 0) FROM [dbo].[jst_inoutWater] WHERE [wms_co_id] = ?', - [self::WAREHOUSE_ID], + 'SELECT COALESCE(MAX([Id]), 0) FROM [dbo].[jst_inoutWater]', ); } @@ -39,6 +39,7 @@ SELECT h.[Id] AS source_id, h.[io_id], h.[wms_co_id], + h.[wh_id], h.[status], h.[type] AS io_type, CONVERT(varchar(27), h.[io_date], 126) AS occurred_at, @@ -46,14 +47,13 @@ SELECT FROM [dbo].[jst_inoutWater] h WHERE h.[Id] > ? AND h.[Id] <= ? - AND h.[wms_co_id] = ? AND h.[io_date] >= ? AND NOT EXISTS ( SELECT 1 FROM [dbo].[jst_inoutWater] newer WHERE newer.[io_id] = h.[io_id] AND newer.[Id] > h.[Id] ) ORDER BY h.[Id] -SQL, [$afterId, $throughId, self::WAREHOUSE_ID, self::START_DATE]); +SQL, [$afterId, $throughId, self::START_DATE]); } /** @return list> */ @@ -70,6 +70,7 @@ SQL, [$afterId, $throughId, self::WAREHOUSE_ID, self::START_DATE]); [Id] AS source_id, [io_id], [wms_co_id], + [wh_id], [status], [type] AS io_type, CONVERT(varchar(27), [io_date], 126) AS occurred_at, @@ -103,7 +104,7 @@ SQL, [$cursorAt, $throughAt, $cursorAt, $cursorAt, $cursorId]); foreach (array_chunk($ioIds, 500) as $chunk) { $placeholders = implode(',', array_fill(0, count($chunk), '?')); $batch = $this->query()->select( - 'SELECT h.[Id] AS source_id, h.[io_id], h.[wms_co_id], h.[status], ' + 'SELECT h.[Id] AS source_id, h.[io_id], h.[wms_co_id], h.[wh_id], h.[status], ' . 'h.[type] AS io_type, CONVERT(varchar(27), h.[io_date], 126) AS occurred_at, ' . 'CONVERT(varchar(27), h.[modified], 126) AS modified_at ' . 'FROM [dbo].[jst_inoutWater] h ' @@ -165,8 +166,7 @@ SQL, [$cursorAt, $throughAt, $cursorAt, $cursorAt, $cursorId]); public function inventoryHighWatermark(): int { return (int) $this->query()->scalar( - 'SELECT COALESCE(MAX([Id]), 0) FROM [dbo].[jst_inventoryInfo] WHERE [wms_co_id] = ?', - [self::WAREHOUSE_ID], + 'SELECT COALESCE(MAX([Id]), 0) FROM [dbo].[jst_inventoryInfo]', ); } @@ -185,13 +185,18 @@ SQL, [$cursorAt, $throughAt, $cursorAt, $cursorAt, $cursorId]); [wms_co_id], [sku_id] AS sku_code, [qty], + [return_qty], + [in_qty], + [defective_qty], + [customize_qty_1], + [customize_qty_2], + [customize_qty_3], CONVERT(varchar(27), [modified], 126) AS source_modified_at FROM [dbo].[jst_inventoryInfo] WHERE [Id] > ? AND [Id] <= ? - AND [wms_co_id] = ? ORDER BY [Id] -SQL, [$afterId, $highWatermark, self::WAREHOUSE_ID]); +SQL, [$afterId, $highWatermark]); } private function query(): UpstreamReadOnlyQuery diff --git a/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php b/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php new file mode 100644 index 00000000..e5bf0197 --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php @@ -0,0 +1,302 @@ + '淘宝', + 'taobao-wechat' => '淘宝', + 'pinduoduo' => '拼多多', + 'jd-transactions' => '京东', + 'jingxi' => '京喜', + 'jd-wallet' => '京东', + 'douyin' => '抖音', + 'dewu' => '得物', + 'vipshop' => '唯品会MP', + 'vipshop-jx' => '唯品会jx', + ]; + + /** + * 页签 → 该页签可能出现的平台。 + * + * 大部分页签只有一个平台;淘系支付宝与淘系微信账户同一页签内混有 + * 天猫/淘宝/阿里巴巴的原始店铺,需要按店铺名前缀再分平台。 + */ + private const TAB_PLATFORMS = [ + 'taobao-alipay' => ['淘宝', '天猫', '阿里巴巴'], + 'taobao-wechat' => ['淘宝', '天猫'], + 'pinduoduo' => ['拼多多'], + 'jd-transactions' => ['京东'], + 'jingxi' => ['京喜'], + 'jd-wallet' => ['京东'], + 'douyin' => ['抖音'], + 'dewu' => ['得物'], + 'vipshop' => ['唯品会MP'], + 'vipshop-jx' => ['唯品会jx'], + ]; + + /** 店铺名前缀可识别的平台(顺序敏感:先长后短)。 */ + private const STORE_PREFIX_PLATFORMS = [ + '唯品会JX' => '唯品会jx', + '唯品会MP' => '唯品会MP', + '阿里巴巴' => '阿里巴巴', + '拼多多' => '拼多多', + '天猫' => '天猫', + '淘宝' => '淘宝', + '抖音' => '抖音', + '得物' => '得物', + '京喜' => '京喜', + '京东' => '京东', + ]; + + /** + * @return array> [platform => [bill_item => ledger_remark]] + */ + public function map(): array + { + return Cache::rememberForever(self::CACHE_KEY, function (): array { + try { + if (! Schema::hasTable('ec_account_ledger_remarks')) { + return []; + } + + $map = []; + foreach (\Illuminate\Support\Facades\DB::table('ec_account_ledger_remarks') + ->select(['platform', 'bill_item', 'ledger_remark']) + ->get() as $row) { + $platform = trim((string) $row->platform); + $item = trim((string) $row->bill_item); + if ($platform === '' || $item === '') { + continue; + } + $map[$platform][$item] = (string) $row->ledger_remark; + } + + return $map; + } catch (Throwable) { + return []; + } + }); + } + + public function forget(): void + { + Cache::forget(self::CACHE_KEY); + } + + /** 页签默认平台。 */ + public function defaultPlatform(string $tab): ?string + { + return self::TAB_PLATFORM[$tab] ?? null; + } + + /** 页签涉及的平台(筛选下拉与账单项目翻译共用)。 */ + public function platformsForTab(string $tab): array + { + if (isset(self::TAB_PLATFORMS[$tab])) { + return self::TAB_PLATFORMS[$tab]; + } + + $default = $this->defaultPlatform($tab); + + return $default === null ? [] : [$default]; + } + + /** 平台 → 店铺名前缀(一个平台可能对应多个前缀)。 */ + private function prefixesForPlatform(string $platform): array + { + $prefixes = []; + foreach (self::STORE_PREFIX_PLATFORMS as $prefix => $candidate) { + if ($candidate === $platform) { + $prefixes[] = $prefix; + } + } + + return $prefixes; + } + + /** 页签可选的「总账备注」(该页签涉及平台的去重并集)。 */ + public function remarksForTab(string $tab): array + { + $map = $this->map(); + $remarks = []; + foreach ($this->platformsForTab($tab) as $platform) { + foreach (array_values($map[$platform] ?? []) as $remark) { + $remark = trim((string) $remark); + if ($remark !== '') { + $remarks[$remark] = true; + } + } + } + + $list = array_keys($remarks); + sort($list, SORT_NATURAL | SORT_FLAG_CASE); + + return $list; + } + + /** + * 「总账备注」→ 按平台分组的账单项目集合。 + * + * 单平台页签只有一组、且不做店铺名前缀限制,可直接 whereIn(bill_item, items); + * 多平台页签(淘系支付宝 / 淘系微信)必须连店铺名前缀一起过滤,才能与页面上 + * 按「店铺名前缀 → 平台 + 账单项目」逐行取到的总账备注完全一致。 + * + * @return list,excludePrefixes:list,items:list,isDefault:bool}> + */ + public function billItemGroupsForTab(string $tab, ?string $remark): array + { + $want = trim((string) $remark); + if ($want === '') { + return []; + } + + $map = $this->map(); + if ($map === []) { + return []; + } + + $platforms = $this->platformsForTab($tab); + $single = count($platforms) <= 1; + $default = $this->defaultPlatform($tab); + $known = array_keys(self::STORE_PREFIX_PLATFORMS); + + $groups = []; + foreach ($platforms as $platform) { + $items = []; + foreach ($map[$platform] ?? [] as $item => $value) { + if (trim((string) $value) === $want) { + $items[] = (string) $item; + } + } + if ($items === []) { + continue; + } + sort($items); + + $prefixes = $single ? [] : $this->prefixesForPlatform($platform); + $isDefault = ! $single && $platform === $default; + + $groups[] = [ + 'platform' => $platform, + // 单平台页签不做店铺名前缀限制(页签本身就是该平台口径)。 + 'prefixes' => $prefixes, + // 默认平台还要包含「没有已知平台前缀」的店铺。 + 'excludePrefixes' => $isDefault ? array_values(array_diff($known, $prefixes)) : [], + 'items' => $items, + 'isDefault' => $isDefault, + ]; + } + + return $groups; + } + + /** 「总账备注」→ 该页签全部相关账单项目(多平台页签为各平台并集)。 */ + public function billItemsForTab(string $tab, ?string $remark): array + { + $items = []; + foreach ($this->billItemGroupsForTab($tab, $remark) as $group) { + foreach ($group['items'] as $item) { + $items[$item] = true; + } + } + + $list = array_keys($items); + sort($list); + + return $list; + } + + /** 解析某一行账单所属平台:优先店铺名前缀,其次页签默认。 */ + public function platform(?string $storeName, ?string $tabPlatform): ?string + { + $name = trim((string) $storeName); + if ($name !== '') { + foreach (self::STORE_PREFIX_PLATFORMS as $prefix => $platform) { + if (str_starts_with($name, $prefix)) { + return $platform; + } + } + } + + return $tabPlatform; + } + + /** 查总账备注;没有匹配返回 null。 */ + public function remark(?string $storeName, ?string $tabPlatform, ?string $billItem): ?string + { + $item = trim((string) $billItem); + if ($item === '') { + return null; + } + + $map = $this->map(); + if ($map === []) { + return null; + } + + foreach ([$this->platform($storeName, $tabPlatform), $tabPlatform] as $platform) { + if ($platform === null || $platform === '') { + continue; + } + if (isset($map[$platform][$item])) { + return $map[$platform][$item]; + } + } + + return null; + } + + /** + * 给一行账单补上 payload.ledger_remark(内部字段名 ledger_remark)。 + * + * @param array $row + * @return array + */ + public function decorate(array $row, string $tab): array + { + $tabPlatform = $this->defaultPlatform($tab); + $remark = $this->remark( + $row['store_name'] ?? null, + $tabPlatform, + $row['bill_item'] ?? null, + ); + if ($remark === null) { + return $row; + } + + $payload = is_array($row['payload'] ?? null) ? $row['payload'] : []; + $payload['ledger_remark'] = $remark; + $row['payload'] = $payload; + // 淘系支付宝页签按顶层字段取值,这里同时补一份,页面与导出共用。 + $row['ledger_remark'] = $remark; + + return $row; + } + + /** + * @param iterable> $rows + * @return \Generator> + */ + public function decorateAll(iterable $rows, string $tab): \Generator + { + foreach ($rows as $row) { + yield is_array($row) ? $this->decorate($row, $tab) : $row; + } + } +} diff --git a/modules/EcommerceFinance/Services/AccountMappingCoa.php b/modules/EcommerceFinance/Services/AccountMappingCoa.php new file mode 100644 index 00000000..ed60d7a7 --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingCoa.php @@ -0,0 +1,154 @@ +|null */ + private ?array $accounts = null; + + /** @return array */ + public function all(): array + { + if ($this->accounts !== null) { + return $this->accounts; + } + + $path = resource_path('data/coa.json'); + $payload = File::exists($path) ? json_decode((string) File::get($path), true) : null; + $rows = is_array($payload['accounts'] ?? null) ? $payload['accounts'] : []; + + $this->accounts = array_map(static fn (array $row): array => [ + 'code' => (string) ($row[0] ?? ''), + 'name' => (string) ($row[1] ?? ''), + 'level' => (int) ($row[2] ?? 1), + 'category' => (string) ($row[3] ?? ''), + 'balance' => (string) ($row[4] ?? ''), + ], $rows); + + return $this->accounts; + } + + /** @return array 一级科目(用于下拉第一级) */ + public function level1(): array + { + return array_values(array_map( + static fn (array $a): array => ['code' => $a['code'], 'name' => $a['name']], + array_filter($this->all(), static fn (array $a): bool => $a['level'] === 1 && $a['name'] !== '') + )); + } + + /** @return array 某编码子树下的非一级科目 */ + public function descendants(string $code): array + { + if ($code === '') { + return []; + } + + $prefix = $code . '.'; + $hits = []; + foreach ($this->all() as $a) { + if ($a['code'] !== $code && str_starts_with($a['code'], $prefix)) { + $hits[] = ['code' => $a['code'], 'name' => $a['name'], 'level' => $a['level']]; + } + } + + return $hits; + } + + /** 一级科目名 → 编码(账套里一级科目名唯一) */ + public function level1Code(string $name): ?string + { + $name = trim($name); + if ($name === '') { + return null; + } + + foreach ($this->all() as $a) { + if ($a['level'] === 1 && $a['name'] === $name) { + return $a['code']; + } + } + + return null; + } + + /** + * 在「一级科目」子树下按名称找科目编码。 + * + * @return array 命中编码;空数组 = 不存在;多于 1 个 = 同名歧义 + */ + public function resolve(string $level1Name, string $subName): array + { + $subName = trim($subName); + if ($subName === '') { + return []; + } + + $base = $this->level1Code($level1Name); + if ($base === null) { + return []; + } + + $hits = []; + foreach ($this->all() as $a) { + if ($a['name'] === $subName && ($a['code'] === $base || str_starts_with($a['code'], $base . '.'))) { + $hits[] = $a['code']; + } + } + + sort($hits); + + return $hits; + } + + /** 全账套里同名的编码(用于解释「为什么找不到」) @return array */ + public function anywhereByName(string $name): array + { + $name = trim($name); + if ($name === '') { + return []; + } + + $hits = []; + foreach ($this->all() as $a) { + if ($a['name'] === $name) { + $hits[] = $a['code']; + } + } + + sort($hits); + + return $hits; + } + + /** 名称或编码 → 编码(映射表里偶尔会直接写编码) */ + public function toCode(string $level1Token): ?string + { + $token = trim($level1Token); + if ($token === '') { + return null; + } + + if (preg_match('/^\d+(\.\d+)*$/', $token) === 1) { + foreach ($this->all() as $a) { + if ($a['code'] === $token) { + return $token; + } + } + + return null; + } + + return $this->level1Code($token); + } +} diff --git a/modules/EcommerceFinance/Services/AccountMappingMatcher.php b/modules/EcommerceFinance/Services/AccountMappingMatcher.php new file mode 100644 index 00000000..1c77930f --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingMatcher.php @@ -0,0 +1,150 @@ + $businessRemarks 账单上的业务备注(二次备注/账务备注/二级备注等) + * @return array{rule:array,matched:bool,reason:string}|null + */ + public function match(string $platform, string $item, array $businessRemarks = [], string $goodsName = ''): ?array + { + $candidates = []; + foreach ($this->store->all() as $rule) { + if ($this->sameText((string) $rule['platform'], $platform) && $this->sameText((string) $rule['item'], $item)) { + $candidates[] = $rule; + } + } + + if ($candidates === []) { + return null; + } + + $hits = []; + $fallback = null; + foreach ($candidates as $rule) { + $memo = trim((string) ($rule['memo'] ?? '')); + $goods = trim((string) ($rule['goods'] ?? '')); + + if ($memo === '' && $goods === '') { + $fallback ??= $rule; + continue; + } + + if ($memo !== '' && ! $this->rematchMemo($memo, $businessRemarks)) { + continue; + } + if ($goods !== '' && ! $this->containsKeyword($goodsName, $goods)) { + continue; + } + + $hits[] = ['rule' => $rule, 'score' => ($goods !== '' ? 2 : 0) + ($memo !== '' ? 1 : 0)]; + } + + if ($hits !== []) { + usort($hits, static fn (array $a, array $b): int => $b['score'] <=> $a['score'] ?: ((int) $a['rule']['id'] <=> (int) $b['rule']['id'])); + + return [ + 'rule' => $hits[0]['rule'], + 'matched' => true, + 'reason' => $this->hitsReason($hits[0]['rule'], $businessRemarks, $goodsName), + ]; + } + + $rule = $fallback ?? $candidates[0]; + + return [ + 'rule' => $rule, + 'matched' => false, + 'reason' => $fallback !== null + ? '没有命中具体条件,用同平台同项目的兜底规则' + : '没有命中任何条件,也没有兜底规则,暂按第一条处理(需要在映射表里补条件)', + ]; + } + + /** @param array $businessRemarks */ + private function rematchMemo(string $keyword, array $businessRemarks): bool + { + foreach ($businessRemarks as $value) { + $value = trim((string) $value); + if ($value === '' || $this->isPeriodLabel($value)) { + continue; + } + if ($this->containsKeyword($value, $keyword)) { + return true; + } + } + + return false; + } + + /** 形如 202607订单 / 2311退款 的时间标签,不参与业务备注匹配 */ + public function isPeriodLabel(string $value): bool + { + return preg_match(self::PERIOD_PATTERN, trim($value)) === 1; + } + + private function containsKeyword(string $haystack, string $keyword): bool + { + $needles = preg_split('/[\s,,、|]+/u', $keyword) ?: []; + $haystack = $this->squash($haystack); + + foreach ($needles as $needle) { + $needle = $this->squash($needle); + if ($needle !== '' && ! str_contains($haystack, $needle)) { + return false; + } + } + + return $haystack !== ''; + } + + /** 去空格、去大小写差异,便于「推广费-百亿补贴」这类带前后缀的备注命中 */ + private function squash(string $value): string + { + return mb_strtolower(preg_replace('/\s+/u', '', $value) ?? $value); + } + + private function sameText(string $a, string $b): bool + { + return $this->squash($a) === $this->squash($b); + } + + /** @param array $rule @param array $businessRemarks */ + private function hitsReason(array $rule, array $businessRemarks, string $goodsName): string + { + $parts = []; + if (trim((string) ($rule['memo'] ?? '')) !== '') { + $parts[] = '业务备注命中「' . trim((string) $rule['memo']) . '」'; + } + if (trim((string) ($rule['goods'] ?? '')) !== '') { + $parts[] = '商品名称命中「' . trim((string) $rule['goods']) . '」'; + } + + return $parts === [] ? '兜底规则' : implode(',', $parts); + } +} diff --git a/modules/EcommerceFinance/Services/AccountMappingStore.php b/modules/EcommerceFinance/Services/AccountMappingStore.php new file mode 100644 index 00000000..f3a97306 --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingStore.php @@ -0,0 +1,451 @@ + '平台', + 'item' => '账单项目', + 'memo' => '财务备注', + 'goods' => '商品名称关键词', + 'invoice' => '票据口径', + 'category' => '财务类型', + 'dAcct' => '借方科目', + 'dSub' => '借方二级', + 'cAcct' => '贷方科目', + 'cSub' => '贷方二级', + 'basis' => '方向基准', + ]; + + public const BASIS_OUT = '支出基准'; + public const BASIS_IN = '收入基准'; + + public const BASISES = [self::BASIS_OUT, self::BASIS_IN]; + + /** 大类 → 预期方向基准(用于校验「基准与大类是否一致」) */ + public const CATEGORY_BASIS = [ + '费用' => self::BASIS_OUT, + '售后费用' => self::BASIS_OUT, + '平台服务费' => self::BASIS_OUT, + '平台佣金' => self::BASIS_OUT, + '推广' => self::BASIS_OUT, + '保证金' => self::BASIS_OUT, + '暂挂' => self::BASIS_OUT, + '待处理财产损益' => self::BASIS_OUT, + '营业外支出' => self::BASIS_OUT, + '税费' => self::BASIS_OUT, + '提现' => self::BASIS_OUT, + '收入' => self::BASIS_IN, + '往来' => self::BASIS_IN, + '转账' => self::BASIS_IN, + ]; + + /** 票据口径可取值 */ + public const INVOICES = ['0.06', '0.09', '不开票', '-']; + + /** + * 存储目录。 + * + * 用 storage 而不是 runtime:预览/生产容器都只挂了仓库的若干子目录, + * runtime/ 不在挂载范围内(写了会落在容器自己那层,重建就丢); + * storage/app 是 Laravel 规范可写目录,且挂的是持久卷。 + */ + public function dir(): string + { + return storage_path('app/account-mapping'); + } + + public function path(): string + { + return $this->dir() . DIRECTORY_SEPARATOR . 'rules.json'; + } + + public function eventPath(): string + { + return $this->dir() . DIRECTORY_SEPARATOR . 'events.json'; + } + + /** @return array> 按 id 升序的全部规则 */ + public function all(): array + { + $this->ensureSeeded(); + + $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'])); + + return $rules; + } + + public function find(int $id): ?array + { + foreach ($this->all() as $rule) { + if ((int) $rule['id'] === $id) { + return $rule; + } + } + + return null; + } + + /** 新增一条,返回新规则 */ + public function create(array $values, ?int $userId = null): array + { + $rules = $this->all(); + $id = 1; + foreach ($rules as $rule) { + $id = max($id, ((int) $rule['id']) + 1); + } + + $rule = ['id' => $id] + $this->normalize($values); + $rules[] = $rule; + $this->persist($rules); + $this->logEvent('create', $id, null, $rule, $userId); + + return $rule; + } + + /** 修改一条,返回改后的规则 */ + public function update(int $id, array $values, ?int $userId = null): array + { + $rules = $this->all(); + $updated = null; + $before = null; + + foreach ($rules as $index => $rule) { + if ((int) $rule['id'] !== $id) { + continue; + } + $before = $rule; + $updated = ['id' => $id] + $this->normalize(array_replace($rule, $values)); + $rules[$index] = $updated; + break; + } + + if ($updated === null) { + throw new RuntimeException('未找到要修改的规则。'); + } + + $this->persist($rules); + $this->logEvent('update', $id, $before, $updated, $userId); + + return $updated; + } + + public function destroy(int $id, ?int $userId = null): bool + { + $rules = $this->all(); + $before = null; + $kept = []; + + foreach ($rules as $rule) { + if ((int) $rule['id'] === $id) { + $before = $rule; + continue; + } + $kept[] = $rule; + } + + if ($before === null) { + return false; + } + + $this->persist($kept); + $this->logEvent('delete', $id, $before, null, $userId); + + return true; + } + + /** + * 导入:按「平台 + 账单项目 + 财务备注」判重。 + * + * @param array> $rows + * @return array{created:int,updated:int,skipped:int,duplicates:array,total:int} + */ + public function importRows(array $rows, bool $overwrite, ?int $userId = null): array + { + $rules = $this->all(); + $byKey = []; + foreach ($rules as $index => $rule) { + $byKey[$this->keyOf($rule)] = $index; + } + $nextId = 1; + foreach ($rules as $rule) { + $nextId = max($nextId, ((int) $rule['id']) + 1); + } + + $created = 0; + $updated = 0; + $skipped = 0; + $duplicates = []; + + foreach ($rows as $row) { + $values = $this->normalize($row); + if ($this->isEmptyRow($values)) { + continue; + } + + $key = $this->keyOf($values); + if (isset($byKey[$key])) { + if (! $overwrite) { + $skipped++; + $duplicates[] = $key; + continue; + } + $index = $byKey[$key]; + $rules[$index] = ['id' => $rules[$index]['id']] + $values; + $updated++; + continue; + } + + $rules[] = ['id' => $nextId] + $values; + $byKey[$key] = count($rules) - 1; + $nextId++; + $created++; + } + + if ($created + $updated > 0) { + $this->persist($rules); + $this->logEvent('import', null, null, null, $userId, [ + 'created' => $created, + 'updated' => $updated, + 'skipped' => $skipped, + ]); + } + + return [ + 'created' => $created, + 'updated' => $updated, + 'skipped' => $skipped, + 'duplicates' => array_slice($duplicates, 0, 20), + 'total' => count($rows), + ]; + } + + /** 用 resources/data/account-mapping.json 覆盖回初始状态 */ + public function reset(?int $userId = null): int + { + $seed = $this->seed(); + $this->persist($seed); + $this->logEvent('reset', null, null, null, $userId, ['total' => count($seed)]); + + return count($seed); + } + + /** @return array> */ + public function seed(): array + { + $path = resource_path('data/account-mapping.json'); + $payload = File::exists($path) ? json_decode((string) File::get($path), true) : null; + + // 种子文件既可能是顶层数组,也可能是 {"rules": [...]},两种都认 + $rows = []; + if (is_array($payload)) { + if (is_array($payload['rules'] ?? null)) { + $rows = $payload['rules']; + } elseif (array_is_list($payload)) { + $rows = $payload; + } + } + + $out = []; + foreach ($rows as $row) { + if (! is_array($row)) { + continue; + } + $out[] = ['id' => (int) ($row['no'] ?? (count($out) + 1))] + $this->normalize($row); + } + usort($out, static fn (array $a, array $b): int => ((int) $a['id']) <=> ((int) $b['id'])); + + return $out; + } + + /** @return array */ + public function normalize(array $values): array + { + $out = []; + foreach (self::FIELDS as $field) { + $value = $values[$field] ?? ''; + if (is_array($value) || is_object($value)) { + $value = ''; + } + $out[$field] = trim((string) $value); + } + + if (! in_array($out['basis'], self::BASISES, true)) { + $out['basis'] = self::CATEGORY_BASIS[$out['category']] ?? self::BASIS_OUT; + } + + // 区分条件里的「-」「—」表示“不限”,按空处理:否则匹配时会拿它去找关键词,规则永远命中不了 + foreach (['memo', 'goods'] as $field) { + if (in_array($out[$field], ['-', '—', '-'], true)) { + $out[$field] = ''; + } + } + + return $out; + } + + /** + * 判重键:平台 + 账单项目 + 业务备注关键词 + 商品名称关键词。 + * + * 业务备注/商品名称是「区分条件」:同一个账单项目在业务上不同时,靠它们区分; + * 条件完全相同的两条规则才是真重复。 + */ + public function keyOf(array $rule): string + { + return implode('|', [ + trim((string) ($rule['platform'] ?? '')), + trim((string) ($rule['item'] ?? '')), + trim((string) ($rule['memo'] ?? '')), + trim((string) ($rule['goods'] ?? '')), + ]); + } + + /** @return array */ + public function options(): array + { + $rules = $this->all(); + $collect = static function (string $field) use ($rules): array { + $seen = []; + foreach ($rules as $rule) { + $value = trim((string) ($rule[$field] ?? '')); + if ($value !== '') { + $seen[$value] = true; + } + } + $values = array_keys($seen); + sort($values); + + return $values; + }; + + return [ + 'platforms' => $collect('platform'), + 'categories' => array_keys(self::CATEGORY_BASIS), + 'basis' => self::BASISES, + 'invoices' => self::INVOICES, + ]; + } + + /** @return array> 最近的操作记录(倒序) */ + public function events(int $limit = 50): array + { + $payload = $this->read($this->eventPath()); + $events = is_array($payload['events'] ?? null) ? $payload['events'] : []; + + return array_slice(array_reverse($events), 0, $limit); + } + + /** + * 本模块统一用的“现在”:固定按平台时区,不受页面请求里公司设置覆盖的影响。 + * + * 直接用 now() 的话,页面操作写进日志的时间会差 7 小时(Europe/London)。 + */ + public function platformNow(): Carbon + { + $timezone = trim((string) config('app.platform_timezone', '')); + + if ($timezone === '') { + $timezone = (string) config('app.timezone', 'UTC'); + } + + try { + return Carbon::now($timezone); + } catch (\Throwable) { + return Carbon::now(config('app.timezone', 'UTC')); + } + } + + private function isEmptyRow(array $values): bool + { + return trim((string) ($values['platform'] ?? '')) === '' + && trim((string) ($values['item'] ?? '')) === ''; + } + + private function ensureSeeded(): void + { + if (File::exists($this->path())) { + return; + } + + $this->persist($this->seed()); + } + + /** @param array> $rules */ + private function persist(array $rules): void + { + if (! File::isDirectory($this->dir()) && ! File::makeDirectory($this->dir(), 0775, true) && ! File::isDirectory($this->dir())) { + throw new RuntimeException('无法创建映射表存储目录。'); + } + + $json = json_encode( + ['updated_at' => $this->platformNow()->toDateTimeString(), 'rules' => array_values($rules)], + JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT + ); + + if ($json === false) { + throw new RuntimeException('映射表序列化失败。'); + } + + File::put($this->path(), $json, true); + } + + private function logEvent(string $action, ?int $id, ?array $before, ?array $after, ?int $userId, array $extra = []): void + { + $payload = $this->read($this->eventPath()); + $events = is_array($payload['events'] ?? null) ? $payload['events'] : []; + + $events[] = array_merge([ + 'at' => $this->platformNow()->toDateTimeString(), + 'action' => $action, + 'id' => $id, + 'before' => $before, + 'after' => $after, + 'user_id' => $userId, + ], $extra); + + if (count($events) > 500) { + $events = array_slice($events, -500); + } + + File::put($this->eventPath(), (string) json_encode(['events' => $events], JSON_UNESCAPED_UNICODE), true); + } + + /** @return array */ + private function read(string $path): array + { + if (! File::exists($path)) { + return []; + } + + $payload = json_decode((string) File::get($path), true); + + return is_array($payload) ? $payload : []; + } +} diff --git a/modules/EcommerceFinance/Services/AccountMappingValidator.php b/modules/EcommerceFinance/Services/AccountMappingValidator.php new file mode 100644 index 00000000..4752390c --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingValidator.php @@ -0,0 +1,227 @@ +> $rules + * @return array{issues:array>,summary:array} + */ + public function validate(array $rules): array + { + $issues = []; + $dupIndex = []; + foreach ($rules as $rule) { + $dupIndex[implode('|', [ + trim((string) ($rule['platform'] ?? '')), + trim((string) ($rule['item'] ?? '')), + ])][] = (int) $rule['id']; + } + + // 同一「平台 + 账单项目」下,用区分条件(业务备注 + 商品名称)分组: + // 条件相同的两条 = 真重复(提示); + // 条件不同的多条 = 按条件区分(正常,不报)。 + $conditionIndex = []; + foreach ($rules as $rule) { + $conditionIndex[$this->pairKey($rule)][$this->conditionKey($rule)][] = (int) $rule['id']; + } + + foreach ($rules as $rule) { + $id = (int) $rule['id']; + $list = []; + + $list = array_merge($list, $this->accountIssues($rule, 'dAcct', 'dSub', '借方')); + $list = array_merge($list, $this->accountIssues($rule, 'cAcct', 'cSub', '贷方')); + + // 方向基准 + $basis = trim((string) ($rule['basis'] ?? '')); + $category = trim((string) ($rule['category'] ?? '')); + + if ($basis === '') { + $list[] = $this->issue('错误', 'basis_missing', '没有填方向基准,程序无法判断该照抄还是互换。'); + } elseif (! in_array($basis, AccountMappingStore::BASISES, true)) { + $list[] = $this->issue('错误', 'basis_invalid', "方向基准「{$basis}」不是有效值,只能是支出基准或收入基准。"); + } elseif ($category !== '' && isset(AccountMappingStore::CATEGORY_BASIS[$category])) { + $expected = AccountMappingStore::CATEGORY_BASIS[$category]; + if ($expected !== $basis) { + $list[] = $this->issue( + '警告', + 'basis_mismatch', + "大类「{$category}」按口径应是「{$expected}」,这里填的是「{$basis}」,账单收支与基准不一致时方向会反。" + ); + } + } + + if ($category === '') { + $list[] = $this->issue('警告', 'category_missing', '没有填大类,方向基准失去参照,也无法按大类筛选。'); + } + + // 票据口径 + $invoice = trim((string) ($rule['invoice'] ?? '')); + if ($invoice === '') { + $list[] = $this->issue('提示', 'invoice_missing', '票据口径为空,汇算清缴时不好判断调增项。'); + } elseif (! in_array($invoice, AccountMappingStore::INVOICES, true)) { + $list[] = $this->issue('提示', 'invoice_unknown', "票据口径「{$invoice}」不在常用取值(0.06 / 不开票 / -)内。"); + } + + // 借贷两边同一个科目 + $d = trim((string) ($rule['dAcct'] ?? '')); + $c = trim((string) ($rule['cAcct'] ?? '')); + $ds = trim((string) ($rule['dSub'] ?? '')); + $cs = trim((string) ($rule['cSub'] ?? '')); + if ($d !== '' && $d === $c && $ds === $cs) { + $list[] = $this->issue('警告', 'same_account', '借方和贷方是同一个科目,这笔业务不会有损益影响。'); + } + + // 同平台同项目重复 + $pairKey = trim((string) ($rule['platform'] ?? '')) . '|' . trim((string) ($rule['item'] ?? '')); + if (count($dupIndex[$pairKey] ?? []) > 1) { + $sameCondition = array_values(array_diff($conditionIndex[$pairKey][$this->conditionKey($rule)] ?? [], [$id])); + + if ($sameCondition !== []) { + $list[] = $this->issue( + '提示', + 'duplicate_pair', + '同一平台、同一账单项目、区分条件也相同的第 ' . implode('、', $sameCondition) . ' 条规则属于重复,建议合并。' + ); + } + + if (trim((string) ($rule['memo'] ?? '')) === '' && trim((string) ($rule['goods'] ?? '')) === '') { + $list[] = $this->issue( + '提示', + 'fallback_rule', + '这条没有区分条件,属于兜底规则:只有在同项目下其它带条件的规则都没命中时才会用它。' + ); + } + } + + if ($list !== []) { + $issues[$id] = $list; + } + } + + $errRows = 0; + $warnRows = 0; + $errCount = 0; + $warnCount = 0; + $tipCount = 0; + foreach ($issues as $list) { + $levels = array_column($list, 'level'); + if (in_array('错误', $levels, true)) { + $errRows++; + } elseif (in_array('警告', $levels, true)) { + $warnRows++; + } + foreach ($levels as $level) { + if ($level === '错误') { + $errCount++; + } elseif ($level === '警告') { + $warnCount++; + } else { + $tipCount++; + } + } + } + + $total = count($rules); + + return [ + 'issues' => $issues, + 'summary' => [ + 'total' => $total, + 'error_rows' => $errRows, + 'warning_rows' => $warnRows, + 'ok_rows' => max($total - $errRows - $warnRows, 0), + 'error_count' => $errCount, + 'warning_count' => $warnCount, + 'tip_count' => $tipCount, + ], + ]; + } + + /** + * @return array + */ + private function accountIssues(array $rule, string $acctField, string $subField, string $side): array + { + $list = []; + $acct = trim((string) ($rule[$acctField] ?? '')); + $sub = trim((string) ($rule[$subField] ?? '')); + + if ($acct === '') { + $list[] = $this->issue('错误', 'account_missing', "{$side}科目为空,生成不了分录。"); + + return $list; + } + + $base = $this->coa->toCode($acct); + if ($base === null) { + $anywhere = $this->coa->anywhereByName($acct); + $hint = $anywhere === [] ? '账套里没有这个名称的科目,需要先建科目或改成账套已有的一级科目。' + : '它只存在于 ' . implode('、', $anywhere) . ',不是一级科目,应放到对应的一级科目下面。'; + $list[] = $this->issue('错误', 'account_unknown', "{$side}科目「{$acct}」在账套里找不到:{$hint}"); + + return $list; + } + + if ($sub === '' || $sub === $acct) { + return $list; + } + + $hits = $this->coa->resolve($acct, $sub); + if (count($hits) === 1) { + return $list; + } + + if ($hits === []) { + $anywhere = $this->coa->anywhereByName($sub); + $hint = $anywhere === [] + ? '账套里没有这个名称,需要新建,或改用已有明细。' + : '它在 ' . implode('、', $anywhere) . ',不挂在「' . $acct . '」下面。'; + $list[] = $this->issue('警告', 'sub_unknown', "{$side}二级科目「{$sub}」找不到:{$hint}"); + + return $list; + } + + $list[] = $this->issue( + '警告', + 'sub_ambiguous', + "{$side}二级科目「{$sub}」在「{$acct}」下有 " . count($hits) . ' 个(' . implode('、', $hits) . '),程序无法自动选,建议改写为编码。' + ); + + return $list; + } + + /** @return array{level:string,code:string,message:string} */ + private function issue(string $level, string $code, string $message): array + { + return ['level' => $level, 'code' => $code, 'message' => $message]; + } + + /** 平台 + 账单项目 */ + private function pairKey(array $rule): string + { + return trim((string) ($rule['platform'] ?? '')) . '|' . trim((string) ($rule['item'] ?? '')); + } + + /** 区分条件:业务备注关键词 + 商品名称关键词 */ + private function conditionKey(array $rule): string + { + return trim((string) ($rule['memo'] ?? '')) . '|' . trim((string) ($rule['goods'] ?? '')); + } +} diff --git a/modules/EcommerceFinance/Services/AccountMappingWorkbookImporter.php b/modules/EcommerceFinance/Services/AccountMappingWorkbookImporter.php new file mode 100644 index 00000000..6e02675b --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingWorkbookImporter.php @@ -0,0 +1,209 @@ + ['平台', '平台名称', '渠道'], + 'item' => ['账单项目', '项目', '账单类型', '交易类型', '收支项目'], + 'memo' => ['业务备注', '财务备注', '二次备注', '业务备注关键词', '账务备注', '备注'], + 'goods' => ['商品名称关键词', '商品名称', '商品描述', '货品名称'], + 'invoice' => ['票据口径', '票据', '票据类型', '发票'], + 'category' => ['财务类型', '大类', '业务性质', '科目大类', '分类'], + 'basis' => ['方向基准', '基准'], + 'dAcct' => ['借方科目', '借/贷(借)', '借/贷(借)', '借方'], + 'dSub' => ['借方二级'], + 'cAcct' => ['贷方科目'], + 'cSub' => ['贷方二级'], + ]; + + private const INVOICE_MAP = [ + '0' => '不开票', + '0.00' => '不开票', + '0%' => '不开票', + '0.06' => '0.06', + '6%' => '0.06', + '06' => '0.06', + '可开6%专票' => '0.06', + '开6%专票' => '0.06', + '不开票' => '不开票', + '不开票(无票)' => '不开票', + '不开票(无票)' => '不开票', + '无票' => '不开票', + '-' => '-', + '—' => '-', + '不涉及' => '-', + ]; + + /** + * @return array{rows:array>,header_row:int,sheet:string} + */ + public function parse(UploadedFile $file): array + { + $extension = mb_strtolower((string) $file->getClientOriginalExtension()); + + try { + $readerType = match ($extension) { + 'xlsx' => 'Xlsx', + 'xls' => 'Xls', + 'csv' => 'Csv', + default => throw new \RuntimeException('Unsupported workbook format.'), + }; + + $reader = IOFactory::createReader($readerType); + if ($readerType === 'Csv') { + $reader->setInputEncoding('UTF-8'); + } + $spreadsheet = $reader->load($file->getRealPath()); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => '读不出这个文件,请确认是 xlsx / xls / csv,且没有损坏。', + ]); + } + + try { + $best = null; + foreach ($spreadsheet->getWorksheetIterator() as $sheet) { + $grid = $sheet->toArray(null, true, false, false); + $grid = array_values(array_filter($grid, static fn (array $row): bool => $row !== [])); + if ($grid === []) { + continue; + } + $headerRow = $this->locateHeader($grid); + $score = $headerRow === null ? -1 : count(array_filter($this->mapHeader($grid[$headerRow]))); + if ($score <= 0) { + continue; + } + if ($best === null || $score > $best['score']) { + $best = ['score' => $score, 'grid' => $grid, 'header_row' => $headerRow, 'sheet' => $sheet->getTitle()]; + } + } + } finally { + $spreadsheet->disconnectWorksheets(); + } + + if ($best === null) { + throw ValidationException::withMessages([ + 'import' => '没找到表头。至少要有一列「平台」和一列「账单项目」,以及借方、贷方两组科目列。', + ]); + } + + $columns = $this->mapHeader($best['grid'][$best['header_row']]); + $rows = []; + foreach (array_slice($best['grid'], $best['header_row'] + 1) as $gridRow) { + $row = []; + foreach ($columns as $field => $index) { + if ($index === null) { + $row[$field] = ''; + continue; + } + $value = $gridRow[$index] ?? ''; + $row[$field] = trim((string) (is_scalar($value) ? $value : '')); + } + if ($row['platform'] === '' && $row['item'] === '') { + continue; + } + $row['invoice'] = $this->normalizeInvoice($row['invoice']); + $row = $this->inferBasis($row); + $rows[] = $row; + } + + return ['rows' => $rows, 'header_row' => $best['header_row'], 'sheet' => $best['sheet']]; + } + + /** @param array $row */ + private function locateHeader(array $grid): ?int + { + foreach ($grid as $index => $row) { + if (count(array_filter($this->mapHeader($row))) >= 3) { + return $index; + } + } + + return null; + } + + /** + * @param array $header + * @return array + */ + private function mapHeader(array $header): array + { + $cells = []; + foreach ($header as $index => $value) { + $cells[$index] = $this->normalizeHeader((string) (is_scalar($value) ? $value : '')); + } + + $columns = []; + foreach (self::ALIASES as $field => $aliases) { + $columns[$field] = null; + foreach ($aliases as $alias) { + $needle = $this->normalizeHeader($alias); + $found = array_search($needle, $cells, true); + if ($found !== false) { + $columns[$field] = (int) $found; + break; + } + } + } + + // 旧版表头「借/贷(借)」出现两次、没有「贷方科目」:借方组命中的那列起,往后取 4 列。 + $dAcct = $columns['dAcct']; + if ($dAcct !== null && $columns['dSub'] === null && $columns['cAcct'] === null && $columns['cSub'] === null) { + $columns['dSub'] = $dAcct + 1; + $columns['cAcct'] = $dAcct + 2; + $columns['cSub'] = $dAcct + 3; + } elseif ($dAcct === null && $columns['cAcct'] !== null && $columns['dSub'] === null) { + $columns['dAcct'] = max($columns['cAcct'] - 2, 0); + $columns['dSub'] = max($columns['cAcct'] - 1, 0); + $columns['cSub'] = $columns['cAcct'] + 1; + } + + return $columns; + } + + private function normalizeHeader(string $value): string + { + $value = str_replace(['(', ')', '(', ')', ' '], ['(', ')', '(', ')', ''], $value); + + return trim($value); + } + + private function normalizeInvoice(string $value): string + { + $value = trim($value); + if ($value === '') { + return ''; + } + + return self::INVOICE_MAP[$value] ?? $value; + } + + /** @param array $row @return array */ + private function inferBasis(array $row): array + { + $basis = trim((string) ($row['basis'] ?? '')); + if ($basis === '') { + $basis = AccountMappingStore::CATEGORY_BASIS[trim((string) $row['category'])] ?? ''; + } + $row['basis'] = $basis; + + return $row; + } +} diff --git a/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php b/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php index ec9f9c8e..3ea66e29 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php @@ -71,7 +71,7 @@ class BusinessMirrorDatasetRegistry return $this->definitions()[$key]['columns'] ?? null; } - /** @return array */ + /** @return array> */ public function fixedFilters(string $key): array { $definitions = $this->definitions(); @@ -145,7 +145,7 @@ class BusinessMirrorDatasetRegistry }; } - /** @return array */ + /** @return array> */ private function normalizeFixedFilters(string $key, array $filters): array { $normalized = []; @@ -157,7 +157,14 @@ class BusinessMirrorDatasetRegistry if ($column === '' || mb_strlen($column) > 128 || str_contains($column, "\0") || isset($seen[$canonical])) { throw new InvalidArgumentException('业务镜像数据集包含无效的固定过滤字段:' . $key); } - if (! is_scalar($value)) { + if (is_array($value)) { + if (! array_is_list($value) || $value === [] || collect($value)->contains( + static fn (mixed $item): bool => ! is_scalar($item) + )) { + throw new InvalidArgumentException('业务镜像数据集包含无效的固定过滤值:' . $key); + } + $value = array_values($value); + } elseif (! is_scalar($value)) { throw new InvalidArgumentException('业务镜像数据集包含无效的固定过滤值:' . $key); } diff --git a/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php b/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php index bb1a0441..4c06be98 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php @@ -121,8 +121,13 @@ class BusinessMirrorSynchronizer $bindings = []; foreach ($dataset->fixedFilters() as $column => $value) { - $where[] = $this->quote($column) . ' = ?'; - $bindings[] = $value; + if (is_array($value)) { + $where[] = $this->quote($column) . ' IN (' . implode(', ', array_fill(0, count($value), '?')) . ')'; + array_push($bindings, ...$value); + } else { + $where[] = $this->quote($column) . ' = ?'; + $bindings[] = $value; + } } if ($mode === 'incremental' && $dataset->watermarkColumn() !== null) { diff --git a/modules/EcommerceFinance/Services/CourierPayableFinalRegistry.php b/modules/EcommerceFinance/Services/CourierPayableFinalRegistry.php new file mode 100644 index 00000000..78f98186 --- /dev/null +++ b/modules/EcommerceFinance/Services/CourierPayableFinalRegistry.php @@ -0,0 +1,73 @@ + */ + public function titles(): array + { + return [ + 'bookkeeping-details' => '记账明细', + 'compensation-details' => '赔偿明细', + 'advance-details' => '借支明细', + 'other-adjustments' => '其他扣款补款', + ]; + } + + /** @return array */ + public function fields(string $dataset): array + { + $money = static fn (string $label): array => ['label' => $label, 'type' => 'number']; + $text = static fn (string $label): array => ['label' => $label, 'type' => 'text']; + $date = static fn (string $label): array => ['label' => $label, 'type' => 'date']; + $month = static fn (string $label): array => ['label' => $label, 'type' => 'month']; + + return match ($dataset) { + 'bookkeeping-details' => [ + 'started_at' => $text('发起时间'), 'work_order_no' => $text('工单编号'), 'initiator' => $text('发起人'), + 'bookkeeping_reason' => $text('记账原因'), 'reason_level_1' => $text('记账原因-一级选项'), + 'reason_level_2' => $text('记账原因-二级选项'), 'reason_level_3' => $text('记账原因-三级选项'), + 'bookkeeping_type' => $text('记账类型'), 'executor' => $text('执行人'), 'source' => $text('记账来源'), + 'amount' => $money('记账金额'), 'remark' => $text('记账备注说明'), 'attachment' => $text('上传附件'), + 'attachment_preview' => $text('上传附件(预览)'), 'online_order_no' => $text('线上订单号'), + 'internal_order_no' => $text('内部单号'), 'actual_paid_amount' => $money('实付金额'), + 'carrier' => $text('物流公司'), 'tracking_no' => $text('物流单号'), 'shop_name' => $text('店铺名称'), + 'platform' => $text('平台'), 'shipping_warehouse' => $text('订单发货仓库'), + 'processing_status' => $text('记账处理状态'), 'counterparty_agreed' => $text('被记账方是否同意记账'), + 'counterparty_note' => $text('被记账方处理说明'), 'specialist_result' => $text('专员记账判定结果'), + 'specialist_note' => $text('专员处理说明'), 'updated_at' => $text('修改时间'), + 'work_order_type' => $text('工单类型'), 'product_image' => $text('商品图片'), + 'product_code' => $text('商品编码'), 'style_code' => $text('款式编码'), + 'other_attribute_6' => $text('其它属性6'), 'product_name' => $text('商品名称'), + 'platform_sku_id' => $text('平台商品skuid'), 'platform_product_id' => $text('平台商品id'), + 'product_quantity' => $money('商品数量'), 'product_price' => $money('商品价格'), + 'product_amount' => $money('商品金额'), 'buyer_paid_amount' => $money('买家实付'), + 'supplier' => $text('供应商'), 'accepting_department' => $text('受理部门'), + 'order_shipped_at' => $text('订单发货时间'), 'work_order_remark' => $text('工单备注'), + ], + 'compensation-details' => [ + 'paid_at' => $date('赔付日期'), 'carrier' => $text('承运商'), 'tracking_no' => $text('快递单号'), + 'amount' => $money('赔付金额'), 'reason' => $text('赔付原因'), 'remark' => $text('备注'), + ], + 'advance-details' => [ + 'carrier' => $text('快递名称'), 'agreement_name' => $text('协议签订名称'), + 'agreement_amount' => $money('借支金额-借款协议'), 'actual_paid_amount' => $money('实际打款金额'), + 'monthly_deduction' => $money('本月扣款金额'), 'deduction_start_month' => $month('分期起始扣款月份'), + 'deduction_end_month' => $month('分期最后次扣款月份'), 'remaining_periods' => $money('分期剩余期数'), + 'advanced_at' => $date('借支日期'), 'loan_term' => $text('借款期限'), 'remark' => $text('备注'), + 'payment_status' => $text('是否打款'), 'payment_month' => $month('打款月份'), + 'serial_no' => $text('流水号'), 'agreement_file' => $text('借支协议'), 'reviewer' => $text('审核人'), + ], + 'other-adjustments' => [ + 'project' => $text('项目'), 'adjusted_at' => $date('日期'), 'carrier' => $text('承运商'), + 'amount' => $money('补款金额'), 'reason' => $text('补款原因'), 'remark' => $text('备注'), + 'remark_2' => $text('备注2'), + ], + default => throw ValidationException::withMessages(['dataset' => '不支持该快递应付页面。']), + }; + } +} diff --git a/modules/EcommerceFinance/Services/DewuSettlementBillImporter.php b/modules/EcommerceFinance/Services/DewuSettlementBillImporter.php new file mode 100644 index 00000000..9b3a12be --- /dev/null +++ b/modules/EcommerceFinance/Services/DewuSettlementBillImporter.php @@ -0,0 +1,731 @@ + ['记录编码'], + 'order_no' => ['订单号'], + 'online_order_no' => ['线上单号'], + 'custom_remark' => ['自定义备注'], + 'bill_item' => ['账单项目'], + 'store_name' => ['店铺'], + 'order_type' => ['订单类型'], + 'goods_name' => ['商品名称'], + 'goods_no' => ['商品货号'], + 'quantity' => ['数量'], + 'channel' => ['渠道'], + 'business_type' => ['业务类型'], + 'income_amount' => ['收入金额'], + 'expense_amount' => ['支出金额'], + 'online_real_store' => ['线上单号对应实际店铺'], + 'order_created_at' => ['订单创建时间'], + 'paid_refunded_at' => ['支付/退款时间'], + 'ship_return_at' => ['发货/退货时间'], + 'settle_status' => ['结算状态'], + 'pay_period' => ['收款账期'], + 'pulled_at' => ['拉取时间'], + 'source_updated_at' => ['修改时间'], + 'source_modified_by' => ['修改人'], + ]; + + private readonly ConnectionInterface $connection; + + public function __construct(DatabaseManager $databases) + { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{status:string,row_count:int,excluded_rows:int,store_count:int,bill_item_count:int,channel_counts:array,income_total:string,expense_total:string,net_total:string,period_start:string,period_end:string,source_sha256:string} + */ + public function import( + string $path, + string $fromDate, + string $toDate, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + int $batchSize = 1000, + ): array { + $path = $this->validatedPath($path); + [$from, $to] = $this->period($fromDate, $toDate); + $this->assertSchemaReady(); + if ($expectedCount <= 0) { + throw new RuntimeException('权威笔数控制数必须大于零。'); + } + $expectedIncome = $this->controlAmount($expectedIncome, '收入'); + $expectedExpense = $this->controlAmount($expectedExpense, '支出'); + + $batchSize = min(max($batchSize, 100), 5000); + $hash = hash_file('sha256', $path); + if (! is_string($hash)) { + throw new RuntimeException('无法计算得物完整账单文件摘要。'); + } + + $existing = $this->connection->table(self::IMPORT_TABLE) + ->where('source_sha256', $hash) + ->first(); + if ($existing !== null && $existing->status === 'succeeded') { + $this->assertSameImportRequest( + $existing, + $from, + $to, + $expectedCount, + $expectedIncome, + $expectedExpense, + ); + if ($this->activeRowCount($hash, $from, $to) === (int) $existing->row_count) { + return $this->result((array) $existing, 'unchanged'); + } + } + + $generation = $existing !== null ? (string) $existing->generation : (string) Str::uuid(); + $now = now(); + $import = [ + 'generation' => $generation, + 'source_filename' => mb_substr(basename($path), 0, 255), + 'source_sha256' => $hash, + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'status' => 'running', + 'expected_row_count' => $expectedCount, + 'expected_income_total' => $expectedIncome, + 'expected_expense_total' => $expectedExpense, + 'row_count' => 0, + 'excluded_rows' => 0, + 'store_count' => 0, + 'bill_item_count' => 0, + 'channel_counts' => null, + 'income_total' => '0.00', + 'expense_total' => '0.00', + 'net_total' => '0.00', + 'completed_at' => null, + 'last_error_code' => null, + 'updated_at' => $now, + ]; + if ($existing === null) { + $this->connection->table(self::IMPORT_TABLE)->insert($import + ['created_at' => $now]); + } else { + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($import); + } + + $stats = null; + try { + $stats = $this->stage($path, $generation, $from, $to, $batchSize); + $this->assertControls($stats, $expectedCount, $expectedIncome, $expectedExpense); + $this->activate($generation, $hash, $from, $to, $stats, $batchSize); + + return $this->result([ + 'row_count' => $stats['row_count'], + 'excluded_rows' => $stats['excluded_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'channel_counts' => $stats['channel_counts'], + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'source_sha256' => $hash, + ], 'succeeded'); + } catch (Throwable $exception) { + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + $failure = [ + 'status' => 'failed', + 'last_error_code' => mb_substr(class_basename($exception), 0, 120), + 'updated_at' => now(), + ]; + if (is_array($stats)) { + $failure += [ + 'row_count' => $stats['row_count'], + 'excluded_rows' => $stats['excluded_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'channel_counts' => json_encode($stats['channel_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + ]; + } + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($failure); + + throw $exception; + } + } + + private function validatedPath(string $path): string + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new RuntimeException('得物完整账单文件不存在或不可读。'); + } + if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') { + throw new RuntimeException('聚胜算完整账单导入只支持 XLSX 文件。'); + } + + return $realPath; + } + + /** @return array{0:DateTimeImmutable,1:DateTimeImmutable} */ + private function period(string $fromDate, string $toDate): array + { + $from = DateTimeImmutable::createFromFormat('!Y-m-d', $fromDate); + $to = DateTimeImmutable::createFromFormat('!Y-m-d', $toDate); + if ($from === false || $to === false + || $from->format('Y-m-d') !== $fromDate + || $to->format('Y-m-d') !== $toDate + || $from > $to) { + throw new RuntimeException('得物账单导入账期无效。'); + } + + return [$from, $to]; + } + + private function assertSchemaReady(): void + { + $schema = Schema::connection($this->connection->getName()); + foreach ([self::IMPORT_TABLE, self::STAGING_TABLE, self::ROW_TABLE] as $table) { + if (! $schema->hasTable($table)) { + throw new RuntimeException('得物完整账单表尚未完成迁移:' . $table); + } + } + } + + /** + * @return array{row_count:int,excluded_rows:int,store_count:int,bill_item_count:int,channel_counts:array,income_total:string,expense_total:string,net_total:string} + */ + private function stage( + string $path, + string $generation, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $batchSize, + ): array { + $archive = new ZipArchive(); + if ($archive->open($path) !== true) { + throw new RuntimeException('无法打开得物完整账单 XLSX 文件。'); + } + + try { + $worksheet = $this->firstWorksheet($archive); + $sharedStrings = $this->sharedStrings($path, $archive); + } finally { + $archive->close(); + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取得物完整账单工作表。'); + } + + $headerMap = null; + $batch = []; + $rowCount = 0; + $incomeTotal = '0.00'; + $expenseTotal = '0.00'; + $stores = []; + $billItems = []; + $channelCounts = []; + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + + $rowNumber = (int) ($reader->getAttribute('r') ?: 0); + $cells = $this->rowCells($reader->readOuterXml(), $sharedStrings); + if ($headerMap === null) { + $headerMap = $this->headerMap($cells); + continue; + } + + $values = []; + foreach ($headerMap as $header => $column) { + $values[$header] = trim((string) ($cells[$column] ?? '')); + } + if (implode('', $values) === '') { + continue; + } + $recordCode = $this->required($values, 'record_code', $rowNumber, '记录编码'); + $channel = $this->required($values, 'channel', $rowNumber, '渠道'); + $storeName = $this->nullable($values['store_name']); + $billItem = $this->nullable($values['bill_item']); + $paidRefundedAt = $this->optionalDateTime($values['paid_refunded_at'], $rowNumber, '支付/退款时间'); + $shipReturnAt = $this->optionalDateTime($values['ship_return_at'], $rowNumber, '发货/退货时间'); + $billDate = $shipReturnAt ?? $paidRefundedAt; + if ($billDate === null) { + throw new RuntimeException("第 {$rowNumber} 行缺少可用于账期核验的发货/退货时间或支付/退款时间。"); + } + if ($billDate < $from->format('Y-m-d') . ' 00:00:00' + || $billDate >= $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') { + throw new RuntimeException("第 {$rowNumber} 行账单时间超出指定账期。"); + } + + $income = $this->money($values['income_amount'], $rowNumber, '收入金额', false); + $expense = $this->money($values['expense_amount'], $rowNumber, '支出金额', true); + $signed = bcsub($income, $expense, 2); + + $batch[] = [ + 'generation' => $generation, + 'record_code' => mb_substr($recordCode, 0, 191), + 'order_no' => $this->nullable($values['order_no'], 191), + 'online_order_no' => $this->nullable($values['online_order_no'], 191), + 'custom_remark' => $this->nullable($values['custom_remark']), + 'bill_item' => $billItem, + 'store_name' => $storeName, + 'order_type' => $this->nullable($values['order_type']), + 'goods_name' => $this->nullable($values['goods_name'], 1000), + 'goods_no' => $this->nullable($values['goods_no'], 191), + 'quantity' => $this->nullable($values['quantity'], 64), + 'channel' => mb_substr($channel, 0, 255), + 'business_type' => $this->nullable($values['business_type']), + 'income_amount' => $income, + 'expense_amount' => $expense, + 'signed_amount' => $signed, + 'online_real_store' => $this->nullable($values['online_real_store']), + 'order_created_at' => $this->optionalDateTime($values['order_created_at'], $rowNumber, '订单创建时间'), + 'paid_refunded_at' => $paidRefundedAt, + 'ship_return_at' => $shipReturnAt, + 'bill_date' => $billDate, + 'settle_status' => $this->nullable($values['settle_status']), + 'pay_period' => $this->nullable($values['pay_period']), + 'pulled_at' => $this->optionalDateTime($values['pulled_at'], $rowNumber, '拉取时间'), + 'source_updated_at' => $this->optionalDateTime($values['source_updated_at'], $rowNumber, '修改时间'), + 'source_modified_by' => $this->nullable($values['source_modified_by']), + 'source_row_number' => $rowNumber, + ]; + $rowCount++; + if ($storeName !== null) { + $stores[$storeName] = true; + } + if ($billItem !== null) { + $billItems[$billItem] = true; + } + $channelCounts[$channel] = ($channelCounts[$channel] ?? 0) + 1; + $incomeTotal = bcadd($incomeTotal, $income, 2); + $expenseTotal = bcadd($expenseTotal, $expense, 2); + + if (count($batch) >= $batchSize) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + $batch = []; + } + } + } finally { + $reader->close(); + } + + if ($headerMap === null) { + throw new RuntimeException('未找到聚胜算得物账单标准表头。'); + } + if ($batch !== []) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + } + if ($rowCount === 0) { + throw new RuntimeException('文件中没有得物完整账单数据。'); + } + + return [ + 'row_count' => $rowCount, + 'excluded_rows' => 0, + 'store_count' => count($stores), + 'bill_item_count' => count($billItems), + 'channel_counts' => $channelCounts, + 'income_total' => $incomeTotal, + 'expense_total' => $expenseTotal, + 'net_total' => bcsub($incomeTotal, $expenseTotal, 2), + ]; + } + + private function assertControls(array $stats, int $count, string $income, string $expense): void + { + if ($stats['row_count'] !== $count + || bccomp($stats['income_total'], $income, 2) !== 0 + || bccomp($stats['expense_total'], $expense, 2) !== 0) { + throw new RuntimeException(sprintf( + '权威控制数不一致:实际 %d 笔,收入 %s,支出 %s;期望 %d 笔,收入 %s,支出 %s。', + $stats['row_count'], + $stats['income_total'], + $stats['expense_total'], + $count, + $income, + $expense, + )); + } + } + + private function assertSameImportRequest( + object $existing, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + ): void { + if ((string) $existing->period_start !== $from->format('Y-m-d') + || (string) $existing->period_end !== $to->format('Y-m-d') + || (int) $existing->expected_row_count !== $expectedCount + || bccomp((string) $existing->expected_income_total, $expectedIncome, 2) !== 0 + || bccomp((string) $existing->expected_expense_total, $expectedExpense, 2) !== 0) { + throw new RuntimeException('该文件已有成功导入记录,但本次账期或权威控制数与历史记录不一致。'); + } + } + + private function activeRowCount( + string $hash, + DateTimeImmutable $from, + DateTimeImmutable $to, + ): int { + return $this->connection->table(self::ROW_TABLE) + ->where('source_sha256', $hash) + ->where('bill_date', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('bill_date', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->count(); + } + + private function activate( + string $generation, + string $hash, + DateTimeImmutable $from, + DateTimeImmutable $to, + array $stats, + int $batchSize, + ): void { + $now = now(); + $columns = [ + 'order_no', 'online_order_no', 'custom_remark', 'bill_item', 'store_name', 'order_type', + 'goods_name', 'goods_no', 'quantity', 'channel', 'business_type', 'income_amount', + 'expense_amount', 'signed_amount', 'online_real_store', 'order_created_at', + 'paid_refunded_at', 'ship_return_at', 'bill_date', 'settle_status', 'pay_period', + 'pulled_at', 'source_updated_at', 'source_modified_by', + 'source_row_number', 'source_generation', 'source_sha256', 'imported_at', + ]; + + $this->connection->transaction(function () use ( + $generation, $hash, $from, $to, $stats, $batchSize, $columns, $now + ): void { + $this->connection->table(self::ROW_TABLE) + ->where('bill_date', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('bill_date', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->delete(); + + $this->connection->table(self::STAGING_TABLE) + ->where('generation', $generation) + ->orderBy('id') + ->chunkById($batchSize, function ($rows) use ($generation, $hash, $columns, $now): void { + $payload = []; + foreach ($rows as $row) { + $payload[] = [ + 'record_code' => $row->record_code, + 'order_no' => $row->order_no, + 'online_order_no' => $row->online_order_no, + 'custom_remark' => $row->custom_remark, + 'bill_item' => $row->bill_item, + 'store_name' => $row->store_name, + 'order_type' => $row->order_type, + 'goods_name' => $row->goods_name, + 'goods_no' => $row->goods_no, + 'quantity' => $row->quantity, + 'channel' => $row->channel, + 'business_type' => $row->business_type, + 'income_amount' => $row->income_amount, + 'expense_amount' => $row->expense_amount, + 'signed_amount' => $row->signed_amount, + 'online_real_store' => $row->online_real_store, + 'order_created_at' => $row->order_created_at, + 'paid_refunded_at' => $row->paid_refunded_at, + 'ship_return_at' => $row->ship_return_at, + 'bill_date' => $row->bill_date, + 'settle_status' => $row->settle_status, + 'pay_period' => $row->pay_period, + 'pulled_at' => $row->pulled_at, + 'source_updated_at' => $row->source_updated_at, + 'source_modified_by' => $row->source_modified_by, + 'source_row_number' => $row->source_row_number, + 'source_generation' => $generation, + 'source_sha256' => $hash, + 'imported_at' => $now, + ]; + } + $this->connection->table(self::ROW_TABLE)->upsert($payload, ['record_code'], $columns); + }); + + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update([ + 'status' => 'succeeded', + 'row_count' => $stats['row_count'], + 'excluded_rows' => $stats['excluded_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'channel_counts' => json_encode($stats['channel_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'completed_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + }); + + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + } + + /** @return array */ + private function rowCells(string $xml, array $sharedStrings): array + { + $row = simplexml_load_string($xml); + if (! $row instanceof SimpleXMLElement) { + return []; + } + + $cells = []; + foreach ($row->xpath('./*[local-name()="c"]') ?: [] as $cell) { + $reference = (string) ($cell['r'] ?? ''); + if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) !== 1) { + continue; + } + $type = (string) ($cell['t'] ?? ''); + if ($type === 'inlineStr') { + $nodes = $cell->xpath('.//*[local-name()="t"]') ?: []; + $value = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } else { + $nodes = $cell->xpath('./*[local-name()="v"]') ?: []; + $raw = isset($nodes[0]) ? (string) $nodes[0] : ''; + $value = $type === 's' ? (string) ($sharedStrings[(int) $raw] ?? '') : $raw; + } + $cells[$this->columnIndex($matches[1])] = $value; + } + + return $cells; + } + + /** @param array $cells @return array */ + private function headerMap(array $cells): ?array + { + $lookup = []; + foreach ($cells as $column => $value) { + $lookup[trim($value)] = $column; + } + + $mapping = []; + foreach (self::HEADER_ALIASES as $field => $aliases) { + foreach ($aliases as $alias) { + if (array_key_exists($alias, $lookup)) { + $mapping[$field] = $lookup[$alias]; + break; + } + } + if (! array_key_exists($field, $mapping)) { + return null; + } + } + + return $mapping; + } + + private function required(array $values, string $key, int $row, ?string $label = null): string + { + $value = trim((string) ($values[$key] ?? '')); + if ($value === '') { + throw new RuntimeException("第 {$row} 行缺少" . ($label ?? $key) . '。'); + } + + return $value; + } + + private function money( + string $value, + int $row, + string $field, + bool $absolute = false, + bool $allowNegative = false, + ): string { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + $value = $value === '' ? '0' : $value; + if (! is_numeric($value) || (! $allowNegative && ! $absolute && bccomp($value, '0', 6) < 0)) { + throw new RuntimeException("第 {$row} 行{$field}不是有效金额。"); + } + if ($absolute && bccomp($value, '0', 6) < 0) { + $value = bcmul($value, '-1', 6); + } + + return bcadd($value, '0', 2); + } + + private function controlAmount(string $value, string $label): string + { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + if (! is_numeric($value) || bccomp($value, '0', 6) < 0) { + throw new RuntimeException("权威{$label}控制数无效。"); + } + + return bcadd($value, '0', 2); + } + + private function dateTime(string $value, int $row, string $field): string + { + $parsed = $this->parseDateTime($value); + if ($parsed === null) { + throw new RuntimeException("第 {$row} 行{$field}不是有效日期时间。"); + } + + return $parsed; + } + + private function optionalDateTime(string $value, int $row, string $field): ?string + { + if (trim($value) === '') { + return null; + } + + return $this->dateTime($value, $row, $field); + } + + private function parseDateTime(string $value): ?string + { + $value = trim($value); + try { + if (is_numeric($value)) { + $seconds = (int) round((((float) $value) - 25569) * 86400); + + return Carbon::createFromTimestampUTC($seconds)->format('Y-m-d H:i:s'); + } + + return Carbon::parse($value)->format('Y-m-d H:i:s'); + } catch (Throwable) { + return null; + } + } + + private function nullable(string $value, int $max = 255): ?string + { + $value = trim($value); + + return $value === '' ? null : mb_substr($value, 0, $max); + } + + private function columnIndex(string $letters): int + { + $index = 0; + foreach (str_split(strtoupper($letters)) as $letter) { + $index = ($index * 26) + ord($letter) - 64; + } + + return $index - 1; + } + + /** @return list */ + private function sharedStrings(string $path, ZipArchive $archive): array + { + if ($archive->locateName('xl/sharedStrings.xml') === false) { + return []; + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, 'xl/sharedStrings.xml'), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取 XLSX 共享文本。'); + } + + $strings = []; + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') { + continue; + } + $item = simplexml_load_string($reader->readOuterXml()); + $nodes = $item instanceof SimpleXMLElement ? ($item->xpath('.//*[local-name()="t"]') ?: []) : []; + $strings[] = implode('', array_map( + static fn (SimpleXMLElement $node): string => (string) $node, + $nodes, + )); + } + } finally { + $reader->close(); + } + + return $strings; + } + + private function firstWorksheet(ZipArchive $archive): string + { + $worksheets = []; + for ($index = 0; $index < $archive->numFiles; $index++) { + $name = $archive->getNameIndex($index); + if (is_string($name) && preg_match('#^xl/worksheets/sheet\d+\.xml$#', $name) === 1) { + $worksheets[] = $name; + } + } + sort($worksheets, SORT_NATURAL); + if ($worksheets === []) { + throw new RuntimeException('XLSX 文件中没有工作表。'); + } + + return $worksheets[0]; + } + + private function zipUri(string $path, string $entry): string + { + return 'zip://' . str_replace('\\', '/', $path) . '#' . $entry; + } + + private function result(array $row, string $status): array + { + return [ + 'status' => $status, + 'row_count' => (int) ($row['row_count'] ?? 0), + 'excluded_rows' => (int) ($row['excluded_rows'] ?? 0), + 'store_count' => (int) ($row['store_count'] ?? 0), + 'bill_item_count' => (int) ($row['bill_item_count'] ?? 0), + 'channel_counts' => $this->channelCounts($row['channel_counts'] ?? []), + 'income_total' => bcadd((string) ($row['income_total'] ?? '0'), '0', 2), + 'expense_total' => bcadd((string) ($row['expense_total'] ?? '0'), '0', 2), + 'net_total' => bcadd((string) ($row['net_total'] ?? '0'), '0', 2), + 'period_start' => (string) ($row['period_start'] ?? ''), + 'period_end' => (string) ($row['period_end'] ?? ''), + 'source_sha256' => (string) ($row['source_sha256'] ?? ''), + ]; + } + + /** @return array */ + private function channelCounts(mixed $value): array + { + if (is_string($value)) { + try { + $value = json_decode($value, true, 512, JSON_THROW_ON_ERROR); + } catch (Throwable) { + return []; + } + } + if (! is_array($value)) { + return []; + } + + $counts = []; + foreach ($value as $channel => $count) { + if (is_string($channel) && $channel !== '' && is_numeric($count)) { + $counts[$channel] = (int) $count; + } + } + + return $counts; + } +} diff --git a/modules/EcommerceFinance/Services/DouyinAuthoritativeBillImporter.php b/modules/EcommerceFinance/Services/DouyinAuthoritativeBillImporter.php index 9fd0a47d..7d8e3635 100644 --- a/modules/EcommerceFinance/Services/DouyinAuthoritativeBillImporter.php +++ b/modules/EcommerceFinance/Services/DouyinAuthoritativeBillImporter.php @@ -9,18 +9,26 @@ use InvalidArgumentException; use RuntimeException; use Throwable; -/** Imports a complete, explicitly reconciled month without changing upstream bills. */ +/** Imports a reconciled month-to-date range without changing upstream bills. */ class DouyinAuthoritativeBillImporter { public function __construct(private readonly DatabaseManager $databases) {} - public function import(string $path, string $month, int $expectedCount, string $expectedIncome, string $expectedExpense): array + public function import(string $path, string $month, int $expectedCount, string $expectedIncome, string $expectedExpense, ?string $through = null): array { if (! preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) || $expectedCount < 1) { throw new InvalidArgumentException('必须指定完整月份和核对后的笔数。'); } $start = $month . '-01'; $end = Carbon::parse($start)->addMonth()->format('Y-m-d'); + if ($through !== null) { + if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $through) + || ! checkdate((int) substr($through, 5, 2), (int) substr($through, 8, 2), (int) substr($through, 0, 4)) + || $through < $start || $through >= $end) { + throw new InvalidArgumentException('截止日期必须是指定月份内的有效日期。'); + } + $end = Carbon::parse($through)->addDay()->format('Y-m-d'); + } $expectedIncomeCents = $this->cents($expectedIncome); $expectedExpenseCents = $this->cents($expectedExpense); $file = fopen($path, 'rb'); @@ -91,7 +99,13 @@ class DouyinAuthoritativeBillImporter 'row_count' => $count, 'income' => $this->decimal($income), 'expense' => $this->decimal($expense), 'imported_at' => now()->format('Y-m-d H:i:s'), ]; - $db->transaction(fn () => $db->table('douyin_authoritative_periods')->updateOrInsert(['period_start' => $start], $state)); + $db->transaction(function () use ($db, $start, $end, $state): void { + $previous = $db->table('douyin_authoritative_periods')->where('period_start', $start)->lockForUpdate()->first(); + if ($previous !== null && $previous->period_end > $end) { + throw new InvalidArgumentException('截止日期早于已校准范围,请导出包含已校准日期的完整结果。'); + } + $db->table('douyin_authoritative_periods')->updateOrInsert(['period_start' => $start], $state); + }); return $state; } catch (Throwable $e) { $db->table('douyin_authoritative_bills')->where('generation', $generation)->delete(); diff --git a/modules/EcommerceFinance/Services/InternalFlowWorkbookImporter.php b/modules/EcommerceFinance/Services/InternalFlowWorkbookImporter.php new file mode 100644 index 00000000..397a7349 --- /dev/null +++ b/modules/EcommerceFinance/Services/InternalFlowWorkbookImporter.php @@ -0,0 +1,326 @@ + 'company_name', 'label' => '抬头', 'type' => 'text'], + ['field' => 'tag', 'label' => '标签', 'type' => 'text'], + ['field' => 'projected_sales', 'label' => '预计9月销量', 'type' => 'amount'], + ['field' => 'invoiced_to_buyer', 'label' => '开票-给买家开票', 'type' => 'amount'], + ['field' => 'internal_invoiced', 'label' => '开票-内部开票', 'type' => 'amount'], + ['field' => 'required_input_cost', 'label' => '所需进项成本', 'type' => 'amount'], + ['field' => 'receipt_from_supplier', 'label' => '收票-供应商', 'type' => 'amount'], + ['field' => 'receipt_from_suofeiya', 'label' => '收票-索菲亚', 'type' => 'amount'], + ['field' => 'receipt_from_gujia', 'label' => '收票-顾家', 'type' => 'amount'], + ['field' => 'internal_transfer_1', 'label' => '收票-内部流转(来源)1', 'type' => 'amount'], + ['field' => 'internal_transfer_2', 'label' => '收票-内部流转(来源)2', 'type' => 'amount'], + ['field' => 'internal_transfer_3', 'label' => '收票-内部流转(来源)3', 'type' => 'amount'], + ['field' => 'receipt_total', 'label' => '收票-合计', 'type' => 'amount'], + ['field' => 'remaining_gap', 'label' => '剩余缺口', 'type' => 'amount'], + ['field' => 'invoicing_ratio', 'label' => '开票比例', 'type' => 'text'], + ]; + + private const HEADER_ROWS = 3; + + private readonly ConnectionInterface $connection; + + public function __construct(DatabaseManager $databases) + { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{imported:int,skipped:int,source_file:string} + */ + public function import(string $path): array + { + $realPath = realpath($path); + + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new RuntimeException('内部流转工作簿不存在或不可读:' . $path); + } + + if (! Schema::connection($this->connection->getName())->hasTable(self::TABLE)) { + throw new RuntimeException('内部流转数据表尚未创建,请先执行数据库迁移。'); + } + + [$rows, $skipped] = $this->readRows($realPath); + + if ($rows === []) { + throw new RuntimeException('表格中没有可导入的数据行,请检查“' . self::SHEET_TITLE . '”工作表。'); + } + + $now = Carbon::now(); + $sourceFile = basename($realPath); + + $this->connection->transaction(function () use ($rows, $now, $sourceFile): void { + // 该报表是一份整体替换的月度数据集,重新导入时先清空上一版。 + $this->connection->table(self::TABLE)->delete(); + + foreach (array_chunk($rows, 200) as $chunk) { + $this->connection->table(self::TABLE)->insert(array_map( + static fn (array $row): array => $row + [ + 'source_file' => $sourceFile, + 'imported_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + $chunk, + )); + } + }); + + return [ + 'imported' => count($rows), + 'skipped' => $skipped, + 'source_file' => $sourceFile, + ]; + } + + /** + * @return array{0: list>, 1: int} + */ + private function readRows(string $path): array + { + $spreadsheet = IOFactory::load($path); + $sheet = $this->resolveSheet($spreadsheet->getAllSheets()); + + $grid = $sheet->toArray(null, true, false, false); + $this->expandMergedCells($grid, $sheet); + + $headerRow = $this->resolveHeaderRow($grid); + $columnMap = $this->resolveColumnMap($grid, $headerRow); + $missing = array_values(array_diff( + array_column(self::COLUMNS, 'field'), + array_values($columnMap), + )); + + if ($missing !== []) { + $labels = implode('、', array_map( + static fn (string $field): string => (string) (collect(self::COLUMNS)->firstWhere('field', $field)['label'] ?? $field), + $missing, + )); + + throw new RuntimeException('内部流转表头缺少列:' . $labels . '。'); + } + + $types = array_column(self::COLUMNS, 'type', 'field'); + $rows = []; + $skipped = 0; + $sortOrder = 0; + + foreach (array_slice($grid, $headerRow + self::HEADER_ROWS) as $line) { + $values = []; + + foreach ($columnMap as $columnIndex => $field) { + $values[$field] = $this->normalizeValue($line[$columnIndex] ?? null, $types[$field] ?? 'text'); + } + + $title = trim((string) ($values['company_name'] ?? '')); + + if ($title === '' || $title === '合计') { + if ($title !== '' || collect($values)->filter(static fn ($value): bool => $value !== null && $value !== '')->isNotEmpty()) { + $skipped++; + } + + continue; + } + + $values['company_name'] = $title; + $values['sort_order'] = ++$sortOrder; + $rows[] = $values; + } + + return [$rows, $skipped]; + } + + /** + * @param list $sheets + */ + private function resolveSheet(array $sheets): Worksheet + { + foreach ($sheets as $sheet) { + if ($sheet->getTitle() === self::SHEET_TITLE) { + return $sheet; + } + } + + throw new RuntimeException('未找到“' . self::SHEET_TITLE . '”工作表。'); + } + + /** + * @param list> $grid + */ + private function expandMergedCells(array &$grid, Worksheet $sheet): void + { + foreach ($sheet->getMergeCells() as $range) { + try { + [[$startColumn, $startRow], [$endColumn, $endRow]] = Coordinate::rangeBoundaries($range); + } catch (\Throwable) { + continue; + } + + $value = $grid[$startRow - 1][$startColumn - 1] ?? null; + + for ($row = $startRow; $row <= $endRow; $row++) { + for ($column = $startColumn; $column <= $endColumn; $column++) { + $grid[$row - 1][$column - 1] = $value; + } + } + } + } + + /** + * @param list> $grid + */ + private function resolveHeaderRow(array $grid): int + { + foreach (array_slice($grid, 0, 10, true) as $index => $line) { + if (collect($line)->contains(fn ($value): bool => $this->normalizeHeader($value) === '抬头')) { + return (int) $index; + } + } + + throw new RuntimeException('未找到以“抬头”开头的工作簿表头。'); + } + + /** + * 按三行表头的标签路径匹配目标字段,允许列位置变化。 + * + * @param list> $grid + * @return array 列下标 => 字段名 + */ + private function resolveColumnMap(array $grid, int $headerRow): array + { + $map = []; + $columnCount = 0; + + foreach (array_slice($grid, $headerRow, self::HEADER_ROWS) as $line) { + $columnCount = max($columnCount, count($line)); + } + + for ($column = 0; $column < $columnCount; $column++) { + $path = []; + + for ($row = $headerRow; $row < $headerRow + self::HEADER_ROWS; $row++) { + $value = $this->normalizeHeader($grid[$row][$column] ?? null); + + if ($value !== '') { + $path[] = $value; + } + } + + $field = $this->matchField($path); + + if ($field !== null) { + $map[$column] = $field; + } + } + + return $map; + } + + /** + * @param list $path + */ + private function matchField(array $path): ?string + { + if ($path === []) { + return null; + } + + $leaf = (string) end($path); + + return match (true) { + $leaf === '抬头' => 'company_name', + $leaf === '标签' => 'tag', + preg_match('/^预计\d+月销量$/u', $leaf) === 1 => 'projected_sales', + $leaf === '给买家开票' => 'invoiced_to_buyer', + $leaf === '内部开票' => 'internal_invoiced', + $leaf === '所需进项成本' => 'required_input_cost', + $leaf === '供应商' => 'receipt_from_supplier', + $leaf === '索菲亚' => 'receipt_from_suofeiya', + $leaf === '顾家' => 'receipt_from_gujia', + $leaf === '合计' => 'receipt_total', + $leaf === '剩余缺口' => 'remaining_gap', + $leaf === '开票比例' => 'invoicing_ratio', + in_array($leaf, ['1', '2', '3'], true) && in_array('内部流转(来源)', $path, true) => 'internal_transfer_' . $leaf, + default => null, + }; + } + + private function normalizeHeader(mixed $value): string + { + if ($value === null || is_bool($value) || is_array($value)) { + return ''; + } + + $text = trim((string) $value); + $text = str_replace(['(', ')', ' ', ' '], ['(', ')', '', ''], $text); + + return $text; + } + + private function normalizeValue(mixed $value, string $type): ?string + { + if ($value === null) { + return null; + } + + if ($type === 'text') { + if (is_float($value) && floor($value) === $value) { + return (string) (int) $value; + } + + $text = trim((string) $value); + + return $text === '' ? null : $text; + } + + if (is_int($value) || is_float($value)) { + return $this->decimal($value); + } + + $text = trim((string) $value); + + if ($text === '' || in_array($text, ['/', '—', '-', 'N/A'], true)) { + return null; + } + + $normalized = str_replace([',', ','], '', $text); + + return is_numeric($normalized) ? $this->decimal((float) $normalized) : null; + } + + private function decimal(float $value): string + { + $formatted = rtrim(rtrim(number_format($value, 6, '.', ''), '0'), '.'); + + return $formatted === '' || $formatted === '-' ? '0' : $formatted; + } +} diff --git a/modules/EcommerceFinance/Services/InventoryReportAuthoritativeImporter.php b/modules/EcommerceFinance/Services/InventoryReportAuthoritativeImporter.php new file mode 100644 index 00000000..aabe3f60 --- /dev/null +++ b/modules/EcommerceFinance/Services/InventoryReportAuthoritativeImporter.php @@ -0,0 +1,527 @@ + */ + private const REQUIRED_HEADERS = [ + '货主', '月份', '仓储方', '仓库', '商品编码', '分类', '期初数量', '期末数量', + '加工进仓', '加工出仓', '采购进仓', '采购退货', '其它进仓', '其它退货', + '销售出仓', '销售退货', '盘点', '调拨出', '调拨入', '期初', '其它出库', + ]; + + /** @var list */ + private const MOVEMENT_HEADERS = [ + '加工进仓', '加工出仓', '采购进仓', '采购退货', '其它进仓', '其它退货', + '销售出仓', '销售退货', '盘点', '调拨出', '调拨入', '期初', '其它出库', + ]; + + private readonly ConnectionInterface $connection; + + public function __construct(DatabaseManager $databases) + { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** @return array{status:string,source_rows:int,source_month:string,generation:string} */ + public function import(string $path): array + { + $path = $this->validatedPath($path); + $this->assertSchemaReady(); + + $generation = (string) Str::uuid(); + $now = now(); + $hash = hash_file('sha256', $path); + if (! is_string($hash)) { + throw new RuntimeException('无法计算进销存月报文件摘要。'); + } + + $this->connection->table(self::STATE_TABLE)->insertOrIgnore([ + 'dataset_key' => self::DATASET_KEY, + 'status' => 'pending', + 'created_at' => $now, + 'updated_at' => $now, + ]); + $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->update([ + 'status' => 'running', + 'pending_generation' => $generation, + 'last_attempted_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + + try { + $source = $this->readAndStore($path, $generation, $now); + $this->connection->transaction(function () use ( + $generation, + $path, + $hash, + $source, + $now, + ): void { + if ($this->hasMonthlyStateTable()) { + $this->connection->table(self::MONTH_TABLE)->updateOrInsert( + [ + 'dataset_key' => self::DATASET_KEY, + 'source_month' => $source['source_month'], + ], + [ + 'status' => 'succeeded', + 'active_generation' => $generation, + 'source_filename' => mb_substr(basename($path), 0, 255), + 'source_sha256' => $hash, + 'source_row_count' => $source['source_rows'], + 'last_succeeded_at' => $now, + 'updated_at' => $now, + ], + ); + } + $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->update([ + 'status' => 'succeeded', + 'active_generation' => $generation, + 'pending_generation' => null, + 'source_filename' => mb_substr(basename($path), 0, 255), + 'source_sha256' => $hash, + 'source_month' => $source['source_month'], + 'source_row_count' => $source['source_rows'], + 'last_succeeded_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + }); + } catch (Throwable $exception) { + $this->connection->table(self::ROW_TABLE) + ->where('generation', $generation) + ->delete(); + $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->update([ + 'status' => 'failed', + 'pending_generation' => null, + 'last_error_code' => class_basename($exception), + 'updated_at' => now(), + ]); + + throw $exception; + } + + try { + $keepGenerations = [$generation]; + if ($this->hasMonthlyStateTable()) { + $keepGenerations = array_merge( + $keepGenerations, + $this->connection->table(self::MONTH_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->whereNotNull('active_generation') + ->pluck('active_generation') + ->map(static fn (mixed $value): string => (string) $value) + ->all(), + ); + } + $keepGenerations = array_values(array_unique(array_filter($keepGenerations))); + $this->connection->table(self::ROW_TABLE) + ->whereNotIn('generation', $keepGenerations) + ->delete(); + } catch (Throwable $exception) { + report($exception); + } + + return [ + 'status' => 'succeeded', + 'source_rows' => $source['source_rows'], + 'source_month' => $source['source_month'], + 'generation' => $generation, + ]; + } + + private function validatedPath(string $path): string + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new InvalidArgumentException('进销存月报文件不存在或不可读。'); + } + if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') { + throw new InvalidArgumentException('进销存权威月报导入只支持 XLSX 文件。'); + } + + return $realPath; + } + + private function assertSchemaReady(): void + { + $schema = Schema::connection($this->connection->getName()); + foreach ([self::STATE_TABLE, self::ROW_TABLE] as $table) { + if (! $schema->hasTable($table)) { + throw new RuntimeException('进销存权威月报表尚未完成迁移:' . $table); + } + } + } + + private function hasMonthlyStateTable(): bool + { + return Schema::connection($this->connection->getName())->hasTable(self::MONTH_TABLE); + } + + /** @return array{source_rows:int,source_month:string} */ + private function readAndStore(string $path, string $generation, mixed $importedAt): array + { + $archive = new ZipArchive(); + if ($archive->open($path) !== true) { + throw new InvalidArgumentException('无法打开进销存月报 XLSX 文件。'); + } + + try { + $sharedStrings = $this->sharedStrings($path, $archive); + $worksheet = $this->worksheetWithHeaders($path, $archive, $sharedStrings); + } finally { + $archive->close(); + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new InvalidArgumentException('无法读取进销存月报 XLSX 工作表。'); + } + + $columns = []; + $seen = []; + $sourceMonth = null; + $rowCount = 0; + $batch = []; + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + + $rowNumber = (int) ($reader->getAttribute('r') ?: 0); + $values = $this->row($reader->readOuterXml(), $sharedStrings); + if ($columns === []) { + $columns = $this->headerColumns($values); + if ($columns === [] && $rowNumber < 20) { + continue; + } + if ($columns === []) { + throw new InvalidArgumentException('前 20 行中未找到进销存月报标准表头。'); + } + continue; + } + if ($this->emptyRow($values)) { + continue; + } + + $month = $this->month($values[$columns['月份']] ?? null, $rowNumber); + if ($sourceMonth !== null && $sourceMonth !== $month) { + throw new InvalidArgumentException('进销存权威月报必须只包含一个月份。'); + } + $sourceMonth = $month; + + $owner = $this->requiredText($values[$columns['货主']] ?? null, $rowNumber, '货主'); + $warehouseProvider = $this->requiredText( + $values[$columns['仓储方']] ?? null, + $rowNumber, + '仓储方', + ); + $warehouse = $this->requiredText($values[$columns['仓库']] ?? null, $rowNumber, '仓库'); + $productCode = ProductCatalogAuthoritativeExportImporter::normalizeSkuId( + (string) ($values[$columns['商品编码']] ?? ''), + ); + if ($productCode === '') { + throw new InvalidArgumentException("第 {$rowNumber} 行“商品编码”不能为空。"); + } + + $rowKey = hash('sha256', implode("\0", [ + $month, + $warehouseProvider, + $warehouse, + $productCode, + ])); + if (isset($seen[$rowKey])) { + throw new InvalidArgumentException( + "第 {$rowNumber} 行与第 {$seen[$rowKey]} 行的月份、仓储方、仓库和商品编码重复。", + ); + } + $seen[$rowKey] = $rowNumber; + + $opening = $this->number($values[$columns['期初数量']] ?? null, $rowNumber, '期初数量'); + $closing = $this->number($values[$columns['期末数量']] ?? null, $rowNumber, '期末数量'); + $movement = 0.0; + $movementValues = []; + foreach (self::MOVEMENT_HEADERS as $header) { + $movementValues[$header] = $this->number( + $values[$columns[$header]] ?? null, + $rowNumber, + $header, + ); + $movement += $movementValues[$header]; + } + if (abs(($opening + $movement) - $closing) > 0.0001) { + throw new InvalidArgumentException( + "第 {$rowNumber} 行期初数量加进出数量不等于期末数量。", + ); + } + + $batch[] = [ + 'generation' => $generation, + 'row_key' => $rowKey, + 'report_month' => $month, + 'owner' => mb_substr($owner, 0, 191), + 'warehouse_provider' => mb_substr($warehouseProvider, 0, 191), + 'warehouse' => mb_substr($warehouse, 0, 191), + 'product_code' => mb_substr($productCode, 0, 191), + 'category' => $this->nullableText($values[$columns['分类']] ?? null, 191), + 'opening_quantity' => $opening, + 'closing_quantity' => $closing, + 'processing_in' => $movementValues['加工进仓'], + 'processing_out' => $movementValues['加工出仓'], + 'purchase_in' => $movementValues['采购进仓'], + 'purchase_return' => $movementValues['采购退货'], + 'other_in' => $movementValues['其它进仓'], + 'other_return' => $movementValues['其它退货'], + 'sales_out' => $movementValues['销售出仓'], + 'sales_return' => $movementValues['销售退货'], + 'stocktake' => $movementValues['盘点'], + 'transfer_out' => $movementValues['调拨出'], + 'transfer_in' => $movementValues['调拨入'], + 'opening' => $movementValues['期初'], + 'other_out' => $movementValues['其它出库'], + 'imported_at' => $importedAt, + ]; + $rowCount++; + + if (count($batch) >= 500) { + $this->connection->table(self::ROW_TABLE)->insert($batch); + $batch = []; + } + } + } finally { + $reader->close(); + } + + if ($batch !== []) { + $this->connection->table(self::ROW_TABLE)->insert($batch); + } + if ($columns === [] || $rowCount === 0 || $sourceMonth === null) { + throw new InvalidArgumentException('进销存权威月报中没有可用明细。'); + } + + return ['source_rows' => $rowCount, 'source_month' => $sourceMonth]; + } + + /** @return array */ + private function row(string $xml, array $sharedStrings): array + { + $row = simplexml_load_string($xml); + if (! $row instanceof SimpleXMLElement) { + return []; + } + + $values = []; + foreach ($row->xpath('./*[local-name()="c"]') ?: [] as $cell) { + $reference = (string) ($cell['r'] ?? ''); + if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) !== 1) { + continue; + } + $column = Coordinate::columnIndexFromString(strtoupper($matches[1])); + $type = (string) ($cell['t'] ?? ''); + if ($type === 'inlineStr') { + $nodes = $cell->xpath('.//*[local-name()="t"]') ?: []; + $value = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } else { + $nodes = $cell->xpath('./*[local-name()="v"]') ?: []; + $raw = isset($nodes[0]) ? (string) $nodes[0] : ''; + $value = $type === 's' ? (string) ($sharedStrings[(int) $raw] ?? '') : $raw; + } + $values[$column] = $value; + } + + return $values; + } + + /** @param array $values @return array */ + private function headerColumns(array $values): array + { + $lookup = []; + foreach ($values as $column => $value) { + $heading = trim((string) $value); + if ($heading !== '') { + $lookup[$heading] = $column; + } + } + foreach (self::REQUIRED_HEADERS as $header) { + if (! isset($lookup[$header])) { + return []; + } + } + + return array_intersect_key($lookup, array_flip(self::REQUIRED_HEADERS)); + } + + /** @param array $values */ + private function emptyRow(array $values): bool + { + foreach ($values as $value) { + if (trim((string) $value) !== '') { + return false; + } + } + + return true; + } + + private function month(mixed $value, int $rowNumber): string + { + try { + $date = is_numeric($value) + ? Carbon::instance(ExcelDate::excelToDateTimeObject((float) $value)) + : Carbon::parse(str_replace('/', '-', trim((string) $value))); + } catch (Throwable) { + throw new InvalidArgumentException("第 {$rowNumber} 行“月份”不是有效日期。"); + } + + return $date->startOfMonth()->toDateString(); + } + + private function requiredText(mixed $value, int $rowNumber, string $label): string + { + $text = trim((string) $value); + if ($text === '') { + throw new InvalidArgumentException("第 {$rowNumber} 行“{$label}”不能为空。"); + } + + return $text; + } + + private function nullableText(mixed $value, int $length): ?string + { + $text = trim((string) $value); + + return $text === '' ? null : mb_substr($text, 0, $length); + } + + private function number(mixed $value, int $rowNumber, string $label): float + { + if ($value === null || trim((string) $value) === '') { + return 0.0; + } + $normalized = str_replace([',', ','], '', trim((string) $value)); + if (! is_numeric($normalized)) { + throw new InvalidArgumentException("第 {$rowNumber} 行“{$label}”不是有效数字。"); + } + + return round((float) $normalized, 4); + } + + /** @return list */ + private function sharedStrings(string $path, ZipArchive $archive): array + { + if ($archive->locateName('xl/sharedStrings.xml') === false) { + return []; + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, 'xl/sharedStrings.xml'), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new InvalidArgumentException('无法读取 XLSX 共享文本。'); + } + + $strings = []; + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') { + continue; + } + $item = simplexml_load_string($reader->readOuterXml()); + $nodes = $item instanceof SimpleXMLElement + ? ($item->xpath('.//*[local-name()="t"]') ?: []) + : []; + $strings[] = implode('', array_map( + static fn (SimpleXMLElement $node): string => (string) $node, + $nodes, + )); + } + } finally { + $reader->close(); + } + + return $strings; + } + + /** + * Exports may contain pivot summaries or helper sheets before the detail + * sheet. Select the worksheet that actually contains the authoritative + * monthly-report headers instead of assuming sheet1 is the data sheet. + * + * @param array $sharedStrings + */ + private function worksheetWithHeaders(string $path, ZipArchive $archive, array $sharedStrings): string + { + $worksheets = []; + for ($index = 0; $index < $archive->numFiles; $index++) { + $name = $archive->getNameIndex($index); + if (is_string($name) && preg_match('#^xl/worksheets/sheet\d+\.xml$#', $name) === 1) { + $worksheets[] = $name; + } + } + sort($worksheets, SORT_NATURAL); + if ($worksheets === []) { + throw new InvalidArgumentException('XLSX 文件中没有工作表。'); + } + + foreach ($worksheets as $worksheet) { + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + continue; + } + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + + if ($this->headerColumns($this->row($reader->readOuterXml(), $sharedStrings)) !== []) { + return $worksheet; + } + } + } finally { + $reader->close(); + } + } + + throw new InvalidArgumentException('XLSX 文件中未找到包含完整进销存月报表头的工作表。'); + } + + private function zipUri(string $path, string $entry): string + { + return 'zip://' . str_replace('\\', '/', $path) . '#' . $entry; + } +} diff --git a/modules/EcommerceFinance/Services/JdDailyBillImporter.php b/modules/EcommerceFinance/Services/JdDailyBillImporter.php new file mode 100644 index 00000000..7dae4ba9 --- /dev/null +++ b/modules/EcommerceFinance/Services/JdDailyBillImporter.php @@ -0,0 +1,141 @@ + '线上单号', 'document_no' => '单据编号', + 'merchant_order_no' => '商户订单号', 'document_type' => '单据类型', + 'product_id' => '商品编码', 'product_name' => '商品名称', + 'cost_happened_at' => '费用发生时间', 'cost_name' => '费用项', + 'currency' => '币种', 'settle_remark' => '钱包结算备注', + 'shop_no' => '店铺号', 'jd_shop_no' => '京东门店编码', + 'brand_shop_no' => '品牌门店编号', 'shop_name' => '门店名称', + 'account_code' => '账户代码', + ]; + + public function __construct(private readonly DatabaseManager $databases) {} + + public function import(string $path, string $month, int $expectedCount, string $expectedIncome, string $expectedExpense, ?string $through = null): array + { + if (! preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) || $expectedCount < 1) { + throw new InvalidArgumentException('必须指定完整月份及核对笔数。'); + } + $expectedIn = $this->cents($expectedIncome); + $expectedOut = $this->cents($expectedExpense); + $start = $month . '-01'; + $end = Carbon::parse($start)->addMonth()->format('Y-m-d'); + if ($through !== null) { + $date = \DateTimeImmutable::createFromFormat('!Y-m-d', $through); + if (! $date || $date->format('Y-m-d') !== $through || $through < $start || $through >= $end) { + throw new InvalidArgumentException('截止日期必须是指定月份内的有效日期。'); + } + $end = $date->modify('+1 day')->format('Y-m-d'); + } + $file = fopen($path, 'rb'); + if ($file === false) throw new RuntimeException('无法读取京东日账单明细。'); + $db = $this->databases->connection(config('upstream_mirrors.connection', 'business_mirror')); + $generation = (string) Str::uuid(); + $count = $income = $expense = 0; + $batch = []; + try { + $headers = fgetcsv($file); + if (! is_array($headers)) throw new InvalidArgumentException('明细为空。'); + $headers[0] = preg_replace('/^\xEF\xBB\xBF/', '', $headers[0]); + $required = array_merge(['记录编码', '店铺', '账单项目', '订单编号', '费用结算时间', '收入金额', '支出金额'], array_values(self::PAYLOAD_FIELDS)); + if (count(array_unique($headers)) !== count($headers) || array_diff($required, $headers)) { + throw new InvalidArgumentException('京东日账单字段缺失或重复。'); + } + while (($values = fgetcsv($file)) !== false) { + if ($values === [null]) continue; + if (count($values) !== count($headers)) throw new InvalidArgumentException('明细列数不一致。'); + $r = array_combine($headers, $values); + $code = trim($r['记录编码']); + if (! preg_match('/^\d{1,64}$/', $code)) throw new InvalidArgumentException('记录编码为空或失真。'); + $time = $this->dateTime($r['费用结算时间']); + if ($time === null || $time < $start || $time >= $end || trim($r['店铺']) === '') { + throw new InvalidArgumentException('费用结算时间或店铺不符合导入范围。'); + } + if (trim($r['币种']) !== 'CNY') throw new InvalidArgumentException('不能合并不同币种的账单金额。'); + $in = $this->cents($r['收入金额']); + $out = $this->cents($r['支出金额']); + $payload = []; + foreach (self::PAYLOAD_FIELDS as $key => $label) $payload[$key] = $r[$label] !== '' ? $r[$label] : null; + $payload['cost_happened_at'] = $this->dateTime($r['费用发生时间']); + $row = [ + 'id' => 'shengsuan-jd:' . $code, 'record_code' => $code, + 'store_name' => trim($r['店铺']), 'bill_item' => $r['账单项目'], + 'order_no' => $r['订单编号'], 'occurred_at' => $time, + 'income' => $this->decimal($in), 'expense' => $this->decimal($out), + 'custom_remark' => $r['自定义备注'] ?? null, 'remark' => $r['备注'] ?? null, + 'updated_at' => $this->dateTime($r['修改时间'] ?? ''), + 'modifier' => $r['修改人'] ?? null, 'payload' => $payload, + ]; + $batch[] = [ + 'generation' => $generation, 'record_code' => $code, 'store_name' => $row['store_name'], + 'bill_item' => $row['bill_item'], 'order_no' => $row['order_no'], 'occurred_at' => $time, + 'income' => $row['income'], 'expense' => $row['expense'], + 'row_data' => json_encode($row, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + ]; + $count++; $income += $in; $expense += $out; + // The generation primary key rejects duplicate source records, including across batches. + if (count($batch) === 500) { + $db->table('jd_daily_bill_rows')->insert($batch); + $batch = []; + } + } + if ($count !== $expectedCount || $income !== $expectedIn || $expense !== $expectedOut) { + throw new InvalidArgumentException('笔数或收支合计不一致,未启用此明细。'); + } + if ($batch !== []) $db->table('jd_daily_bill_rows')->insert($batch); + $state = [ + 'period_start' => $start, 'period_end' => $end, 'active_generation' => $generation, + 'source_filename' => basename($path), 'source_sha256' => hash_file('sha256', $path), + 'row_count' => $count, 'income' => $this->decimal($income), 'expense' => $this->decimal($expense), + 'imported_at' => now()->format('Y-m-d H:i:s'), + ]; + // Publish only the reconciled date range; keep the preceding generation for rollback. + $db->transaction(function () use ($db, $start, $end, $state): void { + $previous = $db->table('jd_daily_bill_periods')->where('period_start', $start)->lockForUpdate()->first(); + if ($previous !== null && $previous->period_end > $end) { + throw new InvalidArgumentException('截止日期早于已导入范围,未替换现有账单。'); + } + $db->table('jd_daily_bill_periods')->updateOrInsert(['period_start' => $start], $state); + }); + return $state; + } catch (Throwable $e) { + $db->table('jd_daily_bill_rows')->where('generation', $generation)->delete(); + throw $e; + } finally { + fclose($file); + } + } + + private function cents(string $value): int + { + if (! preg_match('/^\d{1,14}(?:\.\d{1,2})?$/', trim($value))) throw new InvalidArgumentException('金额必须为精确到分的非负数。'); + [$whole, $fraction] = array_pad(explode('.', trim($value), 2), 2, ''); + return (int) $whole * 100 + (int) str_pad($fraction, 2, '0'); + } + + private function decimal(int $value): string + { + return intdiv($value, 100) . '.' . str_pad((string) ($value % 100), 2, '0', STR_PAD_LEFT); + } + + private function dateTime(string $value): ?string + { + if (trim($value) === '') return null; + $date = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value); + if (! $date || $date->format('Y-m-d H:i:s') !== $value) throw new InvalidArgumentException('账单时间格式无效。'); + return $value; + } +} diff --git a/modules/EcommerceFinance/Services/JdWalletBillImporter.php b/modules/EcommerceFinance/Services/JdWalletBillImporter.php new file mode 100644 index 00000000..b0f9d996 --- /dev/null +++ b/modules/EcommerceFinance/Services/JdWalletBillImporter.php @@ -0,0 +1,147 @@ + '线上单号', 'serial_no' => '流水号', + 'tx_order_no' => '交易订单号', 'account_name' => '账户名称', + 'bill_date' => '账单日期', 'merchant_order_no' => '商户订单号', + 'tx_remark' => '交易备注', 'tx_type' => '交易类型', 'currency' => '币种', + 'book_request_no' => '记账请求号', 'business_order_no' => '业务订单号', + ]; + + public function __construct(private readonly DatabaseManager $databases) {} + + public function import(string $path, string $month, int $expectedCount, string $expectedIncome, string $expectedExpense, ?string $through = null): array + { + if (! preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) || $expectedCount < 1) { + throw new InvalidArgumentException('必须指定完整月份及核对笔数。'); + } + $expectedIn = $this->cents($expectedIncome); + $expectedOut = $this->cents($expectedExpense); + $start = $month . '-01'; + $end = Carbon::parse($start)->addMonth()->format('Y-m-d'); + if ($through !== null) { + $date = \DateTimeImmutable::createFromFormat('!Y-m-d', $through); + if (! $date || $date->format('Y-m-d') !== $through || $through < $start || $through >= $end) { + throw new InvalidArgumentException('截止日期必须是指定月份内的有效日期。'); + } + $end = $date->modify('+1 day')->format('Y-m-d'); + } + $file = fopen($path, 'rb'); + if ($file === false) throw new RuntimeException('无法读取京东钱包明细。'); + $db = $this->databases->connection(config('upstream_mirrors.connection', 'business_mirror')); + $generation = (string) Str::uuid(); + $count = $income = $expense = 0; + $batch = []; + try { + $headers = fgetcsv($file); + if (! is_array($headers)) throw new InvalidArgumentException('明细为空。'); + $headers[0] = preg_replace('/^\xEF\xBB\xBF/', '', $headers[0]); + $required = array_merge(['记录编码', '店铺', '账单项目', '账户余额', '费用结算时间', '收入金额', '支出金额'], array_values(self::PAYLOAD_FIELDS)); + if (count(array_unique($headers)) !== count($headers) || array_diff($required, $headers)) { + throw new InvalidArgumentException('京东钱包字段缺失或重复。'); + } + while (($values = fgetcsv($file)) !== false) { + if ($values === [null]) continue; + if (count($values) !== count($headers)) throw new InvalidArgumentException('明细列数不一致。'); + $r = array_combine($headers, $values); + $code = trim($r['记录编码']); + if (! preg_match('/^\d{1,64}$/', $code)) throw new InvalidArgumentException('记录编码为空或失真。'); + $time = $this->dateTime($r['费用结算时间']); + if ($time === null || $time < $start || $time >= $end || trim($r['店铺']) === '') { + throw new InvalidArgumentException('费用结算时间或店铺不符合导入范围。'); + } + if (trim($r['币种']) !== 'CNY') throw new InvalidArgumentException('不能合并不同币种的账单金额。'); + $in = $this->cents($r['收入金额']); + $out = $this->cents($r['支出金额']); + $payload = []; + foreach (self::PAYLOAD_FIELDS as $key => $label) $payload[$key] = $r[$label] !== '' ? $r[$label] : null; + $payload['bill_date'] = $this->dateTime($r['账单日期']); + $balance = $this->signedCents($r['账户余额']); + $row = [ + 'id' => 'shengsuan-jd-wallet:' . $code, 'record_code' => $code, + 'store_name' => trim($r['店铺']), 'bill_item' => $r['账单项目'], + 'order_no' => $r['交易订单号'], 'occurred_at' => $time, + 'income' => $this->decimal($in), 'expense' => $this->decimal($out), + 'balance' => $this->decimal($balance), + 'custom_remark' => $r['自定义备注'] ?? null, 'remark' => $r['交易备注'] ?? null, + 'updated_at' => $this->dateTime($r['修改时间'] ?? ''), + 'modifier' => $r['修改人'] ?? null, 'payload' => $payload, + ]; + $batch[] = [ + 'generation' => $generation, 'record_code' => $code, 'store_name' => $row['store_name'], + 'bill_item' => $row['bill_item'], 'order_no' => $row['order_no'], 'occurred_at' => $time, + 'income' => $row['income'], 'expense' => $row['expense'], + 'balance' => $row['balance'], 'account_name' => $r['账户名称'], + 'row_data' => json_encode($row, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + ]; + $count++; $income += $in; $expense += $out; + // The generation primary key rejects duplicate source records, including across batches. + if (count($batch) === 500) { + $db->table('jd_wallet_bill_rows')->insert($batch); + $batch = []; + } + } + if ($count !== $expectedCount || $income !== $expectedIn || $expense !== $expectedOut) { + throw new InvalidArgumentException('笔数或收支合计不一致,未启用此明细。'); + } + if ($batch !== []) $db->table('jd_wallet_bill_rows')->insert($batch); + $state = [ + 'period_start' => $start, 'period_end' => $end, 'active_generation' => $generation, + 'source_filename' => basename($path), 'source_sha256' => hash_file('sha256', $path), + 'row_count' => $count, 'income' => $this->decimal($income), 'expense' => $this->decimal($expense), + 'imported_at' => now()->format('Y-m-d H:i:s'), + ]; + // Activate only the reconciled range and retain the previous generation for rollback. + $db->transaction(function () use ($db, $start, $end, $state): void { + $previous = $db->table('jd_wallet_bill_periods')->where('period_start', $start)->lockForUpdate()->first(); + if ($previous !== null && $previous->period_end > $end) { + throw new InvalidArgumentException('截止日期早于已导入范围,未替换现有账单。'); + } + $db->table('jd_wallet_bill_periods')->updateOrInsert(['period_start' => $start], $state); + }); + return $state; + } catch (Throwable $e) { + $db->table('jd_wallet_bill_rows')->where('generation', $generation)->delete(); + throw $e; + } finally { + fclose($file); + } + } + + private function cents(string $value): int + { + if (! preg_match('/^\d{1,14}(?:\.\d{1,2})?$/', trim($value))) throw new InvalidArgumentException('金额必须为精确到分的非负数。'); + [$whole, $fraction] = array_pad(explode('.', trim($value), 2), 2, ''); + return (int) $whole * 100 + (int) str_pad($fraction, 2, '0'); + } + + private function signedCents(string $value): int + { + $value = trim($value); + return str_starts_with($value, '-') ? -$this->cents(substr($value, 1)) : $this->cents($value); + } + + private function decimal(int $value): string + { + return ($value < 0 ? '-' : '') . intdiv(abs($value), 100) . '.' . str_pad((string) (abs($value) % 100), 2, '0', STR_PAD_LEFT); + } + + private function dateTime(string $value): ?string + { + if (trim($value) === '') return null; + $date = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value); + if (! $date || $date->format('Y-m-d H:i:s') !== $value) throw new InvalidArgumentException('账单时间格式无效。'); + return $value; + } +} diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index 668c415f..3ff9bcf0 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -4,7 +4,11 @@ namespace Modules\EcommerceFinance\Services\Jushuitan; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; +use InvalidArgumentException; +use Modules\EcommerceFinance\Services\UpstreamConnection; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; +use PDOException; +use RuntimeException; use Throwable; /** @@ -21,17 +25,57 @@ use Throwable; */ class ShippingReplicaSynchronizer { + private const UPSTREAM_RECONNECT_RETRIES = 2; + private const SOURCE = 'operations_replica'; private const DATASET = 'jst.sctrade'; + private const FREIGHT_DATASET_PREFIX = 'jst.sctrade.freight.'; + private const ITEMS_DATASET_PREFIX = 'jst.sctrade.items.'; private const AUTOSHIP_OFFSET = 1000000000; private const OUTBOUND_OFFSET = 2000000000; private const PURCHASE_OUT_OFFSET = 3000000000; + private const DEMO_SOURCE_IDS = [9000001, 9000002, 9000003, 9000004, 9000005, 9000006]; private const FLUSH = 300; + private const PRESERVED_PACKAGE_FIELDS = [ + 'buyer_nick', 'seller_memo', 'package_no', 'download_time', 'freight_rate', 'freight_formula', + 'settle_volume_cm3', 'recon_weight_kg', 'recon_volume_cm3', 'front_no', + ]; + private const PRESERVED_CONTACT_FIELDS = ['receiver_name', 'receiver_mobile', 'receiver_phone']; + private const PRESERVED_ITEM_FIELDS = ['finished_barcode', 'finished_name', 'finished_supplier']; private const VIEW = 'rpt.Jst_SendData_View_extension'; private const OUTBOUND = 'rpt.jst_salesOutboundInfo'; private const PURCHASE_OUT = 'rpt.jst_purchaseout'; + private int $maxExpressBatches = 5000; + private int $maxAutoShipBatches = 600; + private bool $skipFreight = false; + private bool $replaceWindow = false; + + /** @var array>> */ + private array $replacementPackages = []; + /** @var array */ + private array $replacementHasFreight = []; + /** @var array */ + private array $replacementHasItems = []; + /** @var array> */ + private array $replacementSyntheticSkuIds = []; + private int $replacementRowCount = 0; + private int $packagesProcessed = 0; + private int $packagesWithoutItems = 0; + private int $packagesRetainedForMissingItems = 0; + private int $packagesRetainedForUnmatchedAmount = 0; + private int $staleMirrorPackages = 0; + + /** @var array */ + private array $seenSourceIds = []; + + /** @var array 发货明细已占用的窗口内订单号 */ + private array $expressOrderIds = []; + + /** @var list */ + private array $dwsFailedDays = []; + private readonly \Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery $up; private readonly \Illuminate\Database\ConnectionInterface $db; @@ -53,6 +97,9 @@ class ShippingReplicaSynchronizer /** 快递单号(去@) => [交易单号 => true]:同一单号被不同交易单号共用(合包/拼单)时,按交易单号区分是否已处理 */ private array $doneTrackSo = []; + /** @var array 本轮按规则排除的包裹 source_id(取消/拆分/合并/线上发货),窗口内旧记录需清掉 */ + private array $excludedSourceIds = []; + /** @var array 最近一次 loadViewItems 的 io_id => 平台(视图 shop_site,工作平台口径) */ private array $ioSite = []; @@ -64,6 +111,11 @@ class ShippingReplicaSynchronizer /** @var array 最近一次 loadViewItems 的 io_id => 视图店铺名(发货明细缺店铺时兜底) */ private array $ioShop = []; + /** @var array 已查询订单元数据缓存 o_id=>字段 */ + private array $orderMetadata = []; + + /** @var array 窗口内出库单映射(见 emptyIoMap) */ + private array $outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; public function __construct(UpstreamReadOnlyQueryFactory $factory) { @@ -77,20 +129,34 @@ class ShippingReplicaSynchronizer return new self(app(UpstreamReadOnlyQueryFactory::class)); } - public function sync(?Carbon $from = null, ?Carbon $to = null, int $limit = 2000, ?callable $progress = null): array + public function sync(?Carbon $from = null, ?Carbon $to = null, int $limit = 2000, ?callable $progress = null, bool $skipFreight = false): array { $this->markRunning(); try { $windowed = $from && $to; + if ($skipFreight && ! $windowed) { + throw new InvalidArgumentException('跳过运费仅支持指定起止日期的历史补录。'); + } + $this->skipFreight = $skipFreight; + $this->replaceWindow = (bool) $windowed; + $this->packagesProcessed = 0; + $this->packagesWithoutItems = 0; + $this->packagesRetainedForMissingItems = 0; + $this->packagesRetainedForUnmatchedAmount = 0; + $this->staleMirrorPackages = 0; + $this->seenSourceIds = []; + $this->expressOrderIds = []; + $this->dwsFailedDays = []; $now = now(); $fromS = $windowed ? $from->format('Y-m-d H:i:s') : null; $toS = $windowed ? $to->format('Y-m-d H:i:s') : null; + if ($skipFreight) { + $this->markFreightIncomplete($fromS, $toS); + } - $this->db->table('jst_oms_shipping')->where('source_id', '>=', 9000000) - ->where('source_id', '<', self::AUTOSHIP_OFFSET)->delete(); - if ($windowed) { - $this->db->table('jst_oms_shipping') - ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)->delete(); + $this->db->table('jst_oms_shipping')->whereIn('source_id', self::DEMO_SOURCE_IDS)->delete(); + if ($skipFreight && $progress) { + $progress('仅补数量:按包裹分批替换,已有运费/结算重量在事务中保留;不预删日期窗口'); } $total = 0; @@ -101,75 +167,138 @@ class ShippingReplicaSynchronizer $this->doneTrack = []; $this->emittedTrack = []; $this->doneTrackSo = []; + $this->excludedSourceIds = []; $this->ioDate = []; if ($windowed) { $this->preloadDws($from, $to); + $this->preloadOutboundMap($fromS, $toS); if ($progress) { $progress('dws 预载完成:' . count($this->dwsCache) . ' 个 sourceno'); + $progress(sprintf( + '出库映射预载完成:%d 个快递单号,%d 个内部单号', + count($this->outboundMap['byL']), + count($this->outboundMap['byO']), + )); } $total = $this->syncExpress(true, $fromS, $toS, $limit, $now, $progress); + $this->orderMetadata = []; // 全表扫描后释放(数百万订单),后续各步不再使用 + gc_collect_cycles(); $auto = $this->syncAutoShip($fromS, $toS, $now, $progress); $outb = $this->syncOutbound($fromS, $toS, $now, $progress); $pout = $this->syncPurchaseOut($fromS, $toS, $now, $progress); - $this->dwsCache = []; - gc_collect_cycles(); - $removed = $this->dedupAtPrefix($fromS, $toS); - if ($progress && $removed > 0) { - $progress('去除@重复单号:' . $removed . ' 条'); + $purged = $this->purgeExcludedPackages($fromS, $toS); + if ($progress && $purged > 0) { + $progress('清除已排除包裹(取消/拆分/合并/线上发货):' . $purged . ' 行'); + } + $this->staleMirrorPackages = $this->countUnseenMirrorPackages($fromS, $toS); + if (! $skipFreight && $this->staleMirrorPackages === 0) { + $removed = $this->dedupAtPrefix($fromS, $toS); + if ($progress && $removed > 0) { + $progress('去除@重复单号:' . $removed . ' 条'); + } } } else { $total = $this->syncExpress(false, $fromS, $toS, $limit, $now, $progress); } - $this->markSucceeded(); - return ['processed' => $total, 'autoship' => $auto, 'outbound' => $outb, 'purchase_out' => $pout]; + if ($windowed && ! $skipFreight && $this->staleMirrorPackages === 0) { + $this->markCovered(self::FREIGHT_DATASET_PREFIX, $fromS, $toS); + } + + if ($windowed && ($this->dwsFailedDays !== [] || $this->packagesWithoutItems > 0 + || $this->packagesRetainedForUnmatchedAmount > 0)) { + $this->markItemsIncomplete($fromS, $toS); + } elseif ($windowed && ! $skipFreight && $this->staleMirrorPackages === 0) { + $this->markCovered(self::ITEMS_DATASET_PREFIX, $fromS, $toS); + } + + $result = ['processed' => $total, 'autoship' => $auto]; + if ($windowed) { + $result['outbound'] = $outb; + $result['purchase_out'] = $pout; + $result['packages'] = $this->packagesProcessed; + $result['unique_packages'] = count($this->seenSourceIds); + $result['packages_without_items'] = $this->packagesWithoutItems; + $result['packages_retained_for_missing_items'] = $this->packagesRetainedForMissingItems; + $result['packages_retained_for_unmatched_amount'] = $this->packagesRetainedForUnmatchedAmount; + $result['dws_failed_days'] = $this->dwsFailedDays; + $result['stale_mirror_packages'] = $this->staleMirrorPackages; + } + if ($skipFreight) { + $result['freight_incomplete'] = true; + } + + if ($this->staleMirrorPackages > 0) { + $this->markIncompleteWindow($this->staleMirrorPackages); + } else { + $this->markSucceeded(); + } + return $result; } catch (Throwable $e) { $this->markFailed($e->getMessage()); throw $e; + } finally { + $this->dwsCache = []; + $this->orderMetadata = []; + $this->outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; + $this->replacementPackages = []; + $this->replacementHasFreight = []; + $this->replacementHasItems = []; + $this->replacementSyntheticSkuIds = []; + $this->replacementRowCount = 0; + $this->skipFreight = false; + $this->replaceWindow = false; + $this->dwsFailedDays = []; + $this->seenSourceIds = []; + $this->expressOrderIds = []; + gc_collect_cycles(); } } - /** 去除以 @ 开头、去@后已存在的重复单号(换单/重拉产生;工作平台只保留干净版)。 */ + /** @X 与 X 仅在同一订单、同一发货日去重;提供日期窗口时不使用窗口外记录作匹配;剩余 @ 前缀统一去掉。 */ public function dedupAtPrefix(?string $fromS = null, ?string $toS = null): int { - // 只删"同一交易单号下 @X 与 X 并存"的 @X 行;不同交易单号/窗口外的旧行不作为依据, - // 避免窗口外残留的旧 X 行把窗口内真实包裹 @X 误删(如作废重出的出库单)。 - // 只在本次同步窗口内互相比对:窗口外的历史残留行不参与(否则会误删窗口内真实包裹) - $win = function ($q) use ($fromS, $toS) { - if ($fromS !== null && $toS !== null) { - $q->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); + $query = $this->db->table('jst_oms_shipping') + ->whereNotNull('express_no')->where('express_no', '!=', ''); + if ($fromS !== null && $toS !== null) { + $query->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); + } + $clean = []; + $prefixed = []; + foreach ($query->distinct()->cursor(['source_id', 'trade_no', 'express_no', 'ship_time']) as $row) { + $tradeNo = trim((string) $row->trade_no); + $expressNo = (string) $row->express_no; + $sourceId = (int) $row->source_id; + $shipDate = substr((string) $row->ship_time, 0, 10); + if ($tradeNo === '' || $sourceId <= 0 || $shipDate === '') { + continue; + } + if ($expressNo[0] === '@') { + $prefixed[$sourceId] = [$tradeNo, $shipDate, substr($expressNo, 1)]; + } else { + $clean[$tradeNo][$shipDate][$expressNo] = true; } - - return $q; - }; - $at = $win($this->db->table('jst_oms_shipping')->where('express_no', 'like', '@%')) - ->select('express_no', 'trade_no')->distinct()->get(); - if ($at->isEmpty()) { - return 0; } - $plain = []; - foreach ($at as $r) { - $plain[substr((string) $r->express_no, 1)] = true; - } - $have = []; - foreach (array_chunk(array_keys($plain), 500) as $chunk) { - foreach ($win($this->db->table('jst_oms_shipping')->whereIn('express_no', $chunk)) - ->select('express_no', 'trade_no')->distinct()->get() as $r) { - $have[(string) $r->express_no . '|' . (string) $r->trade_no] = true; + $toDel = []; + foreach ($prefixed as $sourceId => [$tradeNo, $shipDate, $expressNo]) { + if ($expressNo !== '' && isset($clean[$tradeNo][$shipDate][$expressNo])) { + $toDel[] = $sourceId; } } $removed = 0; - foreach ($at as $r) { - $x = substr((string) $r->express_no, 1); - if (isset($have[$x . '|' . (string) $r->trade_no])) { - $removed += (int) $win($this->db->table('jst_oms_shipping') - ->where('express_no', (string) $r->express_no) - ->where('trade_no', $r->trade_no))->delete(); + foreach (array_chunk($toDel, 500) as $chunk) { + $delete = $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk); + if ($fromS !== null && $toS !== null) { + $delete->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); } + $removed += (int) $delete->delete(); } - // 剩余 @X:工作平台导出单号不带 @,统一去掉前缀 - $win($this->db->table('jst_oms_shipping')->where('express_no', 'like', '@%')) - ->update(['express_no' => $this->db->raw('SUBSTRING(express_no, 2)')]); + // 剩余 @X:工作平台导出单号不带 @,统一去掉前缀(只处理本次窗口) + $strip = $this->db->table('jst_oms_shipping')->where('express_no', 'like', '@%'); + if ($fromS !== null && $toS !== null) { + $strip->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); + } + $strip->update(['express_no' => $this->db->raw('SUBSTR(express_no, 2)')]); return $removed; } @@ -178,11 +307,10 @@ class ShippingReplicaSynchronizer private function syncExpress(bool $windowed, ?string $fromS, ?string $toS, int $limit, $now, ?callable $progress = null): int { $batch = 1500; - $maxBatches = 5000; + $maxBatches = $this->maxExpressBatches; $cols = 'e.id, e.so_id, e.inner_order_id, e.logistic_id, e.logistic_company_name, e.send_time, e.pay_time, ' . 'e.shop_name, e.platform_name, e.dis_co_name, e.warehouse_name, e.receiver_address, ' - . 'e.weight, e.f_weight, e.buyer_message, e.order_labels, jo.l_id AS jo_lid, jo.send_date AS jo_send, ' - . 'jo.status AS jo_status, jo.labels AS jo_labels'; + . 'e.weight, e.f_weight, e.buyer_message, e.order_labels'; // 窗口模式:只按主键 e.id 翻页(有索引,毫秒级),send_time 窗口过滤放到 PHP, // 避免每页都对无索引的 send_time 做全表扫描(那是"卡死"的真凶)。 @@ -192,9 +320,7 @@ class ShippingReplicaSynchronizer $total = 0; $scanned = 0; $lastId = null; - $entered = false; - - for ($b = 0; $b < $maxBatches; $b++) { + for ($b = 0; $b <= $maxBatches; $b++) { $where = $windowed ? '1 = 1' : 'e.send_time IS NOT NULL'; $bind = []; if ($lastId !== null) { @@ -202,36 +328,41 @@ class ShippingReplicaSynchronizer $bind[] = $lastId; } $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_order_express_details e " - . 'LEFT JOIN rpt.jst_Orders jo ON jo.o_id = e.inner_order_id ' . "WHERE {$where} ORDER BY e.id DESC"; - $rows = $this->up->select($sql, $bind); + $rows = $this->selectWithReconnect($sql, $bind); if ($rows === []) { break; } + if ($b === $maxBatches) { + throw new RuntimeException('发货扫描达到批次上限,仍有未读取的上游数据。'); + } $cnt = count($rows); $scanned += $cnt; foreach ($rows as $r) { $lastId = $r['id']; } - $pageNewest = null; - $pageHit = false; + // 主表分页不联接订单表;每页只按 inner_order_id 分块补齐订单字段, + // 并复用已经缓存的结果,避免 LEFT JOIN 在大历史窗口上拖垮游标。 + $this->loadOrderMetadataForRows($rows); + $rows = array_map(fn (array $row): array => $this->mergeOrderMetadata($row), $rows); + if ($windowed) { $kept = []; foreach ($rows as $r) { + $jd = $r['jo_send'] ?? null; + $joTs = ($jd !== null && $jd !== '') ? strtotime((string) $jd) : null; + $oid = (string) ($r['inner_order_id'] ?? ''); + if ($oid !== '' && $joTs !== null && $joTs !== false && $joTs >= $fromTs && $joTs < $toTs) { + $this->expressOrderIds[$oid] = true; + } $st = $r['send_time'] ?? null; $ts = ($st !== null && $st !== '') ? strtotime((string) $st) : null; if ($ts === null) { - $jd = $r['jo_send'] ?? null; - $ts = ($jd !== null && $jd !== '') ? strtotime((string) $jd) : null; - } - if ($ts !== null && ($pageNewest === null || $ts > $pageNewest)) { - $pageNewest = $ts; + $ts = $joTs; } if ($ts !== null && $ts >= $fromTs && $ts < $toTs) { $kept[] = $r; - $pageHit = true; - $entered = true; } } $rows = $kept; @@ -254,7 +385,7 @@ class ShippingReplicaSynchronizer $logs[$lg] = true; } } - [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds)); + [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds), ! $windowed); $dws = []; foreach (array_keys($soIds) as $mso) { if (empty($bySo[$mso]) && ! empty($this->dwsCache[$mso])) { @@ -262,7 +393,7 @@ class ShippingReplicaSynchronizer } } // 主口径:发货数据视图按出库单(io_id)取实发商品 - $ioMap = $this->loadIoMap(array_keys($logs), array_keys($oids)); + $ioMap = $this->ioMapFor($windowed, array_keys($logs), array_keys($oids)); $swap = $this->pairChangedTracking($rows, $ioMap); $ioIds = []; foreach ($rows as $r) { @@ -275,7 +406,7 @@ class ShippingReplicaSynchronizer } $viewItems = $this->loadViewItems(array_keys($ioIds)); $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo, $dws, $viewItems)); - $freight = $this->loadFreight(array_keys($soIds)); + $freight = $this->skipFreight ? [] : $this->loadFreight(array_keys($soIds)); foreach ($rows as $r) { $pkgId = (int) ($r['id'] ?? 0); @@ -287,6 +418,7 @@ class ShippingReplicaSynchronizer // 只登记本行自己的单号,不登记订单单号(可能是子单真实单号,需留给出库单兜底) $this->markDone('', (string) ($r['logistic_id'] ?? '')); $this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['logistic_id'] ?? '')); + $this->excludeSource($pkgId); continue; } $sw = $swap[(string) $pkgId] ?? null; @@ -302,6 +434,7 @@ class ShippingReplicaSynchronizer ); $this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['logistic_id'] ?? ''), (string) ($r['jo_lid'] ?? '')); if ($this->excludedByLabel($r['order_labels'] ?? null) || $this->excludedByLabel($r['jo_labels'] ?? null)) { + $this->excludeSource($pkgId); continue; // 线上发货(平台代发/云仓):工作平台不拉,对齐排除(发货明细标签可能滞后,订单标签一并判断) } $so = (string) ($r['so_id'] ?? ''); @@ -334,10 +467,6 @@ class ShippingReplicaSynchronizer if ($progress && $b % 20 === 0) { $progress(sprintf('发货:已扫描 %d 行,命中窗口 %d 件', $scanned, $total)); } - // 表远大于窗口时提前结束:已进入窗口,且本页整页都早于窗口(id≈时间倒序)。 - if ($windowed && $entered && ! $pageHit && $pageNewest !== null && $fromTs !== null && $pageNewest < $fromTs) { - break; - } if ($cnt < $batch) { break; } @@ -346,18 +475,103 @@ class ShippingReplicaSynchronizer } } if ($progress) { - $progress(sprintf('发货完成:扫描 %d 行,写入 %d 件', $scanned, $total)); + $progress(sprintf('发货完成:扫描 %d 行,处理 %d 件', $scanned, $total)); } - $this->flush(); + $this->flushPending(); return $total; } + /** 按当前页订单键补齐订单字段,并复用已缓存的结果。 */ + private function loadOrderMetadataForRows(array $rows): void + { + $oids = []; + foreach ($rows as $row) { + $oid = (string) ($row['inner_order_id'] ?? ''); + if ($oid !== '' && ! array_key_exists($oid, $this->orderMetadata)) { + $oids[$oid] = true; + } + } + foreach (array_chunk(array_keys($oids), 800) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + $sql = "SELECT o_id, l_id, send_date, status, labels FROM rpt.jst_Orders om WHERE om.o_id IN ({$ph})"; + foreach ($this->selectWithReconnect($sql, $chunk) as $row) { + $oid = (string) ($row['o_id'] ?? ''); + if ($oid === '') { + continue; + } + // 全表扫描会缓存数百万订单:只留判断需要的精简字段(状态仅存会被排除的三种,标签只存是否线上发货) + $st = (string) ($row['status'] ?? ''); + $this->orderMetadata[$oid] = [ + 'l_id' => $row['l_id'] ?? null, + 'send_date' => $row['send_date'] ?? null, + 'status' => in_array($st, ['Cancelled', 'Split', 'Merged'], true) ? $st : null, + 'online' => $this->excludedByLabel($row['labels'] ?? null), + ]; + } + foreach ($chunk as $oid) { + // 记录无匹配订单,避免后续分页反复查询同一个缺失键。 + $this->orderMetadata[$oid] ??= ['l_id' => null, 'send_date' => null, 'status' => null, 'online' => false]; + } + } + } + + /** 将订单元数据映射到发货明细,保留测试/兼容来源已提供的字段。 */ + private function mergeOrderMetadata(array $row): array + { + $oid = (string) ($row['inner_order_id'] ?? ''); + $metadata = $oid !== '' ? ($this->orderMetadata[$oid] ?? []) : []; + if (($row['jo_lid'] ?? '') === '' && ($metadata['l_id'] ?? '') !== '') { + $row['jo_lid'] = $metadata['l_id']; + } + if (($row['jo_send'] ?? '') === '' && ($metadata['send_date'] ?? '') !== '') { + $row['jo_send'] = $metadata['send_date']; + } + // 订单状态/标签:取消/拆分/合并 与 订单级"线上发货"标签的排除判断用 + if (($row['jo_status'] ?? '') === '' && ($metadata['status'] ?? '') !== '') { + $row['jo_status'] = $metadata['status']; + } + if (($row['jo_labels'] ?? '') === '' && ! empty($metadata['online'])) { + $row['jo_labels'] = '线上发货'; + } + + return $row; + } + + /** @return list> */ + private function selectWithReconnect(string $sql, array $bindings): array + { + for ($retry = 0; ; $retry++) { + try { + return $this->up->select($sql, $bindings); + } catch (PDOException $e) { + if (! $this->isTransientCursorFailure($e) || $retry >= self::UPSTREAM_RECONNECT_RETRIES) { + throw $e; + } + + // select() returns only after fetchAll(), so no partial result was consumed. + UpstreamConnection::reset(self::SOURCE); + usleep(250000); + } + } + } + + private function isTransientCursorFailure(PDOException $e): bool + { + $message = strtolower($e->getMessage()); + + return str_contains($message, 'pdo_dblib: dbnextrow() returned fail') + || str_contains($message, 'adaptive server connection timed out [20003]'); + } + /** 并入自动发货仓:jst_Orders 已发货但不在发货明细表。 */ private function syncAutoShip(string $fromS, string $toS, $now, ?callable $progress = null): int { $batch = 400; - $maxBatches = 600; + $maxBatches = $this->maxAutoShipBatches; $cols = 'o.Id AS rid, o.o_id, o.so_id, o.l_id, o.logistics_company, o.order_from, o.labels, ' . 'o.shop_name, o.send_date, o.pay_date, o.weight, o.buyer_message, ' . 'o.receiver_state, o.receiver_city, o.receiver_district, o.receiver_address, ' @@ -366,19 +580,32 @@ class ShippingReplicaSynchronizer $total = 0; $lastRid = null; - for ($b = 0; $b < $maxBatches; $b++) { - $where = "o.status = 'Sent' AND o.send_date >= ? AND o.send_date < ? " - . 'AND NOT EXISTS (SELECT 1 FROM rpt.jst_order_express_details e WHERE e.inner_order_id = o.o_id)'; + for ($b = 0; $b <= $maxBatches; $b++) { + $where = "o.status = 'Sent' AND o.send_date >= ? AND o.send_date < ?"; $bind = [$fromS, $toS]; if ($lastRid !== null) { $where .= ' AND o.Id < ?'; $bind[] = $lastRid; } $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_Orders o WHERE {$where} ORDER BY o.Id DESC"; - $rows = $this->up->select($sql, $bind); + $rows = $this->selectWithReconnect($sql, $bind); if ($rows === []) { break; } + if ($b === $maxBatches) { + throw new RuntimeException('代发仓扫描达到批次上限,仍有未读取的上游数据。'); + } + + $cnt = count($rows); + $eligible = []; + foreach ($rows as $r) { + $lastRid = $r['rid']; + $oid = (string) ($r['o_id'] ?? ''); + if ($oid !== '' && ! isset($this->expressOrderIds[$oid])) { + $eligible[] = $r; + } + } + $rows = $eligible; $oids = []; $soIds = []; @@ -396,16 +623,15 @@ class ShippingReplicaSynchronizer if ($lg !== '') { $logs[$lg] = true; } - $lastRid = $r['rid']; } - [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds)); + [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds), false); $dws = []; foreach (array_keys($soIds) as $mso) { if (empty($bySo[$mso]) && ! empty($this->dwsCache[$mso])) { $dws[$mso] = $this->dwsCache[$mso]; } } - $ioMap = $this->loadIoMap(array_keys($logs), array_keys($oids)); + $ioMap = $this->ioMapFor(true, array_keys($logs), array_keys($oids)); $ioIds = []; foreach ($rows as $r) { $io = $this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), (string) ($r['o_id'] ?? '')); @@ -415,9 +641,8 @@ class ShippingReplicaSynchronizer } $viewItems = $this->loadViewItems(array_keys($ioIds)); $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo, $dws, $viewItems)); - $freight = $this->loadFreight(array_keys($soIds)); + $freight = $this->skipFreight ? [] : $this->loadFreight(array_keys($soIds)); - $cnt = count($rows); foreach ($rows as $r) { $oid = (string) ($r['o_id'] ?? ''); if ($oid === '') { @@ -431,6 +656,7 @@ class ShippingReplicaSynchronizer $this->markDone($this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), $oid), (string) ($r['l_id'] ?? '')); $this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['l_id'] ?? '')); if ($this->excludedByLabel($r['labels'] ?? null)) { + $this->excludeSource(self::AUTOSHIP_OFFSET + (int) $oid); continue; // 线上发货:对齐排除 } $so = (string) ($r['so_id'] ?? ''); @@ -454,9 +680,9 @@ class ShippingReplicaSynchronizer } } if ($progress) { - $progress(sprintf('代发仓完成:写入 %d 件', $total)); + $progress(sprintf('代发仓完成:处理 %d 件', $total)); } - $this->flush(); + $this->flushPending(); return $total; } @@ -483,6 +709,38 @@ class ShippingReplicaSynchronizer return $map[$base] ?? $raw; } + /** 记下按规则排除的包裹;同步结束后清掉它在本窗口里的旧记录(此前版本可能写入过)。 */ + private function excludeSource(int $sourceId): void + { + if ($sourceId > 0) { + $this->excludedSourceIds[$sourceId] = true; + } + } + + /** + * 清除本窗口内"本轮明确排除"的包裹旧记录,并视为已扫描(不计入未见镜像包裹)。 + * 只删明确排除的 source_id,未出现在上游扫描里的其它旧记录仍按原逻辑保留待核。 + */ + private function purgeExcludedPackages(string $fromS, string $toS): int + { + $this->flushPending(); + $ids = []; + foreach (array_keys($this->excludedSourceIds) as $id) { + if (! isset($this->seenSourceIds[$id])) { + $ids[] = $id; + $this->seenSourceIds[$id] = true; + } + } + $removed = 0; + foreach (array_chunk($ids, 500) as $chunk) { + $removed += (int) $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk) + ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)->delete(); + } + $this->excludedSourceIds = []; + + return $removed; + } + /** 登记 单号×交易单号 已处理。 */ private function markTrackSo(string $so, string ...$tracks): void { @@ -516,7 +774,7 @@ class ShippingReplicaSynchronizer */ private function syncOutbound(string $fromS, string $toS, $now, ?callable $progress = null): int { - $mm = $this->up->select('SELECT MIN(Id) AS lo, MAX(Id) AS hi FROM ' . self::OUTBOUND . ' WHERE io_date >= ? AND io_date < ?', [$fromS, $toS]); + $mm = $this->selectWithReconnect('SELECT MIN(Id) AS lo, MAX(Id) AS hi FROM ' . self::OUTBOUND . ' WHERE io_date >= ? AND io_date < ?', [$fromS, $toS]); $lo = (int) ($mm[0]['lo'] ?? 0); $hi = (int) ($mm[0]['hi'] ?? 0); if ($lo <= 0 || $hi < $lo) { @@ -538,7 +796,7 @@ class ShippingReplicaSynchronizer $page = 0; for ($a = $lo; $a <= $hi; $a += $step) { $page++; - $rows = $this->up->select( + $rows = $this->selectWithReconnect( "SELECT {$cols} FROM " . self::OUTBOUND . ' WHERE Id >= ? AND Id < ? AND io_date >= ? AND io_date < ?', [$a, $a + $step, $fromS, $toS] ); @@ -584,7 +842,7 @@ class ShippingReplicaSynchronizer } } $skus = $this->loadSkus($this->collectSkuIds($viewItems)); - $freight = $this->loadFreight(array_map('strval', array_keys($soIds))); + $freight = $this->skipFreight ? [] : $this->loadFreight(array_map('strval', array_keys($soIds))); foreach ($pick as $io => $r) { $io = (string) $io; if (empty($viewItems[$io])) { @@ -614,7 +872,7 @@ class ShippingReplicaSynchronizer $progress(sprintf('出库单兜底:已扫描 %d 行,补吐 %d 包裹', $scanned, $emitted)); } } - $this->flush(); + $this->flushPending(); if ($progress) { $progress(sprintf( '出库单兜底完成:扫描 %d 行,补吐 %d 包裹 / %d 行;跳过 已处理%d 无单号%d 取消删除%d 标签%d 无商品%d', @@ -631,7 +889,7 @@ class ShippingReplicaSynchronizer */ private function syncPurchaseOut(string $fromS, string $toS, $now, ?callable $progress = null): int { - $rows = $this->up->select( + $rows = $this->selectWithReconnect( 'SELECT io_id, io_date, status, l_id, so_id, logistics_company, receiver_state, receiver_city, receiver_district, ' . 'receiver_address, receiver_name, receiver_mobile FROM ' . self::PURCHASE_OUT . ' WHERE io_date >= ? AND io_date < ?', [$fromS, $toS] @@ -663,7 +921,7 @@ class ShippingReplicaSynchronizer $poQty = []; foreach (array_chunk($ioIds, 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); - foreach ($this->up->select("SELECT io_id, sku_id, qty FROM rpt.jst_purchaseoutItem WHERE io_id IN ({$ph})", $ck) as $pr) { + foreach ($this->selectWithReconnect("SELECT io_id, sku_id, qty FROM rpt.jst_purchaseoutItem WHERE io_id IN ({$ph})", $ck) as $pr) { $pk = mb_strtolower(trim((string) ($pr['sku_id'] ?? ''))); $poQty[(string) $pr['io_id']][$pk] = ($poQty[(string) $pr['io_id']][$pk] ?? 0) + (float) ($pr['qty'] ?? 0); } @@ -714,7 +972,7 @@ class ShippingReplicaSynchronizer $emitted++; } } - $this->flush(); + $this->flushPending(); if ($progress) { $progress(sprintf( '采购退货出库完成:窗口 %d 单,补吐 %d 包裹 / %d 行;跳过 已处理%d 已取消%d 视图无商品%d', @@ -737,7 +995,7 @@ class ShippingReplicaSynchronizer $sql = 'SELECT io_id, MAX(shop_site) AS site, MAX(so_id) AS so, MAX(receiver_state) AS st, MAX(receiver_city) AS ci, ' . 'MAX(receiver_district) AS di, MAX(shop_name) AS sn, MAX(expressName) AS ex FROM ' . self::VIEW . " WHERE io_id IN ({$ph}) GROUP BY io_id"; - foreach ($this->up->select($sql, $chunk) as $r) { + foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $out[(string) $r['io_id']] = $r; } } @@ -781,7 +1039,7 @@ class ShippingReplicaSynchronizer /** * 输出一个包裹的所有明细行(每件一行;无商品则一行空商品)。 - * @return int 写入行数 + * @return int 组装行数 */ private function emitPackage(int $pkgId, array $pkg, array $items, array $skus, array $freight, string $so, ?string $tracking, $now, bool $auto = false): int { @@ -791,23 +1049,37 @@ class ShippingReplicaSynchronizer if ($tk !== '') { $this->emittedTrack[$tk] = true; } + $this->seenSourceIds[$pkgId] = true; + $this->packagesProcessed++; + if ($n === 0) { + $this->packagesWithoutItems++; + } $f = $freight[$so . '|' . ($tracking ?? '')] ?? ($freight[$so . '|'] ?? []); + $hasFreight = isset($f['cost']); + $packageRows = []; if ($n === 0) { - $this->push($pkgId, $pkgId, $this->buildRow($pkg, [], [], $f, true, '1/1', $now, $auto)); + $packageRows[] = $this->packageRow($pkgId, $pkgId, $this->buildRow($pkg, [], [], $f, true, '1/1', $now, $auto)); + $this->writePackage($pkgId, $packageRows, $hasFreight, false, []); return 1; } $count = 0; + $syntheticSkuIds = []; foreach ($items as $idx => $it) { $first = ($idx === 0); $sk = (! empty($it['sku']) && isset($skus[(string) $it['sku']])) ? $skus[(string) $it['sku']] : []; $skuSid = (int) ($it['id'] ?? ($pkgId * 100 + $idx)); - $this->push($pkgId, $skuSid, $this->buildRow($pkg, $it, $sk, $f, $first, '1/' . $n, $now, $auto)); + if (($it['id'] ?? null) === null) { + $syntheticSkuIds[$skuSid] = true; + } + $packageRows[] = $this->packageRow($pkgId, $skuSid, $this->buildRow($pkg, $it, $sk, $f, $first, '1/' . $n, $now, $auto)); $count++; } + $this->writePackage($pkgId, $packageRows, $hasFreight, true, $syntheticSkuIds); + return $count; } @@ -866,7 +1138,7 @@ class ShippingReplicaSynchronizer $pkgWeight = (float) ($pkg['weight'] ?? 0) ?: null; $freightW = (float) ($f['w'] ?? 0); - $settleW = $freightW > 0 ? $freightW : ($pkgWeight ?: $onlineW); + $settleW = $this->skipFreight ? null : ($freightW > 0 ? $freightW : ($pkgWeight ?: $onlineW)); return $this->cleanPayload([ 'express_no' => $pkg['tracking'], @@ -982,7 +1254,7 @@ class ShippingReplicaSynchronizer } /** @return array{0:array,1:array} [byOid, bySo] */ - private function loadAllItems(array $oids, array $soIds): array + private function loadAllItems(array $oids, array $soIds, bool $loadBySoId = true): array { $byOid = []; $bySo = []; @@ -993,22 +1265,28 @@ class ShippingReplicaSynchronizer continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); - foreach ($this->up->select("SELECT {$sel} FROM rpt.jst_OrderItem WHERE o_id IN ({$ph}) ORDER BY Id", $chunk) as $r) { + foreach ($this->selectWithReconnect("SELECT {$sel} FROM rpt.jst_OrderItem WHERE o_id IN ({$ph}) ORDER BY Id", $chunk) as $r) { $k = (string) ($r['o_id'] ?? ''); if ($k !== '') { $byOid[$k][] = $this->itemArr($r); } } } - foreach (array_chunk($soIds, 800) as $chunk) { - if ($chunk === []) { - continue; - } - $ph = implode(',', array_fill(0, count($chunk), '?')); - foreach ($this->up->select("SELECT {$sel} FROM rpt.jst_OrderItem WHERE raw_so_id IN ({$ph}) ORDER BY Id", $chunk) as $r) { - $k = (string) ($r['raw_so_id'] ?? ''); - if ($k !== '') { - $bySo[$k][] = $this->itemArr($r); + // raw_so_id lacks a usable index in the production replica. Windowed sync already + // preloads DWS rows by sourceno, so querying this fallback can turn every batch into + // a full-table scan and exceed the upstream timeout. Keep it only for the small, + // non-windowed diagnostic mode where DWS is not preloaded. + if ($loadBySoId) { + foreach (array_chunk($soIds, 800) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + foreach ($this->selectWithReconnect("SELECT {$sel} FROM rpt.jst_OrderItem WHERE raw_so_id IN ({$ph}) ORDER BY Id", $chunk) as $r) { + $k = (string) ($r['raw_so_id'] ?? ''); + if ($k !== '') { + $bySo[$k][] = $this->itemArr($r); + } } } } @@ -1027,8 +1305,9 @@ class ShippingReplicaSynchronizer $d = $day->format('Y-m-d'); $day = $day->addDay(); try { - $rows = $this->up->select("SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE stat_date = ?", [$d]); + $rows = $this->selectWithReconnect("SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE stat_date = ?", [$d]); } catch (Throwable) { + $this->dwsFailedDays[] = $d; continue; } foreach ($rows as $r) { @@ -1062,7 +1341,7 @@ class ShippingReplicaSynchronizer } $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = "SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE sourceno IN ({$ph})"; - foreach ($this->up->select($sql, $chunk) as $r) { + foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $so = (string) ($r['sourceno'] ?? ''); $barcode = (string) ($r['skuoid'] ?? ''); if ($so === '' || $barcode === '') { @@ -1108,24 +1387,72 @@ class ShippingReplicaSynchronizer return []; } - /** 快递单号/内部单号 -> 出库单 io_id(优先快递单号,精确到该次出库)。 */ + /** 窗口同步按 io_date 一次预载,避免对无可用索引的 l_id/o_id 反复执行 IN 查询。 */ + private function preloadOutboundMap(string $fromS, string $toS): void + { + $map = $this->emptyIoMap(); + $sql = 'SELECT l_id, o_id, io_id, io_date, status FROM ' . self::OUTBOUND . ' WHERE io_date >= ? AND io_date < ?'; + foreach ($this->selectWithReconnect($sql, [$fromS, $toS]) as $r) { + $this->addIoRow($map, $r, true, true); + } + unset($map['rank']); + $this->outboundMap = $map; + } + + private function ioMapFor(bool $windowed, array $logisticIds, array $oIds): array + { + return $windowed ? $this->outboundMap : $this->loadIoMap($logisticIds, $oIds); + } + + /** + * 出库单映射:byL 单号->io、byO 订单->io、byLO 单号|订单->io、byOAll 订单->[io=>单号](仅有效单)、ioL io->单号。 + * 同一单号/订单可能有多张出库单(作废重出):优先有效(非 Delete/Cancelled),再取最新 io_date。 + */ + private function emptyIoMap(): array + { + return ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => [], 'rank' => ['L' => [], 'O' => [], 'LO' => []]]; + } + + private function addIoRow(array &$m, array $r, bool $indexByL, bool $indexByO): void + { + $rio = (string) ($r['io_id'] ?? ''); + if ($rio === '') { + return; + } + if (! empty($r['io_date'])) { + $this->ioDate[$rio] = (string) $r['io_date']; + } + $l = ltrim(trim((string) ($r['l_id'] ?? '')), '@'); + $o = (string) ($r['o_id'] ?? ''); + $m['ioL'][$rio] = $l; + $st = strtolower(trim((string) ($r['status'] ?? ''))); + $ok = ! in_array($st, ['delete', 'deleted', 'cancelled', 'cancel', 'canceled'], true); + $rk = ($ok ? '1' : '0') . '|' . (string) ($r['io_date'] ?? '') . '|' . str_pad($rio, 12, '0', STR_PAD_LEFT); + if ($indexByL && $l !== '' && (! isset($m['rank']['L'][$l]) || strcmp($rk, $m['rank']['L'][$l]) > 0)) { + $m['byL'][$l] = $rio; + $m['rank']['L'][$l] = $rk; + } + // 同一单号多订单共用(拼单/合包):按 单号+订单 精确定位,避免拿到别的订单的商品 + $lo = $l . '|' . $o; + if ($indexByL && $l !== '' && $o !== '' && (! isset($m['rank']['LO'][$lo]) || strcmp($rk, $m['rank']['LO'][$lo]) > 0)) { + $m['byLO'][$lo] = $rio; + $m['rank']['LO'][$lo] = $rk; + } + if ($indexByO && $o !== '') { + if ($ok) { + $m['byOAll'][$o][$rio] = $l; + } + if (! isset($m['rank']['O'][$o]) || strcmp($rk, $m['rank']['O'][$o]) > 0) { + $m['byO'][$o] = $rio; + $m['rank']['O'][$o] = $rk; + } + } + } + + /** 快递单号/内部单号 -> 出库单 io_id(非窗口诊断模式按需查询;窗口模式用预载映射)。 */ private function loadIoMap(array $logisticIds, array $oIds): array { - // 同一单号/订单可能有多张出库单(作废重出):优先有效(非 Delete/Cancelled),再取最新 io_date - $byL = []; - $byO = []; - $byOAll = []; - $ioL = []; - $rankL = []; - $rankO = []; - $byLO = []; - $rankLO = []; - $rank = static function (array $r): string { - $st = strtolower(trim((string) ($r['status'] ?? ''))); - $ok = in_array($st, ['delete', 'deleted', 'cancelled', 'cancel', 'canceled'], true) ? '0' : '1'; - - return $ok . '|' . (string) ($r['io_date'] ?? '') . '|' . str_pad((string) ($r['io_id'] ?? ''), 12, '0', STR_PAD_LEFT); - }; + $map = $this->emptyIoMap(); foreach (array_chunk(array_values(array_unique(array_filter($logisticIds))), 800) as $chunk) { if ($chunk === []) { continue; @@ -1140,26 +1467,8 @@ class ShippingReplicaSynchronizer } $q = array_keys($q); $ph = implode(',', array_fill(0, count($q), '?')); - foreach ($this->up->select('SELECT l_id, io_id, io_date, status, o_id FROM ' . self::OUTBOUND . " WHERE l_id IN ({$ph})", $q) as $r) { - $rio = (string) ($r['io_id'] ?? ''); - if ($rio !== '' && ! empty($r['io_date'])) { - $this->ioDate[$rio] = (string) $r['io_date']; - } - $l = ltrim(trim((string) ($r['l_id'] ?? '')), '@'); - if ($rio !== '') { - $ioL[$rio] = $l; - } - $rk = $rank($r); - if ($l !== '' && $rio !== '' && (! isset($rankL[$l]) || strcmp($rk, $rankL[$l]) > 0)) { - $byL[$l] = $rio; - $rankL[$l] = $rk; - } - // 同一单号多订单共用(拼单/合包):按 单号+订单 精确定位,避免拿到别的订单的商品 - $lo = $l . '|' . (string) ($r['o_id'] ?? ''); - if ($l !== '' && $rio !== '' && (! isset($rankLO[$lo]) || strcmp($rk, $rankLO[$lo]) > 0)) { - $byLO[$lo] = $rio; - $rankLO[$lo] = $rk; - } + foreach ($this->selectWithReconnect('SELECT l_id, io_id, io_date, status, o_id FROM ' . self::OUTBOUND . " WHERE l_id IN ({$ph})", $q) as $r) { + $this->addIoRow($map, $r, true, false); } } foreach (array_chunk(array_values(array_unique(array_filter($oIds))), 800) as $chunk) { @@ -1167,28 +1476,13 @@ class ShippingReplicaSynchronizer continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); - foreach ($this->up->select('SELECT o_id, io_id, io_date, l_id, status FROM ' . self::OUTBOUND . " WHERE o_id IN ({$ph})", $chunk) as $r) { - $rio = (string) ($r['io_id'] ?? ''); - if ($rio !== '' && ! empty($r['io_date'])) { - $this->ioDate[$rio] = (string) $r['io_date']; - } - $o = (string) ($r['o_id'] ?? ''); - $l = ltrim(trim((string) ($r['l_id'] ?? '')), '@'); - if ($rio !== '') { - $ioL[$rio] = $l; - } - $rk = $rank($r); - if ($o !== '' && $rio !== '' && $rk[0] === '1') { - $byOAll[$o][$rio] = $l; - } - if ($o !== '' && $rio !== '' && (! isset($rankO[$o]) || strcmp($rk, $rankO[$o]) > 0)) { - $byO[$o] = $rio; - $rankO[$o] = $rk; - } + foreach ($this->selectWithReconnect('SELECT o_id, io_id, io_date, l_id, status FROM ' . self::OUTBOUND . " WHERE o_id IN ({$ph})", $chunk) as $r) { + $this->addIoRow($map, $r, false, true); } } + unset($map['rank']); - return ['byL' => $byL, 'byO' => $byO, 'byOAll' => $byOAll, 'ioL' => $ioL, 'byLO' => $byLO]; + return $map; } /** @@ -1227,7 +1521,7 @@ class ShippingReplicaSynchronizer $q[] = '@' . $c; } $ph = implode(',', array_fill(0, count($q), '?')); - foreach ($this->up->select("SELECT DISTINCT logistic_id FROM rpt.jst_order_express_details WHERE logistic_id IN ({$ph})", $q) as $x) { + foreach ($this->selectWithReconnect("SELECT DISTINCT logistic_id FROM rpt.jst_order_express_details WHERE logistic_id IN ({$ph})", $q) as $x) { $inExpress[ltrim(trim((string) ($x['logistic_id'] ?? '')), '@')] = true; } } @@ -1286,7 +1580,7 @@ class ShippingReplicaSynchronizer $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = 'SELECT io_id, sku_ids, qty, type, sku_name, shop_i_id, wareHoursName, l, w, h, volume, weight, supplier_name, shop_site, shop_name, receiver_state, receiver_city, receiver_district FROM ' . self::VIEW . " WHERE io_id IN ({$ph})"; - foreach ($this->up->select($sql, $chunk) as $r) { + foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $io = (string) ($r['io_id'] ?? ''); if ($io !== '' && ! isset($this->ioSite[$io]) && trim((string) ($r['shop_site'] ?? '')) !== '') { $this->ioSite[$io] = trim((string) $r['shop_site']); @@ -1427,7 +1721,7 @@ class ShippingReplicaSynchronizer $o2io = []; foreach (array_chunk($ioKeys, 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); - foreach ($this->up->select('SELECT io_id, o_id FROM ' . self::OUTBOUND . " WHERE io_id IN ({$ph})", $ck) as $r) { + foreach ($this->selectWithReconnect('SELECT io_id, o_id FROM ' . self::OUTBOUND . " WHERE io_id IN ({$ph})", $ck) as $r) { $o = (string) ($r['o_id'] ?? ''); if ($o !== '') { $o2io[$o][(string) $r['io_id']] = true; @@ -1437,7 +1731,7 @@ class ShippingReplicaSynchronizer $ordQty = []; foreach (array_chunk(array_map('strval', array_keys($o2io)), 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); - foreach ($this->up->select("SELECT o_id, sku_id, qty FROM rpt.jst_OrderItem WHERE o_id IN ({$ph})", $ck) as $r) { + foreach ($this->selectWithReconnect("SELECT o_id, sku_id, qty FROM rpt.jst_OrderItem WHERE o_id IN ({$ph})", $ck) as $r) { $k = mb_strtolower(trim((string) ($r['sku_id'] ?? ''))); foreach ($o2io[(string) $r['o_id']] ?? [] as $io => $_) { $ordQty[(string) $io][$k] = ($ordQty[(string) $io][$k] ?? 0) + (float) ($r['qty'] ?? 0); @@ -1447,7 +1741,7 @@ class ShippingReplicaSynchronizer $fysW = []; foreach (array_chunk($ioKeys, 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); - foreach ($this->up->select("SELECT io_id, sku_id, weight FROM rpt.fys_jstFreightCostDetail WHERE io_id IN ({$ph})", $ck) as $r) { + foreach ($this->selectWithReconnect("SELECT io_id, sku_id, weight FROM rpt.fys_jstFreightCostDetail WHERE io_id IN ({$ph})", $ck) as $r) { $k = mb_strtolower(trim((string) ($r['sku_id'] ?? ''))); $fysW[(string) $r['io_id']][$k] = ($fysW[(string) $r['io_id']][$k] ?? 0) + (float) ($r['weight'] ?? 0); } @@ -1600,6 +1894,183 @@ class ShippingReplicaSynchronizer } } + private function packageRow(int $sourceId, int $skuSourceId, array $payload): array + { + $payload['source_id'] = $sourceId; + $payload['sku_source_id'] = $skuSourceId; + + return $payload; + } + + /** @param list> $rows */ + private function writePackage(int $sourceId, array $rows, bool $hasFreight, bool $hasItems, array $syntheticSkuIds): void + { + if (! $this->replaceWindow) { + foreach ($rows as $row) { + $this->push($sourceId, (int) $row['sku_source_id'], $row); + } + return; + } + + $this->replacementRowCount -= count($this->replacementPackages[$sourceId] ?? []); + $this->replacementPackages[$sourceId] = $rows; + $this->replacementHasFreight[$sourceId] = $hasFreight; + $this->replacementHasItems[$sourceId] = $hasItems; + $this->replacementSyntheticSkuIds[$sourceId] = $syntheticSkuIds; + $this->replacementRowCount += count($rows); + if ($this->replacementRowCount >= self::FLUSH) { + $this->flushReplacements(); + } + } + + private function flushPending(): void + { + if ($this->replaceWindow) { + $this->flushReplacements(); + } else { + $this->flush(); + } + } + + private function flushReplacements(): void + { + if ($this->replacementPackages === []) { + return; + } + $packages = $this->replacementPackages; + $hasFreight = $this->replacementHasFreight; + $hasItems = $this->replacementHasItems; + $syntheticSkuIds = $this->replacementSyntheticSkuIds; + $this->db->transaction(function () use ($packages, $hasFreight, $hasItems, $syntheticSkuIds): void { + $ids = array_keys($packages); + $previous = []; + $previousItems = []; + $oldAmountSkuIds = []; + $oldHasItems = []; + $oldRows = $this->db->table('jst_oms_shipping')->whereIn('source_id', $ids) + ->select(array_merge( + ['source_id', 'sku_source_id', 'express_no', 'express_name2', 'freight', 'settle_freight', 'weight_kg', 'settle_weight_kg', + 'item_id', 'barcode', 'product_name', 'product_code', 'qty', 'amount'], + self::PRESERVED_PACKAGE_FIELDS, + self::PRESERVED_CONTACT_FIELDS, + self::PRESERVED_ITEM_FIELDS, + )) + ->get(); + foreach ($oldRows as $oldRow) { + $id = (int) $oldRow->source_id; + $row = (array) $oldRow; + $previousItems[$id][(int) $oldRow->sku_source_id] = $row; + if ($row['amount'] !== null) { + $oldAmountSkuIds[$id][(int) $oldRow->sku_source_id] = true; + } + foreach (['item_id', 'barcode', 'product_name', 'product_code', 'qty', 'amount', + 'finished_barcode', 'finished_name', 'finished_supplier'] as $field) { + if ($row[$field] !== null && $row[$field] !== '') { + $oldHasItems[$id] = true; + break; + } + } + if (! isset($previous[$id])) { + $previous[$id] = $row; + continue; + } + foreach (array_merge( + ['freight', 'settle_freight', 'weight_kg', 'settle_weight_kg', 'express_no', 'express_name2'], + self::PRESERVED_PACKAGE_FIELDS, + self::PRESERVED_CONTACT_FIELDS, + ) as $field) { + if (($previous[$id][$field] ?? null) === null || $previous[$id][$field] === '') { + $previous[$id][$field] = $row[$field]; + } + } + } + + $rows = []; + $replaceIds = []; + foreach ($packages as $id => $packageRows) { + if (! ($hasItems[$id] ?? false) && ($oldHasItems[$id] ?? false)) { + $this->packagesRetainedForMissingItems++; + continue; + } + $unmatchedOldAmounts = $oldAmountSkuIds[$id] ?? []; + $unsafeAmount = false; + foreach ($packageRows as &$packageRow) { + $skuId = (int) $packageRow['sku_source_id']; + $oldItem = $previousItems[$id][$skuId] ?? null; + if ($packageRow['amount'] !== null) { + unset($unmatchedOldAmounts[$skuId]); + continue; + } + if ($oldItem === null || $oldItem['amount'] === null) { + continue; + } + if (isset($syntheticSkuIds[$id][$skuId])) { + $oldBarcode = trim((string) $oldItem['barcode']); + $newBarcode = trim((string) ($packageRow['barcode'] ?? '')); + if ($oldBarcode === '' || $newBarcode === '' || $oldBarcode !== $newBarcode) { + $unsafeAmount = true; + break; + } + } + $packageRow['amount'] = $oldItem['amount']; + unset($unmatchedOldAmounts[$skuId]); + } + unset($packageRow); + if (! $unsafeAmount && $unmatchedOldAmounts !== []) { + foreach ($packageRows as $packageRow) { + if ($packageRow['amount'] === null) { + $unsafeAmount = true; + break; + } + } + } + if ($unsafeAmount) { + $this->packagesRetainedForUnmatchedAmount++; + continue; + } + $replaceIds[] = $id; + foreach ($packageRows as &$packageRow) { + foreach (self::PRESERVED_PACKAGE_FIELDS as $field) { + $packageRow[$field] ??= null; + } + foreach (self::PRESERVED_ITEM_FIELDS as $field) { + $packageRow[$field] = $previousItems[$id][(int) $packageRow['sku_source_id']][$field] ?? null; + } + } + unset($packageRow); + if (isset($previous[$id])) { + foreach (self::PRESERVED_PACKAGE_FIELDS as $field) { + $packageRows[0][$field] = $previous[$id][$field] ?? null; + } + foreach (self::PRESERVED_CONTACT_FIELDS as $field) { + if (($packageRows[0][$field] ?? null) === null || $packageRows[0][$field] === '') { + $packageRows[0][$field] = $previous[$id][$field] ?? null; + } + } + if ($this->skipFreight) { + $packageRows[0] = $this->withPreservedFreight($packageRows[0], $previous[$id]); + } elseif (! ($hasFreight[$id] ?? false)) { + $packageRows[0] = $this->withPreservedCharges($packageRows[0], $previous[$id], false); + } + } + array_push($rows, ...$packageRows); + } + if ($replaceIds === []) { + return; + } + $this->db->table('jst_oms_shipping')->whereIn('source_id', $replaceIds)->delete(); + foreach (array_chunk($rows, self::FLUSH) as $chunk) { + $this->db->table('jst_oms_shipping')->insert($chunk); + } + }); + + $this->replacementPackages = []; + $this->replacementHasFreight = []; + $this->replacementHasItems = []; + $this->replacementSyntheticSkuIds = []; + $this->replacementRowCount = 0; + } + private function flush(): void { if ($this->buffer === []) { @@ -1650,7 +2121,7 @@ class ShippingReplicaSynchronizer continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); - foreach ($this->up->select("SELECT sku_id, l, w, h, pack_volume, weight, supplier_name, name, i_id FROM rpt.jst_sku WHERE sku_id IN ({$ph})", $chunk) as $r) { + foreach ($this->selectWithReconnect("SELECT sku_id, l, w, h, pack_volume, weight, supplier_name, name, i_id FROM rpt.jst_sku WHERE sku_id IN ({$ph})", $chunk) as $r) { $out[(string) $r['sku_id']] = [ 'l' => $r['l'] ?? null, 'w' => $r['w'] ?? null, 'h' => $r['h'] ?? null, 'vol' => $r['pack_volume'] ?? null, 'weight' => $r['weight'] ?? null, @@ -1675,7 +2146,7 @@ class ShippingReplicaSynchronizer $sql = 'SELECT so_id, expressNo, SUM(freightCost) AS cost, SUM(weight) AS w, ' . 'MAX(expressName) AS name, MAX(receiver_state) AS state ' . "FROM rpt.fys_jstFreightCostDetail WHERE so_id IN ({$ph}) GROUP BY so_id, expressNo"; - foreach ($this->up->select($sql, $chunk) as $r) { + foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $expno = (string) ($r['expressNo'] ?? ''); $val = ['cost' => $r['cost'] ?? null, 'w' => $r['w'] ?? null, 'name' => $r['name'] ?? null, 'state' => $r['state'] ?? null, 'no' => $expno ?: null]; $out[((string) $r['so_id']) . '|' . $expno] = $val; @@ -1686,6 +2157,43 @@ class ShippingReplicaSynchronizer return $out; } + private function countUnseenMirrorPackages(string $fromS, string $toS): int + { + $unseen = 0; + $ids = $this->db->table('jst_oms_shipping') + ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) + ->distinct()->pluck('source_id'); + foreach ($ids as $id) { + if (! isset($this->seenSourceIds[(int) $id])) { + $unseen++; + } + } + + return $unseen; + } + + private function withPreservedFreight(array $payload, array $previous): array + { + $payload = $this->withPreservedCharges($payload, $previous); + if (! empty($previous['express_no'])) { + $payload['express_no'] = $previous['express_no']; + } + $payload['express_name2'] = $previous['express_name2'] ?? $payload['express_name2']; + + return $payload; + } + + private function withPreservedCharges(array $payload, array $previous, bool $includeNull = true): array + { + foreach (['freight', 'settle_freight', 'weight_kg', 'settle_weight_kg'] as $field) { + if ($includeNull || $previous[$field] !== null) { + $payload[$field] = $previous[$field]; + } + } + + return $payload; + } + private function cleanPayload(array $data): array { foreach ($data as $k => $v) { @@ -1735,6 +2243,67 @@ class ShippingReplicaSynchronizer ]); } + private function windowDatasetKey(string $prefix, string $fromS, string $toS): string + { + return $prefix . Carbon::parse($fromS)->format('YmdHis') . '-' . Carbon::parse($toS)->format('YmdHis'); + } + + private function markFreightIncomplete(string $fromS, string $toS): void + { + $this->db->table('jst_sync_state')->updateOrInsert( + ['dataset_key' => $this->windowDatasetKey(self::FREIGHT_DATASET_PREFIX, $fromS, $toS)], + [ + 'status' => 'pending', + 'last_error' => '本窗口采用数量优先补录;上游运费查询已跳过,新记录的运费和结算重量待补齐,空白不代表 0。', + 'updated_at' => now(), + 'created_at' => now(), + ], + ); + } + + private function markItemsIncomplete(string $fromS, string $toS): void + { + $detail = sprintf( + '部分日期窗口的商品或金额待核对:%d 个包裹未匹配商品,%d 个包裹金额无法安全匹配,DWS 预载失败 %d 天。', + $this->packagesWithoutItems, + $this->packagesRetainedForUnmatchedAmount, + count($this->dwsFailedDays), + ); + $this->db->table('jst_sync_state')->updateOrInsert( + ['dataset_key' => $this->windowDatasetKey(self::ITEMS_DATASET_PREFIX, $fromS, $toS)], + ['status' => 'pending', 'last_error' => $detail, 'updated_at' => now(), 'created_at' => now()], + ); + } + + private function markCovered(string $prefix, string $fromS, string $toS): void + { + $from = Carbon::parse($fromS)->format('YmdHis'); + $to = Carbon::parse($toS)->format('YmdHis'); + $states = $this->db->table('jst_sync_state')->where('dataset_key', 'like', $prefix . '%') + ->where('status', '!=', 'succeeded')->pluck('dataset_key'); + foreach ($states as $key) { + $range = substr((string) $key, strlen($prefix)); + if (! preg_match('/^\d{14}-\d{14}$/', $range)) { + continue; + } + [$pendingFrom, $pendingTo] = explode('-', $range, 2); + if ($from <= $pendingFrom && $pendingTo <= $to) { + $this->db->table('jst_sync_state')->where('dataset_key', $key)->update([ + 'status' => 'succeeded', 'last_error' => null, 'last_succeeded_at' => now(), 'updated_at' => now(), + ]); + } + } + } + + private function markIncompleteWindow(int $unseen): void + { + $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update([ + 'status' => 'partial', + 'last_error' => "本窗口尚有 {$unseen} 个镜像包裹未在上游扫描中出现,已保留原记录,需按源键核对。", + 'updated_at' => now(), + ]); + } + private function markFailed(string $err): void { $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update([ diff --git a/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php b/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php index 5caa4edf..95cdae60 100644 --- a/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php +++ b/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php @@ -42,11 +42,11 @@ class JushuitanCostPriceHistorySynchronizer $until = Carbon::parse((string) $state['window_ends_at']); } elseif ($full) { $since = $this->historyStart(); - $until = now()->addSecond(); + $until = now(); } else { $overlap = max((int) config('services.jushuitan.cost_price_history_overlap_hours', 48), 1); $since = Carbon::parse((string) $state['last_succeeded_at'])->subHours($overlap); - $until = now()->addSecond(); + $until = now(); } $state = $this->mirror->startRun($mode, $generation, $since, $until, $resume); @@ -55,9 +55,9 @@ class JushuitanCostPriceHistorySynchronizer : Carbon::parse((string) $state['cursor_window_started_at']); $page = max((int) ($state['cursor_page'] ?? 1), 1); $pageSize = min(max( - $pageSize ?? (int) config('services.jushuitan.cost_price_history_page_size', 2000), + $pageSize ?? (int) config('services.jushuitan.cost_price_history_page_size', 50), 1, - ), 2000); + ), 50); $maxPages = max( $maxPages ?? (int) config('services.jushuitan.cost_price_history_max_pages', 30), 0, @@ -66,9 +66,9 @@ class JushuitanCostPriceHistorySynchronizer $processedSourceRows = (int) ($state['last_processed_source_rows'] ?? 0); $upsertedRows = (int) ($state['last_upserted_rows'] ?? 0); $windowDays = min(max( - (int) config('services.jushuitan.cost_price_history_window_days', 30), + (int) config('services.jushuitan.cost_price_history_window_days', 7), 1, - ), 30); + ), 7); try { while ($windowStartedAt->lt($until)) { @@ -88,7 +88,7 @@ class JushuitanCostPriceHistorySynchronizer $upsertedRows += count($records); $pages++; - $hasNextPage = $result['total_pages'] > 0 && $page < $result['total_pages']; + $hasNextPage = $result['has_next']; // 相邻窗口在边界秒保留一次重叠,避免接口时间精度高于秒时漏掉记录; // operation_id 的幂等 upsert 会消除边界重复。 $nextWindowStartedAt = $hasNextPage @@ -133,7 +133,11 @@ class JushuitanCostPriceHistorySynchronizer 'rows' => $upsertedRows, ]; } catch (Throwable $exception) { - $this->mirror->fail($exception::class); + $message = trim($exception->getMessage()); + $errorCode = preg_match('/^[a-z0-9_]+$/', $message) === 1 + ? $message + : $exception::class; + $this->mirror->fail($errorCode); throw $exception; } } diff --git a/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php b/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php index 0bfc6b11..c5b37720 100644 --- a/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php +++ b/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php @@ -10,7 +10,7 @@ use RuntimeException; class JushuitanOpenApiClient { /** - * @return array{records:list>,source_rows:int,current_page:int,total_pages:int,total_count:int} + * @return array{records:list>,source_rows:int,current_page:int,has_next:bool} */ public function getCostPriceOperationHistory( Carbon $start, @@ -19,56 +19,57 @@ class JushuitanOpenApiClient int $pageSize, ): array { $payload = $this->request([ - 'current_page' => max($page, 1), - 'page_size' => min(max($pageSize, 1), 2000), - 'start_time' => $start->format('Y-m-d H:i:s'), - 'end_time' => $end->format('Y-m-d H:i:s'), + 'page_index' => max($page, 1), + 'page_size' => min(max($pageSize, 1), 50), + 'modified_begin' => $start->format('Y-m-d H:i:s'), + 'modified_end' => $end->format('Y-m-d H:i:s'), ]); - $data = is_array($payload['data'] ?? null) ? $payload['data'] : []; - $pageInfo = is_array($data['page'] ?? null) ? $data['page'] : []; + $records = is_array($payload['datas'] ?? null) ? $payload['datas'] : []; return [ - 'records' => $this->normalizeCostPriceOperations($data['list'] ?? []), - 'source_rows' => is_array($data['list'] ?? null) ? count($data['list']) : 0, - 'current_page' => max((int) ($pageInfo['current_page'] ?? $page), 1), - 'total_pages' => max((int) ($pageInfo['pages'] ?? 0), 0), - 'total_count' => max((int) ($pageInfo['count'] ?? 0), 0), + 'records' => $this->normalizeCostPriceOperations($records), + 'source_rows' => count($records), + 'current_page' => max((int) ($payload['page_index'] ?? $page), 1), + 'has_next' => (bool) ($payload['has_next'] ?? false), ]; } /** @param array $biz @return array */ private function request(array $biz): array { - $appKey = trim((string) config('services.jushuitan.app_key')); - $appSecret = trim((string) config('services.jushuitan.app_secret')); - $accessToken = trim((string) config('services.jushuitan.access_token')); - if ($appKey === '' || $appSecret === '' || $accessToken === '') { - throw new RuntimeException('jushuitan_api_credentials_missing'); + $partnerId = trim((string) config('services.jushuitan.partner_id')); + $partnerKey = trim((string) config('services.jushuitan.partner_key')); + $token = trim((string) config('services.jushuitan.token')); + if ($partnerId === '' || $partnerKey === '' || $token === '') { + throw new RuntimeException('jushuitan_classic_api_credentials_missing'); } + $method = (string) config( + 'services.jushuitan.product_operation_history_method', + 'worklog.query', + ); + $timestamp = (string) now()->timestamp; + // URL parameter order is part of the classic API signature contract. $params = [ - 'access_token' => $accessToken, - 'app_key' => $appKey, - 'biz' => json_encode( - $biz, - JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, - ), - 'charset' => 'utf-8', - 'timestamp' => (string) now()->timestamp, - 'version' => '2', + 'method' => $method, + 'partnerid' => $partnerId, + 'token' => $token, + 'ts' => $timestamp, ]; - $params['sign'] = $this->sign($params, $appSecret); + $params['sign'] = $this->sign($method, $partnerId, $token, $timestamp, $partnerKey); - $baseUrl = rtrim((string) config('services.jushuitan.base_url'), '/'); - $path = (string) config( - 'services.jushuitan.product_operation_history_path', - '/open/webapi/itemapi/itemsku/queryitemskuopshistory', + $baseUrl = (string) config( + 'services.jushuitan.base_url', + 'https://open.erp321.com/api/open/query.aspx', ); /** @var PendingRequest $request */ - $request = Http::asForm() + $request = Http::asJson() ->acceptJson() ->timeout(max((int) config('services.jushuitan.timeout', 20), 1)); - $response = $request->post($baseUrl . '/' . ltrim($path, '/'), $params); + $response = $request->post( + $baseUrl . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986), + $biz, + ); if (! $response->successful()) { throw new RuntimeException('jushuitan_api_http_' . $response->status()); @@ -80,25 +81,32 @@ class JushuitanOpenApiClient } $code = (int) ($payload['code'] ?? -1); if ($code !== 0) { - throw new RuntimeException('jushuitan_api_code_' . $code); + throw new RuntimeException($this->errorCode($code, $payload)); } return $payload; } - /** @param array $params */ - private function sign(array $params, string $appSecret): string + /** @param array $payload */ + private function errorCode(int $code, array $payload): string { - ksort($params, SORT_STRING); - $plain = $appSecret; - foreach ($params as $key => $value) { - if ($key === 'sign' || $value === null || $value === '') { - continue; - } - $plain .= $key . (string) $value; + $message = mb_strtolower(trim((string) ($payload['msg'] ?? $payload['message'] ?? ''))); + if ($code === 100 && str_contains($message, 'partnerid')) { + return 'jushuitan_classic_api_partner_id_invalid'; } - return md5($plain); + return 'jushuitan_api_code_' . $code; + } + + private function sign( + string $method, + string $partnerId, + string $token, + string $timestamp, + string $partnerKey, + ): string + { + return md5($method . $partnerId . 'token' . $token . 'ts' . $timestamp . $partnerKey); } /** @param mixed $records @return list> */ @@ -114,7 +122,7 @@ class JushuitanOpenApiClient continue; } $skuId = trim((string) ($record['sku_id'] ?? '')); - $description = trim((string) ($record['operation_description'] ?? '')); + $description = trim((string) ($record['remark'] ?? $record['operation_description'] ?? '')); if ($skuId === '' || ! str_contains($description, '采购价')) { continue; } @@ -127,7 +135,7 @@ class JushuitanOpenApiClient 'product_name' => $this->nullableString($record['name'] ?? null), 'properties_value' => $this->nullableString($record['properties_value'] ?? null), 'sku_type' => $this->nullableString($record['sku_type'] ?? null), - 'operation_type' => $this->nullableString($record['operation_type'] ?? null), + 'operation_type' => $this->nullableString($record['type'] ?? $record['operation_type'] ?? null), 'operation_description' => $description, 'operator_name' => $this->nullableString($record['creator_name'] ?? null), 'operated_at' => $this->nullableString($record['created'] ?? null), diff --git a/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php b/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php index a1b442af..9b5dd533 100644 --- a/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php +++ b/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php @@ -45,15 +45,34 @@ class JushuitanShopBalanceImporter 'xlsx', 'xls' => $this->workbookRows($realPath), default => throw new InvalidArgumentException('店铺余额仅支持聚水潭接口 JSON 或官方 XLSX/XLS 导出文件。'), }; - [$selectedDate, $storeField, $accountField, $balanceField, $platformField] = $this->fields($headers, $requestedDate); - $rows = $this->normalizeRows( - $dataRows, - $selectedDate, - $storeField, - $accountField, - $balanceField, - $platformField, - ); + $walletFields = $this->jdWalletFields($headers); + if ($walletFields !== null) { + if ($requestedDate === null) { + throw new InvalidArgumentException('京东钱包余额缺少截止日期,请使用 --balance-date 指定导出截止日期。'); + } + + [$storeField, $accountField, $settledAtField, $recordCodeField, $balanceField] = $walletFields; + $selectedDate = $requestedDate; + $rows = $this->normalizeJdWalletRows( + $dataRows, + $selectedDate, + $storeField, + $accountField, + $settledAtField, + $recordCodeField, + $balanceField, + ); + } else { + [$selectedDate, $storeField, $accountField, $balanceField, $platformField] = $this->fields($headers, $requestedDate); + $rows = $this->normalizeRows( + $dataRows, + $selectedDate, + $storeField, + $accountField, + $balanceField, + $platformField, + ); + } if ($rows === []) { throw new InvalidArgumentException('聚水潭店铺余额文件中没有可导入的数据行,已保留原有快照。'); @@ -153,6 +172,7 @@ class JushuitanShopBalanceImporter foreach (array_slice($matrix, 0, 20, true) as $rowNumber => $row) { $values = array_map(static fn (mixed $value): string => trim((string) $value), $row); $hasBalanceColumn = in_array('平台实际期末余额', $values, true) + || in_array('账户余额', $values, true) || count(array_filter($values, fn (string $value): bool => $this->dateFromHeader($value, null) !== null)) > 0; if (in_array('店铺', $values, true) && $hasBalanceColumn) { $headerNumber = $rowNumber; @@ -160,7 +180,7 @@ class JushuitanShopBalanceImporter } } if ($headerNumber === null) { - throw new InvalidArgumentException('聚水潭导出文件中未找到“店铺”和日期列。'); + throw new InvalidArgumentException('聚水潭导出文件中未找到“店铺”和余额列。'); } $headers = []; @@ -176,6 +196,40 @@ class JushuitanShopBalanceImporter ))]; } + /** @return array{0:string,1:?string,2:string,3:string,4:string}|null */ + private function jdWalletFields(array $headers): ?array + { + $fields = []; + + foreach ($headers as $header) { + $title = trim((string) ($header['title'] ?? '')); + $field = trim((string) ($header['fld'] ?? '')); + if ($title !== '' && $field !== '') { + $fields[$title] = $field; + } + } + + if (! isset($fields['费用结算时间']) && ! isset($fields['记录编码']) && ! isset($fields['账户余额'])) { + return null; + } + + $missing = array_values(array_filter( + ['店铺', '费用结算时间', '记录编码', '账户余额'], + static fn (string $title): bool => ! isset($fields[$title]), + )); + if ($missing !== []) { + throw new InvalidArgumentException('京东钱包余额数据缺少“' . implode('”“', $missing) . '”列。'); + } + + return [ + $fields['店铺'], + $fields['账户名称'] ?? null, + $fields['费用结算时间'], + $fields['记录编码'], + $fields['账户余额'], + ]; + } + /** @return array{0:string,1:string,2:?string,3:string,4:?string} */ private function fields(array $headers, ?string $requestedDate): array { @@ -289,6 +343,124 @@ class JushuitanShopBalanceImporter return array_values($rows); } + /** @return list> */ + private function normalizeJdWalletRows( + array $dataRows, + string $balanceDate, + string $storeField, + ?string $accountField, + string $settledAtField, + string $recordCodeField, + string $balanceField, + ): array { + $cutoff = CarbonImmutable::createFromFormat( + '!Y-m-d', + $balanceDate, + (string) config('app.timezone', 'Asia/Shanghai'), + )->endOfDay(); + $latestByStore = []; + + foreach ($dataRows as $row) { + if (! is_array($row)) { + continue; + } + + $storeName = trim((string) ($row[$storeField] ?? '')); + if ($storeName === '' || $storeName === '总计') { + continue; + } + if (mb_strlen($storeName) > 255) { + throw new InvalidArgumentException('聚水潭店铺名称超过 255 个字符:' . mb_substr($storeName, 0, 40)); + } + + $settledAt = $this->settledAt($row[$settledAtField] ?? null, $storeName); + if ($settledAt->isAfter($cutoff)) { + continue; + } + + $recordCode = trim((string) ($row[$recordCodeField] ?? '')); + if (preg_match('/^\d+$/', $recordCode) !== 1) { + throw new InvalidArgumentException("店铺 {$storeName} 的记录编码不是有效非负整数。"); + } + + $sourcePlatform = JushuitanShopBalanceRepository::sourcePlatform($storeName) ?? ''; + $normalizedName = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + $storeKey = hash('sha256', implode("\0", [$sourcePlatform, $normalizedName])); + $candidate = [ + 'settled_at' => $settledAt, + 'record_code' => $recordCode, + 'balance' => $this->amount($row[$balanceField] ?? null, $storeName, $balanceDate), + 'account_id' => $accountField === null ? '' : trim((string) ($row[$accountField] ?? '')), + 'source_platform' => $sourcePlatform, + 'store_name' => $storeName, + 'normalized_store_name' => $normalizedName, + ]; + $current = $latestByStore[$storeKey] ?? null; + + if ($current !== null) { + $comparison = $settledAt->getTimestamp() <=> $current['settled_at']->getTimestamp(); + if ($comparison === 0) { + $comparison = $this->compareNumericStrings($recordCode, $current['record_code']); + if ($comparison === 0 && $candidate['balance'] !== $current['balance']) { + throw new InvalidArgumentException("店铺 {$storeName} 的同一京东钱包记录存在冲突余额。"); + } + } + if ($comparison <= 0) { + continue; + } + } + + $latestByStore[$storeKey] = $candidate; + } + + return array_values(array_map(static function (array $row): array { + $accountId = $row['account_id']; + $rowKey = hash('sha256', implode("\0", [ + $row['source_platform'], + $row['normalized_store_name'], + $accountId, + ])); + + return [ + 'source_platform' => $row['source_platform'], + 'store_name' => $row['store_name'], + 'normalized_store_name' => $row['normalized_store_name'], + 'platform_account_id' => $accountId === '' ? null : mb_substr($accountId, 0, 191), + 'balance' => $row['balance'], + 'source_row_key' => $rowKey, + ]; + }, $latestByStore)); + } + + private function settledAt(mixed $value, string $storeName): CarbonImmutable + { + $raw = trim((string) $value); + + try { + $settledAt = CarbonImmutable::createFromFormat( + '!Y-m-d H:i:s', + $raw, + (string) config('app.timezone', 'Asia/Shanghai'), + ); + } catch (\Throwable) { + throw new InvalidArgumentException("店铺 {$storeName} 的费用结算时间格式无效。"); + } + + if (! $settledAt instanceof CarbonImmutable || $settledAt->format('Y-m-d H:i:s') !== $raw) { + throw new InvalidArgumentException("店铺 {$storeName} 的费用结算时间格式无效。"); + } + + return $settledAt; + } + + private function compareNumericStrings(string $left, string $right): int + { + $left = ltrim($left, '0') ?: '0'; + $right = ltrim($right, '0') ?: '0'; + + return strlen($left) <=> strlen($right) ?: strcmp($left, $right); + } + private function amount(mixed $value, string $storeName, string $date): float { $normalized = str_replace([',', ',', '¥', '¥'], '', trim((string) $value)); diff --git a/modules/EcommerceFinance/Services/LedgerRemarkFilter.php b/modules/EcommerceFinance/Services/LedgerRemarkFilter.php new file mode 100644 index 00000000..7dddbd0a --- /dev/null +++ b/modules/EcommerceFinance/Services/LedgerRemarkFilter.php @@ -0,0 +1,106 @@ + $items */ + public static function itemsWhereIn(Builder $query, array $items, string $itemColumn): void + { + $values = self::clean($items); + if ($values === []) { + return; + } + + $query->whereIn($itemColumn, $values); + } + + /** + * 按平台分组收窄查询: + * (店铺属于平台A AND 账单项目 IN A的项目) OR (店铺属于平台B AND ...) ... + * + * 店铺归属由调用方表达:普通账单表用店铺名列,共享原始账单镜像用 shop_id 子查询。 + * + * @param list,excludePrefixes?:list,items?:list}> $groups + * @param callable(Builder $sub, string $prefix): void $storeLike + * @param callable(Builder $sub, string $prefix): void $storeNotLike + */ + public static function applyGroups( + Builder $query, + array $groups, + string $itemColumn, + callable $storeLike, + callable $storeNotLike, + ): void { + $plans = []; + foreach ($groups as $group) { + $items = self::clean((array) ($group['items'] ?? [])); + if ($items === []) { + continue; + } + + $prefixes = self::clean((array) ($group['prefixes'] ?? [])); + $excludes = array_values(array_diff(self::clean((array) ($group['excludePrefixes'] ?? [])), $prefixes)); + $plans[] = ['prefixes' => $prefixes, 'excludes' => $excludes, 'items' => $items]; + } + + if ($plans === []) { + return; + } + + $query->where(function (Builder $outer) use ($plans, $itemColumn, $storeLike, $storeNotLike): void { + foreach ($plans as $plan) { + $outer->orWhere(function (Builder $sub) use ($plan, $itemColumn, $storeLike, $storeNotLike): void { + if ($plan['prefixes'] !== [] || $plan['excludes'] !== []) { + $sub->where(function (Builder $scope) use ($plan, $storeLike, $storeNotLike): void { + if ($plan['prefixes'] !== []) { + // 本平台前缀的店铺 + $scope->orWhere(function (Builder $own) use ($plan, $storeLike): void { + foreach ($plan['prefixes'] as $prefix) { + $storeLike($own, $prefix); + } + }); + } + if ($plan['excludes'] !== []) { + // 没有其它平台前缀的店铺归默认平台 + $scope->orWhere(function (Builder $other) use ($plan, $storeNotLike): void { + foreach ($plan['excludes'] as $prefix) { + $storeNotLike($other, $prefix); + } + }); + } + }); + } + + $sub->whereIn($itemColumn, $plan['items']); + }); + } + }); + } + + /** + * @param array $values + * @return list + */ + private static function clean(array $values): array + { + $clean = []; + foreach ($values as $value) { + $text = trim((string) $value); + if ($text !== '') { + $clean[$text] = true; + } + } + + return array_keys($clean); + } +} diff --git a/modules/EcommerceFinance/Services/PayablesFieldNormalizer.php b/modules/EcommerceFinance/Services/PayablesFieldNormalizer.php new file mode 100644 index 00000000..616db4ab --- /dev/null +++ b/modules/EcommerceFinance/Services/PayablesFieldNormalizer.php @@ -0,0 +1,57 @@ + $fields */ + public function normalize(array $fields, array $input): array + { + $values = []; + + foreach ($fields as $field => $definition) { + if (! array_key_exists($field, $input)) { + continue; + } + + $value = $input[$field]; + if ($value === null || trim((string) $value) === '') { + $values[$field] = null; + continue; + } + + if ($definition['type'] === 'number') { + $number = str_replace([',', ',', '¥', '¥'], '', trim((string) $value)); + if (preg_match('/^-?(?:\d+(?:\.\d{1,4})?|\.\d{1,4})$/', $number) !== 1 + || bccomp(ltrim($number, '-'), '9999999999999999.9999', 4) === 1) { + throw ValidationException::withMessages([ + $field => $definition['label'] . '必须是最多 4 位小数的有效数字。', + ]); + } + $values[$field] = $number; + continue; + } + + $text = trim((string) $value); + if (mb_strlen($text) > 5000) { + throw ValidationException::withMessages([$field => $definition['label'] . '内容过长。']); + } + if ($definition['type'] === 'date' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $text) !== 1) { + throw ValidationException::withMessages([$field => $definition['label'] . '日期格式无效。']); + } + if ($definition['type'] === 'month' && preg_match('/^\d{4}-\d{2}$/', $text) !== 1) { + throw ValidationException::withMessages([$field => $definition['label'] . '月份格式无效。']); + } + $values[$field] = $text; + } + + if ($values === []) { + throw ValidationException::withMessages(['values' => '没有可保存的字段。']); + } + + return $values; + } +} diff --git a/modules/EcommerceFinance/Services/PayablesFinalImporter.php b/modules/EcommerceFinance/Services/PayablesFinalImporter.php new file mode 100644 index 00000000..73b666ac --- /dev/null +++ b/modules/EcommerceFinance/Services/PayablesFinalImporter.php @@ -0,0 +1,147 @@ + $fields 该表的字段定义(决定表头) + * @param string $storeDataset 「终版」目录实际保存记录用的数据集键 + * @return array{created:int,updated:int,rows:int} + */ + public function import(array $fields, string $storeDataset, UploadedFile $file, int $companyId, ?int $userId): array + { + $lookup = ['记录标识' => '_action_key', 'recordkey' => '_action_key', '_action_key' => '_action_key']; + foreach ($fields as $field => $definition) { + $lookup[$this->header($field)] = $field; + $lookup[$this->header($definition['label'])] = $field; + } + + try { + $readerType = match (mb_strtolower($file->getClientOriginalExtension())) { + 'xlsx' => 'Xlsx', + 'xls' => 'Xls', + 'csv' => 'Csv', + default => throw new \RuntimeException('Unsupported workbook format.'), + }; + $spreadsheet = IOFactory::createReader($readerType)->load($file->getRealPath()); + [$rows, $headerRow, $columns] = $this->bestSheet($spreadsheet, $lookup); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。', + ]); + } finally { + if (isset($spreadsheet)) { + $spreadsheet->disconnectWorksheets(); + } + } + + if ($rows === null || $columns === []) { + throw ValidationException::withMessages([ + 'import' => '没有识别到表头,请先下载本页面的导入模板,按模板列填写后重试。', + ]); + } + + $store = $this->store; + $records = []; + foreach (array_slice($rows, $headerRow + 1, null, true) as $rowIndex => $row) { + $line = $rowIndex + 1; + $key = ''; + $rawValues = []; + foreach ($columns as $columnIndex => $field) { + if ($field === '_action_key') { + $key = trim((string) ($row[$columnIndex] ?? '')); + } else { + $rawValues[$field] = $row[$columnIndex] ?? null; + } + } + + if (collect($rawValues)->every(static fn (mixed $value): bool => trim((string) $value) === '')) { + continue; + } + + try { + $values = $this->normalizer->normalize($fields, $rawValues); + } catch (ValidationException $exception) { + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(), + ]); + } + + if ($key === '') { + $key = $store->key($storeDataset, $values); + } + + if (isset($records[$key])) { + throw ValidationException::withMessages(['import' => "第 {$line} 行与前一行内容重复。"]); + } + + $records[$key] = $values; + + if (count($records) > self::MAX_ROWS) { + throw ValidationException::withMessages(['import' => '单次最多导入 10,000 条记录,请拆分文件后重试。']); + } + } + + if ($records === []) { + throw ValidationException::withMessages(['import' => '表格中没有可导入的数据行。']); + } + + $counts = ['created' => 0, 'updated' => 0]; + $store->transaction(function () use ($store, $records, $storeDataset, $companyId, $userId, &$counts): void { + foreach ($records as $key => $values) { + $result = $store->save($storeDataset, $key, $values, $companyId, $userId, 'import'); + $counts['created'] += $result['created']; + $counts['updated'] += $result['updated']; + } + }); + + return $counts + ['rows' => count($records)]; + } + + private function bestSheet(mixed $spreadsheet, array $lookup): array + { + $best = [null, null, []]; + $score = 0; + foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { + $rows = $worksheet->toArray(null, false, false, false); + foreach (array_slice($rows, 0, 20, true) as $rowIndex => $row) { + $columns = []; + foreach ($row as $columnIndex => $heading) { + $key = $this->header($heading); + if ($key !== '' && isset($lookup[$key])) { + $columns[$columnIndex] = $lookup[$key]; + } + } + if (count($columns) > $score) { + $best = [$rows, $rowIndex, $columns]; + $score = count($columns); + } + } + } + + return $best; + } + + private function header(mixed $value): string + { + return mb_strtolower(preg_replace('/[\s\x{FEFF}_\-()()]+/u', '', trim((string) $value))); + } +} diff --git a/modules/EcommerceFinance/Services/PayablesFinalRegistry.php b/modules/EcommerceFinance/Services/PayablesFinalRegistry.php new file mode 100644 index 00000000..583cfc62 --- /dev/null +++ b/modules/EcommerceFinance/Services/PayablesFinalRegistry.php @@ -0,0 +1,82 @@ + 供应商应付(终版)页签 */ + private const SUPPLIER_TITLES = [ + 'product-prices' => '商品价格', + 'payment-reconciliation' => '货款对账', + 'return-reconciliation' => '退货对账', + 'invoice-deductions' => '发票扣款', + 'board-deductions' => '板材扣款', + 'compensation-details' => '赔偿明细', + 'advance-details' => '借支明细', + 'sample-deductions' => '样品扣款', + 'other-adjustments' => '其他扣款补款', + 'delivery-unpriced' => '送货未定价', + 'return-unpriced' => '退货未定价', + 'dropshipping-express' => '代发快递', + 'supplier-payables-report' => '供应商应付表', + ]; + + /** 所有终版导入模板都带“月份”列,方便按月导入和查看。 */ + private const MONTH_FIELD = ['summary_month' => ['label' => '月份', 'type' => 'month']]; + + public function __construct( + private readonly SupplierPayableMaintenanceRegistry $supplier, + private readonly ProductPriceWorkbookImporter $productPrices, + private readonly CourierPayableFinalRegistry $courier, + ) { + } + + public function supports(string $section, string $dataset): bool + { + return array_key_exists($dataset, $this->titles($section)); + } + + /** @return array */ + public function titles(string $section): array + { + return match ($section) { + self::SECTION_SUPPLIER => self::SUPPLIER_TITLES, + self::SECTION_COURIER => $this->courier->titles(), + default => [], + }; + } + + public function title(string $section, string $dataset): string + { + $titles = $this->titles($section); + if (! array_key_exists($dataset, $titles)) { + throw ValidationException::withMessages(['dataset' => '不支持该终版目录页面。']); + } + + return $titles[$dataset]; + } + + /** @return array */ + public function fields(string $section, string $dataset): array + { + $this->title($section, $dataset); + + $fields = $section === self::SECTION_COURIER + ? $this->courier->fields($dataset) + : ($dataset === 'product-prices' + ? $this->productPrices->templateFields() + : $this->supplier->fields($dataset)); + + return self::MONTH_FIELD + $fields; + } +} diff --git a/modules/EcommerceFinance/Services/PinduoduoSettlementBillImporter.php b/modules/EcommerceFinance/Services/PinduoduoSettlementBillImporter.php new file mode 100644 index 00000000..635f46f6 --- /dev/null +++ b/modules/EcommerceFinance/Services/PinduoduoSettlementBillImporter.php @@ -0,0 +1,715 @@ + ['记录编码'], + 'store_name' => ['店铺', '原始店铺'], + 'custom_remark' => ['自定义备注'], + 'bill_item' => ['账单项目'], + 'merchant_order_no' => ['商户订单号'], + 'online_order_no' => ['线上单号'], + 'business_type' => ['财务类型', '业务类型'], + 'business_description' => ['业务描述'], + 'account_name' => ['类型', '账户'], + 'occurred_at' => ['发生时间'], + 'income_amount' => ['收入金额'], + 'expense_amount' => ['支出金额'], + 'signed_amount' => ['金额'], + 'remark' => ['备注'], + 'source_updated_at' => ['修改时间'], + 'source_modified_by' => ['修改人'], + ]; + + private const OPTIONAL_HEADERS = ['signed_amount']; + + private readonly ConnectionInterface $connection; + + public function __construct(DatabaseManager $databases) + { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{status:string,row_count:int,excluded_account_rows:int,store_count:int,bill_item_count:int,account_type_counts:array,income_total:string,expense_total:string,net_total:string,period_start:string,period_end:string,source_sha256:string} + */ + public function import( + string $path, + string $fromDate, + string $toDate, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + int $batchSize = 1000, + ): array { + $path = $this->validatedPath($path); + [$from, $to] = $this->period($fromDate, $toDate); + $this->assertSchemaReady(); + if ($expectedCount <= 0) { + throw new RuntimeException('权威笔数控制数必须大于零。'); + } + $expectedIncome = $this->controlAmount($expectedIncome, '收入'); + $expectedExpense = $this->controlAmount($expectedExpense, '支出'); + + $batchSize = min(max($batchSize, 100), 5000); + $hash = hash_file('sha256', $path); + if (! is_string($hash)) { + throw new RuntimeException('无法计算拼多多完整账单文件摘要。'); + } + + $existing = $this->connection->table(self::IMPORT_TABLE) + ->where('source_sha256', $hash) + ->first(); + if ($existing !== null && $existing->status === 'succeeded') { + $this->assertSameImportRequest( + $existing, + $from, + $to, + $expectedCount, + $expectedIncome, + $expectedExpense, + ); + if ($this->activeRowCount($hash, $from, $to) === (int) $existing->row_count) { + return $this->result((array) $existing, 'unchanged'); + } + } + + $generation = $existing !== null ? (string) $existing->generation : (string) Str::uuid(); + $now = now(); + $import = [ + 'generation' => $generation, + 'source_filename' => mb_substr(basename($path), 0, 255), + 'source_sha256' => $hash, + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'status' => 'running', + 'expected_row_count' => $expectedCount, + 'expected_income_total' => $expectedIncome, + 'expected_expense_total' => $expectedExpense, + 'row_count' => 0, + 'excluded_account_rows' => 0, + 'store_count' => 0, + 'bill_item_count' => 0, + 'account_type_counts' => null, + 'income_total' => '0.00', + 'expense_total' => '0.00', + 'net_total' => '0.00', + 'completed_at' => null, + 'last_error_code' => null, + 'updated_at' => $now, + ]; + if ($existing === null) { + $this->connection->table(self::IMPORT_TABLE)->insert($import + ['created_at' => $now]); + } else { + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($import); + } + + $stats = null; + try { + $stats = $this->stage($path, $generation, $from, $to, $batchSize); + $this->assertControls($stats, $expectedCount, $expectedIncome, $expectedExpense); + $this->activate($generation, $hash, $from, $to, $stats, $batchSize); + + return $this->result([ + 'row_count' => $stats['row_count'], + 'excluded_account_rows' => $stats['excluded_account_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'account_type_counts' => $stats['account_type_counts'], + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'source_sha256' => $hash, + ], 'succeeded'); + } catch (Throwable $exception) { + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + $failure = [ + 'status' => 'failed', + 'last_error_code' => mb_substr(class_basename($exception), 0, 120), + 'updated_at' => now(), + ]; + if (is_array($stats)) { + $failure += [ + 'row_count' => $stats['row_count'], + 'excluded_account_rows' => $stats['excluded_account_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'account_type_counts' => json_encode($stats['account_type_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + ]; + } + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($failure); + + throw $exception; + } + } + + private function validatedPath(string $path): string + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new RuntimeException('拼多多完整账单文件不存在或不可读。'); + } + if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') { + throw new RuntimeException('聚胜算完整账单导入只支持 XLSX 文件。'); + } + + return $realPath; + } + + /** @return array{0:DateTimeImmutable,1:DateTimeImmutable} */ + private function period(string $fromDate, string $toDate): array + { + $from = DateTimeImmutable::createFromFormat('!Y-m-d', $fromDate); + $to = DateTimeImmutable::createFromFormat('!Y-m-d', $toDate); + if ($from === false || $to === false + || $from->format('Y-m-d') !== $fromDate + || $to->format('Y-m-d') !== $toDate + || $from > $to) { + throw new RuntimeException('拼多多账单导入账期无效。'); + } + + return [$from, $to]; + } + + private function assertSchemaReady(): void + { + $schema = Schema::connection($this->connection->getName()); + foreach ([self::IMPORT_TABLE, self::STAGING_TABLE, self::ROW_TABLE] as $table) { + if (! $schema->hasTable($table)) { + throw new RuntimeException('拼多多完整账单表尚未完成迁移:' . $table); + } + } + } + + /** + * @return array{row_count:int,excluded_account_rows:int,store_count:int,bill_item_count:int,account_type_counts:array,income_total:string,expense_total:string,net_total:string} + */ + private function stage( + string $path, + string $generation, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $batchSize, + ): array { + $archive = new ZipArchive(); + if ($archive->open($path) !== true) { + throw new RuntimeException('无法打开拼多多完整账单 XLSX 文件。'); + } + + try { + $worksheet = $this->firstWorksheet($archive); + $sharedStrings = $this->sharedStrings($path, $archive); + } finally { + $archive->close(); + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取拼多多完整账单工作表。'); + } + + $headerMap = null; + $batch = []; + $rowCount = 0; + $excluded = 0; + $incomeTotal = '0.00'; + $expenseTotal = '0.00'; + $stores = []; + $billItems = []; + $accountTypeCounts = []; + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + + $rowNumber = (int) ($reader->getAttribute('r') ?: 0); + $cells = $this->rowCells($reader->readOuterXml(), $sharedStrings); + if ($headerMap === null) { + $headerMap = $this->headerMap($cells); + continue; + } + + $values = []; + foreach ($headerMap as $header => $column) { + $values[$header] = trim((string) ($cells[$column] ?? '')); + } + if (implode('', $values) === '') { + continue; + } + $recordCode = $this->required($values, 'record_code', $rowNumber, '记录编码'); + $accountName = $this->required($values, 'account_name', $rowNumber, '账户类型'); + $storeName = $this->nullable($values['store_name']); + $billItem = $this->nullable($values['bill_item']); + $occurredAt = $this->dateTime($values['occurred_at'], $rowNumber, '发生时间'); + if ($occurredAt < $from->format('Y-m-d') . ' 00:00:00' + || $occurredAt >= $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') { + throw new RuntimeException("第 {$rowNumber} 行发生时间超出指定账期。"); + } + + $income = $this->money($values['income_amount'], $rowNumber, '收入金额', false); + $expense = $this->money($values['expense_amount'], $rowNumber, '支出金额', true); + $calculated = bcsub($income, $expense, 2); + $signed = $calculated; + if (array_key_exists('signed_amount', $headerMap)) { + $signed = $this->money($values['signed_amount'], $rowNumber, '金额', false, true); + if (bccomp($calculated, $signed, 2) !== 0) { + throw new RuntimeException("第 {$rowNumber} 行收入、支出与金额不一致。"); + } + } + + $batch[] = [ + 'generation' => $generation, + 'record_code' => mb_substr($recordCode, 0, 191), + 'store_name' => $storeName, + 'custom_remark' => $this->nullable($values['custom_remark']), + 'bill_item' => $billItem, + 'merchant_order_no' => $this->nullable($values['merchant_order_no'], 191), + 'online_order_no' => $this->nullable($values['online_order_no'], 191), + 'business_type' => $this->nullable($values['business_type']), + 'business_description' => $this->nullable($values['business_description'], 1000), + // Keep the account type from the authoritative export. The + // complete Jushengsuan file contains both wallet and marketing + // account rows, and the finance page must retain both. + 'account_name' => mb_substr($accountName, 0, 255), + 'occurred_at' => $occurredAt, + 'income_amount' => $income, + 'expense_amount' => $expense, + 'signed_amount' => $signed, + 'remark' => $this->nullable($values['remark'], 1000), + 'source_updated_at' => $this->optionalDateTime($values['source_updated_at'], $rowNumber, '修改时间'), + 'source_modified_by' => $this->nullable($values['source_modified_by']), + 'source_row_number' => $rowNumber, + ]; + $rowCount++; + if ($storeName !== null) { + $stores[$storeName] = true; + } + if ($billItem !== null) { + $billItems[$billItem] = true; + } + $accountTypeCounts[$accountName] = ($accountTypeCounts[$accountName] ?? 0) + 1; + $incomeTotal = bcadd($incomeTotal, $income, 2); + $expenseTotal = bcadd($expenseTotal, $expense, 2); + + if (count($batch) >= $batchSize) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + $batch = []; + } + } + } finally { + $reader->close(); + } + + if ($headerMap === null) { + throw new RuntimeException('未找到聚胜算拼多多账单标准表头。'); + } + if ($batch !== []) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + } + if ($rowCount === 0) { + throw new RuntimeException('文件中没有拼多多货款账户数据。'); + } + + return [ + 'row_count' => $rowCount, + 'excluded_account_rows' => $excluded, + 'store_count' => count($stores), + 'bill_item_count' => count($billItems), + 'account_type_counts' => $accountTypeCounts, + 'income_total' => $incomeTotal, + 'expense_total' => $expenseTotal, + 'net_total' => bcsub($incomeTotal, $expenseTotal, 2), + ]; + } + + private function assertControls(array $stats, int $count, string $income, string $expense): void + { + if ($stats['row_count'] !== $count + || bccomp($stats['income_total'], $income, 2) !== 0 + || bccomp($stats['expense_total'], $expense, 2) !== 0) { + throw new RuntimeException(sprintf( + '权威控制数不一致:实际 %d 笔,收入 %s,支出 %s;期望 %d 笔,收入 %s,支出 %s。', + $stats['row_count'], + $stats['income_total'], + $stats['expense_total'], + $count, + $income, + $expense, + )); + } + } + + private function assertSameImportRequest( + object $existing, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + ): void { + if ((string) $existing->period_start !== $from->format('Y-m-d') + || (string) $existing->period_end !== $to->format('Y-m-d') + || (int) $existing->expected_row_count !== $expectedCount + || bccomp((string) $existing->expected_income_total, $expectedIncome, 2) !== 0 + || bccomp((string) $existing->expected_expense_total, $expectedExpense, 2) !== 0) { + throw new RuntimeException('该文件已有成功导入记录,但本次账期或权威控制数与历史记录不一致。'); + } + } + + private function activeRowCount( + string $hash, + DateTimeImmutable $from, + DateTimeImmutable $to, + ): int { + return $this->connection->table(self::ROW_TABLE) + ->where('source_sha256', $hash) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->count(); + } + + private function activate( + string $generation, + string $hash, + DateTimeImmutable $from, + DateTimeImmutable $to, + array $stats, + int $batchSize, + ): void { + $now = now(); + $columns = [ + 'store_name', 'custom_remark', 'bill_item', 'merchant_order_no', 'online_order_no', + 'business_type', 'business_description', 'account_name', 'occurred_at', 'income_amount', + 'expense_amount', 'signed_amount', 'remark', 'source_updated_at', 'source_modified_by', + 'source_row_number', 'source_generation', 'source_sha256', 'imported_at', + ]; + + $this->connection->transaction(function () use ( + $generation, $hash, $from, $to, $stats, $batchSize, $columns, $now + ): void { + $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->delete(); + + $this->connection->table(self::STAGING_TABLE) + ->where('generation', $generation) + ->orderBy('id') + ->chunkById($batchSize, function ($rows) use ($generation, $hash, $columns, $now): void { + $payload = []; + foreach ($rows as $row) { + $payload[] = [ + 'record_code' => $row->record_code, + 'store_name' => $row->store_name, + 'custom_remark' => $row->custom_remark, + 'bill_item' => $row->bill_item, + 'merchant_order_no' => $row->merchant_order_no, + 'online_order_no' => $row->online_order_no, + 'business_type' => $row->business_type, + 'business_description' => $row->business_description, + 'account_name' => $row->account_name, + 'occurred_at' => $row->occurred_at, + 'income_amount' => $row->income_amount, + 'expense_amount' => $row->expense_amount, + 'signed_amount' => $row->signed_amount, + 'remark' => $row->remark, + 'source_updated_at' => $row->source_updated_at, + 'source_modified_by' => $row->source_modified_by, + 'source_row_number' => $row->source_row_number, + 'source_generation' => $generation, + 'source_sha256' => $hash, + 'imported_at' => $now, + ]; + } + $this->connection->table(self::ROW_TABLE)->upsert($payload, ['record_code'], $columns); + }); + + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update([ + 'status' => 'succeeded', + 'row_count' => $stats['row_count'], + 'excluded_account_rows' => $stats['excluded_account_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'account_type_counts' => json_encode($stats['account_type_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'completed_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + }); + + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + } + + /** @return array */ + private function rowCells(string $xml, array $sharedStrings): array + { + $row = simplexml_load_string($xml); + if (! $row instanceof SimpleXMLElement) { + return []; + } + + $cells = []; + foreach ($row->xpath('./*[local-name()="c"]') ?: [] as $cell) { + $reference = (string) ($cell['r'] ?? ''); + if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) !== 1) { + continue; + } + $type = (string) ($cell['t'] ?? ''); + if ($type === 'inlineStr') { + $nodes = $cell->xpath('.//*[local-name()="t"]') ?: []; + $value = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } else { + $nodes = $cell->xpath('./*[local-name()="v"]') ?: []; + $raw = isset($nodes[0]) ? (string) $nodes[0] : ''; + $value = $type === 's' ? (string) ($sharedStrings[(int) $raw] ?? '') : $raw; + } + $cells[$this->columnIndex($matches[1])] = $value; + } + + return $cells; + } + + /** @param array $cells @return array */ + private function headerMap(array $cells): ?array + { + $lookup = []; + foreach ($cells as $column => $value) { + $lookup[trim($value)] = $column; + } + + $mapping = []; + foreach (self::HEADER_ALIASES as $field => $aliases) { + foreach ($aliases as $alias) { + if (array_key_exists($alias, $lookup)) { + $mapping[$field] = $lookup[$alias]; + break; + } + } + if (! array_key_exists($field, $mapping) + && ! in_array($field, self::OPTIONAL_HEADERS, true)) { + return null; + } + } + + return $mapping; + } + + private function required(array $values, string $key, int $row, ?string $label = null): string + { + $value = trim((string) ($values[$key] ?? '')); + if ($value === '') { + throw new RuntimeException("第 {$row} 行缺少" . ($label ?? $key) . '。'); + } + + return $value; + } + + private function money( + string $value, + int $row, + string $field, + bool $absolute = false, + bool $allowNegative = false, + ): string { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + $value = $value === '' ? '0' : $value; + if (! is_numeric($value) || (! $allowNegative && ! $absolute && bccomp($value, '0', 6) < 0)) { + throw new RuntimeException("第 {$row} 行{$field}不是有效金额。"); + } + if ($absolute && bccomp($value, '0', 6) < 0) { + $value = bcmul($value, '-1', 6); + } + + return bcadd($value, '0', 2); + } + + private function controlAmount(string $value, string $label): string + { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + if (! is_numeric($value) || bccomp($value, '0', 6) < 0) { + throw new RuntimeException("权威{$label}控制数无效。"); + } + + return bcadd($value, '0', 2); + } + + private function dateTime(string $value, int $row, string $field): string + { + $parsed = $this->parseDateTime($value); + if ($parsed === null) { + throw new RuntimeException("第 {$row} 行{$field}不是有效日期时间。"); + } + + return $parsed; + } + + private function optionalDateTime(string $value, int $row, string $field): ?string + { + if (trim($value) === '') { + return null; + } + + return $this->dateTime($value, $row, $field); + } + + private function parseDateTime(string $value): ?string + { + $value = trim($value); + try { + if (is_numeric($value)) { + $seconds = (int) round((((float) $value) - 25569) * 86400); + + return Carbon::createFromTimestampUTC($seconds)->format('Y-m-d H:i:s'); + } + + return Carbon::parse($value)->format('Y-m-d H:i:s'); + } catch (Throwable) { + return null; + } + } + + private function nullable(string $value, int $max = 255): ?string + { + $value = trim($value); + + return $value === '' ? null : mb_substr($value, 0, $max); + } + + private function columnIndex(string $letters): int + { + $index = 0; + foreach (str_split(strtoupper($letters)) as $letter) { + $index = ($index * 26) + ord($letter) - 64; + } + + return $index - 1; + } + + /** @return list */ + private function sharedStrings(string $path, ZipArchive $archive): array + { + if ($archive->locateName('xl/sharedStrings.xml') === false) { + return []; + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, 'xl/sharedStrings.xml'), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取 XLSX 共享文本。'); + } + + $strings = []; + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') { + continue; + } + $item = simplexml_load_string($reader->readOuterXml()); + $nodes = $item instanceof SimpleXMLElement ? ($item->xpath('.//*[local-name()="t"]') ?: []) : []; + $strings[] = implode('', array_map( + static fn (SimpleXMLElement $node): string => (string) $node, + $nodes, + )); + } + } finally { + $reader->close(); + } + + return $strings; + } + + private function firstWorksheet(ZipArchive $archive): string + { + $worksheets = []; + for ($index = 0; $index < $archive->numFiles; $index++) { + $name = $archive->getNameIndex($index); + if (is_string($name) && preg_match('#^xl/worksheets/sheet\d+\.xml$#', $name) === 1) { + $worksheets[] = $name; + } + } + sort($worksheets, SORT_NATURAL); + if ($worksheets === []) { + throw new RuntimeException('XLSX 文件中没有工作表。'); + } + + return $worksheets[0]; + } + + private function zipUri(string $path, string $entry): string + { + return 'zip://' . str_replace('\\', '/', $path) . '#' . $entry; + } + + private function result(array $row, string $status): array + { + return [ + 'status' => $status, + 'row_count' => (int) ($row['row_count'] ?? 0), + 'excluded_account_rows' => (int) ($row['excluded_account_rows'] ?? 0), + 'store_count' => (int) ($row['store_count'] ?? 0), + 'bill_item_count' => (int) ($row['bill_item_count'] ?? 0), + 'account_type_counts' => $this->accountTypeCounts($row['account_type_counts'] ?? []), + 'income_total' => bcadd((string) ($row['income_total'] ?? '0'), '0', 2), + 'expense_total' => bcadd((string) ($row['expense_total'] ?? '0'), '0', 2), + 'net_total' => bcadd((string) ($row['net_total'] ?? '0'), '0', 2), + 'period_start' => (string) ($row['period_start'] ?? ''), + 'period_end' => (string) ($row['period_end'] ?? ''), + 'source_sha256' => (string) ($row['source_sha256'] ?? ''), + ]; + } + + /** @return array */ + private function accountTypeCounts(mixed $value): array + { + if (is_string($value)) { + try { + $value = json_decode($value, true, 512, JSON_THROW_ON_ERROR); + } catch (Throwable) { + return []; + } + } + if (! is_array($value)) { + return []; + } + + $counts = []; + foreach ($value as $account => $count) { + if (is_string($account) && $account !== '' && is_numeric($count)) { + $counts[$account] = (int) $count; + } + } + + return $counts; + } +} diff --git a/modules/EcommerceFinance/Services/ProductPriceWorkbookImporter.php b/modules/EcommerceFinance/Services/ProductPriceWorkbookImporter.php new file mode 100644 index 00000000..8d77feae --- /dev/null +++ b/modules/EcommerceFinance/Services/ProductPriceWorkbookImporter.php @@ -0,0 +1,241 @@ + */ + private const HEADERS = [ + '记录标识' => 'upstream_key', + '商品编码' => 'barcode', + 'SPU' => 'spu', + '商品名称' => 'product_name', + '类目' => 'category', + '生产状态' => 'production_status', + '最低售价' => 'minimum_price', + '计算限价' => 'price_limit', + '采购价' => 'purchase_price', + '运费' => 'shipping_fee', + '京喜限价' => 'jingxi_limit_price', + ]; + + /** @var array */ + private const TEXT_LIMITS = [ + 'barcode' => 191, + 'spu' => 191, + 'product_name' => 5000, + 'category' => 255, + 'production_status' => 120, + ]; + + public function __construct(private readonly ProductPriceMirrorRepository $repository) + { + } + + /** @return array */ + public function templateFields(): array + { + $fields = []; + + foreach (self::HEADERS as $label => $field) { + if ($field === 'upstream_key') { + continue; + } + + $fields[$field] = [ + 'label' => $label, + 'type' => isset(self::TEXT_LIMITS[$field]) ? 'text' : 'number', + ]; + } + + return $fields; + } + + /** @return array{created:int,updated:int,rows:int} */ + public function import(UploadedFile $file, int $companyId, ?int $userId): array + { + try { + $spreadsheet = IOFactory::load($file->getRealPath()); + [$rows, $headerRow, $columns] = $this->bestMatchingSheet($spreadsheet); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。', + ]); + } finally { + if (isset($spreadsheet)) { + $spreadsheet->disconnectWorksheets(); + } + } + + if ($rows === null || ! in_array('upstream_key', $columns, true)) { + throw ValidationException::withMessages([ + 'import' => '未找到“记录标识”列,请先导出当前数据,再使用导出的表格进行修改。', + ]); + } + + if (count(array_intersect($columns, ProductPriceMirrorRepository::EDITABLE_FIELDS)) === 0) { + throw ValidationException::withMessages([ + 'import' => '表格中没有可导入的商品价格字段。', + ]); + } + + $records = []; + + foreach (array_slice($rows, $headerRow + 1, null, true) as $rowIndex => $row) { + $line = $rowIndex + 1; + $upstreamKey = ''; + $changes = []; + + foreach ($columns as $columnIndex => $field) { + $value = $row[$columnIndex] ?? null; + + if ($field === 'upstream_key') { + $upstreamKey = strtolower(trim((string) $value)); + continue; + } + + $changes[$field] = $this->normalizeValue($field, $value, $line); + } + + if ($upstreamKey === '' && collect($changes)->every( + static fn (mixed $value): bool => $value === null || $value === '' + )) { + continue; + } + + if (preg_match('/^[a-f0-9]{64}$/', $upstreamKey) !== 1) { + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行“记录标识”无效,请勿修改导出文件中的该列。", + ]); + } + + if (array_key_exists($upstreamKey, $records)) { + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行“记录标识”重复。", + ]); + } + + if (array_key_exists('barcode', $changes) && trim((string) $changes['barcode']) === '') { + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行“商品编码”不能为空。", + ]); + } + + if (collect($changes)->every(static fn (mixed $value): bool => $value === null || $value === '')) { + continue; + } + + $records[$upstreamKey] = $changes; + + if (count($records) > 10000) { + throw ValidationException::withMessages([ + 'import' => '单次最多导入 10,000 条商品价格记录,请拆分文件后重试。', + ]); + } + } + + if ($records === []) { + throw ValidationException::withMessages(['import' => '表格中没有可导入的数据行。']); + } + + try { + $result = $this->repository->applyOverrides($records, $companyId, $userId, 'import'); + } catch (RuntimeException $exception) { + if (str_starts_with($exception->getMessage(), 'product_price_record_not_found:')) { + throw ValidationException::withMessages([ + 'import' => '导入文件包含当前商品价格镜像中不存在的记录,请重新导出后再导入。', + ]); + } + + if ($exception->getMessage() === 'product_price_maintenance_schema_missing') { + throw ValidationException::withMessages([ + 'import' => '商品价格维护功能尚未完成初始化,请稍后重试。', + ]); + } + + throw $exception; + } + + return $result + ['rows' => count($records)]; + } + + private function bestMatchingSheet($spreadsheet): array + { + $lookup = []; + + foreach (self::HEADERS as $label => $field) { + $lookup[$this->normalizeHeader($label)] = $field; + $lookup[$this->normalizeHeader($field)] = $field; + } + + $best = [null, null, []]; + $bestScore = 0; + + foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { + $rows = $worksheet->toArray(null, false, false, false); + + foreach (array_slice($rows, 0, 20, true) as $rowIndex => $row) { + $columns = []; + + foreach ($row as $columnIndex => $heading) { + $key = $this->normalizeHeader($heading); + + if ($key !== '' && isset($lookup[$key])) { + $columns[$columnIndex] = $lookup[$key]; + } + } + + if (count($columns) > $bestScore) { + $best = [$rows, $rowIndex, $columns]; + $bestScore = count($columns); + } + } + } + + return $best; + } + + private function normalizeHeader(mixed $value): string + { + return mb_strtolower(preg_replace('/[\s\x{FEFF}_\-()()]+/u', '', trim((string) $value))); + } + + private function normalizeValue(string $field, mixed $value, int $line): mixed + { + if ($value === null || trim((string) $value) === '') { + return null; + } + + if (isset(self::TEXT_LIMITS[$field])) { + $text = trim((string) $value); + + if (mb_strlen($text) > self::TEXT_LIMITS[$field]) { + $label = array_search($field, self::HEADERS, true) ?: $field; + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行“{$label}”内容过长。", + ]); + } + + return $text; + } + + $number = str_replace([',', ',', '¥', '¥'], '', trim((string) $value)); + + if (preg_match('/^(?:\d+(?:\.\d{1,4})?|\.\d{1,4})$/', $number) !== 1 + || bccomp($number, '9999999999999999.9999', 4) === 1) { + $label = array_search($field, self::HEADERS, true) ?: $field; + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行“{$label}”必须是大于或等于 0、最多 4 位小数的有效金额。", + ]); + } + + return ltrim($number, '+'); + } +} diff --git a/modules/EcommerceFinance/Services/ProductPurchasePriceMirrorSynchronizer.php b/modules/EcommerceFinance/Services/ProductPurchasePriceMirrorSynchronizer.php index 0690d2aa..1a827005 100644 --- a/modules/EcommerceFinance/Services/ProductPurchasePriceMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/ProductPurchasePriceMirrorSynchronizer.php @@ -25,7 +25,10 @@ class ProductPurchasePriceMirrorSynchronizer } $state = $this->mirror->state(); - if (! $full && ($state['initial_completed_at'] ?? null) === null) { + if (! $full && ( + ($state['initial_completed_at'] ?? null) === null + || (int) ($state['projection_version'] ?? 1) < ProductPurchasePriceMirrorRepository::CURRENT_PROJECTION_VERSION + )) { return ['status' => 'requires_full_sync', 'mode' => 'incremental', 'batches' => 0, 'rows' => 0]; } @@ -33,6 +36,7 @@ class ProductPurchasePriceMirrorSynchronizer $resume = is_array($state) && ($state['run_mode'] ?? null) === $mode && in_array($state['status'] ?? null, ['running', 'failed'], true) + && (int) ($state['projection_version'] ?? 1) >= ProductPurchasePriceMirrorRepository::CURRENT_PROJECTION_VERSION && ($state['window_started_at'] ?? null) !== null && ($state['window_ends_at'] ?? null) !== null; $generation = $resume && is_string($state['generation'] ?? null) diff --git a/modules/EcommerceFinance/Services/StoreReportInitialPeriods.php b/modules/EcommerceFinance/Services/StoreReportInitialPeriods.php new file mode 100644 index 00000000..561b31f2 --- /dev/null +++ b/modules/EcommerceFinance/Services/StoreReportInitialPeriods.php @@ -0,0 +1,234 @@ +} */ + public static function current(): array + { + if (! self::seeded()) { + return self::fromConfig(); + } + + $shops = []; + foreach (self::storedShopNames() as $name) { + $rule = self::storedRule($name); + if ($rule !== null) { + $shops[$name] = $rule; + } + } + + return [ + 'initial_effective_at' => self::cleanDate(setting(self::EFFECTIVE_AT_KEY, null)) ?? self::DEFAULT_EFFECTIVE_AT, + 'shops' => self::normalizeShops($shops), + ]; + } + + public static function effectiveAt(): string + { + return self::current()['initial_effective_at']; + } + + /** @return array */ + public static function shops(): array + { + return self::current()['shops']; + } + + public static function seeded(): bool + { + return setting(self::signatureKey(), null) !== null; + } + + /** 把代码文件里的期初数据固化成可编辑的设置值。 */ + public static function seedFromConfig(): void + { + if (self::seeded()) { + return; + } + + $config = self::fromConfig(); + $payload = [self::EFFECTIVE_AT_KEY => $config['initial_effective_at']]; + foreach ($config['shops'] as $name => $rule) { + $payload += self::rulePayload($name, $rule); + } + $payload[self::shopListKey()] = implode("\n", array_keys($config['shops'])); + $payload[self::signatureKey()] = (string) count($config['shops']); + + setting($payload)->save(); + } + + /** @param array $shops */ + public static function saveShops(array $shops, ?string $effectiveAt = null): void + { + $current = self::current(); + $normalized = self::normalizeShops($shops); + $payload = [ + self::EFFECTIVE_AT_KEY => self::cleanDate($effectiveAt) ?? $current['initial_effective_at'], + self::shopListKey() => implode("\n", array_keys($normalized)), + self::signatureKey() => (string) count($normalized), + ]; + foreach ($normalized as $name => $rule) { + $payload += self::rulePayload($name, $rule); + } + + setting($payload)->save(); + + // 删除本次保存后不再存在的店铺键。 + foreach ($current['shops'] as $name => $rule) { + if (isset($normalized[$name])) { + continue; + } + self::forgetKeys($name); + } + } + + /** @return array{previous_company:string,company:string,changed_at:string}|null */ + public static function shop(string $storeName): ?array + { + return self::shops()[trim($storeName)] ?? null; + } + + /** @param array{previous_company:string,company:string,changed_at:string} $rule */ + public static function putShop(string $storeName, array $rule): void + { + $shops = self::shops(); + $shops[trim($storeName)] = $rule; + self::saveShops($shops); + } + + public static function forgetShop(string $storeName): void + { + $shops = self::shops(); + $name = trim($storeName); + unset($shops[$name]); + self::saveShops($shops); + self::forgetKeys($name); + } + + /** + * @return array{initial_effective_at:string,shops:array} + */ + private static function fromConfig(): array + { + return [ + 'initial_effective_at' => self::cleanDate(config('store_report_initial_periods.initial_effective_at')) + ?? self::DEFAULT_EFFECTIVE_AT, + 'shops' => self::normalizeShops((array) config('store_report_initial_periods.shops', [])), + ]; + } + + /** @param array $shops */ + private static function normalizeShops(array $shops): array + { + $clean = []; + foreach ($shops as $storeName => $rule) { + $name = trim((string) $storeName); + if ($name === '' || ! is_array($rule)) { + continue; + } + $changedAt = self::cleanDate($rule['changed_at'] ?? null); + if ($changedAt === null) { + continue; + } + $clean[$name] = [ + 'previous_company' => trim((string) ($rule['previous_company'] ?? '')), + 'company' => trim((string) ($rule['company'] ?? '')), + 'changed_at' => $changedAt, + ]; + } + + uasort($clean, static fn (array $left, array $right): int => strcmp($left['changed_at'], $right['changed_at'])); + + return $clean; + } + + private static function cleanDate(mixed $value): ?string + { + $value = trim((string) ($value ?? '')); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/D', $value) !== 1) { + return null; + } + + return $value; + } + + private static function shopKey(string $storeName): string + { + return sha1(mb_strtolower(trim($storeName))); + } + + private static function shopListKey(): string + { + return self::PREFIX . '.shop_list'; + } + + private static function signatureKey(): string + { + return self::PREFIX . '.seeded'; + } + + private static function ruleKey(string $storeName, string $field): string + { + return self::PREFIX . '.shop.' . self::shopKey($storeName) . '.' . $field; + } + + /** @return list */ + private static function storedShopNames(): array + { + $list = setting(self::shopListKey(), ''); + $list = is_array($list) ? implode("\n", $list) : (string) $list; + + return array_values(array_filter(array_map('trim', explode("\n", $list)))); + } + + /** @return array{previous_company:string,company:string,changed_at:string}|null */ + private static function storedRule(string $storeName): ?array + { + $changedAt = self::cleanDate(setting(self::ruleKey($storeName, 'changed_at'), null)); + if ($changedAt === null) { + return null; + } + + return [ + 'previous_company' => trim((string) setting(self::ruleKey($storeName, 'previous_company'), '')), + 'company' => trim((string) setting(self::ruleKey($storeName, 'company'), '')), + 'changed_at' => $changedAt, + ]; + } + + /** + * @param array{previous_company:string,company:string,changed_at:string} $rule + * @return array + */ + private static function rulePayload(string $storeName, array $rule): array + { + return [ + self::ruleKey($storeName, 'previous_company') => $rule['previous_company'], + self::ruleKey($storeName, 'company') => $rule['company'], + self::ruleKey($storeName, 'changed_at') => $rule['changed_at'], + self::ruleKey($storeName, 'name') => trim($storeName), + ]; + } + + private static function forgetKeys(string $storeName): void + { + foreach (['previous_company', 'company', 'changed_at', 'name'] as $field) { + setting()->forget(self::ruleKey($storeName, $field)); + } + setting()->save(); + } +} diff --git a/modules/EcommerceFinance/Services/StoreReportLogic.php b/modules/EcommerceFinance/Services/StoreReportLogic.php new file mode 100644 index 00000000..76a4dd2f --- /dev/null +++ b/modules/EcommerceFinance/Services/StoreReportLogic.php @@ -0,0 +1,83 @@ +>> + */ + public static function rules(): array + { + return [ + '主体期间来源' => [ + [ + 'code' => 'R1', + 'object' => '期初数据(已变更店铺)', + 'logic' => '变更店铺由负责人提供的期初数据锁定:老主体 2026-07-01 生效、失效时间为店铺变更到新主体的前一天;新主体从变更当天生效,失效时间显示「存续中」。', + 'source' => '店铺变更初始数据(' . self::INITIAL_PERIODS_CONFIG . ')', + 'priority' => '期初数据优先,覆盖流程历史', + ], + [ + 'code' => 'R2', + 'object' => '其他店铺的期初期间', + 'logic' => '未列入期初数据的店铺自 2026-07-01 起按财务系统登记主体生成一条期间,失效时间显示「存续中」;系统主体缺失时退回店铺基础信息页展示的主体。', + 'source' => 'ops_fys_shop_info + ops_fys_company_info', + 'priority' => '一条期间,从 2026-07-01 起', + ], + [ + 'code' => 'R3', + 'object' => '爬虫抓到的新主体', + 'logic' => '爬虫主体先按统一社会信用代码归一到工商主体名称;与当前期间最后一个主体不同时生成新期间,生效时间为首次抓到日期,老期间失效时间改为前一天,新期间失效时间显示「存续中」。', + 'source' => 'crawl_shop_company + store_report_shop_period_changes', + 'priority' => '爬虫驱动新增期间,日期一经记录不再前移', + ], + [ + 'code' => 'R4', + 'object' => '主体名称笔误', + 'logic' => '爬虫名称与系统名称不同、但税号归一到同一工商主体时不算主体变更,只保留名称不一致预警,不新增期间。', + 'source' => 'crawl_shop_company + fys_companyInfo', + 'priority' => '同税号视为同一主体', + ], + ], + '期间切割与展示' => [ + [ + 'code' => 'R5', + 'object' => '一行一期间', + 'logic' => '同一店铺的每个主体期间在报表中只显示一行,不再展开流程表历史记录;期间按日期严格衔接,不重复、不留空档。', + 'source' => 'StoreReportPeriodBuilder', + 'priority' => '去重后按主体期间展示', + ], + [ + 'code' => 'R6', + 'object' => '流程历史行的处理', + 'logic' => '报表期间不再直接读取 fys_shopInfo_flow 的原始行(历史重复行来源);流程数据仅作备查和同日冲突预警,不参与期间生成。', + 'source' => 'store_report_lifecycle_rows(备查)', + 'priority' => '不作为期间来源', + ], + [ + 'code' => 'R7', + 'object' => '关店与非正常状态', + 'logic' => '店铺状态为关店、关店中或其他非正常状态时,生效时间和失效时间都显示「-」;只有正常在营店铺展示期间日期。', + 'source' => 'ops_fys_shop_info.shopState', + 'priority' => '状态优先于期间展示', + ], + [ + 'code' => 'R8', + 'object' => '收入归属', + 'logic' => '期间销量按日汇总的实际发生日期归属:变更日当天归新主体,老主体统计到变更日前一天,主体切换不重复统计、不少计收入。', + 'source' => 'store_report_daily_rows + 主体期间', + 'priority' => '按日归属,区间不重叠', + ], + ], + ]; + } +} diff --git a/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php b/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php index a09bfa9f..70353e07 100644 --- a/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php @@ -24,7 +24,7 @@ class StoreReportMirrorSynchronizer ); } - /** @return array{lifecycles:array,bills:array,daily:array} */ + /** @return array{lifecycles:array,period_changes:array,bills:array,daily:array} */ public function sync( ?int $batchSize = null, ?int $maxBatches = null, @@ -47,6 +47,7 @@ class StoreReportMirrorSynchronizer fn (int $cursor, int $limit): array => $this->upstream->lifecycleBatch($cursor, $limit), fn (array $rows, string $generation): array => $this->mapLifecycles($rows, $generation), ); + $periodChanges = $this->syncShopPeriodChanges(); $bills = $this->syncDataset( StoreReportRepository::BILLS_DATASET, 'store_report_bill_rows', @@ -58,11 +59,105 @@ class StoreReportMirrorSynchronizer return [ 'lifecycles' => $lifecycles, + 'period_changes' => $periodChanges, 'bills' => $bills, 'daily' => $this->syncDailySummary($dailyBatchSize, $dailyMaxBatches), ]; } + /** + * 把爬虫首次抓到的新主体写入店铺主体期间变更记录。 + * + * 爬虫主体名称先按税号归一到工商主体资料,避免同一主体的名称笔误被当成变更; + * 只有与当前期间最后一个主体不同才新增记录,重复执行不会重复插入, + * 记录下来的首次抓到日期会固定新主体的生效时间,后续爬虫更新不再前移。 + * + * @return array{status:string,checked:int,created:int,reason?:string} + */ + private function syncShopPeriodChanges(): array + { + // 控制台没有网页公司上下文;先定位首家公司的期初设置,避免回退到代码文件旧值。 + try { + \App\Models\Common\Company::query()->orderBy('id')->first()?->makeCurrent(); + } catch (Throwable) { + // 读取失败时期间构建器会回退到配置文件,不阻断同步。 + } + + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable('ops_crawl_shop_company')) { + return ['status' => 'skipped', 'checked' => 0, 'created' => 0, 'reason' => 'crawl_mirror_not_ready']; + } + if (! $schema->hasTable(StoreReportPeriodBuilder::CHANGES_TABLE)) { + return ['status' => 'skipped', 'checked' => 0, 'created' => 0, 'reason' => 'change_table_missing']; + } + + $ranked = $this->connection->table('ops_crawl_shop_company') + ->selectRaw('id, shop_name, company_name, tax_no, crawl_date, row_number() over (partition by shop_name order by crawl_date desc, id desc) AS row_rank'); + $latest = $this->connection->table($ranked, 'crawler_latest') + ->where('row_rank', 1) + ->get(['shop_name', 'company_name', 'tax_no', 'crawl_date']); + if ($latest->isEmpty()) { + return ['status' => 'succeeded', 'checked' => 0, 'created' => 0]; + } + + $masterNames = []; + if ($schema->hasTable('ops_fys_company_info')) { + $rankedCompanies = $this->connection->table('ops_fys_company_info') + ->selectRaw('unifiedSocialCreditCode, businessLicenseName, row_number() over (partition by unifiedSocialCreditCode order by Id desc) AS row_rank'); + foreach ($this->connection->table($rankedCompanies, 'company_latest') + ->where('row_rank', 1) + ->get(['unifiedSocialCreditCode', 'businessLicenseName']) as $row) { + $code = trim((string) ($row->unifiedSocialCreditCode ?? '')); + $name = trim((string) ($row->businessLicenseName ?? '')); + if ($code !== '' && $name !== '') { + $masterNames[$code] = $name; + } + } + } + + $changes = []; + foreach ($latest as $row) { + $name = trim((string) ($row->shop_name ?? '')); + $taxNo = trim((string) ($row->tax_no ?? '')); + $company = $masterNames[$taxNo] ?? trim((string) ($row->company_name ?? '')); + $observed = substr(trim((string) ($row->crawl_date ?? '')), 0, 10); + if ($name === '' || $company === '' || $observed === '') { + continue; + } + $changes[$name] = ['company' => $company, 'tax_no' => $taxNo, 'observed_on' => $observed]; + } + if ($changes === []) { + return ['status' => 'succeeded', 'checked' => 0, 'created' => 0]; + } + + $periods = app(StoreReportPeriodBuilder::class)->build(array_map( + static fn (string $name): array => ['erp_store_name' => $name], + array_keys($changes), + )); + + $created = 0; + foreach ($changes as $name => $change) { + $list = $periods[$name] ?? []; + $last = $list === [] ? null : $list[count($list) - 1]; + if ($this->sameCompany($last['company_name'] ?? null, $change['company'])) { + continue; + } + + $created += (int) $this->connection->table(StoreReportPeriodBuilder::CHANGES_TABLE)->insertOrIgnore([ + 'erp_store_name' => $name, + 'company_name' => $change['company'], + 'unified_social_credit_code' => $change['tax_no'] === '' ? null : $change['tax_no'], + 'observed_on' => $change['observed_on'], + 'source' => 'crawl_shop_company', + 'business_key' => hash('sha256', implode('|', [$name, $change['company'], $change['observed_on']])), + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + return ['status' => 'succeeded', 'checked' => count($changes), 'created' => $created]; + } + /** * @param callable(int,int):array> $fetch * @param callable(array>,string):array{upserts:array>,deletes:array} $map @@ -119,10 +214,16 @@ class StoreReportMirrorSynchronizer } $mapped = $map($rows, $generation); - $this->storeBatch($dataset, $table, $generation, $nextCursor, $mapped, $initial, $storedRows); + $storedRows = $this->storeBatch( + $dataset, + $table, + $generation, + $nextCursor, + $mapped, + $storedRows, + ); $cursor = $nextCursor; $sourceRows += count($rows); - $storedRows += $initial ? count($mapped['upserts']) : 0; $batches++; if (count($rows) < $batchSize) { @@ -163,12 +264,30 @@ class StoreReportMirrorSynchronizer string $generation, int $cursor, array $mapped, - bool $initial, int $storedRows, - ): void { - $this->connection->transaction(function () use ( - $dataset, $table, $generation, $cursor, $mapped, $initial, $storedRows, - ): void { + ): int { + return $this->connection->transaction(function () use ( + $dataset, $table, $generation, $cursor, $mapped, $storedRows, + ): int { + $upsertIds = []; + foreach ($mapped['upserts'] as $row) { + $upsertIds[(int) $row['source_id']] = true; + } + $deleteIds = array_fill_keys(array_map('intval', $mapped['deletes']), true); + $touchedIds = array_keys($upsertIds + $deleteIds); + $existingIds = []; + foreach (array_chunk($touchedIds, 1000) as $chunk) { + foreach ($this->connection->table($table) + ->where('generation', $generation) + ->whereIn('source_id', $chunk) + ->pluck('source_id') as $sourceId) { + $existingIds[(int) $sourceId] = true; + } + } + $inserted = count(array_diff_key($upsertIds, $existingIds)); + $deleted = count(array_diff_key(array_intersect_key($deleteIds, $existingIds), $upsertIds)); + $nextStoredRows = max($storedRows + $inserted - $deleted, 0); + $dailyDeltas = $table === 'store_report_bill_rows' && $this->dailySummaryReady($generation) ? $this->dailyDeltas($generation, $mapped) : []; @@ -195,9 +314,11 @@ class StoreReportMirrorSynchronizer } $this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->update([ 'cursor_id' => $cursor, - 'row_count' => $initial ? $storedRows + count($mapped['upserts']) : $storedRows, + 'row_count' => $nextStoredRows, 'updated_at' => now(), ]); + + return $nextStoredRows; }); } @@ -212,18 +333,13 @@ class StoreReportMirrorSynchronizer int $sourceRows, ): array { $now = now(); - $actualRows = (int) $this->connection->table( - $dataset === StoreReportRepository::BILLS_DATASET - ? 'store_report_bill_rows' - : 'store_report_lifecycle_rows', - )->where('generation', $generation)->count(); $values = [ 'status' => 'succeeded', 'run_mode' => null, 'cursor_id' => $cursor, 'last_succeeded_at' => $now, 'last_error_code' => null, - 'row_count' => $actualRows, + 'row_count' => $storedRows, 'updated_at' => $now, ]; if ($mode === 'full') { @@ -235,7 +351,7 @@ class StoreReportMirrorSynchronizer } $this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->update($values); - return $this->result('succeeded', $mode, $batches, $sourceRows, $actualRows, $cursor); + return $this->result('succeeded', $mode, $batches, $sourceRows, $storedRows, $cursor); } /** @return array{status:string,mode:string,batches:int,source_rows:int,stored_rows:int,cursor_id:int} */ @@ -518,6 +634,14 @@ class StoreReportMirrorSynchronizer return mb_substr($value, 0, $length); } + private function sameCompany(mixed $left, mixed $right): bool + { + $left = mb_strtolower(trim((string) ($left ?? ''))); + $right = mb_strtolower(trim((string) ($right ?? ''))); + + return $left !== '' && $left === $right; + } + private function dateTime(mixed $value): ?string { $value = trim((string) ($value ?? '')); diff --git a/modules/EcommerceFinance/Services/StoreReportPeriodBuilder.php b/modules/EcommerceFinance/Services/StoreReportPeriodBuilder.php new file mode 100644 index 00000000..091fa92a --- /dev/null +++ b/modules/EcommerceFinance/Services/StoreReportPeriodBuilder.php @@ -0,0 +1,258 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public static function initialEffectiveAt(): string + { + return StoreReportInitialPeriods::effectiveAt(); + } + + /** + * @param array> $stores 报表店铺行;只需要 erp_store_name,company_name 作为系统主体缺失时的回退值。 + * @return array> + */ + public function build(array $stores): array + { + $names = []; + $fallbackCompanies = []; + $knownEntities = []; + foreach ($stores as $store) { + $name = trim((string) ($store['erp_store_name'] ?? '')); + if ($name === '') { + continue; + } + $names[$name] = $name; + $company = trim((string) ($store['company_name'] ?? '')); + if ($company !== '') { + $fallbackCompanies[$name] = $company; + } + // 店铺行已带系统主体时不再重复查询镜像;null 表示系统确实没有登记主体。 + if (array_key_exists('system_company_name', $store)) { + $knownEntities[$name] = $this->cleanCompany($store['system_company_name']); + } + } + + return $this->assemble(array_values($names), $fallbackCompanies, $knownEntities); + } + + /** + * @param list $names + * @param array $fallbackCompanies + * @param array $knownEntities + * @return array> + */ + private function assemble(array $names, array $fallbackCompanies, array $knownEntities = []): array + { + if ($names === []) { + return []; + } + + $initial = StoreReportInitialPeriods::shops(); + $initialDate = self::initialEffectiveAt(); + $missing = array_values(array_diff($names, array_keys($knownEntities))); + $entities = $knownEntities + $this->systemEntities($missing); + $changes = $this->crawledChanges($names); + $periods = []; + + foreach ($names as $name) { + $rule = $initial[$name] ?? null; + $changedAt = is_array($rule) ? $this->date($rule['changed_at'] ?? null) : null; + // 变更日必须晚于期初日,否则老主体期间为空,直接按新主体从期初日起算。 + if (is_array($rule) && $changedAt !== null && $changedAt > $initialDate) { + $list = [ + [ + 'company_name' => $this->cleanCompany($rule['previous_company'] ?? null), + 'effective_at' => $initialDate, + 'expires_at' => $this->dayBefore($changedAt), + 'source' => 'initial', + ], + [ + 'company_name' => $this->cleanCompany($rule['company'] ?? null), + 'effective_at' => $changedAt, + 'expires_at' => null, + 'source' => 'initial', + ], + ]; + } else { + $list = [[ + 'company_name' => (is_array($rule) ? $this->cleanCompany($rule['company'] ?? null) : null) + ?? ($entities[$name] ?? ($fallbackCompanies[$name] ?? null)), + 'effective_at' => $initialDate, + 'expires_at' => null, + 'source' => 'baseline', + ]]; + } + + foreach ($changes[$name] ?? [] as $change) { + $company = $this->cleanCompany($change['company_name'] ?? null); + $observed = $this->date($change['observed_on'] ?? null); + if ($company === null || $observed === null || $observed < $initialDate) { + continue; + } + + $last = &$list[count($list) - 1]; + if ($this->sameCompany($last['company_name'], $company)) { + continue; + } + // 变更必须晚于当前期间生效日,避免爬虫记录早于期初数据时产生重叠。 + if (strcmp($observed, (string) $last['effective_at']) <= 0) { + continue; + } + + $last['expires_at'] = $this->dayBefore($observed); + $list[] = [ + 'company_name' => $company, + 'effective_at' => $observed, + 'expires_at' => null, + 'source' => 'crawl', + ]; + unset($last); + } + unset($last); + + $periods[$name] = $list; + } + + return $periods; + } + + /** + * 财务系统登记的店铺主体(与 rpt.fys_shopInfo + fys_companyInfo 一致)。 + * + * @param list $names + * @return array + */ + private function systemEntities(array $names): array + { + $entities = []; + foreach (array_chunk($names, 500) as $chunk) { + $placeholders = implode(',', array_fill(0, count($chunk), '?')); + try { + $rows = $this->connection->select( + "SELECT s.erpShopName AS store_name, c.businessLicenseName AS company_name + FROM ops_fys_shop_info AS s + LEFT JOIN ( + SELECT unifiedSocialCreditCode, MAX(Id) AS latest_id + FROM ops_fys_company_info + WHERE unifiedSocialCreditCode IS NOT NULL + GROUP BY unifiedSocialCreditCode + ) AS latest ON latest.unifiedSocialCreditCode = s.unifiedSocialCreditCode + LEFT JOIN ops_fys_company_info AS c ON c.Id = latest.latest_id + WHERE s.erpShopName IN ({$placeholders})", + $chunk, + ); + } catch (Throwable) { + return []; + } + foreach ($rows as $row) { + $name = trim((string) ($row->store_name ?? '')); + $company = $this->cleanCompany($row->company_name ?? null); + if ($name !== '' && $company !== null) { + $entities[$name] = $company; + } + } + } + + return $entities; + } + + /** + * 爬虫首次抓到的新主体记录,按抓到日期升序构成后续期间。 + * + * @param list $names + * @return array> + */ + private function crawledChanges(array $names): array + { + $changes = []; + foreach (array_chunk($names, 500) as $chunk) { + $placeholders = implode(',', array_fill(0, count($chunk), '?')); + try { + $rows = $this->connection->select( + "SELECT erp_store_name, company_name, observed_on + FROM " . self::CHANGES_TABLE . " + WHERE erp_store_name IN ({$placeholders}) + ORDER BY observed_on ASC, id ASC", + $chunk, + ); + } catch (Throwable) { + return []; + } + foreach ($rows as $row) { + $name = trim((string) ($row->erp_store_name ?? '')); + if ($name === '') { + continue; + } + $changes[$name][] = [ + 'company_name' => $row->company_name ?? null, + 'observed_on' => $row->observed_on ?? null, + ]; + } + } + + return $changes; + } + + private function cleanCompany(mixed $value): ?string + { + $company = trim((string) ($value ?? '')); + + return $company === '' ? null : $company; + } + + private function sameCompany(?string $left, ?string $right): bool + { + return mb_strtolower(trim((string) $left)) === mb_strtolower(trim((string) $right)); + } + + private function date(mixed $value): ?string + { + $value = trim((string) ($value ?? '')); + if ($value === '') { + return null; + } + + try { + return Carbon::parse($value)->format('Y-m-d'); + } catch (Throwable) { + return null; + } + } + + private function dayBefore(string $date): string + { + return Carbon::parse($date)->subDay()->format('Y-m-d'); + } +} diff --git a/modules/EcommerceFinance/Services/SupplierPayableImportTemplate.php b/modules/EcommerceFinance/Services/SupplierPayableImportTemplate.php new file mode 100644 index 00000000..b4ebe33d --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierPayableImportTemplate.php @@ -0,0 +1,91 @@ + $fields */ + public function download(string $title, array $fields, bool $optionalRecordKey = false): StreamedResponse + { + return response()->streamDownload(function () use ($title, $fields, $optionalRecordKey): void { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle($this->sheetTitle($title)); + + $headers = array_merge(['记录标识'], array_column($fields, 'label')); + $sheet->fromArray($headers, null, 'A1'); + $lastColumn = Coordinate::stringFromColumnIndex(count($headers)); + $headerRange = 'A1:' . $lastColumn . '1'; + + $sheet->getStyle($headerRange)->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER], + 'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'D8D2C7']]], + ]); + $sheet->getRowDimension(1)->setRowHeight(24); + $sheet->freezePane('A2'); + $sheet->setAutoFilter($headerRange); + $sheet->getColumnDimension('A')->setWidth(38); + + $columnIndex = 2; + foreach ($fields as $definition) { + $column = Coordinate::stringFromColumnIndex($columnIndex); + $width = max(14, min(30, mb_strlen($definition['label']) * 2 + 4)); + $sheet->getColumnDimension($column)->setWidth($width); + if ($definition['type'] === 'number') { + $sheet->getStyle($column . '2:' . $column . '10001')->getNumberFormat()->setFormatCode('0.0000'); + } else { + $sheet->getStyle($column . '2:' . $column . '10001')->getNumberFormat()->setFormatCode('@'); + } + $columnIndex++; + } + $sheet->getStyle('A2:A10001')->getNumberFormat()->setFormatCode('@'); + + $instructions = $spreadsheet->createSheet(); + $instructions->setTitle('填写说明'); + $instructions->fromArray([ + ['项目', '说明'], + ['记录标识', $optionalRecordKey + ? '选填。留空表示新增一行;需要修改已导入的行时,请先导出、修改后再导入。' + : '必填。请从本页面导出的文件中复制,不能修改。'], + ['日期', '请填写 YYYY-MM-DD,例如 2026-09-17。'], + ['月份', '请填写 YYYY-MM,例如 2026-09。'], + ['数字', '最多支持 4 位小数;金额可直接填写数字。'], + ['空白单元格', '导入后将清空该字段,请确认后再导入。'], + ], null, 'A1'); + $instructions->getStyle('A1:B1')->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + ]); + $instructions->getColumnDimension('A')->setWidth(18); + $instructions->getColumnDimension('B')->setWidth(58); + $instructions->getStyle('A1:B6')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER)->setWrapText(true); + foreach (range(1, 6) as $row) { + $instructions->getRowDimension($row)->setRowHeight($row === 1 ? 24 : 32); + } + + $spreadsheet->setActiveSheetIndex(0); + (new Xlsx($spreadsheet))->save('php://output'); + $spreadsheet->disconnectWorksheets(); + }, $title . '_导入模板_' . now()->format('Ymd') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } + + private function sheetTitle(string $title): string + { + $title = str_replace(['\\', '/', '?', '*', '[', ']', ':'], '', $title) ?: '导入模板'; + + return mb_substr($title, 0, 31); + } +} diff --git a/modules/EcommerceFinance/Services/SupplierPayableMaintenanceRegistry.php b/modules/EcommerceFinance/Services/SupplierPayableMaintenanceRegistry.php new file mode 100644 index 00000000..bbb88348 --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierPayableMaintenanceRegistry.php @@ -0,0 +1,124 @@ + */ + public function fields(string $dataset): array + { + $money = static fn (string $label): array => ['label' => $label, 'type' => 'number']; + $text = static fn (string $label): array => ['label' => $label, 'type' => 'text']; + $date = static fn (string $label): array => ['label' => $label, 'type' => 'date']; + $month = static fn (string $label): array => ['label' => $label, 'type' => 'month']; + + return match ($dataset) { + 'payment-reconciliation' => [ + 'supplier' => $text('供应商'), 'skuCode' => $text('货号'), 'productCode' => $text('商品编码'), + 'skuName' => $text('规格名称'), 'qty' => $money('数量'), 'unitPrice' => $money('单价'), + 'amount' => $money('金额'), 'guessUnitPrice' => $money('预估单价'), 'guessAmount' => $money('预估金额'), + 'supplierGoodsCode' => $text('供应商商品编码'), 'remark' => $text('备注'), + 'warehouse' => $text('仓库名称'), 'expressName' => $text('快递名称'), 'expressNo' => $text('快递单号'), + ], + 'return-reconciliation', 'return-unpriced' => [ + 'send_time' => $date('发货时间'), 'supplier' => $text('明细供应商'), 'barcode' => $text('条形码'), + 'sku_name' => $text('商品名称'), 'qty' => $money('发货量'), 'unit_price' => $money('单价'), + 'amount' => $money('金额'), 'guess_unit_price' => $money('预估单价'), 'guess_amount' => $money('预估金额'), + 'supplier_barcode' => $text('供应商条码'), 'remark' => $text('备注'), 'title' => $text('标题'), + 'warehouse' => $text('仓库名称'), 'express_no' => $text('快递单号'), + 'express_name' => $text('快递名称'), 'labels' => $text('标记多标签'), 'reconciler' => $text('对账人'), + ], + 'invoice-deductions' => [ + 'month_str' => $month('日期'), 'category' => $text('类别'), 'payee' => $text('打款抬头'), + 'receiver' => $text('收款方'), 'board_factory' => $text('供板材厂家/代扣厂家'), + 'subsidy_fee' => $money('补贴费用'), 'remark' => $text('备注'), 'price' => $money('对私打款金额'), + 'detail' => $text('明细'), 'note' => $text('注明'), 'person_charge' => $text('负责人'), + ], + 'compensation-details' => [ + 'month' => $month('日期'), 'supplier' => $text('供应商'), 'amount' => $money('赔付金额'), + 'reason' => $text('赔付原因'), 'remark' => $text('备注'), + ], + 'advance-details' => [ + 'supplier' => $text('供应商'), 'contract_name' => $text('协议签订名称'), + 'advance_amount' => $money('借支金额'), 'actual_pay' => $money('实际打款金额'), + 'month_deduct' => $money('本月扣款金额'), 'should_deduct' => $money('应扣金额'), + 'deduct_start_month' => $month('分期起始扣款月份'), 'deduct_end_month' => $month('分期最后扣款月份'), + 'remain_periods' => $money('分期剩余期数'), 'month_str' => $month('借支日期'), + 'loan_term' => $text('借款期限'), 'remark' => $text('备注'), 'is_paid' => $text('是否打款'), + 'pay_month' => $month('打款月份'), 'serial_no' => $text('流水号'), + 'loan_agreement' => $text('借支协议'), 'person_charge' => $text('负责人'), + ], + 'sample-deductions' => [ + 'finish_time' => $date('日期'), 'department' => $text('部门'), 'creator' => $text('申请人'), + 'sku_id' => $text('商品代码'), 'skuName' => $text('商品名称'), 'num' => $money('数量'), + 'supplier' => $text('厂家'), 'purchase' => $text('对应采购'), 'productCode' => $text('扣款厂家商品代码'), + 'shipping_fee' => $money('运费'), 'cost_price' => $money('成本价'), + 'total_amount' => $money('合计扣款金额'), 'estimated_price' => $money('预估价'), + 'estimated_price_all' => $money('预估金额'), 'remark' => $text('备注'), + ], + 'delivery-unpriced' => [ + 'transactionNo' => $text('来源单号'), 'distributionNo' => $text('单据编号(采购单号)'), + 'date' => $date('创建时间'), 'supplier' => $text('供应商'), 'sku' => $text('货号'), + 'barCode' => $text('条码'), 'skuName' => $text('规格名'), 'supplier_barcode' => $text('供应商条码'), + 'remark' => $text('备注'), 'warehouse' => $text('仓库'), 'expressName' => $text('快递名称'), + 'expressNo' => $text('快递单号'), 'purchase' => $text('负责人'), + ], + 'other-adjustments' => [ + 'project' => $text('项目'), 'month_str' => $month('日期'), 'supplier' => $text('厂家'), + 'supplement_amount' => $money('补款金额'), 'supplement_reason' => $text('补款原因'), + 'remark' => $text('备注'), 'remark2' => $text('备注2'), 'person_charge' => $text('负责人'), + ], + 'dropshipping-express' => [ + 'reconciliation_person' => $text('对账人'), 'month_str' => $month('日期'), 'supplier' => $text('供应商'), + 'express_freight' => $money('快递运费'), 'express_account' => $money('快递记账'), + 'replenish_freight' => $money('补运费'), 'replenish_account' => $money('补记账'), + 'return_fee' => $money('退回费'), 'intercept_fee' => $money('拦截'), + 'change_address_fee' => $money('改地址'), 'turnover_fee' => $money('翻箱费'), + 'overlong_fee' => $money('超长费'), 'total_freight' => $money('合计运费'), + 'remark' => $text('备注'), 'express_name' => $text('快递'), 'remark2' => $text('备注2'), + ], + 'board-deductions' => [ + 'stock_in_date' => $date('入库日期'), 'stock_out_date' => $date('出库日期'), + 'furniture_factory' => $text('家具厂'), 'lamination_factory' => $text('压贴厂'), + 'deduction_type' => $text('类型'), 'specification' => $text('规格'), 'material_name' => $text('原料名称'), + 'received_quantity' => $money('实收数量'), 'unit_price' => $money('单价'), 'amount' => $money('金额'), + 'unit' => $text('单位'), 'batch_date' => $date('批次日期'), 'stock_out_number' => $text('出库单号'), + 'stock_out_remark' => $text('出库备注'), 'claim_number' => $text('申领单号'), + 'number_type' => $text('单号类型'), 'delivery_number' => $text('送货单号'), + ], + 'supplier-payables-report' => [ + 'checker' => $text('对账人'), 'settlement_method' => $text('结算方式'), 'company' => $text('供应商公司主体名称'), + 'supplier' => $text('供应商简称'), 'express_freight' => $money('快递运费'), + 'beginning_payable' => $money('月初未付'), 'unpriced' => $money('之前未定价-本月定价'), + 'advance_loan' => $money('预支借款'), 'loan' => $money('货款金额'), 'refund' => $money('退货金额'), + 'procurement' => $money('采购小计'), 'invoice_deduction' => $money('发票扣款'), + 'board_deduction' => $money('板材扣款'), 'sample_deduction' => $money('样品扣款'), + 'total_compensation' => $money('总赔偿金额'), 'other_adjustment' => $money('其他费用'), + 'supplier_supplement' => $money('补给厂家'), 'supplier_balance' => $money('供应商余额'), + 'should_pay' => $money('应付余额'), 'estimated_price' => $money('预估金额'), + 'to_corporate' => $money('对公打款金额'), 'to_private' => $money('对私打款金额'), + 'cashier_paid' => $money('已销账金额'), 'remarks' => $text('备注'), + 'private_reason' => $text('对私原因'), 'deposit' => $money('押款金额'), + 'negative_reason' => $text('负数原因'), + ], + default => throw ValidationException::withMessages(['dataset' => '不支持该供应商应付页面。']), + }; + } + + public function normalize(string $dataset, array $input): array + { + return app(PayablesFieldNormalizer::class)->normalize($this->fields($dataset), $input); + } + + public function publicDefinition(string $dataset): array + { + return [ + 'dataset' => $dataset, + 'fields' => collect($this->fields($dataset))->map( + static fn (array $definition, string $name): array => ['name' => $name] + $definition + )->values()->all(), + ]; + } +} diff --git a/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php b/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php new file mode 100644 index 00000000..eff299b5 --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php @@ -0,0 +1,128 @@ +> $rows */ + public function decorate(string $dataset, array $rows, int $companyId): array + { + if ($rows === []) { + return []; + } + + $keys = []; + foreach ($rows as $row) { + $keys[] = $this->key($dataset, $row); + } + + $overrides = $this->connection()->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset) + ->whereIn('record_key', $keys) + ->get() + ->keyBy('record_key'); + + foreach ($rows as $index => &$row) { + $key = $keys[$index]; + $row['_action_key'] = $key; + $override = $overrides->get($key); + if ($override) { + $values = json_decode((string) $override->values, true) ?: []; + $row = array_merge($row, $values); + $row['_overridden'] = true; + } else { + $row['_overridden'] = false; + } + } + unset($row); + + return $rows; + } + + /** @return array{created:int,updated:int} */ + public function save(string $dataset, string $recordKey, array $values, int $companyId, ?int $userId, string $source = 'manual'): array + { + $connection = $this->connection(); + $existing = $connection->table('supplier_payable_overrides') + ->where(['company_id' => $companyId, 'dataset' => $dataset, 'record_key' => $recordKey]) + ->first(); + $before = $existing ? (json_decode((string) $existing->values, true) ?: []) : null; + $now = now(); + + $connection->transaction(function () use ($connection, $existing, $dataset, $recordKey, $values, $companyId, $userId, $now, $source, $before): void { + $connection->table('supplier_payable_overrides')->updateOrInsert( + ['company_id' => $companyId, 'dataset' => $dataset, 'record_key' => $recordKey], + [ + 'values' => json_encode($values, JSON_UNESCAPED_UNICODE), + 'updated_by' => $userId, + 'created_by' => $existing->created_by ?? $userId, + 'created_at' => $existing->created_at ?? $now, + 'updated_at' => $now, + ], + ); + $connection->table('supplier_payable_override_events')->insert([ + 'company_id' => $companyId, + 'dataset' => $dataset, + 'record_key' => $recordKey, + 'source' => $source, + 'before_values' => $before === null ? null : json_encode($before, JSON_UNESCAPED_UNICODE), + 'after_values' => json_encode($values, JSON_UNESCAPED_UNICODE), + 'user_id' => $userId, + 'created_at' => $now, + ]); + }); + + return ['created' => $existing ? 0 : 1, 'updated' => $existing ? 1 : 0]; + } + + public function transaction(Closure $callback): mixed + { + return $this->connection()->transaction($callback); + } + + /** + * 列出某个数据集已经保存的全部记录(「终版」目录的独立数据就是这些行)。 + * + * @return array> + */ + public function listRows(string $dataset, int $companyId): array + { + return $this->connection()->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset) + ->orderBy('id') + ->get() + ->map(static function (object $record): array { + $values = json_decode((string) $record->values, true) ?: []; + $values['_action_key'] = (string) $record->record_key; + + return $values; + }) + ->all(); + } + + private function connection(): ConnectionInterface + { + return DB::connection(config('database.supplier_payable_maintenance_connection')); + } +} diff --git a/modules/EcommerceFinance/Services/SupplierPayableWorkbookImporter.php b/modules/EcommerceFinance/Services/SupplierPayableWorkbookImporter.php new file mode 100644 index 00000000..727e90cc --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierPayableWorkbookImporter.php @@ -0,0 +1,129 @@ +registry->fields($dataset); + $lookup = ['记录标识' => '_action_key', 'recordkey' => '_action_key', '_action_key' => '_action_key']; + foreach ($definitions as $field => $definition) { + $lookup[$this->header($field)] = $field; + $lookup[$this->header($definition['label'])] = $field; + } + + try { + $readerType = match (mb_strtolower($file->getClientOriginalExtension())) { + 'xlsx' => 'Xlsx', + 'xls' => 'Xls', + 'csv' => 'Csv', + default => throw new \RuntimeException('Unsupported workbook format.'), + }; + $spreadsheet = IOFactory::createReader($readerType)->load($file->getRealPath()); + [$rows, $headerRow, $columns] = $this->bestSheet($spreadsheet, $lookup); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。', + ]); + } finally { + if (isset($spreadsheet)) { + $spreadsheet->disconnectWorksheets(); + } + } + + if ($rows === null || ! in_array('_action_key', $columns, true)) { + throw ValidationException::withMessages([ + 'import' => '未找到“记录标识”列,请先导出当前数据,再使用导出的表格修改。', + ]); + } + + $records = []; + foreach (array_slice($rows, $headerRow + 1, null, true) as $rowIndex => $row) { + $line = $rowIndex + 1; + $key = ''; + $rawValues = []; + foreach ($columns as $columnIndex => $field) { + if ($field === '_action_key') { + $key = trim((string) ($row[$columnIndex] ?? '')); + } else { + $rawValues[$field] = $row[$columnIndex] ?? null; + } + } + if ($key === '' && collect($rawValues)->every(static fn (mixed $value): bool => trim((string) $value) === '')) { + continue; + } + if (! str_starts_with($key, 'id:') && ! preg_match('/^hash:[a-f0-9]{64}$/', $key)) { + throw ValidationException::withMessages(['import' => "第 {$line} 行“记录标识”无效,请勿修改该列。"]); + } + if (isset($records[$key])) { + throw ValidationException::withMessages(['import' => "第 {$line} 行“记录标识”重复。"]); + } + try { + $records[$key] = $this->registry->normalize($dataset, $rawValues); + } catch (ValidationException $exception) { + throw ValidationException::withMessages([ + 'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(), + ]); + } + if (count($records) > 10000) { + throw ValidationException::withMessages(['import' => '单次最多导入 10,000 条记录,请拆分文件后重试。']); + } + } + + if ($records === []) { + throw ValidationException::withMessages(['import' => '表格中没有可导入的数据行。']); + } + + $counts = ['created' => 0, 'updated' => 0]; + $this->overrides->transaction(function () use ($records, $dataset, $companyId, $userId, &$counts): void { + foreach ($records as $key => $values) { + $result = $this->overrides->save($dataset, $key, $values, $companyId, $userId, 'import'); + $counts['created'] += $result['created']; + $counts['updated'] += $result['updated']; + } + }); + + return $counts + ['rows' => count($records)]; + } + + private function bestSheet(mixed $spreadsheet, array $lookup): array + { + $best = [null, null, []]; + $score = 0; + foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { + $rows = $worksheet->toArray(null, false, false, false); + foreach (array_slice($rows, 0, 20, true) as $rowIndex => $row) { + $columns = []; + foreach ($row as $columnIndex => $heading) { + $key = $this->header($heading); + if ($key !== '' && isset($lookup[$key])) { + $columns[$columnIndex] = $lookup[$key]; + } + } + if (count($columns) > $score) { + $best = [$rows, $rowIndex, $columns]; + $score = count($columns); + } + } + } + return $best; + } + + private function header(mixed $value): string + { + return mb_strtolower(preg_replace('/[\s\x{FEFF}_\-()()]+/u', '', trim((string) $value))); + } +} diff --git a/modules/EcommerceFinance/Services/TaobaoAlipaySettlementBillImporter.php b/modules/EcommerceFinance/Services/TaobaoAlipaySettlementBillImporter.php new file mode 100644 index 00000000..da358240 --- /dev/null +++ b/modules/EcommerceFinance/Services/TaobaoAlipaySettlementBillImporter.php @@ -0,0 +1,631 @@ + ['记录编码'], + 'store_name' => ['原始店铺', '店铺'], + 'custom_remark' => ['自定义备注'], + 'bill_item' => ['账单项目'], + 'alipay_account' => ['支付宝账号', '平台账号'], + 'account_order_no' => ['账务订单号'], + 'business_serial_no' => ['业务流水号'], + 'merchant_order_no' => ['商户订单号'], + 'business_base_order_no' => ['业务基础订单号'], + 'goods_name' => ['商品名称', '商品编码'], + 'counterparty_account' => ['对方账号'], + 'occurred_at' => ['发生时间'], + 'income_amount' => ['收入', '收入金额'], + 'expense_amount' => ['支出', '支出金额'], + 'balance_amount' => ['余额', '收支净额', '金额'], + 'business_type' => ['业务类型', '财务类型'], + 'remark' => ['备注'], + 'online_order_no' => ['线上单号'], + 'online_real_store' => ['线上单号对应实际店铺'], + 'business_description' => ['业务描述'], + 'business_bill_source' => ['业务账单来源', '平台渠道'], + 'business_order_no' => ['业务订单号'], + 'source_created_at' => ['创建时间'], + 'source_updated_at' => ['修改时间'], + 'source_modified_by' => ['修改人'], + ]; + + private const OPTIONAL_HEADERS = [ + 'store_name', 'custom_remark', 'alipay_account', 'account_order_no', + 'business_serial_no', 'merchant_order_no', 'business_base_order_no', + 'goods_name', 'counterparty_account', 'balance_amount', 'business_type', + 'remark', 'online_order_no', 'online_real_store', 'business_description', + 'business_bill_source', 'business_order_no', 'source_created_at', + 'source_updated_at', 'source_modified_by', + ]; + + private readonly ConnectionInterface $connection; + + public function __construct(DatabaseManager $databases) + { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{status:string,source_filename:string,source_sha256:string,period_start:string,period_end:string,row_count:int,store_count:int,bill_item_count:int,business_type_counts:array,income_total:string,expense_total:string,net_total:string} + */ + public function import( + string $path, + string $fromDate, + string $toDate, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + int $batchSize = 500, + ): array { + $path = $this->validatedPath($path); + [$from, $to] = $this->period($fromDate, $toDate); + $this->assertSchemaReady(); + if ($expectedCount <= 0) { + throw new RuntimeException('权威笔数控制数必须大于零。'); + } + + $expectedIncome = $this->controlAmount($expectedIncome, '收入'); + $expectedExpense = $this->controlAmount($expectedExpense, '支出'); + $hash = hash_file('sha256', $path); + if (! is_string($hash)) { + throw new RuntimeException('无法计算淘系支付宝完整账单文件摘要。'); + } + + $existing = $this->connection->table(self::IMPORT_TABLE) + ->where('source_sha256', $hash)->first(); + if ($existing !== null && $existing->status === 'succeeded') { + $this->assertSameImportRequest($existing, $from, $to, $expectedCount, $expectedIncome, $expectedExpense); + if ($this->activeRowCount($hash, $from, $to) === (int) $existing->row_count) { + return $this->result((array) $existing, $path, $hash, $from, $to, 'unchanged'); + } + } + + $generation = $existing !== null ? (string) $existing->generation : (string) Str::uuid(); + $now = now(); + $import = [ + 'generation' => $generation, + 'source_filename' => mb_substr(basename($path), 0, 255), + 'source_sha256' => $hash, + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'status' => 'running', + 'expected_row_count' => $expectedCount, + 'expected_income_total' => $expectedIncome, + 'expected_expense_total' => $expectedExpense, + 'row_count' => 0, + 'store_count' => 0, + 'bill_item_count' => 0, + 'business_type_counts' => null, + 'income_total' => '0.00', + 'expense_total' => '0.00', + 'net_total' => '0.00', + 'completed_at' => null, + 'last_error_code' => null, + 'updated_at' => $now, + ]; + if ($existing === null) { + $this->connection->table(self::IMPORT_TABLE)->insert($import + ['created_at' => $now]); + } else { + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($import); + } + + $stats = null; + try { + $stats = $this->readAndStage($path, $generation, $from, $to, $expectedCount, $expectedIncome, $expectedExpense, $batchSize); + $this->activate($generation, $hash, $from, $to, $stats, $batchSize); + + return $this->result($stats, $path, $hash, $from, $to, 'succeeded'); + } catch (Throwable $exception) { + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + $failure = [ + 'status' => 'failed', + 'last_error_code' => mb_substr(class_basename($exception), 0, 120), + 'updated_at' => now(), + ]; + if (is_array($stats)) { + $failure += [ + 'row_count' => $stats['row_count'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'business_type_counts' => json_encode($stats['business_type_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + ]; + } + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($failure); + + throw $exception; + } + } + + private function validatedPath(string $path): string + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new RuntimeException('淘系支付宝完整账单文件不存在或不可读。'); + } + if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') { + throw new RuntimeException('淘系支付宝完整账单导入只支持 XLSX 文件。'); + } + + return $realPath; + } + + /** @return array{0:DateTimeImmutable,1:DateTimeImmutable} */ + private function period(string $fromDate, string $toDate): array + { + $from = DateTimeImmutable::createFromFormat('!Y-m-d', $fromDate); + $to = DateTimeImmutable::createFromFormat('!Y-m-d', $toDate); + if ($from === false || $to === false + || $from->format('Y-m-d') !== $fromDate + || $to->format('Y-m-d') !== $toDate + || $from > $to) { + throw new RuntimeException('淘系支付宝账单导入账期无效。'); + } + + return [$from, $to]; + } + + private function assertSchemaReady(): void + { + $schema = $this->connection->getSchemaBuilder(); + foreach ([self::IMPORT_TABLE, self::STAGING_TABLE, self::ROW_TABLE] as $table) { + if (! $schema->hasTable($table)) { + throw new RuntimeException('淘系支付宝完整账单表尚未完成迁移:' . $table); + } + } + } + + /** @return array{row_count:int,store_count:int,bill_item_count:int,business_type_counts:array,income_total:string,expense_total:string,net_total:string} */ + private function readAndStage( + string $path, + string $generation, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + int $batchSize, + ): array { + $archive = new ZipArchive(); + if ($archive->open($path) !== true) { + throw new RuntimeException('无法打开淘系支付宝完整账单 XLSX 文件。'); + } + try { + $worksheet = $this->firstWorksheet($archive); + $sharedStrings = $this->sharedStrings($archive); + } finally { + $archive->close(); + } + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取淘系支付宝完整账单工作表。'); + } + + $headerMap = null; + $batch = []; + $rowCount = 0; + $incomeTotal = '0.00'; + $expenseTotal = '0.00'; + $stores = []; + $billItems = []; + $businessTypes = []; + $seenCodes = []; + $seenBlank = false; + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + $rowNumber = (int) ($reader->getAttribute('r') ?: 0); + $cells = $this->rowCells($reader->readOuterXml(), $sharedStrings); + if ($headerMap === null) { + $headerMap = $this->headerMap($cells); + continue; + } + + $values = []; + foreach ($headerMap as $field => $column) { + $values[$field] = trim((string) ($cells[$column] ?? '')); + } + $isBlank = implode('', $values) === ''; + if ($isBlank) { + $seenBlank = true; + continue; + } + if ($seenBlank) { + throw new RuntimeException("第 {$rowNumber} 行之后出现非空尾行,拒绝导入。"); + } + + $recordCode = $this->required($values['record_code'], $rowNumber, '记录编码'); + if (isset($seenCodes[$recordCode])) { + throw new RuntimeException("第 {$rowNumber} 行记录编码重复,拒绝导入。"); + } + $seenCodes[$recordCode] = true; + $occurredAt = $this->dateTime($values['occurred_at'], $rowNumber, '发生时间'); + if ($occurredAt < $from->format('Y-m-d') . ' 00:00:00' + || $occurredAt >= $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') { + throw new RuntimeException("第 {$rowNumber} 行发生时间超出指定账期。"); + } + + $income = $this->money($values['income_amount'], $rowNumber, '收入'); + $expense = $this->money($values['expense_amount'], $rowNumber, '支出'); + $balance = array_key_exists('balance_amount', $headerMap) + ? $this->signedMoney($values['balance_amount'], $rowNumber, '余额') + : bcsub($income, $expense, 6); + $store = $this->nullable($values['store_name'] ?? null); + $billItem = $this->nullable($values['bill_item'] ?? null); + $batch[] = [ + 'generation' => $generation, + 'record_code' => mb_substr($recordCode, 0, 191), + 'store_name' => $store, + 'custom_remark' => $this->nullable($values['custom_remark'] ?? null), + 'bill_item' => $billItem, + 'alipay_account' => $this->nullable($values['alipay_account'] ?? null), + 'account_order_no' => $this->nullable($values['account_order_no'] ?? null, 191), + 'business_serial_no' => $this->nullable($values['business_serial_no'] ?? null, 191), + 'merchant_order_no' => $this->nullable($values['merchant_order_no'] ?? null, 191), + 'business_base_order_no' => $this->nullable($values['business_base_order_no'] ?? null, 191), + 'goods_name' => $this->nullable($values['goods_name'] ?? null, 1000), + 'counterparty_account' => $this->nullable($values['counterparty_account'] ?? null), + 'occurred_at' => $occurredAt, + 'income_amount' => $income, + 'expense_amount' => $expense, + 'balance_amount' => $balance, + 'business_type' => $this->nullable($values['business_type'] ?? null), + 'remark' => $this->nullable($values['remark'] ?? null, 1000), + 'online_order_no' => $this->nullable($values['online_order_no'] ?? null, 191), + 'online_real_store' => $this->nullable($values['online_real_store'] ?? null), + 'business_description' => $this->nullable($values['business_description'] ?? null, 1000), + 'business_bill_source' => $this->nullable($values['business_bill_source'] ?? null), + 'business_order_no' => $this->nullable($values['business_order_no'] ?? null, 191), + 'source_created_at' => $this->optionalDateTime($values['source_created_at'] ?? null, $rowNumber, '创建时间'), + 'source_updated_at' => $this->optionalDateTime($values['source_updated_at'] ?? null, $rowNumber, '修改时间'), + 'source_modified_by' => $this->nullable($values['source_modified_by'] ?? null), + 'source_row_number' => $rowNumber, + ]; + $rowCount++; + if ($store !== null) $stores[$store] = true; + if ($billItem !== null) $billItems[$billItem] = true; + $businessType = $this->nullable($values['business_type'] ?? null); + if ($businessType !== null) $businessTypes[$businessType] = ($businessTypes[$businessType] ?? 0) + 1; + $incomeTotal = bcadd($incomeTotal, $income, 2); + $expenseTotal = bcadd($expenseTotal, $expense, 2); + if (count($batch) >= max(100, min($batchSize, 2000))) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + $batch = []; + } + } + } finally { + $reader->close(); + } + + if ($headerMap === null) { + throw new RuntimeException('未找到聚胜算淘系支付宝完整账单标准表头。'); + } + if ($batch !== []) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + } + if ($rowCount === 0) { + throw new RuntimeException('文件中没有淘系支付宝完整账单数据。'); + } + if ($rowCount !== $expectedCount + || bccomp($incomeTotal, $expectedIncome, 2) !== 0 + || bccomp($expenseTotal, $expectedExpense, 2) !== 0) { + throw new RuntimeException(sprintf( + '权威控制数不一致:实际 %d 笔,收入 %s,支出 %s;期望 %d 笔,收入 %s,支出 %s。', + $rowCount, $incomeTotal, $expenseTotal, $expectedCount, $expectedIncome, $expectedExpense, + )); + } + + return [ + 'row_count' => $rowCount, + 'store_count' => count($stores), + 'bill_item_count' => count($billItems), + 'business_type_counts' => $businessTypes, + 'income_total' => $incomeTotal, + 'expense_total' => $expenseTotal, + 'net_total' => bcsub($incomeTotal, $expenseTotal, 2), + ]; + } + + /** @param array $headers @return array */ + private function headerMap(array $headers): array + { + $lookup = []; + foreach ($headers as $column => $value) { + $lookup[trim((string) $value)] = $column; + } + $mapping = []; + foreach (self::HEADER_ALIASES as $field => $aliases) { + foreach ($aliases as $alias) { + if (array_key_exists($alias, $lookup)) { + $mapping[$field] = $lookup[$alias]; + break; + } + } + if (! array_key_exists($field, $mapping) && ! in_array($field, self::OPTIONAL_HEADERS, true)) { + throw new RuntimeException('未找到聚胜算淘系支付宝完整账单标准表头:' . $aliases[0]); + } + } + + return $mapping; + } + + private function activate(string $generation, string $hash, DateTimeImmutable $from, DateTimeImmutable $to, array $stats, int $batchSize): void + { + $now = now(); + $columns = [ + 'store_name', 'custom_remark', 'bill_item', 'alipay_account', 'account_order_no', + 'business_serial_no', 'merchant_order_no', 'business_base_order_no', 'goods_name', + 'counterparty_account', 'occurred_at', 'income_amount', 'expense_amount', 'balance_amount', + 'business_type', 'remark', 'online_order_no', 'online_real_store', 'business_description', + 'business_bill_source', 'business_order_no', 'source_created_at', 'source_updated_at', + 'source_modified_by', 'source_row_number', 'source_generation', 'source_sha256', 'imported_at', + ]; + $this->connection->transaction(function () use ($generation, $hash, $from, $to, $stats, $batchSize, $columns, $now): void { + $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->delete(); + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->orderBy('id') + ->chunkById(max(100, min($batchSize, 2000)), function ($rows) use ($generation, $hash, $columns, $now): void { + $payload = []; + foreach ($rows as $row) { + $data = (array) $row; + unset($data['id'], $data['generation']); + $data['source_generation'] = $generation; + $data['source_sha256'] = $hash; + $data['imported_at'] = $now; + $payload[] = $data; + } + $this->connection->table(self::ROW_TABLE)->upsert($payload, ['record_code'], $columns); + }); + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update([ + 'status' => 'succeeded', + 'row_count' => $stats['row_count'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'business_type_counts' => json_encode($stats['business_type_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'completed_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + }); + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + } + + private function assertSameImportRequest(object $existing, DateTimeImmutable $from, DateTimeImmutable $to, int $count, string $income, string $expense): void + { + if ((string) $existing->period_start !== $from->format('Y-m-d') + || (string) $existing->period_end !== $to->format('Y-m-d') + || (int) $existing->expected_row_count !== $count + || bccomp((string) $existing->expected_income_total, $income, 2) !== 0 + || bccomp((string) $existing->expected_expense_total, $expense, 2) !== 0) { + throw new RuntimeException('该文件已有成功导入记录,但本次账期或权威控制数与历史记录不一致。'); + } + } + + private function activeRowCount(string $hash, DateTimeImmutable $from, DateTimeImmutable $to): int + { + return $this->connection->table(self::ROW_TABLE)->where('source_sha256', $hash) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00')->count(); + } + + private function required(mixed $value, int $row, string $label): string + { + $text = trim((string) ($value ?? '')); + if ($text === '') throw new RuntimeException("第 {$row} 行缺少{$label}。"); + + return $text; + } + + private function nullable(mixed $value, ?int $max = null): ?string + { + $text = trim((string) ($value ?? '')); + if ($text === '') return null; + if ($max !== null && mb_strlen($text) > $max) { + throw new RuntimeException('源文件字段长度超过淘系支付宝账单表定义,拒绝截断导入。'); + } + + return $text; + } + + private function money(mixed $value, int $row, string $label): string + { + $text = str_replace([',', ',', '¥', '¥'], '', trim((string) ($value ?? '0'))); + if ($text === '') $text = '0'; + if (! is_numeric($text) || bccomp($text, '0', 8) < 0) { + throw new RuntimeException("第 {$row} 行{$label}不是有效非负金额。"); + } + + return bcadd($text, '0', 6); + } + + private function signedMoney(mixed $value, int $row, string $label): string + { + $text = str_replace([',', ',', '¥', '¥'], '', trim((string) ($value ?? '0'))); + if ($text === '') $text = '0'; + if (! is_numeric($text)) throw new RuntimeException("第 {$row} 行{$label}不是有效金额。"); + + return bcadd($text, '0', 6); + } + + private function dateTime(mixed $value, int $row, string $label): string + { + $parsed = $this->parseDateTime($value); + if ($parsed === null) throw new RuntimeException("第 {$row} 行{$label}不是有效日期时间。"); + + return $parsed; + } + + private function optionalDateTime(mixed $value, int $row, string $label): ?string + { + return trim((string) ($value ?? '')) === '' ? null : $this->dateTime($value, $row, $label); + } + + private function parseDateTime(mixed $value): ?string + { + if ($value === null || $value === '') return null; + try { + if (is_numeric($value)) { + $serial = (float) $value; + $days = (int) floor($serial); + $seconds = (int) round(($serial - $days) * 86400); + + return Carbon::create(1899, 12, 30)->addDays($days)->addSeconds($seconds)->format('Y-m-d H:i:s'); + } + + return Carbon::parse((string) $value)->format('Y-m-d H:i:s'); + } catch (Throwable) { + return null; + } + } + + /** @return array */ + private function rowCells(string $xml, array $sharedStrings): array + { + $row = simplexml_load_string($xml); + if (! $row instanceof SimpleXMLElement) return []; + $cells = []; + foreach ($row->xpath('./*[local-name()="c"]') ?: [] as $cell) { + $reference = (string) ($cell['r'] ?? ''); + if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) !== 1) continue; + $type = (string) ($cell['t'] ?? ''); + if ($type === 'inlineStr') { + $nodes = $cell->xpath('.//*[local-name()="t"]') ?: []; + $value = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } else { + $nodes = $cell->xpath('./*[local-name()="v"]') ?: []; + $raw = isset($nodes[0]) ? (string) $nodes[0] : ''; + $value = $type === 's' ? (string) ($sharedStrings[(int) $raw] ?? '') : $raw; + } + $cells[$this->columnIndex($matches[1])] = $value; + } + + return $cells; + } + + /** @return array */ + private function sharedStrings(ZipArchive $archive): array + { + $index = $archive->locateName('xl/sharedStrings.xml'); + if ($index === false) return []; + $xml = simplexml_load_string((string) $archive->getFromIndex($index)); + if (! $xml instanceof SimpleXMLElement) return []; + + $values = []; + foreach ($xml->xpath('./*[local-name()="si"]') ?: [] as $item) { + $nodes = $item->xpath('.//*[local-name()="t"]') ?: []; + $values[] = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } + + return $values; + } + + private function firstWorksheet(ZipArchive $archive): string + { + $worksheets = []; + for ($index = 0; $index < $archive->numFiles; $index++) { + $name = $archive->getNameIndex($index); + if (is_string($name) && preg_match('#^xl/worksheets/sheet\d+\.xml$#', $name) === 1) { + $worksheets[] = $name; + } + } + sort($worksheets, SORT_NATURAL); + if ($worksheets === []) throw new RuntimeException('XLSX 文件中没有工作表。'); + + return $worksheets[0]; + } + + private function zipUri(string $path, string $entry): string + { + return 'zip://' . str_replace('\\', '/', $path) . '#' . $entry; + } + + private function columnIndex(string $letters): int + { + $index = 0; + foreach (str_split(strtoupper($letters)) as $letter) { + $index = ($index * 26) + (ord($letter) - 64); + } + + return $index - 1; + } + + private function controlAmount(string $value, string $label): string + { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + if (! is_numeric($value) || bccomp($value, '0', 8) < 0) throw new RuntimeException("权威{$label}控制数无效。"); + + return bcadd($value, '0', 2); + } + + private function result(array $stats, string $path, string $hash, DateTimeImmutable $from, DateTimeImmutable $to, string $status): array + { + return [ + 'status' => $status, + 'row_count' => (int) ($stats['row_count'] ?? 0), + 'store_count' => (int) ($stats['store_count'] ?? 0), + 'bill_item_count' => (int) ($stats['bill_item_count'] ?? 0), + 'business_type_counts' => $this->businessTypeCounts($stats['business_type_counts'] ?? []), + 'income_total' => bcadd((string) ($stats['income_total'] ?? '0'), '0', 2), + 'expense_total' => bcadd((string) ($stats['expense_total'] ?? '0'), '0', 2), + 'net_total' => bcadd((string) ($stats['net_total'] ?? '0'), '0', 2), + 'source_filename' => basename($path), + 'source_sha256' => $hash, + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + ]; + } + + /** @return array */ + private function businessTypeCounts(mixed $value): array + { + if (is_string($value)) { + try { + $value = json_decode($value, true, 512, JSON_THROW_ON_ERROR); + } catch (Throwable) { + return []; + } + } + if (! is_array($value)) { + return []; + } + + $counts = []; + foreach ($value as $type => $count) { + if (is_string($type) && $type !== '' && is_numeric($count)) { + $counts[$type] = (int) $count; + } + } + + return $counts; + } +} diff --git a/modules/EcommerceFinance/Services/TaobaoWechatSettlementBillImporter.php b/modules/EcommerceFinance/Services/TaobaoWechatSettlementBillImporter.php new file mode 100644 index 00000000..7a6cb6f8 --- /dev/null +++ b/modules/EcommerceFinance/Services/TaobaoWechatSettlementBillImporter.php @@ -0,0 +1,710 @@ + ['记录编码'], + 'store_name' => ['店铺', '原始店铺'], + 'custom_remark' => ['自定义备注'], + 'bill_item' => ['账单项目'], + 'taobao_order_no' => ['淘宝订单编号'], + 'online_order_no' => ['线上单号'], + 'pay_serial_no' => ['支付流水号'], + 'business_description' => ['业务描述'], + 'entry_type' => ['入账类型'], + 'occurred_at' => ['入账时间'], + 'income_amount' => ['收入金额'], + 'expense_amount' => ['支出金额'], + 'signed_amount' => ['金额'], + 'remark' => ['备注'], + 'jst_pulled_at' => ['JST拉取时间'], + 'source_modified_by' => ['修改人'], + ]; + + private const OPTIONAL_HEADERS = ['signed_amount']; + + private readonly ConnectionInterface $connection; + + public function __construct(DatabaseManager $databases) + { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{status:string,row_count:int,excluded_rows:int,store_count:int,bill_item_count:int,entry_type_counts:array,income_total:string,expense_total:string,net_total:string,period_start:string,period_end:string,source_sha256:string} + */ + public function import( + string $path, + string $fromDate, + string $toDate, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + int $batchSize = 1000, + ): array { + $path = $this->validatedPath($path); + [$from, $to] = $this->period($fromDate, $toDate); + $this->assertSchemaReady(); + if ($expectedCount <= 0) { + throw new RuntimeException('权威笔数控制数必须大于零。'); + } + $expectedIncome = $this->controlAmount($expectedIncome, '收入'); + $expectedExpense = $this->controlAmount($expectedExpense, '支出'); + + $batchSize = min(max($batchSize, 100), 5000); + $hash = hash_file('sha256', $path); + if (! is_string($hash)) { + throw new RuntimeException('无法计算淘系微信完整账单文件摘要。'); + } + + $existing = $this->connection->table(self::IMPORT_TABLE) + ->where('source_sha256', $hash) + ->first(); + if ($existing !== null && $existing->status === 'succeeded') { + $this->assertSameImportRequest( + $existing, + $from, + $to, + $expectedCount, + $expectedIncome, + $expectedExpense, + ); + if ($this->activeRowCount($hash, $from, $to) === (int) $existing->row_count) { + return $this->result((array) $existing, 'unchanged'); + } + } + + $generation = $existing !== null ? (string) $existing->generation : (string) Str::uuid(); + $now = now(); + $import = [ + 'generation' => $generation, + 'source_filename' => mb_substr(basename($path), 0, 255), + 'source_sha256' => $hash, + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'status' => 'running', + 'expected_row_count' => $expectedCount, + 'expected_income_total' => $expectedIncome, + 'expected_expense_total' => $expectedExpense, + 'row_count' => 0, + 'excluded_rows' => 0, + 'store_count' => 0, + 'bill_item_count' => 0, + 'entry_type_counts' => null, + 'income_total' => '0.00', + 'expense_total' => '0.00', + 'net_total' => '0.00', + 'completed_at' => null, + 'last_error_code' => null, + 'updated_at' => $now, + ]; + if ($existing === null) { + $this->connection->table(self::IMPORT_TABLE)->insert($import + ['created_at' => $now]); + } else { + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($import); + } + + $stats = null; + try { + $stats = $this->stage($path, $generation, $from, $to, $batchSize); + $this->assertControls($stats, $expectedCount, $expectedIncome, $expectedExpense); + $this->activate($generation, $hash, $from, $to, $stats, $batchSize); + + return $this->result([ + 'row_count' => $stats['row_count'], + 'excluded_rows' => $stats['excluded_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'entry_type_counts' => $stats['entry_type_counts'], + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'source_sha256' => $hash, + ], 'succeeded'); + } catch (Throwable $exception) { + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + $failure = [ + 'status' => 'failed', + 'last_error_code' => mb_substr(class_basename($exception), 0, 120), + 'updated_at' => now(), + ]; + if (is_array($stats)) { + $failure += [ + 'row_count' => $stats['row_count'], + 'excluded_rows' => $stats['excluded_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'entry_type_counts' => json_encode($stats['entry_type_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + ]; + } + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update($failure); + + throw $exception; + } + } + + private function validatedPath(string $path): string + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new RuntimeException('淘系微信完整账单文件不存在或不可读。'); + } + if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') { + throw new RuntimeException('聚胜算完整账单导入只支持 XLSX 文件。'); + } + + return $realPath; + } + + /** @return array{0:DateTimeImmutable,1:DateTimeImmutable} */ + private function period(string $fromDate, string $toDate): array + { + $from = DateTimeImmutable::createFromFormat('!Y-m-d', $fromDate); + $to = DateTimeImmutable::createFromFormat('!Y-m-d', $toDate); + if ($from === false || $to === false + || $from->format('Y-m-d') !== $fromDate + || $to->format('Y-m-d') !== $toDate + || $from > $to) { + throw new RuntimeException('淘系微信账单导入账期无效。'); + } + + return [$from, $to]; + } + + private function assertSchemaReady(): void + { + $schema = Schema::connection($this->connection->getName()); + foreach ([self::IMPORT_TABLE, self::STAGING_TABLE, self::ROW_TABLE] as $table) { + if (! $schema->hasTable($table)) { + throw new RuntimeException('淘系微信完整账单表尚未完成迁移:' . $table); + } + } + } + + /** + * @return array{row_count:int,excluded_rows:int,store_count:int,bill_item_count:int,entry_type_counts:array,income_total:string,expense_total:string,net_total:string} + */ + private function stage( + string $path, + string $generation, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $batchSize, + ): array { + $archive = new ZipArchive(); + if ($archive->open($path) !== true) { + throw new RuntimeException('无法打开淘系微信完整账单 XLSX 文件。'); + } + + try { + $worksheet = $this->firstWorksheet($archive); + $sharedStrings = $this->sharedStrings($path, $archive); + } finally { + $archive->close(); + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取淘系微信完整账单工作表。'); + } + + $headerMap = null; + $batch = []; + $rowCount = 0; + $excluded = 0; + $incomeTotal = '0.00'; + $expenseTotal = '0.00'; + $stores = []; + $billItems = []; + $entryTypeCounts = []; + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + + $rowNumber = (int) ($reader->getAttribute('r') ?: 0); + $cells = $this->rowCells($reader->readOuterXml(), $sharedStrings); + if ($headerMap === null) { + $headerMap = $this->headerMap($cells); + continue; + } + + $values = []; + foreach ($headerMap as $header => $column) { + $values[$header] = trim((string) ($cells[$column] ?? '')); + } + if (implode('', $values) === '') { + continue; + } + $recordCode = $this->required($values, 'record_code', $rowNumber, '记录编码'); + $entryType = $this->required($values, 'entry_type', $rowNumber, '入账类型'); + $storeName = $this->nullable($values['store_name']); + $billItem = $this->nullable($values['bill_item']); + $occurredAt = $this->dateTime($values['occurred_at'], $rowNumber, '入账时间'); + if ($occurredAt < $from->format('Y-m-d') . ' 00:00:00' + || $occurredAt >= $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') { + throw new RuntimeException("第 {$rowNumber} 行入账时间超出指定账期。"); + } + + $income = $this->money($values['income_amount'], $rowNumber, '收入金额', false); + $expense = $this->money($values['expense_amount'], $rowNumber, '支出金额', true); + $calculated = bcsub($income, $expense, 2); + $signed = $calculated; + if (array_key_exists('signed_amount', $headerMap)) { + $signed = $this->money($values['signed_amount'], $rowNumber, '金额', false, true); + if (bccomp($calculated, $signed, 2) !== 0) { + throw new RuntimeException("第 {$rowNumber} 行收入、支出与金额不一致。"); + } + } + + $batch[] = [ + 'generation' => $generation, + 'record_code' => mb_substr($recordCode, 0, 191), + 'store_name' => $storeName, + 'custom_remark' => $this->nullable($values['custom_remark']), + 'bill_item' => $billItem, + 'taobao_order_no' => $this->nullable($values['taobao_order_no'], 191), + 'online_order_no' => $this->nullable($values['online_order_no'], 191), + 'pay_serial_no' => $this->nullable($values['pay_serial_no']), + 'business_description' => $this->nullable($values['business_description'], 1000), + 'entry_type' => mb_substr($entryType, 0, 255), + 'occurred_at' => $occurredAt, + 'income_amount' => $income, + 'expense_amount' => $expense, + 'signed_amount' => $signed, + 'remark' => $this->nullable($values['remark'], 1000), + 'jst_pulled_at' => $this->optionalDateTime($values['jst_pulled_at'], $rowNumber, 'JST拉取时间'), + 'source_modified_by' => $this->nullable($values['source_modified_by']), + 'source_row_number' => $rowNumber, + ]; + $rowCount++; + if ($storeName !== null) { + $stores[$storeName] = true; + } + if ($billItem !== null) { + $billItems[$billItem] = true; + } + $entryTypeCounts[$entryType] = ($entryTypeCounts[$entryType] ?? 0) + 1; + $incomeTotal = bcadd($incomeTotal, $income, 2); + $expenseTotal = bcadd($expenseTotal, $expense, 2); + + if (count($batch) >= $batchSize) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + $batch = []; + } + } + } finally { + $reader->close(); + } + + if ($headerMap === null) { + throw new RuntimeException('未找到聚胜算淘系微信账单标准表头。'); + } + if ($batch !== []) { + $this->connection->table(self::STAGING_TABLE)->insert($batch); + } + if ($rowCount === 0) { + throw new RuntimeException('文件中没有淘系微信账单数据。'); + } + + return [ + 'row_count' => $rowCount, + 'excluded_rows' => $excluded, + 'store_count' => count($stores), + 'bill_item_count' => count($billItems), + 'entry_type_counts' => $entryTypeCounts, + 'income_total' => $incomeTotal, + 'expense_total' => $expenseTotal, + 'net_total' => bcsub($incomeTotal, $expenseTotal, 2), + ]; + } + + private function assertControls(array $stats, int $count, string $income, string $expense): void + { + if ($stats['row_count'] !== $count + || bccomp($stats['income_total'], $income, 2) !== 0 + || bccomp($stats['expense_total'], $expense, 2) !== 0) { + throw new RuntimeException(sprintf( + '权威控制数不一致:实际 %d 笔,收入 %s,支出 %s;期望 %d 笔,收入 %s,支出 %s。', + $stats['row_count'], + $stats['income_total'], + $stats['expense_total'], + $count, + $income, + $expense, + )); + } + } + + private function assertSameImportRequest( + object $existing, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + ): void { + if ((string) $existing->period_start !== $from->format('Y-m-d') + || (string) $existing->period_end !== $to->format('Y-m-d') + || (int) $existing->expected_row_count !== $expectedCount + || bccomp((string) $existing->expected_income_total, $expectedIncome, 2) !== 0 + || bccomp((string) $existing->expected_expense_total, $expectedExpense, 2) !== 0) { + throw new RuntimeException('该文件已有成功导入记录,但本次账期或权威控制数与历史记录不一致。'); + } + } + + private function activeRowCount( + string $hash, + DateTimeImmutable $from, + DateTimeImmutable $to, + ): int { + return $this->connection->table(self::ROW_TABLE) + ->where('source_sha256', $hash) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->count(); + } + + private function activate( + string $generation, + string $hash, + DateTimeImmutable $from, + DateTimeImmutable $to, + array $stats, + int $batchSize, + ): void { + $now = now(); + $columns = [ + 'store_name', 'custom_remark', 'bill_item', 'taobao_order_no', 'online_order_no', + 'pay_serial_no', 'business_description', 'entry_type', 'occurred_at', 'income_amount', + 'expense_amount', 'signed_amount', 'remark', 'jst_pulled_at', 'source_modified_by', + 'source_row_number', 'source_generation', 'source_sha256', 'imported_at', + ]; + + $this->connection->transaction(function () use ( + $generation, $hash, $from, $to, $stats, $batchSize, $columns, $now + ): void { + $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->delete(); + + $this->connection->table(self::STAGING_TABLE) + ->where('generation', $generation) + ->orderBy('id') + ->chunkById($batchSize, function ($rows) use ($generation, $hash, $columns, $now): void { + $payload = []; + foreach ($rows as $row) { + $payload[] = [ + 'record_code' => $row->record_code, + 'store_name' => $row->store_name, + 'custom_remark' => $row->custom_remark, + 'bill_item' => $row->bill_item, + 'taobao_order_no' => $row->taobao_order_no, + 'online_order_no' => $row->online_order_no, + 'pay_serial_no' => $row->pay_serial_no, + 'business_description' => $row->business_description, + 'entry_type' => $row->entry_type, + 'occurred_at' => $row->occurred_at, + 'income_amount' => $row->income_amount, + 'expense_amount' => $row->expense_amount, + 'signed_amount' => $row->signed_amount, + 'remark' => $row->remark, + 'jst_pulled_at' => $row->jst_pulled_at, + 'source_modified_by' => $row->source_modified_by, + 'source_row_number' => $row->source_row_number, + 'source_generation' => $generation, + 'source_sha256' => $hash, + 'imported_at' => $now, + ]; + } + $this->connection->table(self::ROW_TABLE)->upsert($payload, ['record_code'], $columns); + }); + + $this->connection->table(self::IMPORT_TABLE)->where('generation', $generation)->update([ + 'status' => 'succeeded', + 'row_count' => $stats['row_count'], + 'excluded_rows' => $stats['excluded_rows'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'entry_type_counts' => json_encode($stats['entry_type_counts'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'completed_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + }); + + $this->connection->table(self::STAGING_TABLE)->where('generation', $generation)->delete(); + } + + /** @return array */ + private function rowCells(string $xml, array $sharedStrings): array + { + $row = simplexml_load_string($xml); + if (! $row instanceof SimpleXMLElement) { + return []; + } + + $cells = []; + foreach ($row->xpath('./*[local-name()="c"]') ?: [] as $cell) { + $reference = (string) ($cell['r'] ?? ''); + if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) !== 1) { + continue; + } + $type = (string) ($cell['t'] ?? ''); + if ($type === 'inlineStr') { + $nodes = $cell->xpath('.//*[local-name()="t"]') ?: []; + $value = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } else { + $nodes = $cell->xpath('./*[local-name()="v"]') ?: []; + $raw = isset($nodes[0]) ? (string) $nodes[0] : ''; + $value = $type === 's' ? (string) ($sharedStrings[(int) $raw] ?? '') : $raw; + } + $cells[$this->columnIndex($matches[1])] = $value; + } + + return $cells; + } + + /** @param array $cells @return array */ + private function headerMap(array $cells): ?array + { + $lookup = []; + foreach ($cells as $column => $value) { + $lookup[trim($value)] = $column; + } + + $mapping = []; + foreach (self::HEADER_ALIASES as $field => $aliases) { + foreach ($aliases as $alias) { + if (array_key_exists($alias, $lookup)) { + $mapping[$field] = $lookup[$alias]; + break; + } + } + if (! array_key_exists($field, $mapping) + && ! in_array($field, self::OPTIONAL_HEADERS, true)) { + return null; + } + } + + return $mapping; + } + + private function required(array $values, string $key, int $row, ?string $label = null): string + { + $value = trim((string) ($values[$key] ?? '')); + if ($value === '') { + throw new RuntimeException("第 {$row} 行缺少" . ($label ?? $key) . '。'); + } + + return $value; + } + + private function money( + string $value, + int $row, + string $field, + bool $absolute = false, + bool $allowNegative = false, + ): string { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + $value = $value === '' ? '0' : $value; + if (! is_numeric($value) || (! $allowNegative && ! $absolute && bccomp($value, '0', 6) < 0)) { + throw new RuntimeException("第 {$row} 行{$field}不是有效金额。"); + } + if ($absolute && bccomp($value, '0', 6) < 0) { + $value = bcmul($value, '-1', 6); + } + + return bcadd($value, '0', 2); + } + + private function controlAmount(string $value, string $label): string + { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + if (! is_numeric($value) || bccomp($value, '0', 6) < 0) { + throw new RuntimeException("权威{$label}控制数无效。"); + } + + return bcadd($value, '0', 2); + } + + private function dateTime(string $value, int $row, string $field): string + { + $parsed = $this->parseDateTime($value); + if ($parsed === null) { + throw new RuntimeException("第 {$row} 行{$field}不是有效日期时间。"); + } + + return $parsed; + } + + private function optionalDateTime(string $value, int $row, string $field): ?string + { + if (trim($value) === '') { + return null; + } + + return $this->dateTime($value, $row, $field); + } + + private function parseDateTime(string $value): ?string + { + $value = trim($value); + try { + if (is_numeric($value)) { + $seconds = (int) round((((float) $value) - 25569) * 86400); + + return Carbon::createFromTimestampUTC($seconds)->format('Y-m-d H:i:s'); + } + + return Carbon::parse($value)->format('Y-m-d H:i:s'); + } catch (Throwable) { + return null; + } + } + + private function nullable(string $value, int $max = 255): ?string + { + $value = trim($value); + + return $value === '' ? null : mb_substr($value, 0, $max); + } + + private function columnIndex(string $letters): int + { + $index = 0; + foreach (str_split(strtoupper($letters)) as $letter) { + $index = ($index * 26) + ord($letter) - 64; + } + + return $index - 1; + } + + /** @return list */ + private function sharedStrings(string $path, ZipArchive $archive): array + { + if ($archive->locateName('xl/sharedStrings.xml') === false) { + return []; + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, 'xl/sharedStrings.xml'), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取 XLSX 共享文本。'); + } + + $strings = []; + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') { + continue; + } + $item = simplexml_load_string($reader->readOuterXml()); + $nodes = $item instanceof SimpleXMLElement ? ($item->xpath('.//*[local-name()="t"]') ?: []) : []; + $strings[] = implode('', array_map( + static fn (SimpleXMLElement $node): string => (string) $node, + $nodes, + )); + } + } finally { + $reader->close(); + } + + return $strings; + } + + private function firstWorksheet(ZipArchive $archive): string + { + $worksheets = []; + for ($index = 0; $index < $archive->numFiles; $index++) { + $name = $archive->getNameIndex($index); + if (is_string($name) && preg_match('#^xl/worksheets/sheet\d+\.xml$#', $name) === 1) { + $worksheets[] = $name; + } + } + sort($worksheets, SORT_NATURAL); + if ($worksheets === []) { + throw new RuntimeException('XLSX 文件中没有工作表。'); + } + + return $worksheets[0]; + } + + private function zipUri(string $path, string $entry): string + { + return 'zip://' . str_replace('\\', '/', $path) . '#' . $entry; + } + + private function result(array $row, string $status): array + { + return [ + 'status' => $status, + 'row_count' => (int) ($row['row_count'] ?? 0), + 'excluded_rows' => (int) ($row['excluded_rows'] ?? 0), + 'store_count' => (int) ($row['store_count'] ?? 0), + 'bill_item_count' => (int) ($row['bill_item_count'] ?? 0), + 'entry_type_counts' => $this->entryTypeCounts($row['entry_type_counts'] ?? []), + 'income_total' => bcadd((string) ($row['income_total'] ?? '0'), '0', 2), + 'expense_total' => bcadd((string) ($row['expense_total'] ?? '0'), '0', 2), + 'net_total' => bcadd((string) ($row['net_total'] ?? '0'), '0', 2), + 'period_start' => (string) ($row['period_start'] ?? ''), + 'period_end' => (string) ($row['period_end'] ?? ''), + 'source_sha256' => (string) ($row['source_sha256'] ?? ''), + ]; + } + + /** @return array */ + private function entryTypeCounts(mixed $value): array + { + if (is_string($value)) { + try { + $value = json_decode($value, true, 512, JSON_THROW_ON_ERROR); + } catch (Throwable) { + return []; + } + } + if (! is_array($value)) { + return []; + } + + $counts = []; + foreach ($value as $account => $count) { + if (is_string($account) && $account !== '' && is_numeric($count)) { + $counts[$account] = (int) $count; + } + } + + return $counts; + } +} diff --git a/modules/EcommerceFinance/Services/TaxForecastLogic.php b/modules/EcommerceFinance/Services/TaxForecastLogic.php new file mode 100644 index 00000000..6c78e15e --- /dev/null +++ b/modules/EcommerceFinance/Services/TaxForecastLogic.php @@ -0,0 +1,201 @@ + self::PREFIX . '.vat_small_rate', + 'vat_free_threshold' => self::PREFIX . '.vat_free_threshold', + 'vat_general_enabled' => self::PREFIX . '.vat_general_enabled', + 'surtax_city_rate' => self::PREFIX . '.surtax_city_rate', + 'surtax_education_rate' => self::PREFIX . '.surtax_education_rate', + 'surtax_local_education_rate' => self::PREFIX . '.surtax_local_education_rate', + 'surtax_halved' => self::PREFIX . '.surtax_halved', + 'stamp_duty_rate' => self::PREFIX . '.stamp_duty_rate', + 'stamp_duty_halved' => self::PREFIX . '.stamp_duty_halved', + 'cit_effective_rate' => self::PREFIX . '.cit_effective_rate', + 'cit_threshold' => self::PREFIX . '.cit_threshold', + 'individual_halved_threshold' => self::PREFIX . '.individual_halved_threshold', + 'assessed_income_rate' => self::PREFIX . '.assessed_income_rate', + 'income_forecast_source' => self::PREFIX . '.income_forecast_source', + ]; + + public const INCOME_FORECAST_SOURCES = [ + 'last_month_actual' => '上月实际收入(bills.income)', + 'cost_arrangement' => '公司成本安排的当月收入预测', + 'manual' => '手工录入', + ]; + + /** @return array */ + public static function defaults(): array + { + return [ + 'vat_small_rate' => '1', + 'vat_free_threshold' => '300000', + 'vat_general_enabled' => '1', + 'surtax_city_rate' => '7', + 'surtax_education_rate' => '3', + 'surtax_local_education_rate' => '2', + 'surtax_halved' => '1', + 'stamp_duty_rate' => '0.03', + 'stamp_duty_halved' => '1', + 'cit_effective_rate' => '5', + 'cit_threshold' => '3000000', + 'individual_halved_threshold' => '2000000', + 'assessed_income_rate' => '10', + 'income_forecast_source' => 'last_month_actual', + ]; + } + + /** @return array */ + public static function current(): array + { + $values = []; + foreach (self::KEYS as $key => $settingKey) { + $value = setting($settingKey, null); + $values[$key] = is_array($value) ? implode('', $value) : (string) ($value ?? ''); + } + + return array_merge(self::defaults(), array_filter($values, static fn (string $value): bool => $value !== '')); + } + + public static function value(string $key, mixed $default = null): mixed + { + $current = self::current(); + + return $current[$key] ?? ($default ?? (self::defaults()[$key] ?? null)); + } + + public static function rate(string $key): float + { + return max((float) self::value($key, 0), 0); + } + + public static function amount(string $key): float + { + return max((float) self::value($key, 0), 0); + } + + public static function toggled(string $key): bool + { + return (string) self::value($key, '1') === '1'; + } + + /** @param array $values */ + public static function save(array $values): void + { + $payload = []; + foreach (self::defaults() as $key => $default) { + if (! array_key_exists($key, $values) || ! isset(self::KEYS[$key])) { + continue; + } + $payload[self::KEYS[$key]] = mb_substr(trim((string) $values[$key]), 0, 191); + } + + if ($payload !== []) { + setting($payload)->save(); + } + } + + /** + * 规则目录:页面上的规则清单以这里为准,和取数公式文档 + * docs/税金预测表需求说明.md 保持一致。 + * + * @return array> + */ + public static function rules(): array + { + return [ + '主体识别' => [ + ['code' => 'R1', 'object' => '公司名称、公司税务类型', 'logic' => '读取公司基础信息镜像的营业执照名称和纳税类别及类型,作为增值税口径判断依据。', 'source' => 'rpt.fys_companyInfo(只读镜像)', 'priority' => '税务类型空值时按“无税务登记”处理并提示补充。'], + ['code' => 'R2', 'object' => '工商类型', 'logic' => '区分有限责任公司、个人独资企业、合伙企业、个体工商户,决定所得税种。', 'source' => '待接入:工商登记信息或人工维护', 'priority' => '缺失时所得税列留空,不按企业所得税估算。'], + ['code' => 'R3', 'object' => '征收方式、核定应税所得率', 'logic' => '查账征收按利润计算;核定征收按 收入 × 核定应税所得率 计算;定期定额按核定定额折算。', 'source' => '待接入:电子税务局数据或人工维护', 'priority' => '缺失时按查账征收展示,并在备注列标记待确认。'], + ], + '增值税' => [ + ['code' => 'R4', 'object' => '小规模纳税人免税判断', 'logic' => '季度不含税销售额不超过免税额度时,预计增值税为 0。', 'source' => 'bills.income 按主体期间归集', 'priority' => '免税额度按配置参数执行,默认 30 万元/季。'], + ['code' => 'R5', 'object' => '小规模纳税人征收率', 'logic' => '超过免税额度时,预计增值税 = 不含税销售额 × 征收率。', 'source' => '配置参数', 'priority' => '默认 1%(3% 减按 1%)。'], + ['code' => 'R6', 'object' => '一般纳税人计税', 'logic' => '预计增值税 = 销项税额 − 进项税额;进项缺失时按销项全额提示。', 'source' => 'bills.income 与进项数据', 'priority' => '默认开启,可在配置中关闭改为简易口径。'], + ['code' => 'R7', 'object' => '个体工商户、个人独资企业、合伙企业', 'logic' => '增值税按小规模纳税人口径计算。', 'source' => '同上', 'priority' => '不因工商类型改为一般纳税人口径。'], + ], + '附加税费' => [ + ['code' => 'R8', 'object' => '城建税', 'logic' => '城建税 = 预计增值税 × 城建税税率。', 'source' => '配置参数', 'priority' => '默认市区 7%,县城/镇 5%,其他 1%。'], + ['code' => 'R9', 'object' => '教育费附加、地方教育附加', 'logic' => '教育费附加 = 增值税 × 3%;地方教育附加 = 增值税 × 2%。', 'source' => '配置参数', 'priority' => '税率可调。'], + ['code' => 'R10', 'object' => '六税两费减半', 'logic' => '小规模纳税人、小型微利企业、个体工商户的附加税费减半征收。', 'source' => '配置开关', 'priority' => '默认开启;关闭后按全额计算。'], + ], + '印花税' => [ + ['code' => 'R11', 'object' => '购销合同印花税', 'logic' => '印花税 = 购销合同金额 × 印花税税率(减半开关生效时再乘 50%)。', 'source' => '配置参数与成本安排金额', 'priority' => '默认 0.03% 并减半。'], + ], + '所得税' => [ + ['code' => 'R12', 'object' => '小型微利企业所得税', 'logic' => '应纳税所得额 × 25% × 20%,年不超过上限部分实际税负 5%。', 'source' => '配置参数 + 预计利润', 'priority' => '默认上限 300 万元,超过部分提示分段计算。'], + ['code' => 'R13', 'object' => '经营所得个人所得税', 'logic' => '个人独资企业、合伙企业、个体工商户按经营所得五级超额累进计算;核定征收按 收入 × 核定应税所得率 计算。', 'source' => '配置参数 + 核定通知书', 'priority' => '核定应税所得率默认 10%。'], + ['code' => 'R14', 'object' => '个体工商户减半', 'logic' => '年应纳税所得额不超过上限部分,经营所得个人所得税减半征收。', 'source' => '配置参数', 'priority' => '默认上限 200 万元。'], + ], + '数据来源' => [ + ['code' => 'R15', 'object' => '收入预测', 'logic' => '按主体生效/失效期间把 bills.income 归集到预测月份;未出账时按配置的收入预测口径取值。', 'source' => 'runtime/bills.sqlite', 'priority' => '口径可在配置中切换。'], + ['code' => 'R16', 'object' => '成本费用预测', 'logic' => '供应商成本安排 + 快递成本安排 + 人工成本预测 + 其他费用预测。', 'source' => '公司成本安排页', 'priority' => '成本安排未接入时所得税列留空。'], + ], + ]; + } + + /** + * 数据源现状:只读共享业务镜像,不访问上游。 + * + * @return array + */ + public static function health(): array + { + $health = [ + [ + 'name' => '公司基础信息(含税务类型)', + 'object' => 'ops_fys_company_info', + 'status' => '尚未同步', + 'detail' => '', + ], + [ + 'name' => '工商类型', + 'object' => '待接入', + 'status' => '未接入', + 'detail' => '现有镜像无法区分个人独资企业、合伙企业;确认数据来源后接入。', + ], + [ + 'name' => '征收方式与核定率', + 'object' => '待接入', + 'status' => '未接入', + 'detail' => '查账/核定、核定应税所得率需电子税务局数据或人工维护。', + ], + ]; + + try { + $connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + if ($connection->getSchemaBuilder()->hasTable('ops_fys_company_info')) { + $row = $connection->table('ops_fys_company_info') + ->selectRaw("COUNT(*) AS total, SUM(CASE WHEN taxCategoryAndType = '小规模纳税人' THEN 1 ELSE 0 END) AS small, SUM(CASE WHEN taxCategoryAndType = '一般纳税人' THEN 1 ELSE 0 END) AS general") + ->first(); + $health[0]['status'] = '已同步'; + $health[0]['detail'] = sprintf( + '主体 %d 家:小规模 %d 家、一般纳税人 %d 家', + (int) ($row->total ?? 0), + (int) ($row->small ?? 0), + (int) ($row->general ?? 0), + ); + } + } catch (Throwable) { + $health[0]['detail'] = '读取共享镜像失败,请检查连接与同步状态。'; + } + + return $health; + } +} diff --git a/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSynchronizer.php b/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSynchronizer.php index 87945062..e01ca858 100644 --- a/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSynchronizer.php +++ b/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSynchronizer.php @@ -30,6 +30,14 @@ class ThirdPartyWarehouseStorageSynchronizer private const INVENTORY_TABLE = 'third_party_warehouse_inventory_snapshots'; + private const SUBWAREHOUSE_INVENTORY_TABLE = 'third_party_warehouse_inventory_subwarehouse_snapshots'; + + /** @var array */ + private const SUBWAREHOUSE_QUANTITY_FIELDS = [ + 1 => 'qty', 2 => 'return_qty', 3 => 'in_qty', 4 => 'defective_qty', + 6 => 'customize_qty_1', 7 => 'customize_qty_2', 8 => 'customize_qty_3', + ]; + private readonly ConnectionInterface $connection; private readonly Repository $cache; @@ -263,12 +271,7 @@ class ThirdPartyWarehouseStorageSynchronizer $changedHeaders, )))); $latestHeaders = $this->upstream->latestHeadersForIoIds($changedIoIds, $throughAt); - $targetHeaders = array_values(array_filter( - $latestHeaders, - static fn (array $row): bool => - (int) ($row['wms_co_id'] ?? 0) - === ThirdPartyWarehouseStorageUpstreamRepository::WAREHOUSE_ID, - )); + $targetHeaders = $latestHeaders; $items = $this->upstream->itemsForIoIds(array_map( static fn (array $row): mixed => $row['io_id'] ?? null, $targetHeaders, @@ -395,7 +398,7 @@ class ThirdPartyWarehouseStorageSynchronizer self::HEADER_TABLE, (string) ($state['active_header_generation'] ?? ''), (string) $values['pending_header_generation'], - ['source_key', 'id', 'io_id', 'wms_co_id', 'status', 'io_type', 'occurred_at', 'source_modified_at', 'row_hash', 'synced_at'], + ['source_key', 'id', 'io_id', 'wms_co_id', 'wh_id', 'status', 'io_type', 'occurred_at', 'source_modified_at', 'row_hash', 'synced_at'], ); $this->cloneActiveGeneration( self::ITEM_TABLE, @@ -615,9 +618,14 @@ class ThirdPartyWarehouseStorageSynchronizer fn (array $row): ?array => $this->mapInventory($row, $generation, $now), $rows, ))); + $subwarehouseMapped = []; + foreach ($rows as $row) { + array_push($subwarehouseMapped, ...$this->mapSubwarehouseInventory($row, $generation, $now)); + } $this->connection->transaction(function () use ( $mapped, + $subwarehouseMapped, $generation, $cursor, $now, @@ -625,6 +633,11 @@ class ThirdPartyWarehouseStorageSynchronizer ): void { $this->assertCurrentRunToken($runToken); $this->upsertRows(self::INVENTORY_TABLE, $mapped, ['generation', 'id']); + $this->upsertRows( + self::SUBWAREHOUSE_INVENTORY_TABLE, + $subwarehouseMapped, + ['generation', 'id', 'wh_id'], + ); $this->updateStateForToken([ 'inventory_cursor' => $cursor, 'updated_at' => $now, @@ -692,6 +705,7 @@ class ThirdPartyWarehouseStorageSynchronizer ); $values['header_modified_cursor_id'] = 0; if ($mode === 'full') { + $values['scope_version'] = 2; $values['initial_completed_at'] = $now; $values['last_full_succeeded_at'] = $now; } @@ -991,6 +1005,7 @@ class ThirdPartyWarehouseStorageSynchronizer [self::HEADER_TABLE, 'header_generation', (string) $release->header_generation], [self::ITEM_TABLE, 'item_generation', (string) $release->item_generation], [self::INVENTORY_TABLE, 'inventory_generation', (string) $release->inventory_generation], + [self::SUBWAREHOUSE_INVENTORY_TABLE, 'inventory_generation', (string) $release->inventory_generation], ] as [$table, $column, $generation]) { if ($generation === '' || in_array($generation, $protected, true)) { continue; @@ -1036,6 +1051,7 @@ class ThirdPartyWarehouseStorageSynchronizer 'id' => $id, 'io_id' => $ioId, 'wms_co_id' => $warehouseId, + 'wh_id' => max((int) ($row['wh_id'] ?? 0), 0), 'status' => $this->text($row['status'] ?? null, 32), 'io_type' => $this->text($row['io_type'] ?? null, 64), 'occurred_at' => $this->dateTime($row['occurred_at'] ?? null), @@ -1113,6 +1129,40 @@ class ThirdPartyWarehouseStorageSynchronizer ]; } + /** @return list> */ + private function mapSubwarehouseInventory(array $row, string $generation, mixed $now): array + { + $base = $this->mapInventory($row, $generation, $now); + if ($base === null) { + return []; + } + + $rows = []; + foreach (self::SUBWAREHOUSE_QUANTITY_FIELDS as $warehouseId => $field) { + $quantity = (float) ($row[$field] ?? 0); + if ($quantity == 0.0) { + continue; + } + $values = [ + 'generation' => $generation, + 'source_key' => $base['source_key'], + 'id' => $base['id'], + 'wms_co_id' => $base['wms_co_id'], + 'wh_id' => $warehouseId, + 'sku_code' => $base['sku_code'], + 'qty' => $quantity, + 'source_modified_at' => $base['source_modified_at'], + 'captured_at' => $base['captured_at'], + ]; + $rows[] = $values + [ + 'row_hash' => $this->rowHash($values), + 'synced_at' => $now, + ]; + } + + return $rows; + } + /** * @param list> $rows * @param list $uniqueBy @@ -1226,6 +1276,7 @@ class ThirdPartyWarehouseStorageSynchronizer self::HEADER_TABLE, self::ITEM_TABLE, self::INVENTORY_TABLE, + self::SUBWAREHOUSE_INVENTORY_TABLE, ] as $table) { if (! $schema->hasTable($table)) { throw new RuntimeException('third_party_warehouse_mirror_schema_missing:' . $table); @@ -1275,6 +1326,7 @@ class ThirdPartyWarehouseStorageSynchronizer 'inventory_row_count', 'initial_completed_at', 'last_full_succeeded_at', + 'scope_version', ] as $column) { if (! $schema->hasColumn(self::STATE_TABLE, $column)) { throw new RuntimeException('third_party_warehouse_mirror_state_missing:' . $column); diff --git a/modules/EcommerceFinance/View/BillingDetailsPageData.php b/modules/EcommerceFinance/View/BillingDetailsPageData.php new file mode 100644 index 00000000..598e129e --- /dev/null +++ b/modules/EcommerceFinance/View/BillingDetailsPageData.php @@ -0,0 +1,639 @@ + ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'income' => 'income_amount', 'expense' => 'expense_amount', 'online_order' => 'online_order_no', 'merchant_order' => 'merchant_order_no', 'type' => null, 'periods' => null], + '淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'income' => 'income_amount', 'expense' => 'expense_amount', 'online_order' => 'online_order_no', 'merchant_order' => 'pay_serial_no', 'type' => null, 'periods' => null], + '拼多多' => ['table' => 'pdd_settlement_bill_rows', 'date' => 'occurred_at', 'income' => 'income_amount', 'expense' => 'expense_amount', 'online_order' => 'online_order_no', 'merchant_order' => 'merchant_order_no', 'type' => 'account_name', 'periods' => null], + '京东账单' => ['table' => 'jd_daily_bill_rows', 'date' => 'occurred_at', 'income' => 'income', 'expense' => 'expense', 'online_order' => null, 'merchant_order' => null, 'type' => null, 'periods' => 'jd_daily_bill_periods'], + '京东钱包' => ['table' => 'jd_wallet_bill_rows', 'date' => 'occurred_at', 'income' => 'income', 'expense' => 'expense', 'online_order' => null, 'merchant_order' => null, 'type' => 'account_name', 'periods' => 'jd_wallet_bill_periods'], + '抖音' => ['table' => 'douyin_authoritative_bills', 'date' => 'occurred_at', 'income' => 'income', 'expense' => 'expense', 'online_order' => null, 'merchant_order' => null, 'type' => null, 'periods' => 'douyin_authoritative_periods'], + '得物' => ['table' => 'dewu_settlement_bill_rows', 'date' => 'bill_date', 'income' => 'income_amount', 'expense' => 'expense_amount', 'online_order' => 'online_order_no', 'merchant_order' => 'order_no', 'type' => null, 'periods' => null], + ]; + + private const PLATFORM_PREFIX = [ + '天猫' => '天猫', '淘宝' => '淘宝', '京东' => '京东', '京喜' => '京喜', '京喜小店' => '京喜', + '拼多多' => '拼多多', '抖音' => '抖音', '头条放心购' => '抖音', '得物' => '得物', + '阿里巴巴' => '阿里巴巴', '新佰广1688' => '阿里巴巴', '淘工厂' => '阿里巴巴', + '唯品会MP' => '唯品会MP', '唯品会JX' => '唯品会JX', '支付宝' => '支付宝', + ]; + + public function page(): array + { + return [ + 'view' => 'business.pages.financial-operations.billing-details', + 'options' => $this->options(), + 'columns' => self::COLUMNS, + ] + $this->data(); + } + + /** + * 页面与导出的列定义(顺序即默认显示顺序):key => [标签, 类型]。 + */ + public const COLUMNS = [ + 'record_code' => ['记录编码', 'text'], + 'store_name' => ['店铺', 'text'], + 'finance_remark' => ['财务备注', 'text'], + 'online_order_no' => ['线上单号', 'text'], + 'amount' => ['金额', 'num'], + 'bill_item' => ['账单项目', 'tag'], + 'merchant_order_no' => ['商户订单号', 'text'], + 'custom_remark' => ['自定义备注', 'text'], + 'finance_type' => ['财务类型', 'tag'], + 'type_text' => ['类型', 'text'], + 'occurred_at' => ['发生时间', 'text'], + 'income' => ['收入金额', 'num'], + 'expense' => ['支出金额', 'num'], + 'remark' => ['备注', 'text'], + ]; + + /** 导出用:按请求解析筛选条件(与页面同一套口径) */ + public function exportFilters(array $input): array + { + return $this->parseFilters($input); + } + + /** 导出用:当前筛选下的总行数(进度百分比用) */ + public function exportTotal(array $filters): int + { + if ($filters === []) { + return 0; + } + + $parts = []; + $bind = []; + foreach (self::SOURCES as $label => $meta) { + $branch = $this->branch($label, $meta, $filters); + foreach ($branch['scopes'] as $scope) { + $parts[] = 'SELECT COUNT(*) AS c FROM ' . $branch['table'] . ' WHERE ' . $scope['where']; + $bind = array_merge($bind, $scope['bind']); + } + } + + $total = 0; + foreach ($this->connection()->select(implode(' UNION ALL ', $parts), $bind) as $row) { + $total += (int) $row->c; + } + + return $total; + } + + /** + * 导出用:按 key 过滤列;不传即全部列。 + * + * @param list $keys + * @return array + */ + public function exportColumns(array $keys): array + { + if ($keys === []) { + return self::COLUMNS; + } + $wanted = array_flip(array_map(static fn ($key): string => trim((string) $key), $keys)); + $columns = []; + foreach (self::COLUMNS as $key => $definition) { + if (isset($wanted[$key])) { + $columns[$key] = $definition; + } + } + + return $columns === [] ? self::COLUMNS : $columns; + } + + /** + * 导出用:逐分支流式产出「页面同款」行(财务备注/财务类型已按科目映射表带出)。 + * + * @param array $filters + * @return \Generator> + */ + public function exportRows(array $filters, array $columns = []): \Generator + { + $connection = $this->connection(); + $rules = $this->rules(); + + foreach (self::SOURCES as $label => $meta) { + $branch = $this->branch($label, $meta, $filters); + // 只查导出要用的列:备注这类长文本不查,从镜像库搬的数据量能少好几倍 + $select = $columns === [] ? $branch['cols'] : $this->exportSelectList($meta, $columns); + foreach ($branch['scopes'] as $scope) { + // 用游标(非缓冲查询)逐行产出,避免上百万行一次性读进内存 + foreach ($connection->cursor( + 'SELECT ' . $select . ' FROM ' . $branch['table'] . ' WHERE ' . $scope['where'] + . ' ORDER BY ' . $branch['date'] . ' DESC, record_code DESC', + $scope['bind'] + ) as $raw) { + yield $this->presentRow((array) $raw, $rules); + } + } + } + } + + /** + * 按导出列拼最小查询列表(别名与页面列一致)。 + * + * @param array $meta + * @param array $columns + */ + private function exportSelectList(array $meta, array $columns): string + { + $table = (string) $meta['table']; + $has = fn (string $column): bool => in_array($column, $this->columns($table), true); + $pick = static fn (?string $column): ?string => $column !== null && $column !== '' ? $column : null; + $want = array_flip(array_keys($columns)); + $finance = isset($want['finance_remark']) || isset($want['finance_type']); + + $select = []; + $add = static function (string $alias, ?string $expr) use (&$select): void { + if ($expr === null || isset($select[$alias])) { + return; + } + $select[$alias] = $expr === $alias ? $alias : $expr . ' AS ' . $alias; + }; + + if (isset($want['record_code'])) { $add('record_code', 'record_code'); } + if (isset($want['store_name']) || $finance) { $add('store_name', 'store_name'); } + if (isset($want['bill_item']) || $finance) { $add('bill_item', 'bill_item'); } + if (isset($want['online_order_no'])) { $add('online_order_no', $pick(is_string($meta['online_order']) ? (string) $meta['online_order'] : null)); } + if (isset($want['merchant_order_no'])) { $add('merchant_order_no', $pick(is_string($meta['merchant_order']) ? (string) $meta['merchant_order'] : null)); } + if (isset($want['custom_remark'])) { $add('custom_remark', $has('custom_remark') ? 'custom_remark' : null); } + if (isset($want['remark'])) { $add('remark', $has('remark') ? 'remark' : null); } + if (isset($want['type_text'])) { $add('type_text', $pick(is_string($meta['type']) ? (string) $meta['type'] : null)); } + if (isset($want['occurred_at'])) { $add('occurred_at', (string) $meta['date']); } + if (isset($want['income']) || isset($want['amount'])) { $add('income', (string) $meta['income']); } + if (isset($want['expense']) || isset($want['amount'])) { $add('expense', (string) $meta['expense']); } + + // 一列都没选到时至少取主键列,保证 SQL 合法 + return $select === [] ? 'record_code' : implode(', ', $select); + } + + /** + * 筛选下拉候选:店铺与账单项目(账单项目统一成去 wx 前缀后的名称,与带出财务备注/类型同一口径)。 + * 镜像每天只会新增数据,候选清单按 6 小时缓存,避免每次开页都做一次索引扫描。 + * + * @return array{stores:list,items:list} + */ + public function options(): array + { + try { + return cache()->remember('billing-details-filter-options-v1', now()->addHours(6), function (): array { + $stores = []; + $items = []; + foreach (self::SOURCES as $meta) { + $table = (string) $meta['table']; + try { + foreach ($this->connection()->select('SELECT DISTINCT store_name FROM ' . $table) as $row) { + $store = trim((string) $row->store_name); + if ($store !== '') { $stores[$store] = true; } + } + foreach ($this->connection()->select('SELECT DISTINCT bill_item FROM ' . $table) as $row) { + $item = $this->normalizeItem((string) $row->bill_item); + if ($item !== '') { $items[$item] = true; } + } + } catch (Throwable) { + continue; + } + } + + $stores = array_keys($stores); + $items = array_keys($items); + sort($stores, SORT_NATURAL | SORT_FLAG_CASE); + sort($items, SORT_NATURAL | SORT_FLAG_CASE); + + return ['stores' => $stores, 'items' => $items]; + }); + } catch (Throwable $exception) { + report($exception); + + return ['stores' => [], 'items' => []]; + } + } + + /** @return array */ + public function data(?array $input = null): array + { + $input ??= request()->all(); + $filters = $this->parseFilters($input); + + $rows = []; + $total = 0; + $income = 0.0; + $expense = 0.0; + $status = null; + $error = null; + $limit = $this->perPage($input); + $page = max((int) ($input['page'] ?? request('page', 1)), 1); + $offset = ($page - 1) * $limit; + + try { + $conn = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + + // 每个平台一个分支,日期与筛选已下推到分支内,可各自命中 (日期, record_code) 索引 + $branches = []; + foreach (self::SOURCES as $label => $meta) { + $branches[] = $this->branch($label, $meta, $filters); + } + + // 汇总:按分支聚合并,避免把整月数据物化成临时表 + $summaryParts = []; + $summaryBind = []; + foreach ($branches as $branch) { + foreach ($branch['scopes'] as $scope) { + $summaryParts[] = 'SELECT COUNT(*) AS c, COALESCE(SUM(' . $branch['income'] . '),0) AS inc, ' + . 'COALESCE(SUM(' . $branch['expense'] . '),0) AS exp FROM ' . $branch['table'] + . ' WHERE ' . $scope['where']; + $summaryBind = array_merge($summaryBind, $scope['bind']); + } + } + foreach ($conn->select(implode(' UNION ALL ', $summaryParts), $summaryBind) as $part) { + $total += (int) $part->c; + $income += (float) $part->inc; + $expense += (float) $part->exp; + } + + // 明细:每个分支先用索引取自己的前 offset+limit 行,再合并排序,避免全量排序 + if ($total > 0 && $offset < $total) { + $need = $offset + $limit; + $rowParts = []; + $rowBind = []; + foreach ($branches as $branch) { + foreach ($branch['scopes'] as $scope) { + $rowParts[] = '(SELECT ' . $branch['cols'] . ' FROM ' . $branch['table'] + . ' WHERE ' . $scope['where'] + . ' ORDER BY ' . $branch['date'] . ' DESC, record_code DESC LIMIT ' . $need . ')'; + $rowBind = array_merge($rowBind, $scope['bind']); + } + } + $rows = $conn->select( + implode(' UNION ALL ', $rowParts) . ' ORDER BY occurred_at DESC, record_code DESC LIMIT ' . $limit . ' OFFSET ' . $offset, + $rowBind + ); + } + } catch (Throwable $exception) { + report($exception); + $error = '账单明细数据暂时无法读取:' . $exception->getMessage(); + } + + $rules = $this->rules(); + $rows = array_map(fn ($row): array => $this->presentRow((array) $row, $rules), $rows); + + return [ + 'filters' => $filters, + 'rows' => new LengthAwarePaginator($rows, $total, $limit, $page, [ + 'path' => request()->url(), + 'query' => request()->except('page'), + ]), + 'summary' => ['rows' => $total, 'income' => round($income, 2), 'expense' => round($expense, 2), 'net' => round($income - $expense, 2)], + 'platforms' => array_keys(self::PLATFORM_PREFIX), + 'types' => $this->types(), + 'error' => $error, + 'status' => $status, + ]; + } + + /** + * 组装单个平台分支:统一的输出列 + 每个账期版本一份「筛选已下推」的 WHERE。 + * + * @param array $meta + * @param array $filters + * @return array{table:string,date:string,income:string,expense:string,cols:string,scopes:list}>} + */ + private function branch(string $label, array $meta, array $filters): array + { + $table = (string) $meta['table']; + $dateCol = (string) $meta['date']; + $has = fn (string $column): bool => in_array($column, $this->columns($table), true); + // 各平台账单表列不完全一致(京东/抖音没有 custom_remark、remark),缺的列统一留空 + $customRemark = $has('custom_remark') ? 'custom_remark' : "''"; + $remark = $has('remark') ? 'remark' : "''"; + $online = is_string($meta['online_order']) && $has((string) $meta['online_order']) ? (string) $meta['online_order'] : "''"; + $merchant = is_string($meta['merchant_order']) && $has((string) $meta['merchant_order']) ? (string) $meta['merchant_order'] : "''"; + $typeCol = is_string($meta['type']) && $has((string) $meta['type']) ? (string) $meta['type'] : "''"; + + $cols = "'{$label}' AS source, record_code, store_name, {$customRemark} AS custom_remark, {$online} AS online_order_no, " + . "bill_item, {$merchant} AS merchant_order_no, {$typeCol} AS type_text, {$dateCol} AS occurred_at, " + . "{$meta['income']} AS income, {$meta['expense']} AS expense, {$remark} AS remark"; + + // 公共筛选(不含日期)逐条下推到分支,让各表尽量用自己的索引 + $conditions = []; + $bind = []; + if ($filters['platform'] !== []) { + $parts = []; + foreach ($filters['platform'] as $platform) { + $parts[] = 'store_name LIKE ?'; + $bind[] = $platform . '-%'; + } + $conditions[] = '(' . implode(' OR ', $parts) . ')'; + } + if ($filters['store'] !== []) { + $conditions[] = 'store_name IN (' . $this->literals($filters['store']) . ')'; + } + if ($filters['item'] !== []) { + // 候选取自下拉清单(已去 wx 前缀),这里用同一套归一化表达式比对 + $conditions[] = $this->normalizedItemSql() . ' IN (' . $this->literals($filters['item']) . ')'; + } + if ($filters['keyword'] !== '') { + $keyword = '%' . $filters['keyword'] . '%'; + $haystack = []; + foreach (array_unique(['record_code', $online, $merchant, 'bill_item', $customRemark, $remark]) as $column) { + $haystack[] = $column . ' LIKE ?'; + $bind[] = $keyword; + } + $conditions[] = '(' . implode(' OR ', $haystack) . ')'; + } + if ($filters['type'] !== []) { + $allowed = $this->itemsForTypes($filters['type']); + if ($allowed === []) { + $conditions[] = '1 = 0'; + } else { + // 与页面带出财务备注/类型时一致:wx 前缀的账单项目按去前缀后的名称归类。 + // 项目名以字面量内联:MySQL 对字面量 IN 列表会排序后二分查找, + // 参数化 IN 会逐行线性比对,161 个项目 × 130 万行会退化到 30 秒以上。 + $conditions[] = $this->normalizedItemSql() . ' IN (' . $this->literals($allowed) . ')'; + } + } + + $dateBind = $dateCol === 'bill_date' + ? [$filters['start'], $filters['end']] + : [$filters['start'] . ' 00:00:00', $filters['end'] . ' 23:59:59']; + + $scopes = []; + foreach ($this->generations($meta['periods'] === null ? null : (string) $meta['periods'], $filters['start'], $filters['end']) as $generation) { + $where = []; + $scopeBind = []; + if ($generation !== null) { + $where[] = 'generation = ?'; + $scopeBind[] = $generation; + } + $where[] = "{$dateCol} >= ? AND {$dateCol} <= ?"; + $scopeBind = array_merge($scopeBind, $dateBind); + foreach ($conditions as $condition) { + $where[] = $condition; + } + $scopes[] = ['where' => implode(' AND ', $where), 'bind' => array_merge($scopeBind, $bind)]; + } + + return [ + 'table' => $table, + 'date' => $dateCol, + 'income' => (string) $meta['income'], + 'expense' => (string) $meta['expense'], + 'cols' => $cols, + 'scopes' => $scopes, + ]; + } + + /** @var array> */ + private array $generationCache = []; + + private function connection(): \Illuminate\Database\Connection + { + return DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + } + + /** + * 筛选值统一成字符串列表(表单提交的多选是数组;空值丢弃)。 + * + * @return list + */ + private function values(mixed $raw): array + { + $list = is_array($raw) ? $raw : [$raw]; + $values = []; + foreach ($list as $value) { + $value = trim((string) $value); + if ($value !== '' && ! in_array($value, $values, true)) { + $values[] = $value; + } + } + + return array_slice($values, 0, 500); + } + + /** + * IN 列表以字面量内联(已按驱动转义)。 + * MySQL 对字面量 IN 会排序后二分查找,参数化 IN 会逐行线性比对; + * 财务类型动辄上百个项目 × 上百万行,参数化会退化到 30 秒以上。 + * + * @param list $values + */ + private function literals(array $values): string + { + $pdo = $this->connection()->getPdo(); + + return implode(',', array_map(static fn (string $value): string => $pdo->quote($value), array_values(array_unique($values)))); + } + + /** 账单项目归一化:去掉 wx 前缀(与页面带出财务备注/类型时一致) */ + private function normalizeItem(string $item): string + { + $item = trim($item); + + return preg_match('/^wx/i', $item) === 1 ? ltrim(substr($item, 2)) : $item; + } + + /** + * 解析筛选条件(页面与导出共用同一套口径)。 + * + * @param array $input + * @return array + */ + private function parseFilters(array $input): array + { + $now = now(); + $month = trim((string) ($input['month'] ?? '')) ?: $now->format('Y-m'); + $start = trim((string) ($input['start'] ?? '')) ?: $month . '-01'; + $end = trim((string) ($input['end'] ?? '')) ?: date('Y-m-t', strtotime($start)); + // 日期只接受 Y-m-d,避免拼进 SQL 的字符串被注入 + $start = preg_match('/^\d{4}-\d{2}-\d{2}$/', $start) === 1 ? $start : $now->format('Y-m-01'); + $end = preg_match('/^\d{4}-\d{2}-\d{2}$/', $end) === 1 ? $end : date('Y-m-t', strtotime($start)); + if ($end < $start) { $end = $start; } + + return [ + 'month' => substr($start, 0, 7), + 'start' => $start, + 'end' => $end, + 'platform' => $this->values($input['platform'] ?? []), + 'store' => $this->values($input['store'] ?? []), + 'item' => $this->values($input['item'] ?? []), + 'type' => $this->values($input['type'] ?? []), + 'keyword' => trim((string) ($input['keyword'] ?? '')), + 'per_page' => $this->perPage($input), + ]; + } + + /** 每页条数:只接受 10 / 20 / 50,缺省 20 */ + private function perPage(array $input): int + { + $size = (int) ($input['per_page'] ?? 20); + + return in_array($size, [10, 20, 50], true) ? $size : 20; + } + + /** + * 行展示口径:带出平台、财务备注、财务类型(页面与导出一致)。 + * + * @param array $row + * @param array $rules + * @return array + */ + private function presentRow(array $row, array $rules): array + { + $shop = (string) ($row['store_name'] ?? ''); + $prefix = $shop === '' ? '' : explode('-', $shop)[0]; + $platform = self::PLATFORM_PREFIX[$prefix] ?? ''; + $item = trim((string) ($row['bill_item'] ?? '')); + $normalized = $this->normalizeItem($item); + $rule = $rules[$platform . '|' . $normalized] ?? ($rules[$platform . '|' . $item] ?? null); + + $row['platform'] = $platform; + $row['finance_remark'] = $rule['memo'] ?? ''; + $row['finance_type'] = $rule['category'] ?? ''; + $row['matched'] = $rule !== null; + + return $row; + } + + private function normalizedItemSql(): string + { + return "(CASE WHEN bill_item LIKE 'wx%' THEN LTRIM(SUBSTRING(bill_item, 3)) ELSE bill_item END)"; + } + + /** + * 取与查询区间有交集的账期的 active_generation(与 JD / 抖音账单页仓储同一口径)。 + * + * 只取相交账期,可保证分支数量不随镜像历史累积增长; + * 账期信息不可用时退回 [null],表示该分支不区分版本。 + * + * @return list + */ + private function generations(?string $periodsTable, string $start, string $end): array + { + if ($periodsTable === null) { + return [null]; + } + $cacheKey = $periodsTable . '|' . $start . '|' . $end; + if (array_key_exists($cacheKey, $this->generationCache)) { + return $this->generationCache[$cacheKey]; + } + try { + $connection = $this->connection(); + $columns = array_map(static fn ($column): string => (string) $column->Field, $connection->select('SHOW COLUMNS FROM ' . $periodsTable)); + $active = $connection->table($periodsTable)->distinct()->orderBy('active_generation'); + if (in_array('period_start', $columns, true) && in_array('period_end', $columns, true)) { + $active->where('period_start', '<=', $end)->where('period_end', '>=', $start); + } + $generations = $active->pluck('active_generation') + ->filter(static fn ($generation): bool => is_string($generation) && $generation !== '') + ->values() + ->all(); + if ($generations === []) { + // 查询区间与任何账期都不相交时,退回全部在用版本,保证不漏数 + $generations = $connection->table($periodsTable)->distinct()->orderBy('active_generation') + ->pluck('active_generation') + ->filter(static fn ($generation): bool => is_string($generation) && $generation !== '') + ->values() + ->all(); + } + } catch (Throwable) { + $generations = []; + } + + return $this->generationCache[$cacheKey] = ($generations === [] ? [null] : $generations); + } + + /** @var array> */ + private array $columnCache = []; + + /** @return list */ + private function columns(string $table): array + { + if (! isset($this->columnCache[$table])) { + try { + $this->columnCache[$table] = array_map( + static fn ($c): string => (string) $c->Field, + DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'))->select('SHOW COLUMNS FROM ' . $table) + ); + } catch (Throwable) { + $this->columnCache[$table] = []; + } + } + return $this->columnCache[$table]; + } + + /** 科目映射表:平台|账单项目 → [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) { + $key = trim((string) ($rule['platform'] ?? '')) . '|' . trim((string) ($rule['item'] ?? '')); + $prev = $cache[$key] ?? null; + $isCatchAll = trim((string) ($rule['memo'] ?? '')) === '' && trim((string) ($rule['goods'] ?? '')) === ''; + if ($prev === null || ($isCatchAll && ! $prev['catch'])) { + $cache[$key] = ['memo' => (string) ($rule['memo'] ?? ''), 'category' => (string) ($rule['category'] ?? ''), 'catch' => $isCatchAll]; + } + } + return $cache; + } + + /** @return list */ + private function types(): array + { + $types = []; + foreach ($this->rules() as $rule) { + if ($rule['category'] !== '' && ! in_array($rule['category'], $types, true)) { $types[] = $rule['category']; } + } + sort($types); + return $types; + } + + /** 财务类型 → 该类型下的账单项目集合(用于按类型筛选时保持分页正确) */ + private function itemsForType(string $type): array + { + return $this->itemsForTypes([$type]); + } + + /** + * 多个财务类型 → 其下所有账单项目的并集。 + * + * @param list $types + * @return list + */ + private function itemsForTypes(array $types): array + { + $wanted = array_flip($types); + $items = []; + foreach ($this->rules() as $key => $rule) { + if (isset($wanted[$rule['category']])) { + $items[explode('|', $key, 2)[1]] = true; + } + } + + return array_keys($items); + } +} diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index b94daeac..d874909a 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -5,31 +5,53 @@
+ -
发生时间
至
- +
+ {{ dateFilterLabel }} +
+ + + + + + 至 + + + + + +
+
+
+ +

筛选条件已修改,查询后可导出对应结果。

+
来源:{{ sync.source }} · 已接入月份:{{ (sync.periods || []).join('、') }} · 导入时间:{{ sync.last_succeeded_at }}
{{ sourceGroups.length ? '账单明细' : columnsTitle }}{{ total }} 条
- - + +
@@ -53,30 +75,51 @@ diff --git a/resources/views/business/pages/billing-transactions/planting-details.blade.php b/resources/views/business/pages/billing-transactions/planting-details.blade.php new file mode 100644 index 00000000..84cae8ec --- /dev/null +++ b/resources/views/business/pages/billing-transactions/planting-details.blade.php @@ -0,0 +1,365 @@ +@php + $records = $records ?? null; + $filters = $filters ?? []; + $summary = $summary ?? []; + $filterOptions = $filterOptions ?? ['stores' => [], 'owners' => [], 'types' => [], 'tags' => []]; + $totals = [ + 'rows' => (int) ($summary['rows'] ?? 0), + 'pieces' => (int) ($summary['pieces'] ?? 0), + 'selling_price' => (float) ($summary['selling_price'] ?? 0), + 'payment_amount' => (float) ($summary['payment_amount'] ?? 0), + 'deduction' => (float) ($summary['deduction'] ?? 0), + 'jingxi_diff' => (float) ($summary['jingxi_diff'] ?? 0), + ]; + $money = static fn (mixed $value): string => number_format((float) $value, 2); +@endphp + +
+ @include('business.pages.partials.upstream-data-styles') + + + +
+
+
笔数合计
+
{{ number_format($totals['pieces']) }}
+
+
+
财务打款金额
+
{{ $money($totals['payment_amount']) }}
+
+
+
财务售价
+
{{ $money($totals['selling_price']) }}
+
+
+
扣款
+
{{ $money($totals['deduction']) }}
+
+
+
京喜差价
+
{{ $money($totals['jingxi_diff']) }}
+
+
+ +
+
+ + + + + +
+ +
+ + + + + +
+
+ + + + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +

数据来源:财务「1-8月种菜」原始表导入,共 {{ number_format($totals['rows']) }} 行(当前筛选)。

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + @forelse ($records as $index => $record) + + + + + + + + + + + + + + + + + + + + + + + + @empty + + + + @endforelse + +
序号日期订单编号财务售价财务运费财务佣金京喜差价扣款财务空包费财务打款金额笔数备注正确店铺负责人账户类型创建人标签所属利润中心负责平台ID
{{ $records->firstItem() + $index }}{{ $record->bill_date?->toDateString() ?? '-' }}{{ $record->order_no ?: '-' }}{{ $money($record->finance_selling_price) }}{{ $money($record->finance_freight) }}{{ $money($record->finance_commission) }}{{ $money($record->jingxi_price_diff) }}{{ $money($record->deduction) }}{{ $money($record->finance_empty_package_fee) }}{{ $money($record->finance_payment_amount) }}{{ number_format((int) $record->pieces) }}{{ $record->remark ?: '-' }}{{ $record->store ?: '-' }}{{ $record->owner ?: '-' }}{{ $record->account ?: '-' }}{{ $record->type ?: '-' }}{{ $record->creator ?: '-' }}{{ $record->tag ?: '-' }}{{ $record->profit_center ?: '-' }}{{ $record->responsible_platform ?: '-' }}{{ $record->external_id ?: '-' }}
+ {{ $totals['rows'] === 0 ? '暂无种菜明细数据,请先导入「1-8月种菜」等原始表。' : '当前筛选条件下没有记录,请调整筛选条件后重试。' }} +
+
+ +
+ + 共 {{ number_format($records->total()) }} 条记录 + · 每页 {{ $records->perPage() }} 条 + · 第 {{ $records->currentPage() }} / {{ max($records->lastPage(), 1) }} 页 + +
+ @if ($records->onFirstPage()) + + + + @else + + + + @endif + 第 {{ $records->currentPage() }} / {{ max($records->lastPage(), 1) }} 页 + @if ($records->hasMorePages()) + + + + @else + + + + @endif +
+
+
+
+ + diff --git a/resources/views/business/pages/company-management/tax-forecast-data-logic-edit.blade.php b/resources/views/business/pages/company-management/tax-forecast-data-logic-edit.blade.php new file mode 100644 index 00000000..4a159854 --- /dev/null +++ b/resources/views/business/pages/company-management/tax-forecast-data-logic-edit.blade.php @@ -0,0 +1,211 @@ +@php + use Modules\EcommerceFinance\Services\TaxForecastLogic; + + $rules = TaxForecastLogic::rules(); +@endphp + + + +
+
+ @csrf + +
+

增值税

+

小规模纳税人按季度销售额判断免税;一般纳税人的进销项抵扣可单独关闭。

+
+
+ + +
对应规则 R5,默认 1%(3% 减按 1%)。
+
+
+ + +
对应规则 R4,默认 300000 元/季。
+
+
+ + +
对应规则 R6。
+
+
+
+ +
+

附加税费

+

附加税费以预计增值税为计税依据,六税两费减半开关对附加税费统一生效。

+
+
+ + +
对应规则 R8,市区 7%、县城/镇 5%、其他 1%。
+
+
+ + +
对应规则 R9,默认 3%。
+
+
+ + +
对应规则 R9,默认 2%。
+
+
+ + +
对应规则 R10。
+
+
+
+ +
+

印花税

+

印花税按购销合同金额计算,减半开关单独维护。

+
+
+ + +
对应规则 R11,默认 0.03%。
+
+
+ + +
对应规则 R11。
+
+
+
+ +
+

所得税

+

有限公司按小型微利企业口径,个人独资企业、合伙企业、个体工商户按经营所得口径。

+
+
+ + +
对应规则 R12,默认 5%(25% × 20%)。
+
+
+ + +
超过上限部分提示分段计算。
+
+
+ + +
对应规则 R14,默认 2000000 元。
+
+
+ + +
核定征收主体未单独维护时按此默认值。
+
+
+
+ +
+

预测口径

+

预测月份尚未出账时,收入取值方式。

+
+
+ + +
对应规则 R15。
+
+
+
+ +
+ + 返回规则页 +
+
+ +
+

规则目录(只读)

+

规则编号和逻辑说明与取数公式文档保持一致,用于核对上面参数的实际含义。

+ + + + + + + + + + + + @foreach ($rules as $category => $categoryRules) + @foreach ($categoryRules as $rule) + + + + + + + + @endforeach + @endforeach + +
规则编号规则类别规则对象规则逻辑优先级说明
{{ $rule['code'] }}{{ $category }}{{ $rule['object'] }}{{ $rule['logic'] }}{{ $rule['priority'] }}
+
+
diff --git a/resources/views/business/pages/company-management/tax-forecast-data-logic.blade.php b/resources/views/business/pages/company-management/tax-forecast-data-logic.blade.php new file mode 100644 index 00000000..82b54759 --- /dev/null +++ b/resources/views/business/pages/company-management/tax-forecast-data-logic.blade.php @@ -0,0 +1,183 @@ +@php + use Modules\EcommerceFinance\Services\TaxForecastLogic; + + $parameterRows = [ + ['label' => '小规模增值税征收率', 'value' => ($taxSettings['vat_small_rate'] ?? '1') . '%', 'hint' => '超过免税额度时按不含税销售额计算'], + ['label' => '小规模季度免税额度', 'value' => number_format((float) ($taxSettings['vat_free_threshold'] ?? 0)) . ' 元/季', 'hint' => '季度不含税销售额不超过该额度时增值税为 0'], + ['label' => '一般纳税人进销项抵扣', 'value' => ($taxSettings['vat_general_enabled'] ?? '1') === '1' ? '开启' : '关闭', 'hint' => '关闭后一般纳税人按销项税额全额提示'], + ['label' => '城建税税率', 'value' => ($taxSettings['surtax_city_rate'] ?? '7') . '%', 'hint' => '市区 7%、县城/镇 5%、其他 1%'], + ['label' => '教育费附加', 'value' => ($taxSettings['surtax_education_rate'] ?? '3') . '%', 'hint' => '以预计增值税为计税依据'], + ['label' => '地方教育附加', 'value' => ($taxSettings['surtax_local_education_rate'] ?? '2') . '%', 'hint' => '以预计增值税为计税依据'], + ['label' => '六税两费减半', 'value' => ($taxSettings['surtax_halved'] ?? '1') === '1' ? '开启' : '关闭', 'hint' => '附加税费减半征收'], + ['label' => '印花税税率(购销合同)', 'value' => ($taxSettings['stamp_duty_rate'] ?? '0.03') . '%', 'hint' => '按购销合同金额计算'], + ['label' => '印花税减半', 'value' => ($taxSettings['stamp_duty_halved'] ?? '1') === '1' ? '开启' : '关闭', 'hint' => '小规模、小微减半征收'], + ['label' => '小型微利企业所得税实际税负', 'value' => ($taxSettings['cit_effective_rate'] ?? '5') . '%', 'hint' => '应纳税所得额 × 25% × 20%'], + ['label' => '年应纳税所得额上限', 'value' => number_format((float) ($taxSettings['cit_threshold'] ?? 0)) . ' 元', 'hint' => '超过上限部分提示分段计算'], + ['label' => '个体工商户减半上限', 'value' => number_format((float) ($taxSettings['individual_halved_threshold'] ?? 0)) . ' 元', 'hint' => '经营所得个人所得税减半'], + ['label' => '核定应税所得率默认值', 'value' => ($taxSettings['assessed_income_rate'] ?? '10') . '%', 'hint' => '核定征收主体未单独维护时按此默认值'], + ['label' => '收入预测口径', 'value' => TaxForecastLogic::INCOME_FORECAST_SOURCES[$taxSettings['income_forecast_source'] ?? ''] ?? '上月实际收入(bills.income)', 'hint' => '预测月份未出账时取值方式'], + ]; +@endphp + + + +
+
+ 规则参数由负责人维护,保存后下次预测按新参数计算。 + 编辑配置 +
+
+ 本页是税金预测表当前实际使用的计算口径,与 docs/税金预测表需求说明.md 保持一致; + 工商类型、征收方式(查账/核定)接入前,涉及所得税的列在预测表中留空,不做推测。 + 返回税金预测表 +
+ +
+

当前运行参数

+ + + + + + + + + + @foreach ($parameterRows as $row) + + + + + + @endforeach + +
参数当前值说明
{{ $row['label'] }}{{ $row['value'] }}{{ $row['hint'] }}
+
+ +
+

数据来源

+ + + + + + + + + + + @foreach ($taxHealth as $source) + + + + + + + @endforeach + +
来源对象状态说明
{{ $source['name'] }}{{ $source['object'] }} + {{ $source['status'] }} + + {{ $source['detail'] !== '' ? $source['detail'] : '—' }} +
收入口径:主体维度经营报表同源(bills.income);成本口径:公司成本安排页。
+
+
+ +
+

规则清单

+ + + + + + + + + + + + + + @foreach ($taxRules as $category => $categoryRules) + @foreach ($categoryRules as $rule) + + + + + + + + + + @endforeach + @endforeach + +
规则编号规则类别规则对象规则逻辑数据来源优先级说明状态
{{ $rule['code'] }}{{ $category }}{{ $rule['object'] }}{{ $rule['logic'] }}{{ $rule['source'] }}{{ $rule['priority'] }}已生效
+
+
diff --git a/resources/views/business/pages/courier-payables/agreement-signing.blade.php b/resources/views/business/pages/courier-payables/agreement-signing.blade.php index 5e41b41d..d97fda09 100644 --- a/resources/views/business/pages/courier-payables/agreement-signing.blade.php +++ b/resources/views/business/pages/courier-payables/agreement-signing.blade.php @@ -1,14 +1,18 @@ @php($agreementTasks = $agreementTasks ?? collect()) @php($agreementQuoteSignatures = $agreementQuoteSignatures ?? collect()) @php($agreementSubjects = $agreementSubjects ?? collect()) +@php($agreementCourierNames = collect($agreementCourierNames ?? [])) @php($agreementCourierAccounts = $agreementCourierAccounts ?? []) @php($agreementQuoteVersions = $agreementQuoteVersions ?? collect()) -@php($agreementCourierNames = collect(['新北中通', '新北中通其他', '新德邦快递', '睢宁中通', '武进极兔', '沭阳德邦', '常州圆通其他'])->merge($agreementQuoteVersions->pluck('carrier_name'))->filter()->unique()->values()) @php($agreementCooperationSecondaryEsignAccount = '18052733960') @php($agreementDefaultSubject = $agreementSubjects->firstWhere('is_default', true) ?: $agreementSubjects->first()) @php($agreementCompanyName = $agreementDefaultSubject?->name ?: company()?->name ?: '当前公司') @php($agreementSubjectPayload = $agreementSubjects->map(fn ($subject) => ['id' => $subject->id, 'name' => $subject->name, 'unified_social_credit_code' => $subject->unified_social_credit_code, 'is_default' => (bool) $subject->is_default])->values()) @php($esignConfigured = \App\Services\Esign\EsignClient::configured()) +@php($agreementSearch = trim((string) request('agreement_search', ''))) +@php($agreementStatus = trim((string) request('agreement_status', ''))) +@php($agreementType = trim((string) request('agreement_type', ''))) +@php($agreementFiltersActive = $agreementSearch !== '' || $agreementStatus !== '' || $agreementType !== '')
-
{{ $ready ? '正式维护数据' : '数据表尚未就绪' }} {{ $ready ? '报价规则已保存到当前公司数据表,刷新页面后仍会保留;后续结算页面将按启用中的规则计算。' : '附加费报价数据表尚未完成迁移,当前不能保存规则。请由管理员在目标数据库完成迁移后再使用本页。' }}
+
{{ $ready ? '正式维护数据' : '数据表尚未就绪' }} {{ $ready ? '报价规则已保存到当前公司数据表,刷新页面后仍会保留;后续结算页面将按启用中的规则计算。' : ($dataReady && !$auditReady ? '操作日志表尚未完成迁移;现有报价仍可查看,新增、编辑和启停暂时禁用,避免产生无日志修改。' : '附加费报价数据表尚未完成迁移,当前不能保存规则。请由管理员在目标数据库完成迁移后再使用本页。') }}
快递附加费报价
统一维护各快递的附加费结算规则
@@ -71,14 +125,15 @@
筛选报价规则
-
+
+
-
重置
+
重置
@@ -96,18 +151,99 @@
当前筛选结果(全部):{{ $rows->count() }} 条 · 共 {{ $rows->isEmpty() ? 0 : 1 }} 页规则编号与操作列固定显示;列设置仅保存于当前用户
@foreach ($columns as $column) - + @endforeach @forelse ($rows as $row) - - + + @empty - + @endforelse
@if (empty($column['fixed']))@endif{{ $column['label'] }}@if (empty($column['fixed']))@endif{{ $column['label'] }}
{{ $row['id'] }}{{ $row['courier'] }}{{ $row['scope'] }}{{ $row['reconciler'] }}{{ $row['type'] }}{{ $row['mode'] }}{{ $row['standard'] }}{{ $row['condition'] }}{{ $row['effective_at'] }}{{ $row['status'] }}{{ $row['remark'] ?: '—' }}
@csrf
{{ $row['id'] }}{{ $row['courier'] }}{{ $row['scope'] }}{{ $row['reconciler'] }}{{ $row['supplier'] ?: '—' }}{{ $row['type'] }}{{ $row['mode'] }}{{ $row['standard'] }}{{ $row['condition'] }}{{ $row['effective_at'] }}{{ $row['status'] }}{{ $row['remark'] ?: '—' }}
@csrf
没有符合条件的报价规则,请点击“新增报价规则”。
没有符合条件的报价规则,请点击“新增报价规则”。
-
维护建议:固定单价、按重量、按体积、按尺寸/最长边等方式直接维护标准;聚工单客服核实、取发出运费和按账单等方式只维护触发条件,具体金额由后续结算链路读取业务凭证。当前筛选结果可导出为 CSV;本页暂未启用批量导入,避免在未确认字段规则前覆盖维护数据。
+
维护建议:固定单价、按重量、按体积、按尺寸/最长边等方式直接维护标准;聚工单客服核实、取发出运费和按账单等方式只维护触发条件,具体金额由后续结算链路读取业务凭证。批量导入必须先预览校验,已有规则需明确选择跳过或更新。
+
+ +
+
操作日志
请选择报价
+ @if (!$auditReady) +
操作日志表尚未就绪,完成迁移后将从首次新操作开始记录。
+ @else +
请选择上方一条报价
+ + + @endif +
+ +
diff --git a/resources/views/business/pages/courier-payables/quote-change-show.blade.php b/resources/views/business/pages/courier-payables/quote-change-show.blade.php index 121a1f04..ee8a4082 100644 --- a/resources/views/business/pages/courier-payables/quote-change-show.blade.php +++ b/resources/views/business/pages/courier-payables/quote-change-show.blade.php @@ -72,7 +72,7 @@
@if(!$quoteSignature)
该历史报价版本尚未生成签署原文。
- @if($canManageSignature)
@csrf
@endif + @if($canManageSignature)
@csrf
日期将直接写入待签原文。
@endif @else
签署状态
{{ $quoteSignature->statusLabel() }}
@@ -97,6 +97,7 @@
+
diff --git a/resources/views/business/pages/courier-payables/quote-management.blade.php b/resources/views/business/pages/courier-payables/quote-management.blade.php index db87adb4..9aae654d 100644 --- a/resources/views/business/pages/courier-payables/quote-management.blade.php +++ b/resources/views/business/pages/courier-payables/quote-management.blade.php @@ -9,7 +9,9 @@ ->values() ->all(); $quoteTypes = collect($quotes)->pluck('quote_type')->unique()->sort()->values(); - $quoteView = request('quote_view') === 'warehouse' ? 'warehouse' : 'courier'; + $quoteView = in_array(request('quote_view'), ['warehouse', 'reverse-logistics'], true) + ? request('quote_view') + : 'courier'; @endphp
@@ -538,11 +540,11 @@ } .quote-detail-table .quote-detail-table__row-number { - min-width: 3rem; - width: 3rem; + min-width: 3.75rem; + width: 3.75rem; background: #F8F6F1; color: var(--quote-muted); - text-align: right; + text-align: center; } .quote-detail-table__formula { @@ -654,6 +656,9 @@ + + + + @endif +
diff --git a/resources/views/business/pages/courier-payables/shipping-data.blade.php b/resources/views/business/pages/courier-payables/shipping-data.blade.php index 3f1f6f6e..052e948f 100644 --- a/resources/views/business/pages/courier-payables/shipping-data.blade.php +++ b/resources/views/business/pages/courier-payables/shipping-data.blade.php @@ -1,7 +1,7 @@ @php $filters = $shippingFilters ?? []; $sync = $shippingSync ?? ['code' => 'unavailable', 'last_succeeded_at' => null]; - $statusLabels = ['succeeded' => '数据新鲜', 'running' => '同步中', 'pending' => '等待同步', 'failed' => '同步失败', 'unavailable' => '尚未同步']; + $statusLabels = ['succeeded' => '数据新鲜', 'partial' => !empty($sync['freight_pending']) ? '部分数据已同步 · 运费待补' : '部分数据已同步 · 商品或金额待核对', 'running' => '同步中', 'pending' => '等待同步', 'failed' => '同步失败', 'unavailable' => '尚未同步']; // 按工作平台发货数据界面顺序的 47 列: [列key, 表头, 对齐, 类型] $columns = [ @@ -120,10 +120,14 @@
{{ $statusLabels[$sync['code'] ?? 'unavailable'] ?? '状态未知' }} - @if (!empty($sync['last_succeeded_at'])) 最近同步 {{ $sync['last_succeeded_at'] }} @endif + @if (!empty($sync['last_succeeded_at'])) {{ ($sync['code'] ?? '') === 'partial' ? '最近成功同步' : '最近同步' }} {{ $sync['last_succeeded_at'] }} @endif
+ @if (!empty($sync['warning'])) +
{{ $sync['warning'] }}
+ @endif + @if (!empty($shippingError))
{{ $shippingError }}
@endif diff --git a/resources/views/business/pages/courier-payables/summary-table.blade.php b/resources/views/business/pages/courier-payables/summary-table.blade.php new file mode 100644 index 00000000..1f9eaa2f --- /dev/null +++ b/resources/views/business/pages/courier-payables/summary-table.blade.php @@ -0,0 +1,300 @@ +@php + $courierSummaryImportTemplate = [ + 'freight-difference' => [ + 'dialog_title' => '导入运费差', + 'template_name' => '运费差导入模板', + 'field_count' => 11, + ], + 'other-surcharge-summary' => [ + 'dialog_title' => '导入其他附加费汇总', + 'template_name' => '其他附加费导入模板', + 'field_count' => 11, + ], + 'return-fee' => [ + 'dialog_title' => '导入退件费', + 'template_name' => '退件费导入模板', + 'field_count' => 11, + ], + ][$courierSummaryPage] ?? null; +@endphp + +
+
+
+ {{ $courierSummaryTitle }} + @if ($courierSummarySourceName) + + {{ $courierSummarySourceName }} · + @if ($courierSummaryHasFilters) + 查询到 {{ number_format($courierSummaryRows->total()) }} 条 / 共 {{ number_format($courierSummarySourceTotal) }} 条 + @else + 共 {{ number_format($courierSummarySourceTotal) }} 条 + @endif + + @else + 共 0 条 + @endif +
+ +
+ + @if (is_string(session('success'))) +
{{ session('success') }}
+ @endif + + @if (is_string(session('error'))) + + @endif + + @if ($errors->has('import')) + + @endif + + @if ($courierSummaryError) + + @endif + +
+ + + + +
+ + + + 重置 + +
+
+ +
+ + + + + @foreach ($courierSummaryHeaders as $header) + + @endforeach + + + + @forelse ($courierSummaryRows as $rowIndex => $row) + + + @foreach ($courierSummaryHeaders as $columnIndex => $header) + + @endforeach + + @empty + + + + @endforelse + +
序号{{ $header }}
{{ ($courierSummaryRows->currentPage() - 1) * $courierSummaryRows->perPage() + $rowIndex + 1 }}{{ ($row[$columnIndex] ?? '') !== '' ? $row[$columnIndex] : '-' }}
+ @if ($courierSummaryHasFilters && $courierSummarySourceTotal > 0) + 当前查询条件下没有匹配数据。 + @else + 暂无数据,请先点击“导入”上传汇总表。 + @endif +
+
+ + @if ($courierSummaryRows->hasPages()) +
+ 第 {{ $courierSummaryRows->currentPage() }} / {{ $courierSummaryRows->lastPage() }} 页 + {{ $courierSummaryRows->onEachSide(1)->links() }} +
+ @endif + + @if ($courierSummaryImportTemplate) + +
+ @csrf +
+
+ {{ $courierSummaryImportTemplate['dialog_title'] }} + 支持 .xlsx、.xls、.csv,单个文件不超过 10 MB +
+ +
+
+
+ +
+ {{ $courierSummaryImportTemplate['template_name'] }} + .xlsx · {{ $courierSummaryImportTemplate['field_count'] }} 个字段 +
+ + + 下载模板 + +
+ + +
+
+ + +
+
+
+ @endif +
+ + + +@if ($courierSummaryImportTemplate) + +@endif diff --git a/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php b/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php index d192f2f3..4992a695 100644 --- a/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php +++ b/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php @@ -87,19 +87,6 @@ : (is_countable($rows) ? count($rows) : 0); $summaryReady = ! $pending && collect(['count', 'opening_qty', 'closing_qty']) ->every(static fn (string $key): bool => array_key_exists($key, $summary)); - $settlement = [ - 'ready' => false, 'complete' => false, - 'inbound_fee' => 0, 'outbound_fee' => 0, 'storage_fee' => 0, 'total_fee' => 0, - 'message' => null, - ]; - if ($summaryReady) { - try { - $settlement = app(\Modules\EcommerceFinance\Services\ThirdPartyWarehouseStorageSettlementService::class)->settle($filters); - } catch (\Throwable) { - $settlement['message'] = '仓储费暂时无法核算,请稍后重试。'; - } - } - $settlementComplete = ($settlement['ready'] ?? false) && ($settlement['complete'] ?? false); $showingLastVersion = $rowTotal > 0 && ($error !== '' || in_array($statusCode, [ 'syncing', 'reconciling', 'stale', 'delayed', 'failed', ], true)); @@ -108,7 +95,6 @@ $filters, static fn (mixed $value): bool => $value !== null && $value !== '' ); - $settlementExportUrl = route('business.courier-payables.third-party-warehouse-storage.settlement-export', $activeFilters); if (is_object($rows) && method_exists($rows, 'appends')) { $rows->appends($activeFilters); } @@ -233,7 +219,7 @@ .third-party-warehouse-actions [data-finance-server-export] { display:none; } .third-party-warehouse-page[data-finance-enhanced] .third-party-warehouse-actions [data-finance-server-export] { display:inline-flex; } .third-party-warehouse-page .finance-table-field-picker__panel { right:0; left:auto; } - .third-party-warehouse-summary { display:grid; grid-template-columns:repeat(7,minmax(8rem,1fr)); overflow:hidden; border:1px solid var(--warehouse-border); border-radius:.5rem; background:#fff; } + .third-party-warehouse-summary { display:grid; grid-template-columns:repeat(3,minmax(8rem,1fr)); overflow:hidden; border:1px solid var(--warehouse-border); border-radius:.5rem; background:#fff; } .third-party-warehouse-summary__item { min-width:0; padding:.625rem .75rem; border-right:1px solid var(--warehouse-border); } .third-party-warehouse-summary__item:last-child { border-right:0; } .third-party-warehouse-summary__label { display:block; color:var(--warehouse-muted); font-size:.7rem; } @@ -377,13 +363,6 @@ - $settlementComplete, 'is-disabled' => ! $settlementComplete]) - href="{{ $settlementComplete ? $settlementExportUrl : '#' }}" - @if (! $settlementComplete) aria-disabled="true" @endif - > - 导出仓储费核算 -
- @if (! empty($settlement['message'])) -
- - {{ $settlement['message'] }} -
- @endif -
+ @include('business.pages.partials.upstream-data-styles') + @include('business.pages.partials.multi-select') + @include('business.pages.partials.date-range-picker') + + +

账单明细

+
+ 数据源=各平台已导入账单(与「店铺收款账户账单」同源);财务备注、财务类型由科目映射表按「平台+账单项目(wx 自动去前缀)」带出,匹配不到的留空并标红。 +
+ + + {{-- 多选筛选:一个都不勾=全部;勾选结果由 multi-select 写成 name[] 隐藏域随表单提交 --}} +
+ 平台 + + + + + +
+
+ 店铺 + + + + + +
+
+ 账单项目 + + + + + +
+
+ 财务类型 + + + + + +
+
+ 发生时间 +
+ + + + + + + 至 + + + + + + +
+
+ +
+ + 重置 +
+ + +
+
+
收入合计
+
¥{{ number_format($summary['income'], 2) }}
+
{{ number_format($summary['rows']) }} 笔交易
+
+
+
支出合计
+
¥{{ number_format($summary['expense'], 2) }}
+
按当前筛选
+
+
+
收支差额
+
¥{{ number_format($summary['net'], 2) }}
+
收入合计 - 支出合计
+
+
+
交易笔数
+
{{ number_format($summary['rows']) }}
+
当前筛选结果
+
+
+ + @if (! empty($error)) +
{{ $error }}
+ @else +
+
账单明细{{ number_format($summary['rows']) }} 条
+
+ + +
+ + +
+
+
+ +
+
+ + + + + + + + + + + @forelse ($rows as $row) + + + + + + + + + + + + + + + + + @empty + + @endforelse + +
记录编码店铺财务备注线上单号金额账单项目商户订单号自定义备注财务类型类型发生时间收入金额支出金额备注
{{ $row['record_code'] }}{{ $row['store_name'] }}{!! $row['finance_remark'] !== '' ? e($row['finance_remark']) : '—' !!}{{ $row['online_order_no'] }}{{ number_format((float) $row['income'] - (float) $row['expense'], 2) }}{{ $row['bill_item'] }}{{ $row['merchant_order_no'] }}{{ $row['custom_remark'] }}{!! $row['finance_type'] !== '' ? '' . e($row['finance_type']) . '' : '—' !!}{{ $row['type_text'] }}{{ $row['occurred_at'] }}{{ $row['income'] > 0 ? number_format((float) $row['income'], 2) : '' }}{{ $row['expense'] > 0 ? number_format((float) $row['expense'], 2) : '' }}{{ $row['remark'] }}
当前条件下没有数据。
+
+ +
+
第 {{ $rows->firstItem() ?? 0 }} - {{ $rows->lastItem() ?? 0 }} 条 / 共 {{ number_format($rows->total()) }} 条
+
+ + @if ($rows->onFirstPage()) + « + ‹ + @else + « + ‹ + @endif + {{ $rows->currentPage() }} / {{ max($rows->lastPage(), 1) }} + @if ($rows->hasMorePages()) + › + » + @else + › + » + @endif +
+
+ @endif + + +
diff --git a/resources/views/business/pages/financial-risk-control/index.blade.php b/resources/views/business/pages/financial-risk-control/index.blade.php new file mode 100644 index 00000000..e09776a2 --- /dev/null +++ b/resources/views/business/pages/financial-risk-control/index.blade.php @@ -0,0 +1,739 @@ +@php + $platforms = $storeViolationPlatforms ?? []; + $activePlatform = $storeViolationActivePlatform ?? (string) array_key_first($platforms); + $panels = $storeViolationPanels ?? []; + $filters = $storeViolationFilters ?? []; + $filterOptions = $storeViolationFilterOptions ?? ['statuses' => [], 'handling_statuses' => [], 'categories' => [], 'shops' => []]; + $platformCounts = array_map('intval', $storeViolationPlatformCounts ?? []); + $sync = $storeViolationSync ?? ['code' => 'pending', 'last_succeeded_at' => null, 'row_count' => 0, 'last_error' => null]; + $error = $storeViolationError ?? null; + $preview = $storeViolationPreview ?? null; + $columns = config('store_violations.columns', []); + $handlingStatuses = config('store_violations.handling_statuses', []); + $hasFilters = collect($filters)->contains(static fn ($value): bool => is_string($value) && $value !== ''); + $handlingTone = static fn (string $status): string => match ($status) { + '已处理' => 'is-success', + '处理中' => 'is-info', + '无需处理' => 'is-muted', + default => 'is-warning', + }; + $previewTone = static fn (string $status): string => match ($status) { + 'new' => 'is-success', + 'update' => 'is-info', + 'same' => 'is-muted', + default => 'is-danger', + }; + $previewLabels = ['new' => '新增', 'update' => '更新', 'same' => '一致', 'invalid' => '错误']; +@endphp + + + +
+ @include('business.pages.partials.upstream-data-styles') + + + + @foreach ($platforms as $slug => $platform) + @php + $panel = $panels[$slug] ?? null; + $rows = $panel['rows'] ?? null; + $total = (int) ($panel['total'] ?? 0); + $platformTotal = (int) ($platformCounts[$slug] ?? 0); + $label = $platform['label'] ?? $slug; + @endphp + + + @endforeach +
+ + diff --git a/resources/views/business/pages/financial-risk-control/store-violation-alert.blade.php b/resources/views/business/pages/financial-risk-control/store-violation-alert.blade.php new file mode 100644 index 00000000..6cc9596f --- /dev/null +++ b/resources/views/business/pages/financial-risk-control/store-violation-alert.blade.php @@ -0,0 +1 @@ +@include('business.pages.financial-risk-control.index') diff --git a/resources/views/business/pages/financial-rules/account-mapping.blade.php b/resources/views/business/pages/financial-rules/account-mapping.blade.php new file mode 100644 index 00000000..3a56480c --- /dev/null +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -0,0 +1,1487 @@ +@php + // 数据由 Pages::contentForAccountMapping() 注入: + // $amRows 每条规则 + 该行的校验问题 + // $amSummary 汇总(总数 / 错误行 / 警告行 / 提示数) + // $amOptions 筛选项(平台 / 大类 / 基准 / 票据) + // $amError 数据层读取失败时的提示 + $amRows = $amRows ?? []; + $amSummary = $amSummary ?? ['total' => 0, 'error_rows' => 0, 'warning_rows' => 0, 'ok_rows' => 0, 'error_count' => 0, 'warning_count' => 0, 'tip_count' => 0]; + $amOptions = $amOptions ?? ['platforms' => [], 'categories' => [], 'basis' => [], 'invoices' => []]; + $amError = $amError ?? null; + + $platforms = $amOptions['platforms'] ?? []; + $categories = $amOptions['categories'] ?? []; + $outBase = 0; + $inBase = 0; + foreach ($amRows as $r) { + if (($r['basis'] ?? '') === '支出基准') { $outBase++; } + if (($r['basis'] ?? '') === '收入基准') { $inBase++; } + } +@endphp + +
+ @include('business.pages.partials.upstream-data-styles') + + + +
+
这张表的用法:科目对固定,借贷方向随账单收支走
+ 每条规则只锁定「走哪两个科目」和「方向基准」两件事。实际记账时,按这笔账单在平台上的实际收支代入: +
+ · 基准为 支出基准 的项目 —— 账单支出时照抄表内方向;账单收入(返还 / 退回)时借贷互换。 +
+ · 基准为 收入基准 的项目 —— 账单收入时照抄表内方向;账单支出(退款 / 冲减)时借贷互换。 +
+ · 同一个账单项目在业务上不是同一件事时,用财务备注/商品名称关键词区分:财务备注匹配账单的二次备注、账务备注等(202607订单 这类月份式备注不参与匹配),商品名称按包含匹配;两个都填最优先,其次商品名称,再次财务备注,都不填就是兜底规则。 +
+ 点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行;有新增账单项目时用「导入」追加。 +
+ + @if ($amError) +
读取映射表失败:{{ $amError }}
+ @endif + +
+
+ 共 {{ $amSummary['total'] }} 条规则 + 支出基准 {{ $outBase }} + 收入基准 {{ $inBase }} + 平台 {{ count($platforms) }} 个 + | + 校验:{{ $amSummary['error_rows'] }} 行有错误 · + {{ $amSummary['warning_rows'] }} 行有警告 · + {{ $amSummary['tip_count'] }} 条提示 +
+
+ +
+ +
+ 账单项目 + + + + +
+
+ 平台 + + + + +
+
+ 财务类型 + + + + +
+
+ 方向基准 + + + + +
+ +
+ + + + + + + +
+
+ +
+
+ + + + + + + + + + + + + + + + + + +
序号平台账单项目财务备注商品名称关键词票据财务类型借方科目贷方科目方向基准校验操作
+
+ +
+
+ + + + + + + + diff --git a/resources/views/business/pages/fund-management/withdrawal-management.blade.php b/resources/views/business/pages/fund-management/withdrawal-management.blade.php index f4da90c1..f0b3d0f6 100644 --- a/resources/views/business/pages/fund-management/withdrawal-management.blade.php +++ b/resources/views/business/pages/fund-management/withdrawal-management.blade.php @@ -1,19 +1,69 @@ -
+@php + $withdrawalImportPreview = session('withdrawalImportPreview'); + $withdrawalOpenImport = is_array($withdrawalImportPreview) || $errors->hasAny(['import', 'preview_token']); + $withdrawalFilterQuery = array_filter( + request()->only(['platform', 'withdrawal_path', 'store_entity', 'keyword', 'balance_status']), + static fn ($value): bool => filled($value), + ); + $withdrawalQuery = array_filter( + request()->only(['platform', 'withdrawal_path', 'store_entity', 'keyword', 'balance_status', 'sort', 'direction']), + static fn ($value): bool => filled($value), + ); + $withdrawalSortUrl = static function (string $field, string $direction) use ($withdrawalFilterQuery): string { + $query = http_build_query(array_merge($withdrawalFilterQuery, [ + 'sort' => $field, + 'direction' => $direction, + ])); + + return request()->url() . '?' . $query; + }; + $withdrawalColumns = [ + ['key' => 'platform', 'label' => '店铺平台', 'numeric' => false, 'title' => null], + ['key' => 'erp_store_name', 'label' => 'ERP店铺名称', 'numeric' => false, 'title' => null], + ['key' => 'store_id', 'label' => '平台店铺ID', 'numeric' => false, 'title' => null], + ['key' => 'store_entity', 'label' => '店铺主体', 'numeric' => false, 'title' => null], + ['key' => 'withdrawal_path', 'label' => '提现路径', 'numeric' => false, 'title' => null], + ['key' => 'withdrawal_account', 'label' => '提现账户名称', 'numeric' => false, 'title' => null], + ['key' => 'bank_card', 'label' => '银行卡号', 'numeric' => false, 'title' => null], + ['key' => 'balance', 'label' => $withdrawalBalanceColumnLabel, 'numeric' => true, 'title' => '余额数据日期:' . $withdrawalBalanceDate], + ['key' => 'reserve_standard', 'label' => '预留标准', 'numeric' => true, 'title' => null], + ['key' => 'withdrawal_amount', 'label' => '提现金额', 'numeric' => true, 'title' => null], + ['key' => 'compliance', 'label' => '是否达标', 'numeric' => false, 'title' => null], + ]; +@endphp + +
-
- - 提现配置 +
+
+ + 提现配置 +
+
+ 余额源 {{ number_format($withdrawalBalanceSummary['source']) }} 条 + 已显示余额 {{ number_format($withdrawalBalanceSummary['matched']) }} 条 + @if ($withdrawalBalanceSummary['ambiguous'] > 0) + 多条匹配 {{ number_format($withdrawalBalanceSummary['ambiguous']) }} 条 + @endif +
-
- 余额源 {{ number_format($withdrawalBalanceSummary['source']) }} 条 - 已显示余额 {{ number_format($withdrawalBalanceSummary['matched']) }} 条 - @if ($withdrawalBalanceSummary['ambiguous'] > 0) - 多条匹配 {{ number_format($withdrawalBalanceSummary['ambiguous']) }} 条 - @endif +
+ + + + 导出 +
+ @if ($withdrawalSort['field'] !== '') + + + @endif
+
+ + +
@@ -47,26 +106,49 @@
- @if (request()->hasAny(['platform', 'withdrawal_path', 'keyword', 'balance_status'])) + @if (request()->hasAny(['platform', 'withdrawal_path', 'store_entity', 'keyword', 'balance_status'])) 重置 @endif
- +
- - - - - - - - - - - + @foreach ($withdrawalColumns as $column) + + @endforeach @@ -85,19 +167,30 @@ $balanceTitle = $balanceMatch['status'] === 'matched' ? '聚水潭店铺:' . $balanceMatch['source_store_name'] . ';余额日期:' . $withdrawalBalanceDate : '余额日期:' . $withdrawalBalanceDate; + $reserveStandard = $withdrawalReserveStandards[(int) $row->id] ?? null; + $withdrawalAmount = $withdrawalAmounts[(int) $row->id] ?? null; + $compliance = $withdrawalCompliance[(int) $row->id] ?? null; @endphp - - - - - - - - - - - + + + + + + + + + + + @empty @@ -111,6 +204,42 @@ @endforelse
店铺平台ERP店铺名称平台店铺ID店铺主体提现路径提现账户名称银行卡号{{ $withdrawalBalanceColumnLabel }}预留标准提现金额是否达标 $column['numeric']]) + data-withdrawal-column="{{ $column['key'] }}" + @if ($column['title']) title="{{ $column['title'] }}" @endif + @if ($withdrawalSort['field'] === $column['key']) aria-sort="{{ $withdrawalSort['direction'] === 'asc' ? 'ascending' : 'descending' }}" @endif + > +
+ {{ $column['label'] }} + +
+
{{ $row->store_platform ?: '未配置' }}{{ $row->erp_store_name ?: '-' }}{{ $row->store_id ?: '-' }}{{ $row->store_entity_name ?: '-' }}{{ $row->withdrawal_path ?: '未配置' }}{{ $row->withdrawal_account_name ?: '未配置' }}{{ $bankCard }}{{ $balanceText }}待配置待接入待核验{{ $row->store_platform ?: '未配置' }}{{ $row->erp_store_name ?: '-' }}{{ $row->store_id ?: '-' }}{{ $row->store_entity_name ?: '-' }}{{ $row->withdrawal_path ?: '未配置' }}{{ $row->withdrawal_account_name ?: '未配置' }}{{ $bankCard }}{{ $balanceText }}{{ $reserveStandard === null ? '待配置' : number_format($reserveStandard, 2) }}{{ $withdrawalAmount === null ? '待接入' : number_format($withdrawalAmount, 2) }} + @if ($compliance === 'yes') + 是 + @elseif ($compliance === 'no') + 否 + @else + 待核验 + @endif +
+ +
@@ -128,4 +257,285 @@ @endif
+ +
+ + + + + + diff --git a/resources/views/business/pages/partials/date-range-picker.blade.php b/resources/views/business/pages/partials/date-range-picker.blade.php new file mode 100644 index 00000000..a8712f85 --- /dev/null +++ b/resources/views/business/pages/partials/date-range-picker.blade.php @@ -0,0 +1,324 @@ +{{-- + 开始日期 ─ 至 ─ 结束日期 的日历选择控件(与「小额打款」页同一套交互)。 + 用法: +
+ 发生时间 +
+ + + + + + + 至 + … +
+
+ window.CaiWuDatePicker.setup(document.getElementById('pdFilterForm')); + 说明:样式与脚本目前与退款 › 小额打款工单页保持一致(那页是内联实现), + 后续如要合并,把那边也改成引用本 partial。 +--}} + + diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php index 70f37587..97b46b10 100644 --- a/resources/views/business/pages/partials/directory-table.blade.php +++ b/resources/views/business/pages/partials/directory-table.blade.php @@ -1,6 +1,11 @@ @php $directoryRows = $rows ?? collect(); $directoryFields = $directory['fields'] ?? []; + $isInventoryReportPage = ($page['slug'] ?? '') === 'inventory-report'; + $inventoryWarehouseMappings = $isInventoryReportPage + ? ($inventoryWarehouseMappings ?? collect()) + : collect(); + $warehouseMappingPreview = $isInventoryReportPage ? session('warehouse_mapping_preview') : null; // “最近三个月销量”必须是三个独立的月份列;月份按当前月向前取三个完整月份。 // 保留原字段名作为兼容契约,渲染时展开为 *_1、*_2、*_3 三个值。 $directoryFields = collect($directoryFields)->flatMap(function (array $field): array { @@ -18,11 +23,44 @@ ]; })->all(); })->values()->all(); + // 字段配置里带 group 的目录表按 Excel 样式渲染两层合并表头:同组字段共用一个一级标题, + // 未分组的列标题跨两行显示,列顺序固定为配置顺序。 + $directoryHasGroupedHeader = collect($directoryFields)->contains(fn (array $field): bool => filled($field['group'] ?? null)); + $directoryLastFieldName = collect($directoryFields)->last()['name'] ?? null; $directoryIsPaginated = is_object($directoryRows) && method_exists($directoryRows, 'total'); $directoryTotal = $directoryIsPaginated ? $directoryRows->total() : (is_countable($directoryRows) ? count($directoryRows) : 0); $directoryCurrentPage = $directoryIsPaginated ? $directoryRows->currentPage() : 1; $directoryLastPage = $directoryIsPaginated ? $directoryRows->lastPage() : 1; $directoryPerPage = $directoryIsPaginated ? $directoryRows->perPage() : 0; + // 页面配置在部分导航上下文中会省略父级 slug,优先使用当前路由参数避免功能开关失配。 + $directoryRouteSection = request()->route('section') ?: request()->segment(3) ?: ($section['slug'] ?? ''); + $directoryRoutePage = request()->route('page') ?: request()->segment(4) ?: ($page['slug'] ?? ''); + $directoryPageKey = (string) $directoryRouteSection . '/' . (string) $directoryRoutePage; + $directoryUsesFieldQuery = in_array($directoryPageKey, [ + 'company-management/basic-information', + 'store-management/basic-information', + 'trademark-management/information', + 'store-management/store-accounts', + 'store-management/store-report', + 'company-management/subject-operating-report', + 'company-management/company-cost-arrangement', + 'company-management/tax-forecast', + 'company-management/personnel-inventory', + 'store-management/internal-flow-report', + ], true); + $directoryQueryPageDescriptions = [ + 'company-management/basic-information' => '公司主体、状态和登记资料的查询与导出', + 'store-management/basic-information' => '店铺主体、平台和经营资料的查询与导出', + 'trademark-management/information' => '商标主体、状态和登记资料的查询与导出', + 'store-management/store-accounts' => '店铺账号资料的查询与安全状态导出', + 'store-management/store-report' => '按店铺、主体和月份销量查询经营数据并导出', + 'company-management/subject-operating-report' => '按主体和收入月份查询经营汇总并导出', + 'company-management/company-cost-arrangement' => '按公司类型和发票类型查询成本安排字段', + 'company-management/tax-forecast' => '按税务类型、工商类型和征收方式查询税金预测口径;规则参数在「规则信息 → 税金预测表逻辑配置」维护', + 'company-management/personnel-inventory' => '按人员、职位和公司类型查询人员盘点字段', + 'product-inventory/monthly-weighted-average-price' => '按月份、商品编码、仓储方和分类查询商品月加权平均单价', + 'store-management/internal-flow-report' => '按抬头、标签查询内部流转明细并导出', + ]; @endphp
-
-
- + @if ($directoryUsesFieldQuery) +
- {{ $page['title'] ?? $section['title'] }} · 字段结构 - @if (!empty($directory['description'])) -

{{ $directory['description'] }}

- @endif + {{ $page['title'] ?? $section['title'] }} +

{{ $directoryQueryPageDescriptions[$directoryPageKey] ?? '基础资料的查询与导出' }}

-
- {{ $directory['status'] ?? '尚未同步' }} -
+ {{ $directory['status'] ?? '尚未同步' }} + + @if (!empty($upstreamError)) + + @elseif ($directoryTotal > 0 && in_array($directoryPageKey, ['store-management/store-accounts', 'store-management/store-report', 'company-management/subject-operating-report', 'company-management/company-cost-arrangement', 'company-management/personnel-inventory'], true)) +
+ + 已从共享业务镜像读取 {{ $directoryTotal }} 条数据,当前页面为只读展示。 +
+ @endif + @else + @if ($isInventoryReportPage) + +
+ @else +
+
+ +
+ {{ $page['title'] ?? $section['title'] }} · 字段结构 + @if (!empty($directory['description'])) +

{{ $directory['description'] }}

+ @endif +
+
+ {{ $directory['status'] ?? '尚未同步' }} +
+ @endif @if (!empty($upstreamError)) + @elseif (($directory['status'] ?? null) === '演示数据' && $directoryTotal > 0) +
+ + 已按附件模板导入 {{ $directoryTotal }} 条演示数据,当前页面为只读展示。 +
@elseif ($directoryTotal > 0)
@@ -390,9 +1027,268 @@ {{ $directory['empty'] ?? '数据尚未同步,当前只展示已确认的字段结构。' }}
@endif + @endif + + @if (($page['slug'] ?? '') === 'performance-details' && !empty($receiptStats)) + {{-- 匹配统计:账单笔数、成功/未匹配笔数、双方收入合计核对结果 --}} +
+ 账单收款笔数{{ number_format($receiptStats['payments']) }} + 账单订单数{{ number_format($receiptStats['rows']) }} + 已匹配{{ number_format($receiptStats['orders_matched']) }} + 未匹配{{ number_format($receiptStats['orders_unmatched']) }} + 一单多笔{{ number_format($receiptStats['orders_multi_pay']) }} + 账单收入合计{{ number_format((float) $receiptStats['income_total'], 2) }} + 订单商品金额合计{{ number_format((float) $receiptStats['goods_total'], 2) }} + 差额合计(已匹配){{ number_format((float) $receiptStats['difference_total'], 2) }} +
+ @endif @if (!empty($directoryFields)) - @if (($page['slug'] ?? '') === 'store-report') + @php + $directoryQueryFields = match ($directoryPageKey) { + 'company-management/basic-information' => [ + ['name' => 'unified_social_credit_code', 'label' => '统一社会信用代码', 'placeholder' => '输入完整或部分代码'], + ['name' => 'company_name', 'label' => '公司名称', 'placeholder' => '输入公司名称关键词'], + ['name' => 'taxpayer_type', 'label' => '纳税人类型'], + ['name' => 'company_status', 'label' => '公司状态'], + ['name' => 'legal_representative', 'label' => '法人', 'placeholder' => '按姓名查询'], + ['name' => 'city', 'label' => '城市', 'placeholder' => '城市较多,使用搜索'], + ['name' => 'related_people', 'label' => '相关人员', 'placeholder' => '输入人员姓名,模糊匹配'], + ['name' => 'company_type', 'label' => '公司类型'], + ], + 'product-inventory/monthly-weighted-average-price' => [ + ['name' => 'month', 'label' => '月份', 'kind' => 'date'], + ['name' => 'product_code', 'label' => '商品编码', 'placeholder' => '按商品编码精确查询'], + ['name' => 'warehouse_provider', 'label' => '仓储方', 'placeholder' => '支持包含查询'], + ['name' => 'category', 'label' => '分类', 'placeholder' => '支持包含查询'], + ], + 'store-management/internal-flow-report' => [ + ['name' => 'company_name', 'label' => '抬头', 'placeholder' => '输入公司名称关键词'], + ['name' => 'tag', 'label' => '标签'], + ], + 'company-management/tax-forecast' => [ + ['name' => 'company_name', 'label' => '公司名称', 'placeholder' => '输入公司名称关键词'], + ['name' => 'taxpayer_type', 'label' => '公司税务类型'], + ['name' => 'business_registration_type', 'label' => '工商类型'], + ['name' => 'collection_method', 'label' => '征收方式'], + ['name' => 'forecast_month', 'label' => '预测月份', 'placeholder' => '例如 2026-10'], + ], + default => $directoryFields, + }; + $directoryExcludedQueryFields = match ($directoryPageKey) { + 'store-management/basic-information' => ['opened_at', 'renewed_at'], + 'trademark-management/information' => ['registration_date', 'expiry_date'], + default => [], + }; + if (!empty($directoryExcludedQueryFields)) { + $directoryQueryFields = collect($directoryQueryFields) + ->reject(fn (array $field): bool => in_array( + $field['name'], + $directoryExcludedQueryFields, + true, + )) + ->values() + ->all(); + } + $directoryMoreQueryFields = collect($directoryQueryFields) + ->filter(function (array $field) use ($directoryPageKey): bool { + $kind = $field['kind'] ?? 'text'; + + return in_array($directoryPageKey, [ + 'store-management/store-report', + 'company-management/subject-operating-report', + 'company-management/company-cost-arrangement', + 'company-management/personnel-inventory', + ], true) && in_array($kind, ['date', 'number', 'integer', 'secret', 'secret_status'], true); + }) + ->values() + ->all(); + $directoryPrimaryQueryFields = collect($directoryQueryFields) + ->reject(fn (array $field): bool => in_array($field['name'], array_column($directoryMoreQueryFields, 'name'), true)) + ->values() + ->all(); + $directorySelectFields = match (($section['slug'] ?? '') . '/' . ($page['slug'] ?? '')) { + 'company-management/basic-information' => ['taxpayer_type', 'company_status', 'company_type'], + 'store-management/basic-information' => ['platform', 'store_status', 'withdrawal_account'], + 'trademark-management/information' => ['trademark_status'], + 'store-management/store-accounts' => ['account_type', 'password_configured'], + 'store-management/store-report' => ['status', 'can_change', 'company_type'], + 'company-management/subject-operating-report' => ['company_type', 'can_change_entity'], + 'company-management/company-cost-arrangement' => ['company_type', 'invoice_type'], + 'company-management/tax-forecast' => ['taxpayer_type', 'business_registration_type', 'collection_method'], + 'company-management/personnel-inventory' => ['company_type'], + 'store-management/internal-flow-report' => ['tag'], + default => [], + }; + $directoryColumnNames = collect($directoryFields)->pluck('name')->all(); + $requestedDirectoryColumns = array_values(array_intersect( + array_filter(explode(',', (string) request('columns', ''))), + $directoryColumnNames, + )); + // 主体维度经营报表:没有数据的月份列默认隐藏,仍保留在「筛选字段」中供手动勾选显示。 + $directoryDefaultColumns = $directoryColumnNames; + if ($directoryPageKey === 'company-management/subject-operating-report') { + $directoryDefaultColumns = array_values(array_diff( + $directoryColumnNames, + (array) request()->attributes->get('subject-operating-report.default_hidden_columns', []), + )); + } + $visibleDirectoryColumns = request()->has('columns') ? $requestedDirectoryColumns : $directoryDefaultColumns; + $directoryQueryFormId = 'directory-query-form-' . ($page['slug'] ?? 'page'); + @endphp + @if ($directoryUsesFieldQuery) +
+
+ 查询条件 + 类型较少的字段直接选择,内容较多的字段支持关键词搜索 +
+
+ @if (request()->has('columns')) + + @endif + @foreach ($directoryPrimaryQueryFields as $field) + @php $kind = $field['kind'] ?? 'text'; @endphp + @continue($kind === 'secret' && $field['name'] !== 'withdrawal_account') + @continue(($page['slug'] ?? '') === 'store-accounts' && in_array($field['name'], [ + 'account', + 'password_configured', + 'bound_phone', + 'verification_contact', + 'account_group_name', + 'created_at', + 'updated_at', + ], true)) + + @endforeach + @if ($directoryMoreQueryFields !== []) +
+ 更多查询条件({{ count($directoryMoreQueryFields) }}) +
+ @foreach ($directoryMoreQueryFields as $field) + @php $kind = $field['kind'] ?? 'text'; @endphp + @continue($kind === 'secret' && $field['name'] !== 'withdrawal_account') + @continue(($page['slug'] ?? '') === 'store-accounts' && in_array($field['name'], [ + 'account', + 'password_configured', + 'bound_phone', + 'verification_contact', + 'account_group_name', + 'created_at', + 'updated_at', + ], true)) + + @endforeach +
+
+ @endif +
+
+ 筛选字段{{ count($visibleDirectoryColumns) < count($directoryFields) ? ' ' . count($visibleDirectoryColumns) . '/' . count($directoryFields) : '' }} +
+ 勾选需要显示的表头,可重复调整。 + @foreach ($directoryFields as $field) + + @endforeach +
+
+ + +
+ 导出 Excel +
+ 默认全选,可取消不需要导出的表头。 + @foreach ($directoryFields as $field) + + @endforeach + +
+
+
+
+ @endif + @if (($page['slug'] ?? '') === 'store-report' && ! $directoryUsesFieldQuery)
@php $storeFilterTextFields = [ @@ -447,39 +1343,235 @@ 清除
+ @elseif (($page['slug'] ?? '') === 'performance-details') +
+ + + + +
+ + 清除 +
+
+ @elseif (in_array(($page['slug'] ?? ''), ['inventory-report', 'monthly-weighted-average-price'], true)) +
+ + + + +
+ + 清除 +
+
@endif -
+@if (! $directoryUsesFieldQuery) + @php + $directoryMonthOptions = []; + if ($directoryHasGroupedHeader) { + $directoryMonthOptions = \Illuminate\Support\Facades\DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->table('product_monthly_weighted_average_states') + ->where('status', 'computed') + ->orderByDesc('report_month') + ->pluck('report_month') + ->map(static fn ($month): string => substr((string) $month, 0, 10)) + ->all(); + } + $directoryActiveMonth = substr(trim((string) request('month', '')), 0, 10) ?: ($directoryMonthOptions[0] ?? ''); + @endphp +
- - - + @if (in_array(($page['slug'] ?? ''), ['inventory-report', 'monthly-weighted-average-price', 'performance-details'], true)) + + + + @else +
+ + + + +
+ + + @endif
+ @endif
- +
- - @foreach ($directoryFields as $field) - - @endforeach + @unless ($directoryHasGroupedHeader) + + @endunless + @if ($directoryHasGroupedHeader) + @php + $groupedHeaderRuns = []; + foreach ($directoryFields as $field) { + $group = $field['group'] ?? null; + $lastIndex = count($groupedHeaderRuns) - 1; + if ($group !== null && $lastIndex >= 0 && $groupedHeaderRuns[$lastIndex]['group'] === $group) { + $groupedHeaderRuns[$lastIndex]['fields'][] = $field; + } else { + $groupedHeaderRuns[] = ['group' => $group, 'fields' => [$field]]; + } + } + @endphp + @foreach ($groupedHeaderRuns as $headerRun) + @if ($headerRun['group'] === null) + @foreach ($headerRun['fields'] as $field) + + @endforeach + @else + + @endif + @endforeach + @else + @foreach ($directoryFields as $field) + + @endforeach + @endif + @if ($directoryHasGroupedHeader) + + @foreach ($directoryFields as $field) + @continue(!isset($field['group'])) + + @endforeach + + @endif @forelse ($directoryRows as $rowIndex => $row) - + @unless ($directoryHasGroupedHeader) + + @endunless @foreach ($directoryFields as $field) @php $source = array_key_exists('source', $field) ? $field['source'] : $field['name']; @@ -496,11 +1588,13 @@ $display = substr((string) $value, 0, 10); } elseif ($kind === 'number' && is_numeric($value)) { $display = number_format((float) $value, 2); + } elseif ($kind === 'integer' && is_numeric($value)) { + $display = number_format((int) $value); } elseif ($kind === 'boolean' && $value !== null && $value !== '') { $display = in_array($value, [true, 1, '1', '是', '✔'], true) ? '是' : '否'; } @endphp - @endforeach @empty -
#{{ $field['label'] }}{{ $directory['index_label'] ?? '序号' }}{{ $field['label'] }}{{ $headerRun['group'] }} + @if ($directoryUsesFieldQuery) + @php + $isSorted = request('sort') === $field['name']; + $direction = $isSorted ? request('direction', 'asc') : null; + $nextDirection = $isSorted && $direction === 'asc' ? 'desc' : 'asc'; + @endphp +
+ {{ $field['label'] }} +
+ +
+ 升序 + 降序 + +
+
+
+ @elseif ($isInventoryReportPage && $field['name'] === 'warehouse_short_name') + + @else + {{ $field['label'] }} + @endif +
{{ $field['label'] }}
{{ $rowIndex + 1 + (($directoryCurrentPage - 1) * $directoryPerPage) }}{{ $rowIndex + 1 + (($directoryCurrentPage - 1) * $directoryPerPage) }} + @if (($page['slug'] ?? '') === 'store-accounts' && $field['name'] === 'password_configured') {{ filled($display) ? $display : '—' }} @if ($value === false) @@ -516,14 +1610,14 @@ @endif @else - {{ filled($display) ? $display : '—' }} + {{ filled($display) ? $display : ($isInventoryReportPage && $field['name'] === 'warehouse_short_name' ? '' : '—') }} @endif
+
{{ !empty($upstreamError) ? '资料暂时无法读取,请按上方提示检查连接;这不代表业务数据为 0。' : ($directory['empty'] ?? '尚未同步数据。') }} @@ -554,6 +1648,321 @@ @endif + @if ($isInventoryReportPage) + + @php + // 入库明细数据:先做只读展示(数据来自 inventory:inbound-detail:import 导入的原始明细)。 + $inboundConnection = (string) config('upstream_mirrors.connection', 'business_mirror'); + $inboundMonths = \Illuminate\Support\Facades\DB::connection($inboundConnection) + ->table('inventory_inbound_detail_rows') + ->selectRaw('report_month, count(*) as total') + ->groupBy('report_month') + ->orderByDesc('report_month') + ->get(); + $inboundMonth = substr(trim((string) request('detail_month', '')), 0, 10); + if ($inboundMonth === '' || ! $inboundMonths->contains(fn ($row): bool => substr((string) $row->report_month, 0, 10) === $inboundMonth)) { + $inboundMonth = $inboundMonths->first() ? substr((string) $inboundMonths->first()->report_month, 0, 10) : ''; + } + $inboundPage = max((int) request('detail_page', 1), 1); + $inboundPerPage = 25; + $inboundWarehouse = trim((string) request('detail_warehouse', '')); + $inboundBarcode = trim((string) request('detail_barcode', '')); + $inboundQuery = \Illuminate\Support\Facades\DB::connection($inboundConnection) + ->table('inventory_inbound_detail_rows'); + if ($inboundMonth !== '') { + $inboundQuery->where('report_month', $inboundMonth); + } + if ($inboundWarehouse !== '') { + $like = '%' . addcslashes($inboundWarehouse, '%_\\') . '%'; + $inboundQuery->where(function ($inner) use ($like): void { + $inner->where('warehouse', 'like', $like)->orWhere('warehouse_short_name', 'like', $like); + }); + } + if ($inboundBarcode !== '') { + $inboundQuery->where('barcode', 'like', '%' . addcslashes($inboundBarcode, '%_\\') . '%'); + } + $inboundTotal = (clone $inboundQuery)->count(); + $inboundRows = $inboundQuery + ->orderBy('row_key') + ->forPage($inboundPage, $inboundPerPage) + ->get(); + $inboundLastPage = max((int) ceil($inboundTotal / $inboundPerPage), 1); + @endphp + + + @endif + @if (($page['slug'] ?? '') === 'subject-operating-report')
@endif + @if (!($productCatalogJushuitanCostPriceHistorySyncStatus['initialized'] ?? false) && !$productCatalogError) +
+ + + @if (($productCatalogJushuitanCostPriceHistorySyncStatus['code'] ?? '') === 'initializing') + 聚水潭成本价记录正在执行首次同步,完成前不显示记录数量。 + @elseif (($productCatalogJushuitanCostPriceHistorySyncStatus['code'] ?? '') === 'initial_failed') + 聚水潭成本价记录首次同步失败,当前记录数量不代表聚水潭真实历史。 + @else + 聚水潭成本价记录尚未完成首次同步,完成前不显示记录数量。 + @endif + +
+ @endif +
@@ -854,6 +878,7 @@ @php $jushuitanHistory = $row->jushuitan_cost_price_history ?? []; $jushuitanHistoryCount = (int) ($row->jushuitan_cost_price_history_count ?? count($jushuitanHistory)); + $jushuitanHistoryInitialized = (bool) ($productCatalogJushuitanCostPriceHistorySyncStatus['initialized'] ?? false); $jushuitanHistoryId = 'product-jushuitan-cost-history-' . (int) ($row->autoid ?? 0); $workPlatformHistory = $row->work_platform_price_history ?? $row->price_change_history ?? []; $workPlatformHistoryCount = (int) ($row->work_platform_price_history_count ?? $row->price_change_history_count ?? count($workPlatformHistory)); @@ -872,12 +897,12 @@ data-cost-price="{{ $row->cost_price ?? '' }}" data-work-platform-price="{{ $row->work_platform_price ?? '' }}" aria-label="查看 {{ $row->sku_id ?? '当前商品' }} 的聚水潭成本价记录" - title="{{ $jushuitanHistoryCount > 0 ? '查看聚水潭成本价记录' : '当前商品暂无聚水潭成本价记录' }}" + title="{{ !$jushuitanHistoryInitialized ? '聚水潭成本价记录尚未完成首次同步' : ($jushuitanHistoryCount > 0 ? '查看聚水潭成本价记录' : '当前商品暂无聚水潭成本价记录') }}" @disabled($jushuitanHistoryCount === 0) > - {{ $jushuitanHistoryCount }} 条 + {{ $jushuitanHistoryInitialized ? $jushuitanHistoryCount . ' 条' : '待同步' }} diff --git a/resources/views/business/pages/product-inventory/online-daifa-price.blade.php b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php index 5abc72de..fabe5791 100644 --- a/resources/views/business/pages/product-inventory/online-daifa-price.blade.php +++ b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php @@ -4,16 +4,19 @@ $status = (string) ($onlineDaifaStatus ?? 'unknown'); $syncedAt = $onlineDaifaSyncedAt ?? null; $summary = $onlineDaifaSummary ?? []; + $sources = $onlineDaifaSources ?? []; $error = $onlineDaifaError ?? null; - $json = static fn (mixed $value): string => is_array($value) - ? (json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) ?: '-') - : (string) ($value ?? '-'); - $statusOptions = \Modules\EcommerceFinance\Services\DingPayableWorkflowStatus::filterOptions(); + $statusOptions = \Modules\EcommerceFinance\Services\DingPayableWorkflowStatus::filterOptions() + [ + 'CONFIRMED' => '已确认(采购单)', + 'FINISHED' => '已完成(采购单)', + ]; $num = static fn (mixed $value): string => $value === null || $value === '' ? '-' : (string) $value; $money = static fn (mixed $value): string => $value === null ? '-' : number_format((float) $value, 2); - $productName = static fn (array $row): string => $row['matched_product']['matched'] ?? false - ? (string) ($row['matched_product']['name'] ?? '-') - : '(未匹配)'; + $productName = static fn (array $row): string => ($row['source_type'] ?? 'ding') === 'purchase' + ? '-' + : (($row['matched_product']['matched'] ?? false) + ? (string) ($row['matched_product']['name'] ?? '-') + : '(未匹配)'); $payeeScope = trim((string) config('upstream_mirrors.ding_online_daifa_price.row_filters.payee_name', '')); @endphp @@ -45,9 +48,6 @@ .online-daifa-table tr:hover td { background:#fcfaf4; } .online-daifa-table .num { text-align:right; font-variant-numeric:tabular-nums; } .online-daifa-table .unmatched { color:var(--vip-danger,#B80000); } - .online-daifa-detail { max-width:26rem; white-space:normal; } - .online-daifa-detail summary { cursor:pointer; color:var(--vip-content-accent-dark,#856632); } - .online-daifa-detail pre { max-width:36rem; max-height:18rem; overflow:auto; margin:.5rem 0 0; padding:.65rem; border:1px solid var(--vip-border,#D8D2C7); background:#faf9f6; white-space:pre-wrap; word-break:break-word; font:inherit; } .online-daifa-empty { padding:4rem 1rem; text-align:center; color:var(--vip-content-muted,#595959); } .online-daifa-pagination { display:flex; justify-content:space-between; padding:.75rem 1rem; color:var(--vip-content-muted,#595959); } .online-daifa-pagination a { color:var(--vip-content-accent-dark,#856632); margin-left:.75rem; } @@ -55,7 +55,7 @@
- +
@@ -102,10 +102,13 @@ @endif
- 固定流程:线上代发业务报销流程(钉钉 OA 审批) + 数据来源:钉钉线上代发审批、聚水潭采购单管理(已确认/已完成) @if ($payeeScope !== '') 固定收款人:{{ $payeeScope }} @endif 镜像状态:{{ $status }} @if ($syncedAt) 最近同步:{{ $syncedAt }} @endif + @foreach ($sources as $source) + {{ $source['label'] ?? '数据源' }}:{{ ($source['ready'] ?? false) ? ($source['status'] ?? 'available') : '同步准备中' }} + @endforeach 共 {{ $rows?->total() ?? 0 }} 条
@@ -113,7 +116,8 @@
代发订单金额合计{{ $money($summary['daifa_amount'] ?? null) }}
订单实付金额合计{{ $money($summary['paid_amount'] ?? null) }}
差价合计{{ $money($summary['price_diff'] ?? null) }}
-
已匹配商品目录{{ (int) ($summary['matched_count'] ?? 0) }} / {{ (int) ($summary['count'] ?? 0) }}
+
采购单管理{{ (int) ($summary['purchase_count'] ?? 0) }}
+
已匹配商品目录{{ (int) ($summary['matched_count'] ?? 0) }} / {{ (int) ($summary['matchable_count'] ?? $summary['count'] ?? 0) }}
@@ -123,7 +127,7 @@
- + @forelse ($rows ?? [] as $row) @@ -139,9 +143,9 @@ - + - + @@ -149,10 +153,9 @@ - @empty - + @endforelse
商品ID商品名称(匹配)店铺名称 代发交易单号店铺交易单号 发货数量订单实付金额代发订单金额差价供应商名称商品编码创建时间原始表单供应商名称商品编码创建时间
{{ $row['tag'] ?? '' }} {{ $num($row['product_id']) }} {{ $productName($row) }}{{ $num($row['shop_name']) }}{{ (($row['source_type'] ?? '') === 'purchase' && !($row['order_matched'] ?? false)) ? '(未匹配订单)' : $num($row['shop_name']) }} {{ $num($row['daifa_trade_no']) }}{{ $num($row['shop_trade_no']) }}{{ (($row['source_type'] ?? '') === 'purchase' && !($row['order_matched'] ?? false)) ? '(未匹配订单)' : $num($row['shop_trade_no']) }} {{ $num($row['ship_qty']) }} {{ $money($row['paid_amount']) }} {{ $money($row['daifa_amount']) }}{{ $num($row['supplier_name']) }} {{ $num($row['material_no']) }} {{ $row['workflow_created_at'] ?? '-' }}
展开表单({{ count($row['scheme'] ?? []) }} 项)
{{ $json($row['scheme'] ?? []) }}
{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }}
{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }}
diff --git a/resources/views/business/pages/refunds/small-payment-work-orders.blade.php b/resources/views/business/pages/refunds/small-payment-work-orders.blade.php index 48f208fa..39aab483 100644 --- a/resources/views/business/pages/refunds/small-payment-work-orders.blade.php +++ b/resources/views/business/pages/refunds/small-payment-work-orders.blade.php @@ -36,6 +36,10 @@ default => '业务镜像尚未建立', }; $lastSucceededAt = $smallPaymentSyncStatus['last_succeeded_at'] ?? null; + // 日期控件只承载日期:时区无关,服务端会把纯日期补成整天半开区间(from 00:00:00 / to 次日 00:00:00) + $dateValue = static function (string $value): string { + return substr(str_replace(' ', 'T', trim($value)), 0, 10); + }; @endphp
@@ -91,6 +95,256 @@ background: rgba(147, 95, 7, 0.06); color: var(--vip-warning, #935f07); } + + /* + * 筛选下拉:可滚动的选项面板。 + * 原生 的面板由浏览器绘制,高度/滚动条无法控制(选项多时看不全也滑不动), + * 因此改为自绘面板:固定最大高度 + 内部滚动,风格对齐 .finance-table-field-picker__panel。 + */ + .upstream-data-combobox { + position: relative; + display: flex; + align-items: center; + width: 100%; + } + .upstream-data-combobox input { padding-right: 2.25rem; } + .upstream-data-combobox input::-webkit-search-cancel-button { + -webkit-appearance: none; + appearance: none; + } + .upstream-data-combobox__toggle { + position: absolute; + right: 0.25rem; + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.75rem; + height: 1.75rem; + padding: 0; + border: 0; + border-radius: 0.35rem; + background: transparent; + color: var(--vip-content-muted, #595959); + cursor: pointer; + } + .upstream-data-combobox__toggle:hover { + background: rgba(133, 102, 50, 0.12); + color: var(--vip-content-accent-dark, #856632); + } + .upstream-data-combobox__toggle .material-icons-outlined { + font-size: 1.125rem; + transition: transform 0.15s ease; + } + .upstream-data-combobox.is-open .upstream-data-combobox__toggle .material-icons-outlined { + transform: rotate(180deg); + } + .upstream-data-combobox__menu { + position: absolute; + top: calc(100% + 0.35rem); + left: 0; + right: 0; + z-index: 30; + max-height: min(18rem, 50vh); + overflow: auto; + padding: 0.25rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.5rem; + background: var(--vip-surface, #ffffff); + box-shadow: 0 4px 8px rgba(23, 23, 23, 0.1); + overscroll-behavior: contain; + scrollbar-color: var(--vip-content-accent, #b9954f) #efede8; + scrollbar-width: thin; + } + .upstream-data-combobox__menu[hidden] { display: none; } + .upstream-data-combobox__option { + display: block; + width: 100%; + min-height: 1.75rem; + padding: 0.25rem 0.5rem; + border: 0; + border-radius: 0.35rem; + background: transparent; + color: var(--vip-content-ink, #171717); + cursor: pointer; + font: inherit; + text-align: left; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .upstream-data-combobox__option:hover, + .upstream-data-combobox__option.is-active { + background: rgba(133, 102, 50, 0.12); + color: var(--vip-content-accent-dark, #856632); + } + .upstream-data-combobox__option[aria-selected="true"] { font-weight: 600; } + .upstream-data-combobox__empty { + margin: 0; + padding: 0.5rem; + color: var(--vip-content-muted, #595959); + font-size: 0.75rem; + text-align: center; + } + .upstream-data-combobox__empty[hidden] { display: none; } + + /* + * 日期选择器:对齐「淘系微信账户」账单页的日期控件 + * (文本输入框 + 右侧日历按钮 + 中文月历弹层,选中/今天用品牌色)。 + * 原来是 datetime-local,会显示成 "2026-08-29T00:00",与账单页不一致。 + */ + .upstream-data-field__label { + color: var(--vip-content-muted, #595959); + font-size: 0.75rem; + font-weight: 500; + line-height: 1.333; + } + .upstream-data-field--dates { flex: 1 1 20rem; } + .upstream-data-date-range { + display: flex; + align-items: center; + gap: 0.5rem; + } + .upstream-data-date { + position: relative; + display: flex; + flex: 1 1 8.5rem; + min-width: 0; + } + .upstream-data-date input { + flex: 1 1 auto; + width: auto; + min-width: 0; + padding-right: 1.75rem; + border-radius: 0.5rem 0 0 0.5rem; + cursor: pointer; + } + .upstream-data-date__clear { + position: absolute; + top: 0; + right: 2.25rem; + bottom: 0; + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.5rem; + height: 1.5rem; + margin: auto 0; + padding: 0; + border: 0; + border-radius: 0.25rem; + background: transparent; + color: var(--vip-content-muted, #595959); + cursor: pointer; + } + .upstream-data-date__clear:hover { + background: rgba(133, 102, 50, 0.12); + color: var(--vip-content-accent-dark, #856632); + } + .upstream-data-date__clear[hidden] { display: none; } + .upstream-data-date__clear .material-icons-outlined { font-size: 0.9375rem; } + .upstream-data-date__pick { + display: inline-flex; + flex: 0 0 2.125rem; + align-items: center; + justify-content: center; + width: 2.125rem; + height: 2.125rem; + padding: 0; + border: 1px solid var(--vip-border, #d8d2c7); + border-left: 0; + border-radius: 0 0.5rem 0.5rem 0; + background: var(--vip-surface, #ffffff); + color: var(--vip-content-accent-dark, #856632); + cursor: pointer; + } + .upstream-data-date__pick:hover, + .upstream-data-date__pick:focus-visible { + background: #f7f0de; + color: #6a5129; + outline: none; + } + .upstream-data-date__pick .material-icons-outlined { font-size: 1.125rem; } + .upstream-data-date-range__sep { + color: var(--vip-content-muted, #595959); + font-weight: 400; + } + .upstream-data-calendar { + position: absolute; + top: calc(100% + 0.35rem); + left: 0; + z-index: 30; + width: 16.5rem; + padding: 0.5rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.5rem; + background: var(--vip-surface, #ffffff); + box-shadow: 0 4px 8px rgba(23, 23, 23, 0.1); + } + .upstream-data-calendar[hidden] { display: none; } + .upstream-data-calendar__head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.25rem; + margin-bottom: 0.25rem; + } + .upstream-data-calendar__title { + color: var(--vip-content-ink, #171717); + font-size: 0.8125rem; + font-weight: 600; + } + .upstream-data-calendar__nav { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.5rem; + height: 1.5rem; + padding: 0; + border: 0; + border-radius: 0.25rem; + background: transparent; + color: var(--vip-content-accent-dark, #856632); + cursor: pointer; + } + .upstream-data-calendar__nav:hover { background: #f7f0de; } + .upstream-data-calendar__nav .material-icons-outlined { font-size: 1.125rem; } + .upstream-data-calendar__week, + .upstream-data-calendar__grid { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 0.125rem; + } + .upstream-data-calendar__week span { + padding: 0.25rem 0; + color: var(--vip-content-muted, #595959); + font-size: 0.75rem; + text-align: center; + } + .upstream-data-calendar__day { + height: 1.75rem; + padding: 0; + border: 1px solid transparent; + border-radius: 0.25rem; + background: transparent; + color: var(--vip-content-ink, #171717); + cursor: pointer; + font: inherit; + font-size: 0.75rem; + font-variant-numeric: tabular-nums; + } + .upstream-data-calendar__day:hover { background: #f7f0de; } + .upstream-data-calendar__day.is-outside { color: #b9b3a8; } + .upstream-data-calendar__day.is-today { border-color: var(--vip-content-accent-dark, #856632); } + .upstream-data-calendar__day.is-selected { + border-color: var(--vip-content-accent-dark, #856632); + background: var(--vip-content-accent-dark, #856632); + color: #ffffff; + } + /* 结束日期的日历向右展开会顶出工具栏,改成向左 */ + .upstream-data-date:last-of-type .upstream-data-calendar { + right: 0; + left: auto; + }
@@ -119,13 +373,49 @@ action="{{ route('business.pages.show', ['section' => 'financial-operations', 'page' => 'small-payment-work-orders']) }}" data-filter-contract="small-payment-work-orders.filters" > -
- - -
-
- - +
+ 完成日期 +
+ + + + + + + 至 + + + + + + +
@@ -133,7 +423,49 @@
- +
+ + + +
@@ -145,11 +477,58 @@
- +
- +
+ + + +
- 本页打款金额合计 - ¥ {{ $smallPaymentPageAmount }} + 筛选出的打款金额合计 + ¥ {{ $smallPaymentFilteredAmount }}
@@ -253,4 +632,389 @@
+ + diff --git a/resources/views/business/pages/show.blade.php b/resources/views/business/pages/show.blade.php index 1845a9e5..e9e253d2 100644 --- a/resources/views/business/pages/show.blade.php +++ b/resources/views/business/pages/show.blade.php @@ -5,6 +5,9 @@ && ($page['slug'] ?? null) === 'marketing-account-balance'; $isStoreReceivingAccountsPage = ($section['slug'] ?? null) === 'fund-management' && ($page['slug'] ?? null) === 'store-receiving-accounts'; + $isSupplierWorkspace = in_array($section['slug'] ?? null, ['supplier-payables', 'supplier-payables-final'], true); + $supplierWorkspaceSection = $section; + $isCourierFinalDirectory = ($section['slug'] ?? null) === 'courier-payables-final'; $marketingAccountTabTitles = [ 'taobao-wechat' => '阿里巴巴账户', 'jd-wallet' => '京东', @@ -546,7 +549,7 @@ 'business-page--marketing-account-balance' => $isMarketingAccountBalancePage, ]) @if ($isMarketingAccountBillsPage) data-marketing-account-bills-workspace @endif - @if ($section['slug'] === 'supplier-payables') data-supplier-workspace @endif + @if ($isSupplierWorkspace) data-supplier-workspace @endif > @if ($isMarketingAccountBillsPage)

@@ -571,8 +574,10 @@ @endif - @if ($section['slug'] === 'supplier-payables') - @include('business.pages.supplier-payables.navigation') + @if ($isSupplierWorkspace && $supplierWorkspaceSection) + @include('business.pages.supplier-payables.navigation', ['section' => $supplierWorkspaceSection]) + @elseif ($isCourierFinalDirectory) + @include('business.pages.partials.section-page-tabs', ['section' => $section]) @endif @if ($tabs->isNotEmpty()) @@ -607,6 +612,7 @@ @php $pageView = null; + $sectionView = null; if ($page) { $viewName = 'business.pages.' . $section['slug'] . '.' . $page['slug']; @@ -618,11 +624,21 @@ if (view()->exists($viewName)) { $pageView = $viewName; } + } else { + $viewName = 'business.pages.' . $section['slug'] . '.index'; + + if (view()->exists($viewName)) { + $sectionView = $viewName; + } } @endphp - @if ($section['slug'] === 'courier-payables' && empty($page)) + @if (!empty($payablesFinal)) + @include('business.pages.partials.final-dataset-table', ['payablesFinal' => $payablesFinal]) + @elseif ($section['slug'] === 'courier-payables' && empty($page)) @include('business.pages.courier-payables.final-workspace') + @elseif ($sectionView) + @include($sectionView) @elseif (!empty($content) && !empty($content['view']))
@include($content['view'], $content) @@ -634,6 +650,8 @@ 'page' => $page, 'rows' => $rows, 'upstreamError' => $upstreamError, + 'inventoryWarehouseMappings' => $inventoryWarehouseMappings ?? collect(), + 'receiptStats' => $receiptStats ?? null, ]) @elseif ($pageView) @include($pageView) @@ -747,7 +765,7 @@ - @if ($page['slug'] !== 'installation-details')@endif + @if ($page['slug'] !== 'installation-details')@endif @foreach ($descriptor->fields as $field) @endforeach diff --git a/resources/views/business/pages/supplier-payables/advance-details.blade.php b/resources/views/business/pages/supplier-payables/advance-details.blade.php index b713bc12..a20fcb40 100644 --- a/resources/views/business/pages/supplier-payables/advance-details.blade.php +++ b/resources/views/business/pages/supplier-payables/advance-details.blade.php @@ -6,7 +6,7 @@ {{-- 统计卡片 --}} -
+
借支总金额
@{{ formatMoney(summary.totalAmount) }}
@@ -25,8 +25,7 @@ start-placeholder="月份开始" end-placeholder="月份结束" size="small" style="width: 240px" value-format="yyyy-MM" @change="onFilterChange"> - 查询 - 重置 + @include('business.pages.supplier-payables.maintenance-actions')
@@ -35,7 +34,7 @@
加载中...
- + diff --git a/resources/views/business/pages/supplier-payables/board-deductions.blade.php b/resources/views/business/pages/supplier-payables/board-deductions.blade.php index a17c48c9..aa49074b 100644 --- a/resources/views/business/pages/supplier-payables/board-deductions.blade.php +++ b/resources/views/business/pages/supplier-payables/board-deductions.blade.php @@ -3,6 +3,7 @@ $boardDeductionFilters = $content['boardDeductionFilters'] ?? []; $boardDeductionError = $content['boardDeductionError'] ?? null; $boardDeductionStatus = data_get($content, 'boardDeductionStatus.X-Caiwu-Data-Status'); + $boardActions = url('/' . (company_id() ?: 1) . '/workspace/supplier-payables/actions/board-deductions'); @endphp
@@ -53,6 +54,7 @@ .supplier-board-actions { display: flex; + flex-wrap: wrap; gap: 0.5rem; } @@ -78,6 +80,8 @@ color: #ffffff; } + .supplier-board-button .material-icons-outlined { font-size: 1.125rem; } + .supplier-board-alert { margin-bottom: 1rem; padding: 0.75rem 1rem; @@ -189,17 +193,31 @@
-
- + + 导出 + + - + 重置 +
+ @include('business.pages.supplier-payables.maintenance-import-modal', [ + 'supplierImportAction' => $boardActions . '/import', + 'supplierTemplateUrl' => $boardActions . '/template', + ]) @if ($boardDeductionError) @@ -231,7 +249,7 @@
@forelse ($boardDeductions ?? [] as $row) - + @@ -277,3 +295,4 @@ +@include('business.pages.supplier-payables.maintenance-blade-modal') diff --git a/resources/views/business/pages/supplier-payables/compensation-details.blade.php b/resources/views/business/pages/supplier-payables/compensation-details.blade.php index ddfce9dd..030e290d 100644 --- a/resources/views/business/pages/supplier-payables/compensation-details.blade.php +++ b/resources/views/business/pages/supplier-payables/compensation-details.blade.php @@ -46,8 +46,7 @@ start-placeholder="月份开始" end-placeholder="月份结束" size="small" style="width: 240px" value-format="yyyy-MM" @change="onFilterChange"> - 查询 - 重置 + @include('business.pages.supplier-payables.maintenance-actions') @@ -56,7 +55,7 @@
加载中...
- + diff --git a/resources/views/business/pages/supplier-payables/delivery-unpriced.blade.php b/resources/views/business/pages/supplier-payables/delivery-unpriced.blade.php index adee8b68..46fb957e 100644 --- a/resources/views/business/pages/supplier-payables/delivery-unpriced.blade.php +++ b/resources/views/business/pages/supplier-payables/delivery-unpriced.blade.php @@ -1,7 +1,7 @@
{{-- 统计卡片 --}} -
+
未定价记录数
@{{ (summary.totalCount || 0).toLocaleString() }}
@@ -29,8 +29,7 @@ start-placeholder="日期开始" end-placeholder="日期结束" size="small" style="width: 260px" value-format="yyyy-MM-dd" @change="onFilterChange"> - 查询 - 重置 + @include('business.pages.supplier-payables.maintenance-actions')
@@ -39,7 +38,7 @@
加载中...
- + diff --git a/resources/views/business/pages/supplier-payables/dropshipping-express.blade.php b/resources/views/business/pages/supplier-payables/dropshipping-express.blade.php index 692745e2..86daeccd 100644 --- a/resources/views/business/pages/supplier-payables/dropshipping-express.blade.php +++ b/resources/views/business/pages/supplier-payables/dropshipping-express.blade.php @@ -1,7 +1,7 @@
{{-- 统计卡片 --}} -
+
合计运费
@{{ formatMoney(summary.totalAmount) }}
@@ -23,8 +23,7 @@ start-placeholder="月份开始" end-placeholder="月份结束" size="small" style="width: 240px" value-format="yyyy-MM" @change="onFilterChange"> - 查询 - 重置 + @include('business.pages.supplier-payables.maintenance-actions')
@@ -33,7 +32,7 @@
加载中...
- + diff --git a/resources/views/business/pages/supplier-payables/invoice-deductions.blade.php b/resources/views/business/pages/supplier-payables/invoice-deductions.blade.php index a7cd58eb..2fc0d9dd 100644 --- a/resources/views/business/pages/supplier-payables/invoice-deductions.blade.php +++ b/resources/views/business/pages/supplier-payables/invoice-deductions.blade.php @@ -1,7 +1,7 @@
{{-- 统计卡片 --}} -
+
扣款总金额
@{{ formatMoney(summary.totalPrice) }}
@@ -20,8 +20,7 @@ start-placeholder="月份开始" end-placeholder="月份结束" size="small" style="width: 240px" value-format="yyyy-MM" @change="onFilterChange"> - 查询 - 重置 + @include('business.pages.supplier-payables.maintenance-actions')
@@ -30,7 +29,7 @@
加载中...
- + diff --git a/resources/views/business/pages/supplier-payables/local-navigation.blade.php b/resources/views/business/pages/supplier-payables/local-navigation.blade.php index 94c8e80c..0971904b 100644 --- a/resources/views/business/pages/supplier-payables/local-navigation.blade.php +++ b/resources/views/business/pages/supplier-payables/local-navigation.blade.php @@ -6,6 +6,20 @@ if (!initial) return; const cache = new Map(); const loaded = new Set([...document.scripts].map(script => script.src)); + // 局部替换导航只会换掉工作区节点,页面在 body_end 追加的行内脚本不会执行, + // 导入/编辑弹窗这类按钮就会“点了没反应”。带 data-caiwu-replay 的脚本每次替换后 + // 重新执行一次;各页面用的是同一段脚本,必须重跑才能绑定到新换进来的弹窗元素。 + // 脚本自身用目标元素的 data-ready 做去重,重复插入同一节点不会重复绑定。 + const collectReplayScripts = doc => [...doc.querySelectorAll('body script[data-caiwu-replay]')] + .map(script => script.textContent.trim()) + .filter(code => code !== ''); + const runReplayScripts = codes => { + for (const code of codes || []) { + const script = document.createElement('script'); + script.textContent = code; + document.body.appendChild(script); + } + }; let current = location.href; let pending = false; const heading = document.querySelector('#main-body h1'); @@ -34,7 +48,12 @@ if (!node) throw new Error('页面不可用或登录已过期'); scripts = [...doc.querySelectorAll('script[src]')].map(s => s.src) .filter(src => new URL(src).origin === location.origin && new URL(src).pathname.startsWith('/public/js/ecommerce-finance/') && !loaded.has(src)); - next = {node: document.importNode(node, true), title: doc.title, heading: doc.querySelector('#main-body h1')?.innerHTML || ''}; + next = { + node: document.importNode(node, true), + title: doc.title, + heading: doc.querySelector('#main-body h1')?.innerHTML || '', + replay: collectReplayScripts(doc), + }; } remember(); previous.replaceWith(next.node); @@ -48,6 +67,7 @@ document.body.appendChild(script); }); } + runReplayScripts(next.replay); cache.set(href, next); current = href; document.title = next.title; @@ -71,7 +91,7 @@ navigate(link.href); }); window.addEventListener('popstate', () => { - if (location.pathname.includes('/workspace/supplier-payables/')) navigate(location.href, false); + if (/\/workspace\/supplier-payables(-final)?\//.test(location.pathname)) navigate(location.href, false); }); })(); diff --git a/resources/views/business/pages/supplier-payables/maintenance-actions.blade.php b/resources/views/business/pages/supplier-payables/maintenance-actions.blade.php new file mode 100644 index 00000000..3b72a117 --- /dev/null +++ b/resources/views/business/pages/supplier-payables/maintenance-actions.blade.php @@ -0,0 +1,10 @@ +
+ @include('business.pages.supplier-payables.maintenance-toolbar') + + 查询 + + + 重置 + + @include('business.pages.supplier-payables.maintenance-edit-button') +
diff --git a/resources/views/business/pages/supplier-payables/maintenance-blade-modal.blade.php b/resources/views/business/pages/supplier-payables/maintenance-blade-modal.blade.php new file mode 100644 index 00000000..fe4a3297 --- /dev/null +++ b/resources/views/business/pages/supplier-payables/maintenance-blade-modal.blade.php @@ -0,0 +1,111 @@ +@php + $maintenance = $content['supplierPayableMaintenance'] ?? ['dataset' => '', 'fields' => []]; + $maintenanceAction = $supplierMaintenanceAction + ?? url('/' . (company_id() ?: 1) . '/workspace/supplier-payables/actions/' . $maintenance['dataset']); +@endphp + + + +@once + +@endonce + +@push('body_end') +{{-- data-caiwu-replay:局部替换导航后需要重跑,才能绑定到新换进来的弹窗 --}} + +@endpush diff --git a/resources/views/business/pages/supplier-payables/maintenance-edit-button.blade.php b/resources/views/business/pages/supplier-payables/maintenance-edit-button.blade.php new file mode 100644 index 00000000..2f9eb8dc --- /dev/null +++ b/resources/views/business/pages/supplier-payables/maintenance-edit-button.blade.php @@ -0,0 +1,6 @@ + + 编辑 + diff --git a/resources/views/business/pages/supplier-payables/maintenance-import-modal.blade.php b/resources/views/business/pages/supplier-payables/maintenance-import-modal.blade.php new file mode 100644 index 00000000..bbe3872d --- /dev/null +++ b/resources/views/business/pages/supplier-payables/maintenance-import-modal.blade.php @@ -0,0 +1,97 @@ + + +@once + +@endonce + +@push('body_end') +{{-- data-caiwu-replay:局部替换导航后需要重跑,才能绑定到新换进来的弹窗 --}} + +@endpush diff --git a/resources/views/business/pages/supplier-payables/maintenance-toolbar.blade.php b/resources/views/business/pages/supplier-payables/maintenance-toolbar.blade.php new file mode 100644 index 00000000..35d7e671 --- /dev/null +++ b/resources/views/business/pages/supplier-payables/maintenance-toolbar.blade.php @@ -0,0 +1,43 @@ + + 导入 + + + 导出 + + + +
+ + + 下载导入模板当前页面字段模板(Excel) + + + +
+ + 取消 + 开始导入 + +
+ + + + + + + + + + + 取消 + 保存 + + diff --git a/resources/views/business/pages/supplier-payables/navigation.blade.php b/resources/views/business/pages/supplier-payables/navigation.blade.php index ef119914..c4011d00 100644 --- a/resources/views/business/pages/supplier-payables/navigation.blade.php +++ b/resources/views/business/pages/supplier-payables/navigation.blade.php @@ -13,7 +13,7 @@ $children = $supplierPage['children'] ?? []; $selected = $supplierCurrent === $supplierPage['slug'] || in_array($supplierCurrent, array_column($children, 'slug'), true); @endphp - $selected]) @if ($selected) aria-current="page" @endif>{{ $supplierPage['title'] }} @endforeach @@ -22,7 +22,7 @@ @if (in_array($supplierCurrent, array_column($supplierPage['children'] ?? [], 'slug'), true))
#序号{{ $field['label'] }}
{{ $row->stock_in_date ?: '-' }} {{ $row->stock_out_date ?: '-' }} {{ $row->furniture_factory ?: '-' }}