Merge remote-tracking branch 'origin/main' into feature-sumu-bill-offset-after-sales
This commit is contained in:
commit
f35e5008ad
@ -27,7 +27,7 @@
|
||||
- 提交前检查 `git status`、实际 diff 和暂存区,只提交当前任务文件;不得带入 `.env`、凭据、日志、构建产物或他人的改动。
|
||||
- PR 说明做了什么、修改文件、验证结果,以及是否涉及金额、权限、数据库或配置。小型低风险任务不要求冗长模板说明。
|
||||
- 任务 Codex 在需求满足、相关测试通过且完整 diff 自审无误后,可直接执行 Squash merge、验证远程 `main` 并清理已合并分支,不需要另一位开发者或负责人再次操作。
|
||||
- 生产部署、生产迁移、数据修复、删除或覆盖配置仍需单独明确授权,不能因为代码已合并而自动执行。
|
||||
- 普通代码发布在相关验证通过、完整 diff 自审并合并到最新 `main` 后,由任务 Codex 直接部署和验收,无需另行取得部署授权。上游接入和共享镜像同步按第 6 节自主完成;除此之外的生产迁移、数据修复、删除或覆盖配置仍需单独明确授权。
|
||||
|
||||
## 4. 验证要求
|
||||
|
||||
@ -50,7 +50,7 @@
|
||||
|
||||
- 密码、Token、SSH 私钥、数据库连接串、真实财务数据和生产日志不得进入 Git、PR 或公开文档。
|
||||
- 需要长期保存的敏感信息写入被 Git 忽略的 `runtime/private/敏感信息.md`;写入前用 `git check-ignore` 确认。负责人明确要求时,可在当前一对一对话提供指定范围的敏感信息,但不得扩大传播。
|
||||
- 生产数据库写入、迁移、删除、批量导入和凭据轮换必须先说明影响,准备备份或回滚,并取得明确授权。普通本地只读排查和有限业务查询不需要额外审批。
|
||||
- 本任务所需的上游只读排查、数据字典刷新、数据集登记和启用、共享镜像建表及索引迁移、首次全量、增量、历史回补和镜像校准,由开发者的 Codex 自主完成,无需负责人逐次授权或代执行。Codex 自行核对来源与范围、备份受影响的配置/镜像及同步状态,使用生产同步节点和现有互斥锁分批执行,并核对源数据、完成状态与真实页面;不把这些工作转交给新人。可从上游重建的镜像修复属于此范围;上游写入、原始业务/财务数据修改、无关数据删除、凭据轮换和覆盖生产连接配置仍需单独授权。
|
||||
- `caiwu_system_config` 保存用户、权限、设置、连接资料、数据字典和同步状态;`caiwu_business_mirror` 保存项目已正式接入的上游业务数据。二者不是 SQL Server 网络代理。
|
||||
- 上游数据库统一按只读黑盒处理。业务查询使用固定、参数化的 Repository/查询执行器,禁止把用户输入拼成 SQL 或执行写操作。
|
||||
- 正式页面优先读取共享业务镜像;尚未迁移的旧页面可继续使用现有快照兼容层。接入新数据时沿用现有镜像数据集、稳定游标、断点同步和同步状态模式,不另造一套链路。
|
||||
@ -64,10 +64,11 @@
|
||||
|
||||
## 8. 构建与生产部署
|
||||
|
||||
- 只有用户明确要求“部署、上线”时才执行生产发布;正式发布只使用已合并的最新 `main`。
|
||||
- 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。
|
||||
- Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`。服务器只运行开发机已构建的 `caiwu_akaunting:<commit>` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。
|
||||
- 新人只需表达部署需求;Codex 使用默认生产入口运行脚本。首次通过本机窗口提供一次服务器密码后,加密保存在本人电脑供后续自动使用,不要求新人准备私钥、执行命令或每次重输密码。已有私钥认证仍兼容。
|
||||
- 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。
|
||||
- 发布脚本检测到新增数据库迁移时必须停止,取得负责人明确授权并完成备份后才能使用迁移开关。
|
||||
- 发布脚本检测到新增数据库迁移时,由 Codex 核对全部待执行迁移。仅涉及本任务共享镜像建表、字段、索引和同步登记的迁移,完成备份后自主使用 `-AllowMigrations`;其他迁移仍按第 6 节确认授权。不能因需要迁移开关就把镜像接入停给负责人。
|
||||
- 容器内 Laravel 命令使用 `www-data`。发布后只需确认部署 SHA、应用容器健康、受影响的真实页面/接口、迁移是否执行,以及当前和上一版镜像可回滚。
|
||||
- 程序静态资源随应用镜像同源发布;七牛只存用户上传的业务图片、票据和附件。
|
||||
- 只有本地初始化、服务器维护、生产发布或数据库迁移任务需要读取 `docs/开发与部署SOP.md` 的对应章节;普通功能开发无需加载整份 SOP。
|
||||
|
||||
@ -15,10 +15,10 @@ class RegisterBusinessMirror extends Command
|
||||
{--keys= : 逗号分隔的稳定唯一键}
|
||||
{--columns= : 逗号分隔的明确同步字段,必须包含稳定键及增量字段}
|
||||
{--watermark= : 可靠更新时间字段;留空为仅按主键追加}
|
||||
{--enable-sync : 启用并批准可断点首次同步及后续增量}
|
||||
{--enable-sync : 启用可断点首次同步及后续增量}
|
||||
{--disable-sync : 停用此数据集的自动同步,保留镜像数据}';
|
||||
|
||||
protected $description = '登记声明式镜像数据集;生产启用前需获得同步范围授权';
|
||||
protected $description = '登记声明式镜像数据集;核对范围并备份后可直接启用同步';
|
||||
|
||||
public function handle(BusinessMirrorDatasetRegistry $datasets, UpstreamSourceRegistry $sources): int
|
||||
{
|
||||
|
||||
@ -58,7 +58,7 @@ class SyncProductCatalogMirror extends Command
|
||||
}
|
||||
|
||||
if ($result['status'] === 'requires_full_sync') {
|
||||
$this->warn('普通商品尚未完成首次全量同步,需经授权后显式使用 --full。');
|
||||
$this->warn('普通商品尚未完成首次全量同步,请完成备份后显式使用 --full。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
@ -42,7 +42,7 @@ class SyncProductPurchasePriceMirror extends Command
|
||||
}
|
||||
|
||||
if ($result['status'] === 'requires_full_sync') {
|
||||
$this->warn('采购单价尚未完成首次全量同步,需经授权后显式使用 --full。');
|
||||
$this->warn('采购单价尚未完成首次全量同步,请完成备份后显式使用 --full。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
@ -742,20 +742,7 @@ class Pages extends Controller
|
||||
|
||||
protected function contentForOnlineDaifaPrice(): array
|
||||
{
|
||||
$clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length);
|
||||
$date = static function (mixed $value): string {
|
||||
$value = trim((string) $value);
|
||||
return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1 ? $value : '';
|
||||
};
|
||||
$status = strtoupper(mb_substr(trim((string) request('status', '')), 0, 30));
|
||||
$filters = [
|
||||
'keyword' => $clean(request('keyword', ''), 80),
|
||||
'product_id' => $clean(request('product_id', ''), 64),
|
||||
'shop_name' => $clean(request('shop_name', ''), 120),
|
||||
'status' => preg_match('/^[A-Z_]+$/', $status) === 1 ? $status : '',
|
||||
'created_from' => $date(request('created_from', '')),
|
||||
'created_to' => $date(request('created_to', '')),
|
||||
];
|
||||
$filters = $this->onlineDaifaPriceFilters(request());
|
||||
$page = max((int) request('page', 1), 1);
|
||||
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
|
||||
|
||||
@ -795,6 +782,86 @@ class Pages extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
public function exportOnlineDaifaPrice(Request $request): StreamedResponse
|
||||
{
|
||||
abort_unless($this->onlineDaifaPrices->ready(), 503);
|
||||
|
||||
$filters = $this->onlineDaifaPriceFilters($request);
|
||||
|
||||
return response()->streamDownload(function () use ($filters): void {
|
||||
$csv = fopen('php://output', 'w');
|
||||
if ($csv === false) {
|
||||
throw new \RuntimeException('无法创建线上代发价格导出流。');
|
||||
}
|
||||
|
||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($csv, [
|
||||
'审批编号', '标题', '状态', '申请人', '收款人全称', '商品ID', '商品名称(匹配)', '店铺名称',
|
||||
'代发交易单号', '店铺交易单号', '发货数量', '订单实付金额', '代发订单金额', '差价',
|
||||
'供应商名称', '料号', '创建时间',
|
||||
]);
|
||||
|
||||
foreach ($this->onlineDaifaPrices->exportRows($filters) as $row) {
|
||||
$workflow = (array) ($row['workflow'] ?? []);
|
||||
$approvalNumber = trim((string) ($workflow['businessId'] ?? '')) ?: (string) ($row['process_instance_id'] ?? '');
|
||||
$originator = trim((string) ($workflow['originatorUserName'] ?? ''))
|
||||
?: trim((string) ($workflow['originatorUserId'] ?? ''));
|
||||
$matchedProduct = (array) ($row['matched_product'] ?? []);
|
||||
$productName = ($matchedProduct['matched'] ?? false)
|
||||
? (string) ($matchedProduct['name'] ?? '')
|
||||
: '(未匹配)';
|
||||
|
||||
fputcsv($csv, [
|
||||
$this->csvIdentifier($approvalNumber),
|
||||
$this->csvText($workflow['title'] ?? ''),
|
||||
$this->csvText($row['status_label'] ?? ''),
|
||||
$this->csvText($originator),
|
||||
$this->csvText($row['payee_name'] ?? ''),
|
||||
$this->csvIdentifier($row['product_id'] ?? ''),
|
||||
$this->csvText($productName),
|
||||
$this->csvText($row['shop_name'] ?? ''),
|
||||
$this->csvIdentifier($row['daifa_trade_no'] ?? ''),
|
||||
$this->csvIdentifier($row['shop_trade_no'] ?? ''),
|
||||
$row['ship_qty'] ?? null,
|
||||
$row['paid_amount'] ?? null,
|
||||
$row['daifa_amount'] ?? null,
|
||||
$row['price_diff'] ?? null,
|
||||
$this->csvText($row['supplier_name'] ?? ''),
|
||||
$this->csvIdentifier($row['material_no'] ?? ''),
|
||||
$this->csvText($row['workflow_created_at'] ?? ''),
|
||||
]);
|
||||
}
|
||||
|
||||
fclose($csv);
|
||||
}, '线上代发价格_' . now()->format('Ymd_His') . '.csv', [
|
||||
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function onlineDaifaPriceFilters(Request $request): array
|
||||
{
|
||||
$clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length);
|
||||
$date = static function (mixed $value): string {
|
||||
$value = trim((string) $value);
|
||||
|
||||
return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1 ? $value : '';
|
||||
};
|
||||
$status = strtoupper(mb_substr(trim((string) $request->query('status', '')), 0, 30));
|
||||
|
||||
return [
|
||||
'keyword' => $clean($request->query('keyword', ''), 80),
|
||||
'product_id' => $clean($request->query('product_id', ''), 64),
|
||||
'shop_name' => $clean($request->query('shop_name', ''), 120),
|
||||
'supplier_name' => $clean($request->query('supplier_name', ''), 120),
|
||||
'material_no' => $clean($request->query('material_no', ''), 120),
|
||||
'status' => preg_match('/^[A-Z_]+$/', $status) === 1 ? $status : '',
|
||||
'created_from' => $date($request->query('created_from', '')),
|
||||
'created_to' => $date($request->query('created_to', '')),
|
||||
];
|
||||
}
|
||||
|
||||
protected function contentForJingxiRefundData(): array
|
||||
{
|
||||
return [
|
||||
@ -2009,6 +2076,22 @@ class Pages extends Controller
|
||||
return preg_match('/^[=+\-@]/u', $text) === 1 ? "'" . $text : $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export identifiers as text so Excel does not round or truncate long IDs.
|
||||
* Keep the formula-injection guard from csvText for values beginning with a
|
||||
* formula marker.
|
||||
*/
|
||||
private function csvIdentifier(mixed $value): string
|
||||
{
|
||||
$text = $this->csvText($value);
|
||||
|
||||
if ($text === '' || str_starts_with($text, "'")) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
return "'" . $text;
|
||||
}
|
||||
|
||||
private function emptyProductCatalogContent(
|
||||
array $filters,
|
||||
int $limit,
|
||||
|
||||
@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const TABLE = 'ding_online_daifa_price_mirror';
|
||||
|
||||
private const INDEX = 'idx_daifa_material_no';
|
||||
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if (app()->environment('testing')
|
||||
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema = Schema::connection($this->connection());
|
||||
if (! $schema->hasTable(self::TABLE) || $schema->hasIndex(self::TABLE, self::INDEX)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table(self::TABLE, function (Blueprint $table): void {
|
||||
$table->index('material_no', self::INDEX);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (app()->environment('testing')
|
||||
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema = Schema::connection($this->connection());
|
||||
if (! $schema->hasTable(self::TABLE) || ! $schema->hasIndex(self::TABLE, self::INDEX)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table(self::TABLE, function (Blueprint $table): void {
|
||||
$table->dropIndex(self::INDEX);
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -118,7 +118,7 @@ Codex 在合并前必须进入一次独立自审,不得直接沿用开发阶
|
||||
请进入独立的合并前自审,不要直接沿用开发阶段的完成结论。重新 fetch、读取原始需求和验收标准,并以 origin/main...当前任务分支的完整 diff 为准逐文件审核。检查工作区、WIP 状态、修改边界、公共契约、远程支线重叠、敏感内容、测试证据和目标 main。条件全部满足后,使用 Squash merge 合并到 main,核对远程 main 已包含目标改动,再验证实际页面或接口并删除已合并任务分支。禁止强推;如有冲突、测试失败、自审不通过或涉及尚未授权的生产迁移/数据操作,立即停止并报告。
|
||||
```
|
||||
|
||||
日常 PR 自审、合并、主线验证和分支清理由任务开发者的 Codex 完成,不需要另一位开发者或项目负责人参与。开发者不手工执行 Git 合并命令,也不能绕过 PR。涉及生产迁移、数据修复、删除、覆盖配置或部署时,继续执行仓库现有高风险授权规则。
|
||||
日常 PR 自审、合并、主线验证、普通代码部署与验收和分支清理由任务开发者的 Codex 完成,不需要另一位开发者或项目负责人参与,也无需另行取得普通部署授权。开发者不手工执行 Git 合并命令,也不能绕过 PR;用户明确要求暂不上线时遵循其范围。本任务上游接入、共享镜像迁移、首次全量、回补和校准由 Codex 自主完成备份、执行与验收,无需负责人重复授权或代操作;其他生产迁移、数据修复、删除或覆盖配置继续按 `AGENTS.md` 执行。
|
||||
|
||||
## PR 落后或发生冲突
|
||||
|
||||
|
||||
@ -70,13 +70,13 @@
|
||||
1. 首次全量只能通过 `business-mirror:sync-tables <dataset> --full` 显式启动;失败或中断后使用同一命令继续。
|
||||
2. 日常任务只处理已经完成首次全量的数据集。存在可靠更新时间的表使用 48 小时重叠窗口;没有可靠更新时间的表按稳定主键追加。`rpt.jst_sku` 由普通商品专用任务每分钟优先处理,每轮默认最多 5 批、每批 1000 行,不再参加通用数据集轮转。
|
||||
3. 全量校准使用新的同步代次,只有全部完成后才删除镜像中本轮未出现的旧行,因此中途失败不会清空当前可用数据。
|
||||
4. 普通商品在最近完整校准超过 168 小时后,于周日 02:00-08:00 低峰窗口启动全量校准;一旦启动,后续每分钟从稳定游标继续,直至完整结束。首次全量仍必须显式授权,不能由定时任务自行启动。
|
||||
4. 普通商品在最近完整校准超过 168 小时后,于周日 02:00-08:00 低峰窗口启动全量校准;一旦启动,后续每分钟从稳定游标继续,直至完整结束。首次全量由 Codex 备份后自主执行,定时任务保持既有初始化开关。
|
||||
5. 除专用数据集外,通用任务每轮默认只处理 1 个数据集、每个数据集 2 批,每批 500 行,避免同时压迫两个旧系统。
|
||||
6. 页面切换必须以“总记录数、第一页、第二页、末页、筛选、汇总、空数据和更新时间”作为验收,不能只看首页有数据。
|
||||
7. 普通商品的采购单价同步以采购主表 `updateTime` 加明细 `Id` 作为稳定游标;页面按商品编码选择最近完成的 1688 一键代发价格。同步保存全部状态,使完成单后续取消时也能撤回旧价格;首次全量前只显示普通商品自身采购价。
|
||||
8. 聚水潭官方接口尚未接入时,普通商品历史残留排除由负责人提供的最新完整 XLSX 导出刷新。只排除“导出生成前已创建、但导出中缺失”的镜像行,导出生成后的新增商品保持可见。导入使用新同步代次,只有完整解析成功才原子替换排除表;中断或错误保留上一版。后续接入聚水潭官方“普通商品资料查询”及删除/恢复记录后,由官方接口取代人工导出校准。
|
||||
9. 店铺维度报表是已批准的中央专用数据集:生产节点按 `Id` 断点推进并回看最近 50000 行;原始账单同步后增量维护按店铺/日期汇总的 `store_report_daily_rows`,页面不得现场扫描千万级原始账单。开发机不运行刷新 worker。
|
||||
10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步必须单独授权并在低峰期分批续传;部署、页面请求和普通开发机均不得自动启动。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。
|
||||
10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步由 Codex 备份后自主安排在生产同步节点低峰期分批续传,无需另行授权;页面请求和普通开发机不启动刷新 worker。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。
|
||||
|
||||
## 后续切换顺序
|
||||
|
||||
@ -102,7 +102,7 @@ php artisan business-mirror:sync-tables operations_replica.rpt.work_order_form_c
|
||||
php artisan business-mirror:sync-tables operations_replica.rpt.work_order_form_value --full
|
||||
```
|
||||
|
||||
聚工单“小额打款”两个数据集同样必须在备份和负责人首次写入授权后分别执行全量同步;页面不会在 HTTP 请求中回退直连 `jiansun`:
|
||||
聚工单“小额打款”两个数据集由 Codex 备份后自主分别执行全量同步;页面不会在 HTTP 请求中回退直连 `jiansun`:
|
||||
|
||||
```bash
|
||||
php artisan business-mirror:sync-tables jiansun.dbo.jst_workOrderInfo --full
|
||||
|
||||
@ -29,6 +29,8 @@
|
||||
|
||||
服务器永远不构建源码。
|
||||
|
||||
普通代码发布在相关验证通过、自审并合并到最新 `main` 后,由任务 Codex 按本 SOP 直接部署并验收,无需用户再次授权部署;用户明确要求暂不上线时遵循其范围。本任务所需的共享镜像接入、迁移和同步由 Codex 按 `AGENTS.md` 自主完成;其他数据库迁移、数据修复、删除和覆盖配置仍按其授权边界执行。
|
||||
|
||||
## 2. 每台开发机只做一次的设置
|
||||
|
||||
新人只负责启动 Docker Desktop、在网页中登录,以及输入一次系统数据库密码。下面涉及仓库、脚本、构建、迁移、缓存、容器、数据库验证和排错的动作均由 Codex 执行,不能把命令转交给新人。
|
||||
@ -37,9 +39,11 @@
|
||||
2. 在 Docker Desktop 的 `Settings -> Resources -> Advanced` 中:
|
||||
- Docker 虚拟磁盘上限建议 60GB;
|
||||
- Windows 磁盘至少保留 15GB 可用空间。
|
||||
3. SSH 私钥放到个人目录,例如 `C:\Users\你的用户名\.ssh\caiwu.pem`,不要放进 Git。
|
||||
3. 首次部署仅需在本机密码窗口输入一次服务器密码,之后 Codex 自动复用本机加密保存的登录信息;不要求新人生成、配置或管理私钥。密码使用 Windows 当前用户绑定的 DPAPI 加密,保存在 `%LOCALAPPDATA%\CaiWuXiTong\deploy-credentials`,不进入仓库或日志。已有私钥的机器仍可选传 `-KeyPath`。
|
||||
4. 只使用仓库里的发布脚本。不要自行执行 `docker system prune -a`,也不要重置 Docker Desktop。
|
||||
|
||||
Codex 已有用户提供的密码时可通过 `-Password` 的 `SecureString` 参数直接使用并保存,无需用户再输入;不要把明文写进命令参数或日志。密码变更时由 Codex 使用 `-UpdatePassword` 更新本机登录信息。部署结束保留加密凭据,下次自动使用。
|
||||
|
||||
说明:Docker 虚拟磁盘清理后,Windows 上看到的 `.vhdx` 文件可能不会立刻变小,但内部可用空间已经释放。不要为了让文件数字变小而删除虚拟磁盘。
|
||||
|
||||
## 3. 为什么后续不会反复全量下载和上传
|
||||
@ -69,7 +73,6 @@
|
||||
```powershell
|
||||
.\scripts\deploy-from-workstation.ps1 `
|
||||
-Server 218.93.190.75 `
|
||||
-KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" `
|
||||
-BootstrapServer
|
||||
```
|
||||
|
||||
@ -96,9 +99,7 @@
|
||||
git switch main
|
||||
git pull --ff-only
|
||||
|
||||
.\scripts\deploy-from-workstation.ps1 `
|
||||
-Server 218.93.190.75 `
|
||||
-KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem"
|
||||
.\scripts\deploy-from-workstation.ps1
|
||||
```
|
||||
|
||||
脚本自动完成:
|
||||
@ -131,16 +132,15 @@ git pull --ff-only
|
||||
|
||||
默认禁止自动迁移。脚本发现上次部署后新增了 `database/migrations` 文件时会停止。
|
||||
|
||||
只有负责人明确批准、PR 已写清影响与回滚思路后,才允许:
|
||||
Codex 先核对全部待执行迁移,并准备受影响数据的备份与回滚。仅涉及本任务共享镜像建表、字段、索引和同步登记时,自主执行以下命令,无需负责人另行批准;其他迁移仍按 `AGENTS.md` 的授权边界执行:
|
||||
|
||||
```powershell
|
||||
.\scripts\deploy-from-workstation.ps1 `
|
||||
-Server 218.93.190.75 `
|
||||
-KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" `
|
||||
-AllowMigrations
|
||||
```
|
||||
|
||||
镜像回滚不能自动撤销已经执行的数据库结构变更,因此迁移授权必须单独处理。
|
||||
应用镜像回滚不能自动撤销数据库结构变更;Codex 必须为本次迁移保留对应的数据备份和恢复路径。
|
||||
|
||||
## 7. 测试分支发布
|
||||
|
||||
@ -154,7 +154,7 @@ git pull --ff-only
|
||||
|
||||
## 8. 多上游财务数据库同步
|
||||
|
||||
新数据库和新数据集优先使用 [通用上游数据接入](通用上游数据接入.md):来源由连接记录自动登记,已批准的声明式数据集由调度自动首次同步和增量同步。下面的固定来源、逐项 `--full` 和旧快照说明适用于既有兼容路径,不应当作为新增普通开发任务的重复审批要求。
|
||||
新数据库和新数据集优先使用 [通用上游数据接入](通用上游数据接入.md):来源由连接记录自动登记,已启用的声明式数据集由调度自动首次同步和增量同步。下面的固定来源、逐项 `--full` 和旧快照说明适用于既有兼容路径,不应当作为新增普通开发任务的重复审批要求。
|
||||
|
||||
### 8.1 统一接入边界
|
||||
|
||||
@ -236,7 +236,7 @@ php artisan business-mirror:sync-tables
|
||||
|
||||
完整数据集、来源对象、镜像表和分阶段切换状态见 `docs/上游业务镜像清单.md`。不得把“已登记同步目录”误报成“页面已经切换完成”;每个业务域仍需在首份全量核对通过后,把对应 Repository 改为只读镜像。
|
||||
|
||||
首次 `--full` 属于生产数据写入,必须先备份 `caiwu_system_config` 和 `caiwu_business_mirror`,并由负责人明确授权。已经在发布说明中批准自动初始化的中央专用数据集,由生产节点在迁移授权后小批量续传;普通开发者不配置、不启动也不审批这些任务。后续无参数命令只执行或继续受控增量。
|
||||
首次全量、历史回补和镜像校准由任务 Codex 自主执行:先备份受影响的系统配置、镜像表及同步状态,再在生产同步节点内使用现有上游互斥锁,按稳定游标分批执行或续传 `--full`,直至完成并核对源表/镜像和实际页面。无需负责人另行授权或代跑命令;开发机驱动不支持时直接通过 SSH 使用生产容器,不以本机不能同步为由停止任务。后续无参数命令只执行或继续受控增量,不对无关数据集批量全量。
|
||||
|
||||
### 8.3 开发者需要尚未接入的上游数据时
|
||||
|
||||
@ -272,7 +272,7 @@ php artisan upstream:schema:sync operations_replica
|
||||
3. **登记同步契约**:定义稳定且可审查的数据集键、上游业务键、同步游标、重叠窗口和镜像表。参数必须有限制,批次必须有稳定排序和行数上限;
|
||||
4. **分支内完成自动测试**:使用脱敏 fixture 或测试替身验证正常、空数据和不可用状态;开发机能够直连时,通过通用只读入口或新 Repository 用少量真实只读数据验证,不得在测试、日志或截图中输出凭据和敏感业务行;
|
||||
5. **本地直接验证**:开发阶段可以直接执行固定只读查询确认数据;正式页面测试使用隔离镜像库 fixture,不依赖负责人环境;
|
||||
6. **生产首次同步**:代码审查和测试通过后合并到 `main`;经数据库写入授权后创建镜像表并执行可断点的首次全量;
|
||||
6. **生产首次同步**:代码审查和测试通过后合并到 `main`;由 Codex 完成受影响数据备份后自主创建镜像表并执行可断点的首次全量;
|
||||
7. **完成共享验收**:确认同步状态成功、镜像总数和筛选计数与上游限定查询一致,第二页或末页可读;随后从第二个应用实例读取相同镜像,并证明页面没有再次访问上游;
|
||||
8. **发现压力立即收口**:慢查询、返回量异常或上游告警时,先从共享记录移除该精确范围并保留证据,再缩小字段、时间窗或分页。禁止通过提高并发、扩大 `*` 或全表扫描解决。
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@ php artisan business-mirror:register database_17 public example_orders \
|
||||
--keys=id --columns=id,updated_at,label --watermark=updated_at
|
||||
```
|
||||
|
||||
登记默认不启动同步。生产首次同步涉及系统库登记和业务镜像表创建/写入,应先说明精确字段、批次、影响及备份,再取得负责人授权。授权后对同一声明追加 `--enable-sync`,生产调度即可自动完成或续传首次全量,完成后转为增量;不再为每次部署、分页、筛选重新审批或生成快照。`--disable-sync` 停止后续自动执行,保留已有镜像。
|
||||
登记默认不启动同步。Codex 根据当前功能需求核对精确字段、批次和影响,备份受影响的配置、镜像与同步状态后,自主对同一声明追加 `--enable-sync`;生产调度即可自动完成或续传首次全量,完成后转为增量,无需负责人另行授权。登记和启用均由 Codex 执行,不让新人处理开关或命令。`--disable-sync` 停止后续自动执行,保留已有镜像。
|
||||
|
||||
声明式登记不能覆盖代码维护的数据集,也不能悄悄修改已有声明的稳定键、字段和增量口径;此类变化需评估历史数据/游标兼容性。来源表没有可靠更新时间时只按主键追加,不能承诺自动发现历史修改或删除,需另行声明校准策略。
|
||||
|
||||
@ -46,12 +46,12 @@ php artisan business-mirror:register database_17 public example_orders \
|
||||
|
||||
通用调度默认每轮最多8个数据集、30秒周期预算;未完成窗口与常规数据集交替处理,单数据集默认8秒软预算,积压任务默认最多6批。预算在批次之间检查,单条查询仍受驱动超时限制;不提高上游并发。失败任务至少冷却5分钟。专用商品/价格/钉钉调度保持既有路径。
|
||||
|
||||
只对明确批准的登记数据集自动首次同步;既有代码数据集仍保留原首次授权流程。未完成的旧页面切换不等于已经上线,必须逐页验收并与正在开发的 PR 协调。
|
||||
调度只对已启用的登记数据集自动首次同步;`initial_sync_approved` 是兼容保留的初始化开关,由 Codex 使用 `--enable-sync` 一并设置,不代表需要负责人审批。既有代码数据集由 Codex 自主在生产同步节点执行对应的 `--full`,沿用互斥锁、分批、断点和验收。未完成的旧页面切换不等于已经上线,必须逐页验收并与正在开发的 PR 协调。
|
||||
|
||||
## 类型及验收
|
||||
|
||||
- PostgreSQL 带时区时间戳在镜像中保存为 UTC;业务展示按自己的明确时区换算。无时区日期时间保留原值。`bytea` 使用十六进制文本表示;不自动解释 JSON、数组、枚举中的业务语义。
|
||||
- 验收包含:没有修改来源枚举也能发现新库;TLS/只读保护;字段目录;只复制明确字段;首次同步、第二页、末页、总数和筛选;增量插入与更新;源不可达时读旧镜像;失败和未授权状态。
|
||||
- 验收包含:没有修改来源枚举也能发现新库;TLS/只读保护;字段目录;只复制明确字段;首次同步、第二页、末页、总数和筛选;增量插入与更新;源不可达时读旧镜像;失败和未启用状态。
|
||||
- SQL Server 既有 Repository 与专用同步器需回归。不得把“新连接测试成功”当作全项目页面已迁移或所有业务表已同步。
|
||||
|
||||
## 系统连接保存后回滚的排查
|
||||
|
||||
@ -25,6 +25,17 @@ class AccountBills extends Controller
|
||||
abort(404, '未知的账户类型。');
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'store_name' => ['nullable', 'string', 'max:255'],
|
||||
'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'],
|
||||
'export' => ['nullable', 'boolean'],
|
||||
'columns' => ['nullable', 'array', 'max:40'],
|
||||
'columns.*' => ['string', 'max:128'],
|
||||
]);
|
||||
|
||||
$query = AccountBill::query()
|
||||
->where('company_id', company_id())
|
||||
->where('bill_type', $billType);
|
||||
@ -60,6 +71,10 @@ class AccountBills extends Controller
|
||||
$dir = $request->get('dir') === 'asc' ? 'asc' : 'desc';
|
||||
$query->orderBy($sort, $dir);
|
||||
|
||||
if ($request->boolean('export')) {
|
||||
return $this->export($request, $query, $billType);
|
||||
}
|
||||
|
||||
$perPage = min(max((int) $request->get('limit', 10), 1), 100);
|
||||
$rows = $query->paginate($perPage);
|
||||
|
||||
@ -87,6 +102,52 @@ class AccountBills extends Controller
|
||||
return response()->json($data);
|
||||
}
|
||||
|
||||
private function export(Request $request, $query, string $billType)
|
||||
{
|
||||
$definition = AccountBillColumns::for($billType);
|
||||
$available = collect($definition['columns'] ?? [])->keyBy('field');
|
||||
$requested = $request->input('columns', []);
|
||||
$columns = $requested === []
|
||||
? $available->values()
|
||||
: collect($requested)->unique()->map(fn (string $field) => $available->get($field))->filter()->values();
|
||||
|
||||
abort_if($columns->isEmpty(), 422, '至少选择一个可导出的字段。');
|
||||
|
||||
return response()->streamDownload(function () use ($query, $columns): void {
|
||||
$csv = fopen('php://output', 'w');
|
||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($csv, $columns->pluck('label')->all());
|
||||
|
||||
foreach ($query->cursor() as $row) {
|
||||
fputcsv($csv, $columns->map(function (array $column) use ($row): string {
|
||||
$value = $this->columnValue($row, $column['field']);
|
||||
|
||||
return $this->csvValue($value, $column['kind']);
|
||||
})->all());
|
||||
}
|
||||
fclose($csv);
|
||||
}, $billType . '_account_bills.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
private function columnValue(AccountBill $row, string $field): mixed
|
||||
{
|
||||
if (str_starts_with($field, 'payload.')) {
|
||||
return data_get($row->payload ?? [], substr($field, 8), '');
|
||||
}
|
||||
|
||||
return $row->getAttribute($field) ?? '';
|
||||
}
|
||||
|
||||
private function csvValue(mixed $value, string $kind): string
|
||||
{
|
||||
$text = (string) ($value ?? '');
|
||||
if ($kind === 'num' && preg_match('/^\d{12,}$/', $text)) {
|
||||
return "\t" . $text;
|
||||
}
|
||||
|
||||
return preg_match('/^[=+\-@]/', $text) ? "'" . $text : $text;
|
||||
}
|
||||
|
||||
public function show(AccountBill $bill)
|
||||
{
|
||||
$this->authorizeStoreReceivingBills();
|
||||
|
||||
@ -11,6 +11,34 @@ use RuntimeException;
|
||||
|
||||
class AlipayBills extends Controller
|
||||
{
|
||||
private const EXPORT_COLUMNS = [
|
||||
'record_code' => '记录编码',
|
||||
'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' => '收入',
|
||||
'expense' => '支出',
|
||||
'balance' => '收支净额',
|
||||
'business_type' => '业务类型',
|
||||
'remark' => '备注',
|
||||
'online_order_no' => '线上单号',
|
||||
'online_real_store' => '线上单号对应实际店铺',
|
||||
'business_description' => '业务描述',
|
||||
'business_bill_source' => '业务账单来源',
|
||||
'business_order_no' => '业务订单号',
|
||||
'created_at' => '创建时间',
|
||||
'updated_at' => '修改时间',
|
||||
'modifier' => '修改人',
|
||||
];
|
||||
|
||||
/**
|
||||
* 淘系支付宝账户账单列表(店铺收款账户账单 › 淘系支付宝账户)。
|
||||
* 经由 admin 路由组(web 会话)暴露,前端带 CSRF 调用即可。
|
||||
@ -68,8 +96,13 @@ class AlipayBills extends Controller
|
||||
'start' => ['nullable', 'date_format:Y-m-d'],
|
||||
'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'],
|
||||
'keyword' => ['nullable', 'string', 'max:255'],
|
||||
'columns' => ['nullable', 'array', 'max:25'],
|
||||
'columns.*' => ['string', 'max:64'],
|
||||
]);
|
||||
|
||||
$columns = $this->requestedExportColumns($filters['columns'] ?? []);
|
||||
unset($filters['columns']);
|
||||
|
||||
try {
|
||||
$rows = $repository->exportRows(array_map(static fn (mixed $value): string => trim((string) $value), $filters));
|
||||
} catch (RuntimeException $exception) {
|
||||
@ -80,17 +113,49 @@ class AlipayBills extends Controller
|
||||
return response()->json(['message' => '淘系支付宝账单共享业务镜像正在首次同步,完成后将自动显示。'], 503);
|
||||
}
|
||||
|
||||
return response()->streamDownload(function () use ($rows): void {
|
||||
return response()->streamDownload(function () use ($rows, $columns): void {
|
||||
$csv = fopen('php://output', 'w');
|
||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($csv, ['记录编码', '原始店铺', '平台渠道', '账单项目', '账务订单号', '业务流水号', '商户订单号', '业务基础订单号', '商品编码', '发生时间', '收入(元)', '支出(元)', '收支净额(元)', '收支类型', '线上单号', '业务描述', '业务账单来源', '创建时间', '修改时间']);
|
||||
fputcsv($csv, array_values($columns));
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($csv, [$row['record_code'], $row['store_name'], $row['alipay_account'], $row['bill_item'], $row['account_order_no'], $row['business_serial_no'], $row['merchant_order_no'], $row['business_base_order_no'], $row['goods_name'], $row['occurred_at'], $row['income'], $row['expense'], $row['balance'], $row['business_type'], $row['online_order_no'], $row['business_description'], $row['business_bill_source'], $row['created_at'], $row['updated_at']]);
|
||||
fputcsv($csv, array_map(
|
||||
fn (string $field): string => $this->csvValue($row[$field] ?? '', $field),
|
||||
array_keys($columns),
|
||||
));
|
||||
}
|
||||
fclose($csv);
|
||||
}, 'taobao_alipay_bills.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function requestedExportColumns(array $requested): array
|
||||
{
|
||||
if ($requested === []) {
|
||||
return self::EXPORT_COLUMNS;
|
||||
}
|
||||
|
||||
$columns = [];
|
||||
foreach ($requested as $field) {
|
||||
if (isset(self::EXPORT_COLUMNS[$field])) {
|
||||
$columns[$field] = self::EXPORT_COLUMNS[$field];
|
||||
}
|
||||
}
|
||||
|
||||
abort_if($columns === [], 422, '至少选择一个可导出的字段。');
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
private function csvValue(mixed $value, string $field): string
|
||||
{
|
||||
$text = (string) ($value ?? '');
|
||||
if (preg_match('/(?:_no|_code|serial|goods_name)$/', $field) && preg_match('/^\d{12,}$/', $text)) {
|
||||
return "\t" . $text;
|
||||
}
|
||||
|
||||
return preg_match('/^[=+\-@]/', $text) ? "'" . $text : $text;
|
||||
}
|
||||
|
||||
public function show(AlipayBill $bill)
|
||||
{
|
||||
$this->authorizeStoreReceivingBills();
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
namespace Modules\EcommerceFinance\Repositories;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\DingPayableWorkflowStatus;
|
||||
use RuntimeException;
|
||||
@ -51,6 +52,66 @@ class DingOnlineDaifaPriceMirrorRepository
|
||||
$perPage = min(max($perPage, 1), 100);
|
||||
$state = $this->connection->table('business_mirror_table_states')->where('dataset_key', self::DATASET_KEY)->first();
|
||||
|
||||
$rows = $this->filteredQuery($filters)
|
||||
->orderByDesc('workflow_created_at')
|
||||
->orderByDesc('process_instance_id')
|
||||
->orderByDesc('detail_index')
|
||||
->get();
|
||||
|
||||
$statusFilter = strtoupper(trim((string) ($filters['status'] ?? '')));
|
||||
$matched = [];
|
||||
foreach ($rows as $row) {
|
||||
$workflow = $this->decode((string) $row->workflow_payload, []);
|
||||
if (! $this->matchesStatus($workflow, $statusFilter)) {
|
||||
continue;
|
||||
}
|
||||
$matched[] = $row;
|
||||
}
|
||||
|
||||
$total = count($matched);
|
||||
$pageRows = array_slice($matched, ($page - 1) * $perPage, $perPage);
|
||||
|
||||
$data = [];
|
||||
foreach ($pageRows as $row) {
|
||||
$workflow = $this->decode((string) $row->workflow_payload, []);
|
||||
$data[] = $this->presentRow($row, $workflow);
|
||||
}
|
||||
|
||||
return [
|
||||
'data' => $data,
|
||||
'total' => $total,
|
||||
'status' => (string) ($state->status ?? 'unknown'),
|
||||
'last_synced_at' => $state->last_succeeded_at ? (string) $state->last_succeeded_at : null,
|
||||
'summary' => $this->summary($matched),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return \Generator<int,array<string,mixed>> */
|
||||
public function exportRows(array $filters): \Generator
|
||||
{
|
||||
if (! $this->ready()) {
|
||||
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')
|
||||
->orderByDesc('detail_index')
|
||||
->cursor();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$workflow = $this->decode((string) $row->workflow_payload, []);
|
||||
if (! $this->matchesStatus($workflow, $statusFilter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
yield $this->presentRow($row, $workflow);
|
||||
}
|
||||
}
|
||||
|
||||
private function filteredQuery(array $filters): Builder
|
||||
{
|
||||
$query = $this->connection->table(self::TARGET_TABLE);
|
||||
|
||||
if (($filters['product_id'] ?? '') !== '') {
|
||||
@ -59,6 +120,12 @@ class DingOnlineDaifaPriceMirrorRepository
|
||||
if (($filters['shop_name'] ?? '') !== '') {
|
||||
$query->where('shop_name', (string) $filters['shop_name']);
|
||||
}
|
||||
if (($filters['supplier_name'] ?? '') !== '') {
|
||||
$query->whereRaw("supplier_name LIKE ? ESCAPE '!'", [$this->contains((string) $filters['supplier_name'])]);
|
||||
}
|
||||
if (($filters['material_no'] ?? '') !== '') {
|
||||
$query->where('material_no', (string) $filters['material_no']);
|
||||
}
|
||||
if (($filters['keyword'] ?? '') !== '') {
|
||||
$keyword = (string) $filters['keyword'];
|
||||
$query->where(function ($q) use ($keyword): void {
|
||||
@ -74,64 +141,54 @@ class DingOnlineDaifaPriceMirrorRepository
|
||||
$query->where('workflow_created_at', '<', \Illuminate\Support\Carbon::parse((string) $filters['created_to'])->addDay()->startOfDay()->format('Y-m-d H:i:s'));
|
||||
}
|
||||
|
||||
$rows = $query->orderByDesc('workflow_created_at')->orderByDesc('process_instance_id')->orderByDesc('detail_index')->get();
|
||||
return $query;
|
||||
}
|
||||
|
||||
$statusFilter = strtoupper(trim((string) ($filters['status'] ?? '')));
|
||||
$matched = [];
|
||||
foreach ($rows as $row) {
|
||||
$workflow = $this->decode((string) $row->workflow_payload, []);
|
||||
if ($statusFilter !== '' && DingPayableWorkflowStatus::key($workflow) !== $statusFilter) {
|
||||
continue;
|
||||
}
|
||||
$matched[] = $row;
|
||||
}
|
||||
private function matchesStatus(array $workflow, string $statusFilter): bool
|
||||
{
|
||||
return $statusFilter === '' || DingPayableWorkflowStatus::key($workflow) === $statusFilter;
|
||||
}
|
||||
|
||||
$total = count($matched);
|
||||
$pageRows = array_slice($matched, ($page - 1) * $perPage, $perPage);
|
||||
|
||||
$data = [];
|
||||
foreach ($pageRows as $row) {
|
||||
$workflow = $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
|
||||
? ['matched' => true, 'name' => $resolvedName, 'sku_id' => null, 'i_id' => null]
|
||||
: ['matched' => false, 'name' => null, 'sku_id' => null, 'i_id' => null];
|
||||
$data[] = [
|
||||
'process_instance_id' => (string) $row->process_instance_id,
|
||||
'detail_index' => (int) $row->detail_index,
|
||||
'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 ?? ''),
|
||||
'supplier_name' => (string) ($row->supplier_name ?? ''),
|
||||
'material_no' => (string) ($row->material_no ?? ''),
|
||||
'ship_qty' => $row->ship_qty === null ? null : (int) $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),
|
||||
'matched_product' => $product,
|
||||
'workflow_created_at' => (string) ($row->workflow_created_at ?? ''),
|
||||
];
|
||||
}
|
||||
/** @return array<string,mixed> */
|
||||
private function presentRow(object $row, array $workflow): array
|
||||
{
|
||||
$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
|
||||
? ['matched' => true, 'name' => $resolvedName, 'sku_id' => null, 'i_id' => null]
|
||||
: ['matched' => false, 'name' => null, 'sku_id' => null, 'i_id' => null];
|
||||
|
||||
return [
|
||||
'data' => $data,
|
||||
'total' => $total,
|
||||
'status' => (string) ($state->status ?? 'unknown'),
|
||||
'last_synced_at' => $state->last_succeeded_at ? (string) $state->last_succeeded_at : null,
|
||||
'summary' => $this->summary($matched),
|
||||
'process_instance_id' => (string) $row->process_instance_id,
|
||||
'detail_index' => (int) $row->detail_index,
|
||||
'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 ?? ''),
|
||||
'supplier_name' => (string) ($row->supplier_name ?? ''),
|
||||
'material_no' => (string) ($row->material_no ?? ''),
|
||||
'ship_qty' => $row->ship_qty === null ? null : (int) $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),
|
||||
'matched_product' => $product,
|
||||
'workflow_created_at' => (string) ($row->workflow_created_at ?? ''),
|
||||
];
|
||||
}
|
||||
|
||||
private function contains(string $value): string
|
||||
{
|
||||
return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%';
|
||||
}
|
||||
|
||||
/** @param list<object> $rows */
|
||||
private function summary(array $rows): array
|
||||
{
|
||||
|
||||
@ -1,342 +1,72 @@
|
||||
<template>
|
||||
<div class="account-page">
|
||||
<!-- 汇总卡片 -->
|
||||
<div class="ab-stats">
|
||||
<div class="ab-stat">
|
||||
<div class="ab-stat-k">收入合计</div>
|
||||
<div class="ab-stat-v income">{{ money(summary.income) }}</div>
|
||||
<div class="ab-stat-s">{{ summary.count }} 笔交易</div>
|
||||
</div>
|
||||
<div class="ab-stat">
|
||||
<div class="ab-stat-k">支出合计</div>
|
||||
<div class="ab-stat-v expense">{{ money(summary.expense) }}</div>
|
||||
<div class="ab-stat-s">按当前筛选</div>
|
||||
</div>
|
||||
<div class="ab-stat">
|
||||
<div class="ab-stat-k">期末余额(最新)</div>
|
||||
<div class="ab-stat-v">{{ money(summary.balance) }}</div>
|
||||
<div class="ab-stat-s">最新一条记录</div>
|
||||
</div>
|
||||
<div class="ab-stat">
|
||||
<div class="ab-stat-k">交易笔数</div>
|
||||
<div class="ab-stat-v">{{ summary.count }}</div>
|
||||
<div class="ab-stat-s">当前筛选结果</div>
|
||||
</div>
|
||||
<div class="table-workspace">
|
||||
<div class="tw-stats">
|
||||
<div v-for="stat in stats" :key="stat.label" class="tw-stat"><div class="tw-label">{{ stat.label }}</div><div class="tw-value" :class="stat.className">{{ stat.value }}</div><div class="tw-note">{{ stat.note }}</div></div>
|
||||
</div>
|
||||
|
||||
<!-- 筛选栏 -->
|
||||
<div class="ab-filter">
|
||||
<div class="ab-field">
|
||||
<label>店铺</label>
|
||||
<input v-model.trim="filters.store_name" placeholder="店铺名称" />
|
||||
</div>
|
||||
<div class="ab-field">
|
||||
<label>账单项目</label>
|
||||
<input v-model.trim="filters.bill_item" placeholder="账单项目" />
|
||||
</div>
|
||||
<div class="ab-field ab-field-date">
|
||||
<label>时间</label>
|
||||
<div class="ab-date">
|
||||
<input type="date" v-model="filters.start" /> <span>~</span>
|
||||
<input type="date" v-model="filters.end" />
|
||||
<form class="tw-filter" @submit.prevent="applyFilters">
|
||||
<label>店铺<input v-model.trim="filters.store_name" placeholder="店铺名称" /></label>
|
||||
<label>账单项目<input v-model.trim="filters.bill_item" placeholder="账单项目" /></label>
|
||||
<label class="tw-date">发生时间<span><input v-model="filters.start" type="date" aria-label="开始日期" /><b>至</b><input v-model="filters.end" type="date" aria-label="结束日期" /></span></label>
|
||||
<label class="tw-keyword">关键词(记录编码 / 订单 / 备注)<input v-model.trim="filters.keyword" placeholder="输入关键词" /></label>
|
||||
<div class="tw-actions"><button class="tw-button tw-primary" type="submit">查询</button><button class="tw-button" type="button" @click="resetFilters">重置</button></div>
|
||||
</form>
|
||||
<section class="tw-panel" :aria-label="`${columnsTitle || '账户'}账单明细`">
|
||||
<div v-if="loadError" class="tw-alert" role="alert"><span>账单加载失败,请重试</span><button type="button" @click="fetch">重新加载</button></div>
|
||||
<div class="tw-toolbar">
|
||||
<div><strong>{{ sourceGroups.length ? '账单明细' : columnsTitle }}</strong><span v-if="!loading" class="tw-count">{{ total }} 条</span></div>
|
||||
<div class="tw-tools" v-if="sourceColumns.length">
|
||||
<select v-model="exportMode" title="选择导出范围" aria-label="导出范围"><option value="page-visible">当前页 · 当前显示列</option><option value="filtered-visible">全部筛选结果 · 当前显示列</option><option value="filtered-all">全部筛选结果 · 全部字段</option></select>
|
||||
<button type="button" class="tw-button" @click="exportRows"><span class="material-icons-outlined" aria-hidden="true">download</span>导出</button>
|
||||
<table-column-settings :columns="sourceColumns" :user-key="userKey" page-key="store-receiving-bills" :tab-key="billType" table-key="bill-details" @change="configuredColumns = $event" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="ab-field ab-field-kw">
|
||||
<label>关键词(记录编码 / 订单 / 备注)</label>
|
||||
<input v-model.trim="filters.keyword" placeholder="输入关键词" />
|
||||
</div>
|
||||
<div class="ab-actions">
|
||||
<button class="ab-btn ab-btn-primary" @click="applyFilters">查询</button>
|
||||
<button class="ab-btn" @click="resetFilters">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据表(列由后端配置动态渲染) -->
|
||||
<div class="ab-panel">
|
||||
<div class="ab-phead">
|
||||
<div class="ab-title">{{ columnGroups.length ? '账单明细' : columnsTitle }}</div>
|
||||
<div class="ab-count" v-if="!loading">{{ total }} 条</div>
|
||||
</div>
|
||||
|
||||
<div class="ab-scroll">
|
||||
<table class="ab-table" :class="{ 'ab-table-grouped': columnGroups.length }" v-if="!loading && !loadError && columns.length">
|
||||
<div ref="scroll" class="tw-scroll">
|
||||
<table v-if="!loading && !loadError && configuredColumns.length" class="tw-table">
|
||||
<thead>
|
||||
<tr class="ab-group" v-if="columnGroups.length">
|
||||
<th v-for="(group, i) in columnGroups" :key="i" :colspan="group.span" scope="colgroup">
|
||||
{{ group.label }}
|
||||
</th>
|
||||
</tr>
|
||||
<tr class="ab-col">
|
||||
<th v-for="(c, i) in columns" :key="i" :class="{ 'ab-num': isNumKind(c.kind) }" scope="col"
|
||||
@click="maybeSort(c)">
|
||||
{{ c.label }}
|
||||
<span class="ab-sort" v-if="sortableField(c.field)">⇅</span>
|
||||
</th>
|
||||
</tr>
|
||||
<tr v-if="visibleGroups.length" class="tw-groups"><th v-for="(group,index) in visibleGroups" :key="`${group.label}-${index}`" :colspan="group.span" scope="colgroup">{{ group.label }}</th></tr>
|
||||
<tr class="tw-columns" :class="{ 'is-single': !visibleGroups.length }"><th v-for="column in visibleColumns" :key="column.key" :class="{ 'is-number': isNumber(column.kind), 'is-sortable': sortableField(column.field) }" scope="col" @click="maybeSort(column)">{{ column.label }} <span v-if="sortableField(column.field)" class="tw-sort" aria-hidden="true">{{ sortMark(column.field) }}</span></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="r in rows" :key="r.id">
|
||||
<td v-for="(c, i) in columns" :key="i" :class="cellClass(c)">
|
||||
<span v-if="c.kind === 'tag'" class="ab-tag">{{ cellText(r, c) || '—' }}</span>
|
||||
<template v-else>{{ cellDisplay(r, c) }}</template>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!rows.length" class="ab-empty-row">
|
||||
<td :colspan="columns.length" class="ab-empty">没有符合条件的账单记录</td>
|
||||
</tr>
|
||||
<tr v-for="row in rows" :key="row.id"><td v-for="column in visibleColumns" :key="column.key" :class="cellClass(column)"><span v-if="column.kind === 'tag'" class="tw-tag">{{ displayValue(row,column) }}</span><template v-else>{{ displayValue(row,column) }}</template></td></tr>
|
||||
<tr v-if="!rows.length"><td :colspan="visibleColumns.length" class="tw-empty">没有符合条件的账单记录</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-else-if="loading" class="ab-empty">加载中…</div>
|
||||
<div v-else-if="loadError" class="ab-empty ab-error">
|
||||
<div>账单加载失败,请重试</div>
|
||||
<button class="ab-btn" @click="fetch">重新加载</button>
|
||||
</div>
|
||||
<div v-else class="ab-empty">暂无账单字段</div>
|
||||
<div v-else-if="loading" class="tw-empty" role="status">加载中…</div><div v-else-if="!loadError" class="tw-empty">暂无账单字段</div>
|
||||
</div>
|
||||
|
||||
<!-- 分页 -->
|
||||
<div class="ab-pager" v-if="rows.length">
|
||||
<div class="ab-page-info">第 {{ rangeStart }} - {{ rangeEnd }} 条 / 共 {{ total }} 条</div>
|
||||
<div class="ab-page-right">
|
||||
<span>每页</span>
|
||||
<select v-model.number="perPage" @change="changePage(1)">
|
||||
<option :value="10">10</option>
|
||||
<option :value="20">20</option>
|
||||
<option :value="50">50</option>
|
||||
</select>
|
||||
<button class="ab-page-btn" :disabled="currentPage <= 1" @click="changePage(1)">«</button>
|
||||
<button class="ab-page-btn" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">‹</button>
|
||||
<span class="ab-page-no">{{ currentPage }} / {{ lastPage }}</span>
|
||||
<button class="ab-page-btn" :disabled="currentPage >= lastPage" @click="changePage(currentPage + 1)">›</button>
|
||||
<button class="ab-page-btn" :disabled="currentPage >= lastPage" @click="changePage(lastPage)">»</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="rows.length" class="tw-pager"><div>第 {{ rangeStart }} - {{ rangeEnd }} 条 / 共 {{ total }} 条</div><div class="tw-page-actions"><label>每页 <select v-model.number="perPage" @change="changePage(1)"><option :value="10">10</option><option :value="20">20</option><option :value="50">50</option></select></label><button type="button" :disabled="currentPage<=1" title="第一页" @click="changePage(1)">«</button><button type="button" :disabled="currentPage<=1" title="上一页" @click="changePage(currentPage-1)">‹</button><span>{{ currentPage }} / {{ lastPage }}</span><button type="button" :disabled="currentPage>=lastPage" title="下一页" @click="changePage(currentPage+1)">›</button><button type="button" :disabled="currentPage>=lastPage" title="最后一页" @click="changePage(lastPage)">»</button></div></div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
const SORTABLE = ['occurred_at', 'income', 'expense', 'balance', 'record_code'];
|
||||
|
||||
import TableColumnSettings from './TableColumnSettings.vue';
|
||||
const SORTABLE = ['occurred_at','income','expense','balance','record_code'];
|
||||
export default {
|
||||
name: 'AccountBills',
|
||||
|
||||
props: {
|
||||
apiBase: { type: String, required: true },
|
||||
billType: { type: String, required: true },
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
loading: false,
|
||||
loadError: false,
|
||||
rows: [],
|
||||
columns: [],
|
||||
columnsTitle: '',
|
||||
columnGroups: [],
|
||||
summary: { income: 0, expense: 0, balance: 0, count: 0 },
|
||||
total: 0,
|
||||
currentPage: 1,
|
||||
lastPage: 1,
|
||||
perPage: 10,
|
||||
filters: { store_name: '', bill_item: '', start: '', end: '', keyword: '' },
|
||||
sort: { key: 'occurred_at', dir: 'desc' },
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
rangeStart() {
|
||||
return this.total === 0 ? 0 : (this.currentPage - 1) * this.perPage + 1;
|
||||
},
|
||||
rangeEnd() {
|
||||
return Math.min(this.currentPage * this.perPage, this.total);
|
||||
},
|
||||
},
|
||||
|
||||
mounted() {
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
methods: {
|
||||
async fetch() {
|
||||
this.loading = true;
|
||||
this.loadError = false;
|
||||
const params = {
|
||||
...this.filters,
|
||||
sort: this.sort.key,
|
||||
dir: this.sort.dir,
|
||||
limit: this.perPage,
|
||||
page: this.currentPage,
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await window.axios.get(this.apiBase, { params });
|
||||
const body = res.data || {};
|
||||
this.rows = body.data || [];
|
||||
this.total = body.total || 0;
|
||||
this.currentPage = body.current_page || 1;
|
||||
this.lastPage = body.last_page || 1;
|
||||
this.perPage = body.per_page || this.perPage;
|
||||
this.summary = body.summary || { income: 0, expense: 0, balance: 0, count: 0 };
|
||||
if (body.columns) {
|
||||
this.columns = body.columns.columns || body.columns || [];
|
||||
this.columnsTitle = body.columns.title || '';
|
||||
this.columnGroups = body.columns.groups || [];
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载账单失败', e);
|
||||
this.rows = [];
|
||||
this.columns = [];
|
||||
this.columnsTitle = '';
|
||||
this.columnGroups = [];
|
||||
this.total = 0;
|
||||
this.summary = { income: 0, expense: 0, balance: 0, count: 0 };
|
||||
this.loadError = true;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
applyFilters() {
|
||||
this.currentPage = 1;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = { store_name: '', bill_item: '', start: '', end: '', keyword: '' };
|
||||
this.currentPage = 1;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
changePage(p) {
|
||||
this.currentPage = p;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
maybeSort(c) {
|
||||
if (!this.sortableField(c.field)) return;
|
||||
if (this.sort.key === c.field) {
|
||||
this.sort.dir = this.sort.dir === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sort.key = c.field;
|
||||
this.sort.dir = 'desc';
|
||||
}
|
||||
this.currentPage = 1;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
sortableField(field) {
|
||||
return SORTABLE.indexOf(field) !== -1;
|
||||
},
|
||||
|
||||
getValue(row, field) {
|
||||
if (!field) return '';
|
||||
if (field.indexOf('payload.') === 0) {
|
||||
const key = field.slice(8);
|
||||
const p = row.payload || {};
|
||||
return p[key] === null || p[key] === undefined ? '' : p[key];
|
||||
}
|
||||
return row[field] === null || row[field] === undefined ? '' : row[field];
|
||||
},
|
||||
|
||||
cellText(row, c) {
|
||||
return this.getValue(row, c.field);
|
||||
},
|
||||
|
||||
cellDisplay(row, c) {
|
||||
const v = this.getValue(row, c.field);
|
||||
if (v === '' || v === null || v === undefined) return '—';
|
||||
|
||||
switch (c.kind) {
|
||||
case 'money_in':
|
||||
return '+' + this.money(v);
|
||||
case 'money_out':
|
||||
return '−' + this.money(v);
|
||||
case 'balance':
|
||||
case 'money':
|
||||
return this.money(v);
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
},
|
||||
|
||||
cellClass(c) {
|
||||
const cls = { 'ab-num': this.isNumKind(c.kind) };
|
||||
if (c.kind === 'money_in') cls['ab-in'] = true;
|
||||
if (c.kind === 'money_out') cls['ab-out'] = true;
|
||||
if (c.kind === 'num') cls['ab-mono'] = true;
|
||||
return cls;
|
||||
},
|
||||
|
||||
isNumKind(kind) {
|
||||
return kind === 'money' || kind === 'money_in' || kind === 'money_out' || kind === 'balance' || kind === 'num';
|
||||
},
|
||||
|
||||
money(n) {
|
||||
const v = Number(n || 0);
|
||||
return '¥' + v.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
},
|
||||
name:'AccountBills', components:{ TableColumnSettings }, props:{ apiBase:{type:String,required:true}, billType:{type:String,required:true} },
|
||||
data(){return{loading:false,loadError:false,rows:[],sourceColumns:[],configuredColumns:[],columnsTitle:'',sourceGroups:[],summary:{income:0,expense:0,balance:0,count:0},total:0,currentPage:1,lastPage:1,perPage:20,filters:{store_name:'',bill_item:'',start:'',end:'',keyword:''},sort:{key:'occurred_at',dir:'desc'},exportMode:'filtered-visible'};},
|
||||
computed:{
|
||||
userKey(){const mount=document.querySelector('.business-blank-page');return mount&&mount.dataset.tablePreferencesUser?mount.dataset.tablePreferencesUser:'anonymous';},
|
||||
visibleColumns(){return this.configuredColumns.filter(column=>column.visible);},
|
||||
visibleGroups(){return this.visibleColumns.reduce((groups,column)=>{if(!column.group)return groups;const last=groups[groups.length-1];if(last&&last.label===column.group)last.span+=1;else groups.push({label:column.group,span:1});return groups;},[]);},
|
||||
stats(){return[{label:'收入合计',value:this.money(this.summary.income),note:`${this.summary.count} 笔交易`,className:'is-income'},{label:'支出合计',value:this.money(this.summary.expense),note:'按当前筛选',className:'is-expense'},{label:'期末余额(最新)',value:this.money(this.summary.balance),note:'最新一条记录',className:''},{label:'交易笔数',value:this.summary.count,note:'当前筛选结果',className:''}];},
|
||||
rangeStart(){return this.total===0?0:(this.currentPage-1)*this.perPage+1;},rangeEnd(){return Math.min(this.currentPage*this.perPage,this.total);}
|
||||
},
|
||||
mounted(){this.fetch();},
|
||||
methods:{
|
||||
async fetch(){this.loading=true;this.loadError=false;try{const response=await window.axios.get(this.apiBase,{params:{...this.filters,sort:this.sort.key,dir:this.sort.dir,limit:this.perPage,page:this.currentPage}});const body=response.data||{};this.rows=body.data||[];this.total=body.total||0;this.currentPage=body.current_page||1;this.lastPage=body.last_page||1;this.perPage=body.per_page||this.perPage;this.summary=body.summary||{income:0,expense:0,balance:0,count:0};if(body.columns){this.columnsTitle=body.columns.title||'';this.sourceGroups=body.columns.groups||[];this.sourceColumns=this.attachGroups(body.columns.columns||body.columns||[],this.sourceGroups);}}catch(error){this.rows=[];this.total=0;this.summary={income:0,expense:0,balance:0,count:0};this.loadError=true;}finally{this.loading=false;}},
|
||||
attachGroups(columns,groups){let index=0;return columns.map((column,columnIndex)=>{while(groups[index]&&columnIndex>=groups.slice(0,index+1).reduce((sum,group)=>sum+Number(group.span||0),0))index+=1;return{...column,key:column.field||`column-${columnIndex}`,group:groups[index]?groups[index].label:''};});},
|
||||
applyFilters(){this.currentPage=1;this.fetch();},resetFilters(){this.filters={store_name:'',bill_item:'',start:'',end:'',keyword:''};this.applyFilters();},changePage(page){this.currentPage=page;this.fetch();this.$nextTick(()=>{if(this.$refs.scroll)this.$refs.scroll.scrollTop=0;});},
|
||||
maybeSort(column){if(!this.sortableField(column.field))return;this.sort.dir=this.sort.key===column.field&&this.sort.dir==='desc'?'asc':'desc';this.sort.key=column.field;this.applyFilters();},sortableField(field){return SORTABLE.indexOf(field)!==-1;},sortMark(field){return this.sort.key===field?(this.sort.dir==='asc'?'↑':'↓'):'↕';},
|
||||
getValue(row,field){if(!field)return'';if(field.indexOf('payload.')===0){const payload=row.payload||{};const value=payload[field.slice(8)];return value===null||value===undefined?'':value;}const value=row[field];return value===null||value===undefined?'':value;},rawValue(row,column){return this.getValue(row,column.field);},
|
||||
displayValue(row,column){const value=this.rawValue(row,column);if(value==='')return'—';if(column.kind==='money_in')return Number(value)>0?`+${this.money(value)}`:'—';if(column.kind==='money_out')return Number(value)>0?`-${this.money(value)}`:'—';if(['balance','money'].indexOf(column.kind)!==-1)return this.money(value);return value;},cellClass(column){return{'is-number':this.isNumber(column.kind),'is-id':column.kind==='num','is-income':column.kind==='money_in','is-expense':column.kind==='money_out'};},isNumber(kind){return['money','money_in','money_out','balance','num'].indexOf(kind)!==-1;},money(value){return`¥${Number(value||0).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2})}`;},
|
||||
exportRows(){if(this.exportMode==='page-visible'){this.downloadCurrentPage();return;}const params=new URLSearchParams(this.filters);params.set('export','1');params.set('sort',this.sort.key);params.set('dir',this.sort.dir);if(this.exportMode==='filtered-visible')this.visibleColumns.forEach(column=>params.append('columns[]',column.field));window.location.assign(`${this.apiBase}?${params.toString()}`);},
|
||||
downloadCurrentPage(){const csvRows=[this.visibleColumns.map(column=>column.label),...this.rows.map(row=>this.visibleColumns.map(column=>this.rawValue(row,column)))];const csv=csvRows.map(values=>values.map(this.csvCell).join(',')).join('\r\n');const link=document.createElement('a');link.href=URL.createObjectURL(new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'}));link.download=`${this.billType}_account_bills_page_${this.currentPage}.csv`;link.click();URL.revokeObjectURL(link.href);},csvCell(value){const text=String(value===null||value===undefined?'':value);const safe=/^[=+\-@]/.test(text)?`'${text}`:text;return`"${safe.replace(/"/g,'""')}"`;}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.account-page { padding: 1.25rem 1.5rem 1.5rem; }
|
||||
|
||||
.ab-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.875rem; margin-bottom: 0.875rem; }
|
||||
.ab-stat { background: #fff; border: 1px solid #e6e9f0; border-radius: 0.75rem; padding: 1rem 1.125rem; box-shadow: 0 1px 2px rgba(16,24,40,.04), 0 1px 3px rgba(16,24,40,.06); }
|
||||
.ab-stat-k { font-size: 0.75rem; color: #6b7280; }
|
||||
.ab-stat-v { font-size: 1.375rem; font-weight: 700; margin-top: 0.5rem; letter-spacing: .3px; }
|
||||
.ab-stat-s { font-size: 0.75rem; color: #9aa3b2; margin-top: 0.25rem; }
|
||||
.ab-stat-v.income { color: #f5222d; }
|
||||
.ab-stat-v.expense { color: #16a34a; }
|
||||
|
||||
.ab-filter { display: flex; flex-wrap: wrap; gap: 0.875rem; background: #fff; border: 1px solid #e6e9f0; border-radius: 0.75rem; padding: 1rem 1.125rem; margin-bottom: 0.875rem; }
|
||||
.ab-field { display: flex; flex-direction: column; gap: 0.3125rem; }
|
||||
.ab-field label { font-size: 0.75rem; color: #6b7280; font-weight: 500; }
|
||||
.ab-field input { height: 2.125rem; min-width: 11.25rem; padding: 0 0.625rem; border: 1px solid #e6e9f0; border-radius: 0.5rem; background: #fff; font-size: 0.8125rem; color: #1f2937; outline: none; }
|
||||
.ab-field input:focus { border-color: var(--vip-content-accent); box-shadow: 0 0 0 3px rgba(185,149,79,.16); }
|
||||
.ab-field-kw { flex: 1; min-width: 12.5rem; }
|
||||
.ab-field-kw input { width: 100%; }
|
||||
.ab-date { display: flex; align-items: center; gap: 0.375rem; }
|
||||
.ab-date input { min-width: 8.75rem; }
|
||||
.ab-actions { display: flex; gap: 0.625rem; align-items: flex-end; margin-left: auto; }
|
||||
.ab-btn { height: 2.125rem; padding: 0 0.875rem; border-radius: 0.5rem; border: 1px solid #e6e9f0; background: #fff; color: #1f2937; cursor: pointer; font-size: 0.8125rem; font-weight: 500; }
|
||||
.ab-btn:hover { border-color: #c7cdda; }
|
||||
.ab-btn-primary { background: var(--vip-content-accent); border-color: var(--vip-content-accent); color: #fff; }
|
||||
.ab-btn-primary:hover { background: var(--vip-content-accent-dark); }
|
||||
|
||||
.ab-panel { background: #fff; border: 1px solid #e6e9f0; border-radius: 0.75rem; box-shadow: 0 1px 2px rgba(16,24,40,.04), 0 1px 3px rgba(16,24,40,.06); overflow: hidden; }
|
||||
.ab-phead { display: flex; align-items: center; gap: 0.625rem; padding: 0.875rem 1rem; border-bottom: 1px solid #e6e9f0; }
|
||||
.ab-title { font-weight: 600; font-size: 0.875rem; }
|
||||
.ab-count { color: #9aa3b2; font-size: 0.75rem; }
|
||||
|
||||
.ab-scroll { overflow-x: auto; }
|
||||
.ab-table { border-collapse: collapse; width: 100%; font-size: 0.78125rem; }
|
||||
.ab-table-grouped { min-width: 2200px; }
|
||||
.ab-table thead .ab-group th { background: #f0f3f9; color: #6b7280; font-size: 0.75rem; font-weight: 600; text-align: center; border-bottom: 1px solid #dfe4ec; padding: 0.625rem; white-space: nowrap; }
|
||||
.ab-table thead .ab-col th { background: #fafbfd; color: #1f2937; font-weight: 600; text-align: left; border-bottom: 1px solid #e6e9f0; padding: 0.5625rem 0.625rem; white-space: nowrap; }
|
||||
.ab-table thead .ab-col th.ab-num { text-align: right; }
|
||||
.ab-sort { color: #9aa3b2; margin-left: 0.1875rem; }
|
||||
.ab-table tbody td { padding: 0.5625rem 0.625rem; border-bottom: 1px solid #f1f3f7; white-space: nowrap; color: #1f2937; }
|
||||
.ab-table tbody tr:hover { background: #f7f9ff; }
|
||||
.ab-num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.ab-mono { font-family: ui-monospace, Menlo, Consolas, monospace; color: #6b7280; font-size: 0.71875rem; }
|
||||
.ab-in { color: #f5222d; font-weight: 600; }
|
||||
.ab-out { color: #16a34a; font-weight: 600; }
|
||||
.ab-tag { display: inline-block; padding: 0.0625rem 0.5rem; border-radius: 1rem; font-size: 0.71875rem; font-weight: 500; background: var(--vip-content-accent-soft); color: var(--vip-content-accent-dark); }
|
||||
|
||||
.ab-empty { padding: 3rem; text-align: center; color: #9aa3b2; }
|
||||
.ab-error { color: #dc2626; }
|
||||
.ab-error .ab-btn { margin-top: 0.75rem; color: #1f2937; }
|
||||
|
||||
.ab-pager { display: flex; align-items: center; gap: 0.625rem; padding: 0.875rem 1rem; border-top: 1px solid #e6e9f0; flex-wrap: wrap; }
|
||||
.ab-page-info { color: #6b7280; font-size: 0.78125rem; }
|
||||
.ab-page-right { margin-left: auto; display: flex; align-items: center; gap: 0.375rem; font-size: 0.78125rem; }
|
||||
.ab-page-right select { height: 1.875rem; border: 1px solid #e6e9f0; border-radius: 0.4375rem; padding: 0 0.375rem; }
|
||||
.ab-page-btn { height: 1.875rem; min-width: 1.875rem; padding: 0 0.5rem; border: 1px solid #e6e9f0; background: #fff; border-radius: 0.4375rem; cursor: pointer; font-size: 0.78125rem; color: #1f2937; }
|
||||
.ab-page-btn:hover:not(:disabled) { border-color: var(--vip-content-accent); color: var(--vip-content-accent); }
|
||||
.ab-page-btn:disabled { opacity: .45; cursor: not-allowed; }
|
||||
.ab-page-no { padding: 0 0.375rem; }
|
||||
.table-workspace{padding:1rem;color:#171717;font:400 .8125rem/1.5 "JetBrains Mono","Microsoft YaHei","PingFang SC",monospace}.tw-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.75rem;margin-bottom:.75rem}.tw-stat{padding:.875rem 1rem;border:1px solid #d8d2c7;border-radius:.5rem;background:#fff}.tw-label,.tw-note,.tw-count{color:#595959;font-size:.75rem}.tw-value{margin-top:.375rem;font-size:1.375rem;font-weight:700;font-variant-numeric:tabular-nums}.tw-note{margin-top:.1875rem}.is-income{color:#53793e}.is-expense{color:#b80000}.tw-filter{display:flex;flex-wrap:wrap;gap:.75rem;margin-bottom:.75rem;padding:.875rem 1rem;border:1px solid #d8d2c7;border-radius:.5rem;background:#fff}.tw-filter>label{display:flex;flex-direction:column;gap:.25rem;color:#595959;font-size:.75rem;font-weight:500}.tw-filter input,.tw-tools select{height:2.125rem;min-width:10rem;padding:0 .625rem;border:1px solid #d8d2c7;border-radius:.5rem;background:#fff;color:#171717;font:400 .8125rem/1 inherit}.tw-filter input:focus,.tw-tools select:focus{border-color:#856632;box-shadow:0 0 0 3px rgba(133,102,50,.2);outline:none}.tw-filter .tw-keyword{flex:1;min-width:14rem}.tw-keyword input{width:100%}.tw-date span,.tw-actions,.tw-tools,.tw-page-actions{display:flex;align-items:center;gap:.5rem}.tw-date b{font-weight:400}.tw-date input{min-width:8.5rem}.tw-actions{align-self:flex-end;margin-left:auto}.tw-button,.tw-page-actions button{display:inline-flex;align-items:center;justify-content:center;gap:.375rem;height:2.125rem;padding:0 .875rem;border:1px solid #d8d2c7;border-radius:.5rem;background:#fff;color:#171717;font:500 .8125rem/1 inherit;cursor:pointer}.tw-button:hover{border-color:#856632;color:#856632}.tw-primary{border-color:#856632;background:#856632;color:#fff}.tw-primary:hover{background:#6a5129;color:#fff}.tw-button .material-icons-outlined{font-size:1.125rem}.tw-panel{overflow:visible;border:1px solid #d8d2c7;border-radius:.5rem;background:#fff}.tw-alert{display:flex;align-items:center;justify-content:space-between;gap:1rem;margin:.75rem;padding:.75rem;border:1px solid #b80000;border-radius:.5rem;background:#fff4f4;color:#b80000}.tw-alert button{border:0;background:transparent;color:#b80000;font:inherit;font-weight:600;cursor:pointer}.tw-toolbar{display:flex;align-items:center;justify-content:space-between;gap:.75rem;min-height:3.5rem;padding:.625rem .875rem;border-bottom:1px solid #d8d2c7}.tw-toolbar strong{margin-right:.625rem;font-size:.875rem}.tw-tools{flex-wrap:wrap;justify-content:flex-end}.tw-tools>select{min-width:13.75rem}.tw-scroll{position:relative;max-height:min(62vh,42rem);overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}.tw-table{width:max-content;min-width:100%;border-collapse:separate;border-spacing:0;font-size:.78125rem}.tw-table th,.tw-table td{min-width:7.5rem;padding:.5rem .625rem;border-right:1px solid #eeeae2;border-bottom:1px solid #eeeae2;white-space:nowrap}.tw-table thead th{position:sticky;z-index:4;background:#f7f0de;color:#171717;font-weight:600}.tw-groups th{top:0;height:2rem;text-align:center;color:#856632;font-size:.75rem}.tw-columns th{top:2rem;height:2.25rem;text-align:left;background:#fbfaf7;box-shadow:inset 0 -1px #d8d2c7}.tw-columns.is-single th{top:0}.tw-columns th.is-sortable{cursor:pointer}.tw-columns th.is-sortable:hover,.tw-sort{color:#856632}.tw-table tbody tr:hover{background:#f7f0de}.tw-table .is-number{text-align:right;font-variant-numeric:tabular-nums}.tw-table .is-id{color:#595959}.tw-tag{display:inline-block;padding:.0625rem .375rem;border-radius:.25rem;background:#f7f0de;color:#856632}.tw-empty{padding:3rem 1rem!important;text-align:center!important;color:#595959}.tw-pager{display:flex;align-items:center;justify-content:space-between;gap:.75rem;min-height:3.5rem;padding:.625rem .875rem;border-top:1px solid #d8d2c7;color:#595959}.tw-page-actions select{height:1.875rem;border:1px solid #d8d2c7;border-radius:.375rem}.tw-page-actions button{width:1.875rem;height:1.875rem;padding:0}.tw-page-actions button:disabled{cursor:not-allowed;opacity:.45}@media(max-width:900px){.table-workspace{padding:.75rem}.tw-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.tw-filter>label,.tw-filter .tw-keyword{width:100%}.tw-filter input{width:100%}.tw-date input{min-width:0}.tw-actions{margin-left:0}.tw-toolbar,.tw-pager{align-items:flex-start;flex-direction:column}.tw-tools{justify-content:flex-start}.tw-scroll{max-height:58vh;width:100%}}@media(max-width:520px){.tw-stats{grid-template-columns:1fr}.tw-date span{align-items:stretch;flex-direction:column}.tw-tools>select{min-width:0;max-width:100%}.tw-page-actions{flex-wrap:wrap}}
|
||||
.tw-toolbar { flex-wrap: wrap; }
|
||||
.tw-tools { flex: 1 1 24rem; min-width: 0; }
|
||||
</style>
|
||||
|
||||
224
resources/assets/js/components/business/TableColumnSettings.vue
Normal file
224
resources/assets/js/components/business/TableColumnSettings.vue
Normal file
@ -0,0 +1,224 @@
|
||||
<template>
|
||||
<div ref="root" class="table-column-settings">
|
||||
<button
|
||||
type="button"
|
||||
class="table-column-settings__trigger"
|
||||
:aria-expanded="open ? 'true' : 'false'"
|
||||
aria-haspopup="dialog"
|
||||
title="设置显示字段和字段顺序"
|
||||
@click="open = !open"
|
||||
>
|
||||
<span class="material-icons-outlined" aria-hidden="true">view_column</span>
|
||||
<span>列设置</span>
|
||||
</button>
|
||||
|
||||
<div v-if="open" class="table-column-settings__menu" role="dialog" aria-label="列设置">
|
||||
<div class="table-column-settings__head">
|
||||
<strong>显示字段</strong>
|
||||
<button type="button" class="table-column-settings__reset" @click="reset">
|
||||
<span class="material-icons-outlined" aria-hidden="true">restart_alt</span>
|
||||
恢复默认
|
||||
</button>
|
||||
</div>
|
||||
<p class="table-column-settings__hint">拖动字段可调整表格和导出的字段顺序</p>
|
||||
<div class="table-column-settings__list">
|
||||
<div
|
||||
v-for="(column, index) in workingColumns"
|
||||
:key="column.key"
|
||||
class="table-column-settings__item"
|
||||
:class="{ 'is-dragging': dragIndex === index }"
|
||||
draggable="true"
|
||||
@dragstart="startDrag(index, $event)"
|
||||
@dragover.prevent
|
||||
@drop.prevent="dropAt(index)"
|
||||
@dragend="dragIndex = null"
|
||||
>
|
||||
<span class="material-icons-outlined table-column-settings__drag" aria-hidden="true">drag_indicator</span>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="column.visible"
|
||||
:disabled="column.fixed || (visibleCount === 1 && column.visible)"
|
||||
@change="toggle(column.key)"
|
||||
/>
|
||||
<span>{{ column.label }}</span>
|
||||
</label>
|
||||
<span v-if="column.fixed" class="table-column-settings__fixed">固定</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'TableColumnSettings',
|
||||
|
||||
props: {
|
||||
columns: { type: Array, required: true },
|
||||
userKey: { type: [String, Number], required: true },
|
||||
pageKey: { type: String, required: true },
|
||||
tabKey: { type: String, required: true },
|
||||
tableKey: { type: String, required: true },
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
open: false,
|
||||
workingColumns: [],
|
||||
dragIndex: null,
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
storageKey() {
|
||||
return ['caiwu', 'table-columns', 'v1', this.userKey, this.pageKey, this.tabKey, this.tableKey]
|
||||
.map((part) => encodeURIComponent(String(part)))
|
||||
.join(':');
|
||||
},
|
||||
visibleCount() {
|
||||
return this.workingColumns.filter((column) => column.visible).length;
|
||||
},
|
||||
},
|
||||
|
||||
watch: {
|
||||
columns: {
|
||||
immediate: true,
|
||||
deep: true,
|
||||
handler() {
|
||||
this.restore();
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
mounted() {
|
||||
document.addEventListener('click', this.onDocumentClick);
|
||||
},
|
||||
|
||||
beforeDestroy() {
|
||||
document.removeEventListener('click', this.onDocumentClick);
|
||||
},
|
||||
|
||||
methods: {
|
||||
normalizedDefaults() {
|
||||
return this.columns.map((column, index) => ({
|
||||
...column,
|
||||
key: column.key || column.field || `column-${index}`,
|
||||
visible: column.visible !== false,
|
||||
fixed: column.fixed === true,
|
||||
}));
|
||||
},
|
||||
restore() {
|
||||
const defaults = this.normalizedDefaults();
|
||||
let saved = null;
|
||||
|
||||
try {
|
||||
saved = JSON.parse(window.localStorage.getItem(this.storageKey));
|
||||
} catch (error) {
|
||||
saved = null;
|
||||
}
|
||||
|
||||
const savedMap = new Map(Array.isArray(saved) ? saved.map((item) => [item.key, item]) : []);
|
||||
const ordered = defaults
|
||||
.map((column, defaultIndex) => ({
|
||||
...column,
|
||||
visible: column.fixed ? true : (savedMap.has(column.key) ? savedMap.get(column.key).visible !== false : column.visible),
|
||||
savedOrder: savedMap.has(column.key) ? Number(savedMap.get(column.key).order) : defaultIndex + defaults.length,
|
||||
defaultIndex,
|
||||
}))
|
||||
.sort((left, right) => left.savedOrder - right.savedOrder || left.defaultIndex - right.defaultIndex)
|
||||
.map(({ savedOrder, defaultIndex, ...column }) => column);
|
||||
|
||||
this.workingColumns = ordered;
|
||||
this.emitChange(false);
|
||||
},
|
||||
toggle(key) {
|
||||
const column = this.workingColumns.find((item) => item.key === key);
|
||||
if (!column || column.fixed || (column.visible && this.visibleCount === 1)) return;
|
||||
column.visible = !column.visible;
|
||||
this.emitChange();
|
||||
},
|
||||
startDrag(index, event) {
|
||||
this.dragIndex = index;
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
event.dataTransfer.setData('text/plain', String(index));
|
||||
},
|
||||
dropAt(index) {
|
||||
if (this.dragIndex === null || this.dragIndex === index) return;
|
||||
const next = this.workingColumns.slice();
|
||||
const [moved] = next.splice(this.dragIndex, 1);
|
||||
next.splice(index, 0, moved);
|
||||
this.workingColumns = next;
|
||||
this.dragIndex = null;
|
||||
this.emitChange();
|
||||
},
|
||||
reset() {
|
||||
window.localStorage.removeItem(this.storageKey);
|
||||
this.workingColumns = this.normalizedDefaults();
|
||||
this.emitChange(false);
|
||||
},
|
||||
emitChange(persist = true) {
|
||||
if (persist) {
|
||||
const value = this.workingColumns.map((column, order) => ({
|
||||
key: column.key,
|
||||
visible: column.visible,
|
||||
order,
|
||||
}));
|
||||
window.localStorage.setItem(this.storageKey, JSON.stringify(value));
|
||||
}
|
||||
this.$emit('change', this.workingColumns.map((column) => ({ ...column })));
|
||||
},
|
||||
onDocumentClick(event) {
|
||||
if (this.open && this.$refs.root && !this.$refs.root.contains(event.target)) {
|
||||
this.open = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.table-column-settings { position: relative; }
|
||||
.table-column-settings__trigger,
|
||||
.table-column-settings__reset {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.375rem;
|
||||
height: 2.125rem;
|
||||
padding: 0 0.875rem;
|
||||
border: 1px solid #d8d2c7;
|
||||
border-radius: 0.5rem;
|
||||
background: #fff;
|
||||
color: #171717;
|
||||
font: 500 0.8125rem/1 "JetBrains Mono", "Microsoft YaHei", "PingFang SC", monospace;
|
||||
cursor: pointer;
|
||||
}
|
||||
.table-column-settings__trigger:hover,
|
||||
.table-column-settings__trigger:focus-visible { border-color: #856632; color: #856632; outline: none; }
|
||||
.table-column-settings__trigger .material-icons-outlined { font-size: 1.125rem; }
|
||||
.table-column-settings__menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 0.5rem);
|
||||
right: 0;
|
||||
z-index: 30;
|
||||
width: min(22rem, calc(100vw - 2rem));
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #d8d2c7;
|
||||
border-radius: 0.5rem;
|
||||
background: #fff;
|
||||
box-shadow: 0 4px 8px rgba(23, 23, 23, 0.1);
|
||||
color: #171717;
|
||||
}
|
||||
.table-column-settings__head { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; font-size: 0.8125rem; }
|
||||
.table-column-settings__reset { height: 1.875rem; padding: 0 0.5rem; border-color: transparent; color: #856632; font-size: 0.75rem; }
|
||||
.table-column-settings__reset .material-icons-outlined { font-size: 1rem; }
|
||||
.table-column-settings__hint { margin: 0.375rem 0 0.625rem; color: #595959; font-size: 0.75rem; }
|
||||
.table-column-settings__list { max-height: min(24rem, 60vh); overflow-y: auto; border-top: 1px solid #d8d2c7; }
|
||||
.table-column-settings__item { display: flex; align-items: center; min-height: 2.25rem; border-bottom: 1px solid #eeeae2; font-size: 0.78125rem; }
|
||||
.table-column-settings__item.is-dragging { background: #f7f0de; }
|
||||
.table-column-settings__item label { display: flex; flex: 1; align-items: center; gap: 0.5rem; cursor: pointer; }
|
||||
.table-column-settings__item input { accent-color: #856632; }
|
||||
.table-column-settings__drag { color: #856632; cursor: grab; font-size: 1.125rem; }
|
||||
.table-column-settings__fixed { color: #595959; font-size: 0.71875rem; }
|
||||
</style>
|
||||
@ -1,482 +1,119 @@
|
||||
<template>
|
||||
<div class="taobao-page">
|
||||
<!-- 汇总卡片 -->
|
||||
<div class="tb-stats">
|
||||
<div class="tb-stat">
|
||||
<div class="tb-stat-k">收入合计</div>
|
||||
<div class="tb-stat-v income">{{ money(summary.income) }}</div>
|
||||
<div class="tb-stat-s">{{ summary.count }} 笔交易</div>
|
||||
</div>
|
||||
<div class="tb-stat">
|
||||
<div class="tb-stat-k">支出合计</div>
|
||||
<div class="tb-stat-v expense">{{ money(summary.expense) }}</div>
|
||||
<div class="tb-stat-s">按当前筛选</div>
|
||||
</div>
|
||||
<div class="tb-stat">
|
||||
<div class="tb-stat-k">收支净额</div>
|
||||
<div class="tb-stat-v">{{ money(summary.balance) }}</div>
|
||||
<div class="tb-stat-s">收入合计 - 支出合计</div>
|
||||
</div>
|
||||
<div class="tb-stat">
|
||||
<div class="tb-stat-k">交易笔数</div>
|
||||
<div class="tb-stat-v">{{ summary.count }}</div>
|
||||
<div class="tb-stat-s">当前筛选结果</div>
|
||||
<div class="table-workspace">
|
||||
<div class="tw-stats">
|
||||
<div v-for="stat in stats" :key="stat.label" class="tw-stat">
|
||||
<div class="tw-label">{{ stat.label }}</div>
|
||||
<div class="tw-value" :class="stat.className">{{ stat.value }}</div>
|
||||
<div class="tw-note">{{ stat.note }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 筛选栏 -->
|
||||
<div class="tb-filter">
|
||||
<div class="tb-field">
|
||||
<label>原始店铺</label>
|
||||
<input v-model.trim="filters.store_name" placeholder="如 天猫-亿家达旗舰店" />
|
||||
</div>
|
||||
<div class="tb-field">
|
||||
<label>平台渠道</label>
|
||||
<input v-model.trim="filters.alipay_account" placeholder="如 CommonBillTGCPay" />
|
||||
</div>
|
||||
<div class="tb-field">
|
||||
<label>账单项目</label>
|
||||
<input v-model.trim="filters.bill_item" placeholder="如 交易佣金" />
|
||||
</div>
|
||||
<div class="tb-field">
|
||||
<label>收支类型</label>
|
||||
<select v-model="filters.business_type">
|
||||
<option value="">全部类型</option>
|
||||
<option>收入</option>
|
||||
<option>支出</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="tb-field tb-field-date">
|
||||
<label>发生时间</label>
|
||||
<div class="tb-date">
|
||||
<input type="date" v-model="filters.start" /> <span>~</span>
|
||||
<input type="date" v-model="filters.end" />
|
||||
<form class="tw-filter" @submit.prevent="applyFilters">
|
||||
<label>原始店铺<input v-model.trim="filters.store_name" placeholder="如 天猫-亿家达旗舰店" /></label>
|
||||
<label>平台渠道<input v-model.trim="filters.alipay_account" placeholder="如 CommonBillTGCPay" /></label>
|
||||
<label>账单项目<input v-model.trim="filters.bill_item" placeholder="如 交易佣金" /></label>
|
||||
<label>收支类型<select v-model="filters.business_type"><option value="">全部类型</option><option>收入</option><option>支出</option></select></label>
|
||||
<label class="tw-date">发生时间<span><input v-model="filters.start" type="date" aria-label="开始日期" /><b>至</b><input v-model="filters.end" type="date" aria-label="结束日期" /></span></label>
|
||||
<label class="tw-keyword">关键词(费用 / 订单 / 商品编码)<input v-model.trim="filters.keyword" placeholder="输入费用名称、订单号或商品编码" /></label>
|
||||
<div class="tw-actions"><button class="tw-button tw-primary" type="submit">查询</button><button class="tw-button" type="button" @click="resetFilters">重置</button></div>
|
||||
</form>
|
||||
|
||||
<section class="tw-panel" aria-label="淘系支付宝账户账单明细">
|
||||
<div v-if="error" class="tw-alert" role="alert"><span>{{ error }}</span><button type="button" @click="fetch">重新加载</button></div>
|
||||
<div class="tw-toolbar">
|
||||
<div><strong>账单明细</strong><span v-if="!loading" class="tw-count">{{ total }} 条</span></div>
|
||||
<div class="tw-tools">
|
||||
<select v-model="exportMode" title="选择导出范围" aria-label="导出范围">
|
||||
<option value="page-visible">当前页 · 当前显示列</option>
|
||||
<option value="filtered-visible">全部筛选结果 · 当前显示列</option>
|
||||
<option value="filtered-all">全部筛选结果 · 全部字段</option>
|
||||
</select>
|
||||
<button type="button" class="tw-button" @click="exportRows"><span class="material-icons-outlined" aria-hidden="true">download</span>导出</button>
|
||||
<table-column-settings :columns="defaultColumns" :user-key="userKey" page-key="store-receiving-bills" tab-key="taobao-alipay" table-key="bill-details" @change="configuredColumns = $event" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="tb-field tb-field-kw">
|
||||
<label>关键词(费用 / 订单 / 商品编码)</label>
|
||||
<input v-model.trim="filters.keyword" placeholder="输入费用名称、订单号或商品编码" />
|
||||
</div>
|
||||
<div class="tb-actions">
|
||||
<button class="tb-btn tb-btn-primary" @click="applyFilters">查询</button>
|
||||
<button class="tb-btn" @click="resetFilters">重置</button>
|
||||
<button class="tb-btn" @click="exportRows">导出</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据表 -->
|
||||
<div class="tb-panel">
|
||||
<div v-if="error" class="tb-error" role="alert">{{ error }}</div>
|
||||
<div class="tb-phead">
|
||||
<div class="tb-title">账单明细</div>
|
||||
<div class="tb-count" v-if="!loading">{{ total }} 条</div>
|
||||
</div>
|
||||
|
||||
<div class="tb-scroll">
|
||||
<table class="tb-table" v-if="!loading">
|
||||
<div ref="scroll" class="tw-scroll">
|
||||
<table v-if="!loading && configuredColumns.length" class="tw-table">
|
||||
<thead>
|
||||
<tr class="tb-group">
|
||||
<th colspan="4">基础信息</th>
|
||||
<th colspan="8">账户与交易</th>
|
||||
<th colspan="3">金额(元)</th>
|
||||
<th colspan="6">业务关联</th>
|
||||
<th colspan="4">维护信息</th>
|
||||
</tr>
|
||||
<tr class="tb-col">
|
||||
<th @click="toggleSort('record_code')">记录编码 <span class="tb-sort">⇅</span></th>
|
||||
<th>原始店铺</th>
|
||||
<th>自定义备注</th>
|
||||
<th>账单项目</th>
|
||||
<th>平台渠道</th>
|
||||
<th>账务订单号</th>
|
||||
<th>业务流水号</th>
|
||||
<th>商户订单号</th>
|
||||
<th>业务基础订单号</th>
|
||||
<th>商品编码</th>
|
||||
<th>对方账号</th>
|
||||
<th @click="toggleSort('occurred_at')">发生时间 <span class="tb-sort">⇅</span></th>
|
||||
<th class="tb-num" @click="toggleSort('income')">收入 <span class="tb-sort">⇅</span></th>
|
||||
<th class="tb-num" @click="toggleSort('expense')">支出 <span class="tb-sort">⇅</span></th>
|
||||
<th class="tb-num" @click="toggleSort('balance')">收支净额 <span class="tb-sort">⇅</span></th>
|
||||
<th>业务类型</th>
|
||||
<th>备注</th>
|
||||
<th>线上单号</th>
|
||||
<th>线上单号对应实际店铺</th>
|
||||
<th>业务描述</th>
|
||||
<th>业务账单来源</th>
|
||||
<th>业务订单号</th>
|
||||
<th>创建时间</th>
|
||||
<th>修改时间</th>
|
||||
<th>修改人</th>
|
||||
<tr class="tw-groups"><th v-for="(group, index) in visibleGroups" :key="`${group.label}-${index}`" :colspan="group.span" scope="colgroup">{{ group.label }}</th></tr>
|
||||
<tr class="tw-columns">
|
||||
<th v-for="column in visibleColumns" :key="column.key" :class="{ 'is-number': isNumber(column.kind), 'is-sortable': sortableField(column.field) }" scope="col" @click="maybeSort(column)">
|
||||
{{ column.label }} <span v-if="sortableField(column.field)" class="tw-sort" aria-hidden="true">{{ sortMark(column.field) }}</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="r in rows" :key="r.id">
|
||||
<td class="tb-mono">{{ r.record_code }}</td>
|
||||
<td>{{ r.store_name }}</td>
|
||||
<td class="tb-muted">{{ r.custom_remark || '—' }}</td>
|
||||
<td><span class="tb-tag">{{ r.bill_item }}</span></td>
|
||||
<td class="tb-mono">{{ r.alipay_account }}</td>
|
||||
<td class="tb-mono">{{ r.account_order_no }}</td>
|
||||
<td class="tb-mono">{{ r.business_serial_no }}</td>
|
||||
<td class="tb-mono">{{ r.merchant_order_no || '—' }}</td>
|
||||
<td class="tb-mono tb-muted">{{ r.business_base_order_no || '—' }}</td>
|
||||
<td class="tb-ellipsis">{{ r.goods_name }}</td>
|
||||
<td>{{ r.counterparty_account || '—' }}</td>
|
||||
<td>{{ r.occurred_at || '—' }}</td>
|
||||
<td class="tb-num tb-in" v-if="r.income > 0">+{{ money(r.income) }}</td>
|
||||
<td class="tb-num tb-in" v-else>—</td>
|
||||
<td class="tb-num tb-out" v-if="r.expense > 0">−{{ money(r.expense) }}</td>
|
||||
<td class="tb-num tb-out" v-else>—</td>
|
||||
<td class="tb-num">{{ money(r.balance) }}</td>
|
||||
<td><span class="tb-tag" :class="tagClass(r.business_type)">{{ r.business_type || '—' }}</span></td>
|
||||
<td class="tb-muted tb-ellipsis">{{ r.remark || '—' }}</td>
|
||||
<td class="tb-mono">{{ r.online_order_no || '—' }}</td>
|
||||
<td>{{ r.online_real_store || '—' }}</td>
|
||||
<td class="tb-muted tb-ellipsis">{{ r.business_description || '—' }}</td>
|
||||
<td class="tb-muted">{{ r.business_bill_source || '—' }}</td>
|
||||
<td class="tb-mono tb-muted">{{ r.business_order_no || '—' }}</td>
|
||||
<td class="tb-muted">{{ r.created_at }}</td>
|
||||
<td class="tb-muted">{{ r.updated_at }}</td>
|
||||
<td class="tb-muted">{{ r.modifier || '—' }}</td>
|
||||
</tr>
|
||||
<tr v-if="!rows.length" class="tb-empty-row">
|
||||
<td :colspan="25" class="tb-empty">没有符合条件的账单记录</td>
|
||||
<tr v-for="row in rows" :key="row.id || row.record_code">
|
||||
<td v-for="column in visibleColumns" :key="column.key" :class="cellClass(column)"><span v-if="column.kind === 'tag'" class="tw-tag">{{ displayValue(row, column) }}</span><template v-else>{{ displayValue(row, column) }}</template></td>
|
||||
</tr>
|
||||
<tr v-if="!rows.length"><td :colspan="visibleColumns.length" class="tw-empty">没有符合条件的账单记录</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-else class="tb-empty">加载中…</div>
|
||||
<div v-else-if="loading" class="tw-empty" role="status">加载中…</div>
|
||||
</div>
|
||||
|
||||
<!-- 分页 -->
|
||||
<div class="tb-pager" v-if="rows.length">
|
||||
<div class="tb-page-info">
|
||||
第 {{ rangeStart }} - {{ rangeEnd }} 条 / 共 {{ total }} 条
|
||||
</div>
|
||||
<div class="tb-page-right">
|
||||
<span>每页</span>
|
||||
<select v-model.number="perPage" @change="changePage(1)">
|
||||
<option :value="10">10</option>
|
||||
<option :value="20">20</option>
|
||||
<option :value="50">50</option>
|
||||
</select>
|
||||
<button class="tb-page-btn" :disabled="currentPage <= 1" @click="changePage(1)">«</button>
|
||||
<button class="tb-page-btn" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">‹</button>
|
||||
<span class="tb-page-no">{{ currentPage }} / {{ lastPage }}</span>
|
||||
<button class="tb-page-btn" :disabled="currentPage >= lastPage" @click="changePage(currentPage + 1)">›</button>
|
||||
<button class="tb-page-btn" :disabled="currentPage >= lastPage" @click="changePage(lastPage)">»</button>
|
||||
<div v-if="rows.length" class="tw-pager">
|
||||
<div>第 {{ rangeStart }} - {{ rangeEnd }} 条 / 共 {{ total }} 条</div>
|
||||
<div class="tw-page-actions">
|
||||
<label>每页 <select v-model.number="perPage" @change="changePage(1)"><option :value="10">10</option><option :value="20">20</option><option :value="50">50</option></select></label>
|
||||
<button type="button" :disabled="currentPage <= 1" title="第一页" @click="changePage(1)">«</button><button type="button" :disabled="currentPage <= 1" title="上一页" @click="changePage(currentPage - 1)">‹</button>
|
||||
<span>{{ currentPage }} / {{ lastPage }}</span>
|
||||
<button type="button" :disabled="currentPage >= lastPage" title="下一页" @click="changePage(currentPage + 1)">›</button><button type="button" :disabled="currentPage >= lastPage" title="最后一页" @click="changePage(lastPage)">»</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import TableColumnSettings from './TableColumnSettings.vue';
|
||||
|
||||
const COLUMNS = [
|
||||
['记录编码', 'record_code', 'num', '基础信息'], ['原始店铺', 'store_name', 'text', '基础信息'], ['自定义备注', 'custom_remark', 'text', '基础信息'], ['账单项目', 'bill_item', 'tag', '基础信息'],
|
||||
['平台渠道', 'alipay_account', 'num', '账户与交易'], ['账务订单号', 'account_order_no', 'num', '账户与交易'], ['业务流水号', 'business_serial_no', 'num', '账户与交易'], ['商户订单号', 'merchant_order_no', 'num', '账户与交易'], ['业务基础订单号', 'business_base_order_no', 'num', '账户与交易'], ['商品编码', 'goods_name', 'num', '账户与交易'], ['对方账号', 'counterparty_account', 'text', '账户与交易'], ['发生时间', 'occurred_at', 'date', '账户与交易'],
|
||||
['收入', 'income', 'money_in', '金额(元)'], ['支出', 'expense', 'money_out', '金额(元)'], ['收支净额', 'balance', 'money', '金额(元)'],
|
||||
['业务类型', 'business_type', 'tag', '业务关联'], ['备注', 'remark', 'text', '业务关联'], ['线上单号', 'online_order_no', 'num', '业务关联'], ['线上单号对应实际店铺', 'online_real_store', 'text', '业务关联'], ['业务描述', 'business_description', 'text', '业务关联'], ['业务账单来源', 'business_bill_source', 'text', '业务关联'],
|
||||
['业务订单号', 'business_order_no', 'num', '维护信息'], ['创建时间', 'created_at', 'date', '维护信息'], ['修改时间', 'updated_at', 'date', '维护信息'], ['修改人', 'modifier', 'text', '维护信息'],
|
||||
].map(([label, field, kind, group]) => ({ key: field, label, field, kind, group }));
|
||||
const SORTABLE = ['occurred_at', 'income', 'expense', 'balance', 'record_code'];
|
||||
|
||||
export default {
|
||||
name: 'TaobaoAlipayBills',
|
||||
|
||||
props: {
|
||||
apiBase: { type: String, required: true },
|
||||
exportBase: { type: String, required: true },
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
loading: false,
|
||||
error: '',
|
||||
rows: [],
|
||||
summary: { income: 0, expense: 0, balance: 0, count: 0 },
|
||||
total: 0,
|
||||
currentPage: 1,
|
||||
lastPage: 1,
|
||||
perPage: 10,
|
||||
filters: {
|
||||
store_name: '',
|
||||
alipay_account: '',
|
||||
bill_item: '',
|
||||
business_type: '',
|
||||
start: '',
|
||||
end: '',
|
||||
keyword: '',
|
||||
},
|
||||
sort: { key: 'occurred_at', dir: 'desc' },
|
||||
};
|
||||
},
|
||||
|
||||
name: 'TaobaoAlipayBills', components: { TableColumnSettings },
|
||||
props: { apiBase: { type: String, required: true }, exportBase: { type: String, required: true } },
|
||||
data() { return { loading: false, error: '', rows: [], configuredColumns: [], summary: { income: 0, expense: 0, balance: 0, count: 0 }, total: 0, currentPage: 1, lastPage: 1, perPage: 20, filters: { store_name: '', alipay_account: '', bill_item: '', business_type: '', start: '', end: '', keyword: '' }, sort: { key: 'occurred_at', dir: 'desc' }, exportMode: 'filtered-visible' }; },
|
||||
computed: {
|
||||
rangeStart() {
|
||||
return this.total === 0 ? 0 : (this.currentPage - 1) * this.perPage + 1;
|
||||
},
|
||||
rangeEnd() {
|
||||
return Math.min(this.currentPage * this.perPage, this.total);
|
||||
},
|
||||
userKey() { const mount = document.querySelector('.business-blank-page'); return mount && mount.dataset.tablePreferencesUser ? mount.dataset.tablePreferencesUser : 'anonymous'; },
|
||||
defaultColumns() { return COLUMNS; }, visibleColumns() { return this.configuredColumns.filter((column) => column.visible); },
|
||||
visibleGroups() { return this.visibleColumns.reduce((groups, column) => { const last = groups[groups.length - 1]; if (last && last.label === column.group) last.span += 1; else groups.push({ label: column.group, span: 1 }); return groups; }, []); },
|
||||
stats() { return [{ label: '收入合计', value: this.money(this.summary.income), note: `${this.summary.count} 笔交易`, className: 'is-income' }, { label: '支出合计', value: this.money(this.summary.expense), note: '按当前筛选', className: 'is-expense' }, { label: '收支净额', value: this.money(this.summary.balance), note: '收入合计 - 支出合计', className: '' }, { label: '交易笔数', value: this.summary.count, note: '当前筛选结果', className: '' }]; },
|
||||
rangeStart() { return this.total === 0 ? 0 : (this.currentPage - 1) * this.perPage + 1; }, rangeEnd() { return Math.min(this.currentPage * this.perPage, this.total); },
|
||||
},
|
||||
|
||||
mounted() {
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
mounted() { this.fetch(); },
|
||||
methods: {
|
||||
async fetch() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
const params = {
|
||||
...this.filters,
|
||||
sort: this.sort.key,
|
||||
dir: this.sort.dir,
|
||||
limit: this.perPage,
|
||||
page: this.currentPage,
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await window.axios.get(this.apiBase, { params });
|
||||
const body = res.data || {};
|
||||
this.rows = body.data || [];
|
||||
this.total = body.total || 0;
|
||||
this.currentPage = body.current_page || 1;
|
||||
this.lastPage = body.last_page || 1;
|
||||
this.perPage = body.per_page || this.perPage;
|
||||
this.summary = body.summary || { income: 0, expense: 0, balance: 0, count: 0 };
|
||||
} catch (e) {
|
||||
console.error('加载淘系支付宝账单失败', e);
|
||||
this.rows = [];
|
||||
this.total = 0;
|
||||
this.summary = { income: 0, expense: 0, balance: 0, count: 0 };
|
||||
this.error = (e.response && e.response.data && e.response.data.message)
|
||||
|| '淘系支付宝账单暂时无法读取,请稍后重试。';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
applyFilters() {
|
||||
this.currentPage = 1;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = {
|
||||
store_name: '',
|
||||
alipay_account: '',
|
||||
bill_item: '',
|
||||
business_type: '',
|
||||
start: '',
|
||||
end: '',
|
||||
keyword: '',
|
||||
};
|
||||
this.currentPage = 1;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
changePage(p) {
|
||||
this.currentPage = p;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
exportRows() {
|
||||
const params = new URLSearchParams(this.filters);
|
||||
window.location.href = `${this.exportBase}?${params.toString()}`;
|
||||
},
|
||||
|
||||
toggleSort(key) {
|
||||
if (this.sort.key === key) {
|
||||
this.sort.dir = this.sort.dir === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sort.key = key;
|
||||
this.sort.dir = 'desc';
|
||||
}
|
||||
this.currentPage = 1;
|
||||
this.fetch();
|
||||
},
|
||||
|
||||
tagClass(type) {
|
||||
if (type === '交易分账') return 'tb-tag-amber';
|
||||
if (type === '退款') return 'tb-tag-gray';
|
||||
return '';
|
||||
},
|
||||
|
||||
money(n) {
|
||||
const v = Number(n || 0);
|
||||
return '¥' + v.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
},
|
||||
async fetch() { this.loading = true; this.error = ''; try { const response = await window.axios.get(this.apiBase, { params: { ...this.filters, sort: this.sort.key, dir: this.sort.dir, limit: this.perPage, page: this.currentPage } }); const body = response.data || {}; this.rows = body.data || []; this.total = body.total || 0; this.currentPage = body.current_page || 1; this.lastPage = body.last_page || 1; this.perPage = body.per_page || this.perPage; this.summary = body.summary || { income: 0, expense: 0, balance: 0, count: 0 }; } catch (error) { this.rows = []; this.total = 0; this.summary = { income: 0, expense: 0, balance: 0, count: 0 }; this.error = (error.response && error.response.data && error.response.data.message) || '淘系支付宝账单暂时无法读取,请稍后重试。'; } finally { this.loading = false; } },
|
||||
applyFilters() { this.currentPage = 1; this.fetch(); }, resetFilters() { this.filters = { store_name: '', alipay_account: '', bill_item: '', business_type: '', start: '', end: '', keyword: '' }; this.applyFilters(); },
|
||||
changePage(page) { this.currentPage = page; this.fetch(); this.$nextTick(() => { if (this.$refs.scroll) this.$refs.scroll.scrollTop = 0; }); },
|
||||
maybeSort(column) { if (!this.sortableField(column.field)) return; this.sort.dir = this.sort.key === column.field && this.sort.dir === 'desc' ? 'asc' : 'desc'; this.sort.key = column.field; this.applyFilters(); }, sortableField(field) { return SORTABLE.indexOf(field) !== -1; }, sortMark(field) { return this.sort.key === field ? (this.sort.dir === 'asc' ? '↑' : '↓') : '↕'; },
|
||||
rawValue(row, column) { const value = row[column.field]; return value === null || value === undefined ? '' : value; },
|
||||
displayValue(row, column) { const value = this.rawValue(row, column); if (value === '') return '—'; if (column.kind === 'money_in') return Number(value) > 0 ? `+${this.money(value)}` : '—'; if (column.kind === 'money_out') return Number(value) > 0 ? `-${this.money(value)}` : '—'; if (column.kind === 'money') return this.money(value); return value; },
|
||||
cellClass(column) { return { 'is-number': this.isNumber(column.kind), 'is-id': column.kind === 'num', 'is-income': column.kind === 'money_in', 'is-expense': column.kind === 'money_out' }; }, isNumber(kind) { return ['num', 'money', 'money_in', 'money_out'].indexOf(kind) !== -1; }, money(value) { return `¥${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; },
|
||||
exportRows() { if (this.exportMode === 'page-visible') { this.downloadCurrentPage(); return; } const params = new URLSearchParams(this.filters); params.set('sort', this.sort.key); params.set('dir', this.sort.dir); if (this.exportMode === 'filtered-visible') this.visibleColumns.forEach((column) => params.append('columns[]', column.field)); window.location.assign(`${this.exportBase}?${params.toString()}`); },
|
||||
downloadCurrentPage() { const csvRows = [this.visibleColumns.map((column) => column.label), ...this.rows.map((row) => this.visibleColumns.map((column) => this.rawValue(row, column)))]; const csv = csvRows.map((values) => values.map(this.csvCell).join(',')).join('\r\n'); const link = document.createElement('a'); link.href = URL.createObjectURL(new Blob(['\ufeff', csv], { type: 'text/csv;charset=utf-8' })); link.download = `taobao_alipay_bills_page_${this.currentPage}.csv`; link.click(); URL.revokeObjectURL(link.href); },
|
||||
csvCell(value) { const text = String(value === null || value === undefined ? '' : value); const safe = /^[=+\-@]/.test(text) ? `'${text}` : text; return `"${safe.replace(/"/g, '""')}"`; },
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.taobao-page {
|
||||
padding: 1.25rem 1.5rem 1.5rem;
|
||||
}
|
||||
|
||||
.tb-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.875rem;
|
||||
margin-bottom: 0.875rem;
|
||||
}
|
||||
.tb-stat {
|
||||
background: #ffffff;
|
||||
border: 1px solid #e6e9f0;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1rem 1.125rem;
|
||||
box-shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 1px 3px rgba(16, 24, 40, .06);
|
||||
}
|
||||
.tb-stat-k { font-size: 0.75rem; color: #6b7280; }
|
||||
.tb-stat-v { font-size: 1.375rem; font-weight: 700; margin-top: 0.5rem; letter-spacing: .3px; }
|
||||
.tb-stat-s { font-size: 0.75rem; color: #9aa3b2; margin-top: 0.25rem; }
|
||||
.tb-stat-v.income { color: #f5222d; }
|
||||
.tb-stat-v.expense { color: #16a34a; }
|
||||
|
||||
.tb-filter {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.875rem;
|
||||
background: #ffffff;
|
||||
border: 1px solid #e6e9f0;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1rem 1.125rem;
|
||||
margin-bottom: 0.875rem;
|
||||
}
|
||||
.tb-field { display: flex; flex-direction: column; gap: 0.3125rem; }
|
||||
.tb-field label { font-size: 0.75rem; color: #6b7280; font-weight: 500; }
|
||||
.tb-field input,
|
||||
.tb-field select {
|
||||
height: 2.125rem;
|
||||
min-width: 11.25rem;
|
||||
padding: 0 0.625rem;
|
||||
border: 1px solid #e6e9f0;
|
||||
border-radius: 0.5rem;
|
||||
background: #fff;
|
||||
font-size: 0.8125rem;
|
||||
color: #1f2937;
|
||||
outline: none;
|
||||
}
|
||||
.tb-field input:focus,
|
||||
.tb-field select:focus { border-color: var(--vip-content-accent); box-shadow: 0 0 0 3px rgba(185, 149, 79, .16); }
|
||||
.tb-field-kw { flex: 1; min-width: 12.5rem; }
|
||||
.tb-field-kw input { width: 100%; }
|
||||
.tb-date { display: flex; align-items: center; gap: 0.375rem; }
|
||||
.tb-date input { min-width: 8.75rem; }
|
||||
.tb-actions { display: flex; gap: 0.625rem; align-items: flex-end; margin-left: auto; }
|
||||
.tb-btn {
|
||||
height: 2.125rem;
|
||||
padding: 0 0.875rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e6e9f0;
|
||||
background: #fff;
|
||||
color: #1f2937;
|
||||
cursor: pointer;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.tb-btn:hover { border-color: #c7cdda; }
|
||||
.tb-btn-primary { background: var(--vip-content-accent); border-color: var(--vip-content-accent); color: #fff; }
|
||||
.tb-btn-primary:hover { background: var(--vip-content-accent-dark); }
|
||||
|
||||
.tb-panel {
|
||||
background: #fff;
|
||||
border: 1px solid #e6e9f0;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 1px 3px rgba(16, 24, 40, .06);
|
||||
overflow: hidden;
|
||||
}
|
||||
.tb-error {
|
||||
margin: 1rem;
|
||||
border: 1px solid #d8d2c7;
|
||||
border-radius: 0.5rem;
|
||||
background: #f7f0de;
|
||||
padding: 0.75rem 1rem;
|
||||
color: #935f07;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.tb-phead { display: flex; align-items: center; gap: 0.625rem; padding: 0.875rem 1rem; border-bottom: 1px solid #e6e9f0; }
|
||||
.tb-title { font-weight: 600; font-size: 0.875rem; }
|
||||
.tb-count { color: #9aa3b2; font-size: 0.75rem; }
|
||||
|
||||
.tb-scroll { overflow-x: auto; }
|
||||
.tb-table { border-collapse: collapse; width: 100%; min-width: 2200px; font-size: 0.78125rem; }
|
||||
.tb-table thead .tb-group th {
|
||||
background: #f0f3f9;
|
||||
color: #6b7280;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid #e6e9f0;
|
||||
padding: 0.5625rem 0.625rem;
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tb-table thead .tb-col th {
|
||||
background: #fafbfd;
|
||||
color: #1f2937;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e6e9f0;
|
||||
padding: 0.5625rem 0.625rem;
|
||||
white-space: nowrap;
|
||||
cursor: default;
|
||||
position: relative;
|
||||
}
|
||||
.tb-table thead .tb-col th.tb-num { text-align: right; }
|
||||
.tb-sort { color: #9aa3b2; cursor: pointer; margin-left: 0.1875rem; }
|
||||
.tb-sort:hover { color: var(--vip-content-accent); }
|
||||
.tb-table tbody td {
|
||||
padding: 0.5625rem 0.625rem;
|
||||
border-bottom: 1px solid #f1f3f7;
|
||||
white-space: nowrap;
|
||||
color: #1f2937;
|
||||
}
|
||||
.tb-table tbody tr:hover { background: #f7f9ff; }
|
||||
.tb-num { text-align: right; font-variant-numeric: tabular-nums; font-family: ui-monospace, Menlo, Consolas, monospace; }
|
||||
.tb-mono { font-family: ui-monospace, Menlo, Consolas, monospace; color: #6b7280; font-size: 0.71875rem; }
|
||||
.tb-muted { color: #9aa3b2; }
|
||||
.tb-ellipsis { max-width: 200px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.tb-in { color: #f5222d; font-weight: 600; }
|
||||
.tb-out { color: #16a34a; font-weight: 600; }
|
||||
.tb-tag {
|
||||
display: inline-block;
|
||||
padding: 0.0625rem 0.5rem;
|
||||
border-radius: 1rem;
|
||||
font-size: 0.71875rem;
|
||||
font-weight: 500;
|
||||
background: var(--vip-content-accent-soft);
|
||||
color: var(--vip-content-accent-dark);
|
||||
}
|
||||
.tb-tag-amber { background: #fff4e5; color: #b76e00; }
|
||||
.tb-tag-gray { background: #eef1f6; color: #6b7280; }
|
||||
|
||||
.tb-empty { padding: 3rem; text-align: center; color: #9aa3b2; }
|
||||
|
||||
.tb-pager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
padding: 0.875rem 1rem;
|
||||
border-top: 1px solid #e6e9f0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.tb-page-info { color: #6b7280; font-size: 0.78125rem; }
|
||||
.tb-page-right { margin-left: auto; display: flex; align-items: center; gap: 0.375rem; font-size: 0.78125rem; }
|
||||
.tb-page-right select { height: 1.875rem; border: 1px solid #e6e9f0; border-radius: 0.4375rem; padding: 0 0.375rem; }
|
||||
.tb-page-btn {
|
||||
height: 1.875rem;
|
||||
min-width: 1.875rem;
|
||||
padding: 0 0.5rem;
|
||||
border: 1px solid #e6e9f0;
|
||||
background: #fff;
|
||||
border-radius: 0.4375rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.78125rem;
|
||||
color: #1f2937;
|
||||
}
|
||||
.tb-page-btn:hover:not(:disabled) { border-color: var(--vip-content-accent); color: var(--vip-content-accent); }
|
||||
.tb-page-btn:disabled { opacity: .45; cursor: not-allowed; }
|
||||
.tb-page-no { padding: 0 0.375rem; }
|
||||
|
||||
.business-page-empty {
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
color: #9aa3b2;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.table-workspace { padding: 1rem; color: #171717; font: 400 0.8125rem/1.5 "JetBrains Mono", "Microsoft YaHei", "PingFang SC", monospace; }
|
||||
.tw-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .75rem; margin-bottom: .75rem; }.tw-stat { padding: .875rem 1rem; border: 1px solid #d8d2c7; border-radius: .5rem; background: #fff; }.tw-label,.tw-note,.tw-count { color: #595959; font-size: .75rem; }.tw-value { margin-top: .375rem; font-size: 1.375rem; font-weight: 700; font-variant-numeric: tabular-nums; }.tw-note { margin-top: .1875rem; }.is-income { color: #53793e; }.is-expense { color: #b80000; }
|
||||
.tw-filter { display: flex; flex-wrap: wrap; gap: .75rem; margin-bottom: .75rem; padding: .875rem 1rem; border: 1px solid #d8d2c7; border-radius: .5rem; background: #fff; }.tw-filter>label { display: flex; flex-direction: column; gap: .25rem; color: #595959; font-size: .75rem; font-weight: 500; }.tw-filter input,.tw-filter select,.tw-tools select { height: 2.125rem; min-width: 10rem; padding: 0 .625rem; border: 1px solid #d8d2c7; border-radius: .5rem; background: #fff; color: #171717; font: 400 .8125rem/1 inherit; }.tw-filter input:focus,.tw-filter select:focus,.tw-tools select:focus { border-color: #856632; box-shadow: 0 0 0 3px rgba(133,102,50,.2); outline: none; }.tw-filter .tw-keyword { flex: 1; min-width: 14rem; }.tw-keyword input { width: 100%; }.tw-date span,.tw-actions,.tw-tools,.tw-page-actions { display: flex; align-items: center; gap: .5rem; }.tw-date b { font-weight: 400; }.tw-date input { min-width: 8.5rem; }.tw-actions { align-self: flex-end; margin-left: auto; }
|
||||
.tw-button,.tw-page-actions button { display: inline-flex; align-items: center; justify-content: center; gap: .375rem; height: 2.125rem; padding: 0 .875rem; border: 1px solid #d8d2c7; border-radius: .5rem; background: #fff; color: #171717; font: 500 .8125rem/1 inherit; cursor: pointer; }.tw-button:hover { border-color: #856632; color: #856632; }.tw-primary { border-color: #856632; background: #856632; color: #fff; }.tw-primary:hover { background: #6a5129; color: #fff; }.tw-button .material-icons-outlined { font-size: 1.125rem; }
|
||||
.tw-panel { overflow: visible; border: 1px solid #d8d2c7; border-radius: .5rem; background: #fff; }.tw-alert { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin: .75rem; padding: .75rem; border: 1px solid #935f07; border-radius: .5rem; background: #f7f0de; color: #935f07; }.tw-alert button { border: 0; background: transparent; color: #856632; font: inherit; font-weight: 600; cursor: pointer; }.tw-toolbar { display: flex; align-items: center; justify-content: space-between; gap: .75rem; min-height: 3.5rem; padding: .625rem .875rem; border-bottom: 1px solid #d8d2c7; }.tw-toolbar strong { margin-right: .625rem; font-size: .875rem; }.tw-tools { flex-wrap: wrap; justify-content: flex-end; }.tw-tools>select { min-width: 13.75rem; }
|
||||
.tw-scroll { position: relative; max-height: min(62vh, 42rem); overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }.tw-table { width: max-content; min-width: 100%; border-collapse: separate; border-spacing: 0; font-size: .78125rem; }.tw-table th,.tw-table td { min-width: 7.5rem; padding: .5rem .625rem; border-right: 1px solid #eeeae2; border-bottom: 1px solid #eeeae2; white-space: nowrap; }.tw-table thead th { position: sticky; z-index: 4; background: #f7f0de; color: #171717; font-weight: 600; }.tw-groups th { top: 0; height: 2rem; text-align: center; color: #856632; font-size: .75rem; }.tw-columns th { top: 2rem; height: 2.25rem; text-align: left; background: #fbfaf7; box-shadow: inset 0 -1px #d8d2c7; }.tw-columns th.is-sortable { cursor: pointer; }.tw-columns th.is-sortable:hover,.tw-sort { color: #856632; }.tw-table tbody tr:hover { background: #f7f0de; }.tw-table .is-number { text-align: right; font-variant-numeric: tabular-nums; }.tw-table .is-id { color: #595959; }.tw-tag { display: inline-block; padding: .0625rem .375rem; border-radius: .25rem; background: #f7f0de; color: #856632; }.tw-empty { padding: 3rem 1rem!important; text-align: center!important; color: #595959; }
|
||||
.tw-pager { display: flex; align-items: center; justify-content: space-between; gap: .75rem; min-height: 3.5rem; padding: .625rem .875rem; border-top: 1px solid #d8d2c7; color: #595959; }.tw-page-actions select { height: 1.875rem; border: 1px solid #d8d2c7; border-radius: .375rem; }.tw-page-actions button { width: 1.875rem; height: 1.875rem; padding: 0; }.tw-page-actions button:disabled { cursor: not-allowed; opacity: .45; }
|
||||
@media(max-width:900px){.table-workspace{padding:.75rem}.tw-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.tw-filter>label,.tw-filter .tw-keyword{width:100%}.tw-filter input,.tw-filter select{width:100%}.tw-date input{min-width:0}.tw-actions{margin-left:0}.tw-toolbar,.tw-pager{align-items:flex-start;flex-direction:column}.tw-tools{justify-content:flex-start}.tw-scroll{max-height:58vh;width:100%}}@media(max-width:520px){.tw-stats{grid-template-columns:1fr}.tw-date span{align-items:stretch;flex-direction:column}.tw-tools>select{min-width:0;max-width:100%}.tw-page-actions{flex-wrap:wrap}}
|
||||
.tw-toolbar { flex-wrap: wrap; }
|
||||
.tw-tools { flex: 1 1 24rem; min-width: 0; }
|
||||
</style>
|
||||
|
||||
@ -66,6 +66,14 @@
|
||||
<label for="daifa-shop-name">店铺名称</label>
|
||||
<input id="daifa-shop-name" name="shop_name" value="{{ $filters['shop_name'] ?? '' }}" placeholder="如 抖音-HX旗舰店101">
|
||||
</div>
|
||||
<div class="online-daifa-field">
|
||||
<label for="daifa-supplier-name">供应商名称</label>
|
||||
<input id="daifa-supplier-name" name="supplier_name" value="{{ $filters['supplier_name'] ?? '' }}" placeholder="支持关键词筛选">
|
||||
</div>
|
||||
<div class="online-daifa-field">
|
||||
<label for="daifa-material-no">料号</label>
|
||||
<input id="daifa-material-no" name="material_no" value="{{ $filters['material_no'] ?? '' }}" placeholder="输入精确料号">
|
||||
</div>
|
||||
<div class="online-daifa-field">
|
||||
<label for="daifa-status">状态</label>
|
||||
<select id="daifa-status" name="status">
|
||||
@ -84,6 +92,7 @@
|
||||
</div>
|
||||
<div class="online-daifa-actions">
|
||||
<button class="online-daifa-button primary" type="submit"><span class="material-icons-outlined" aria-hidden="true">search</span>查询</button>
|
||||
<a class="online-daifa-button" href="{{ route('business.product-inventory.online-daifa-price.export', array_merge(['company_id' => company_id()], request()->except('page'))) }}" aria-label="导出当前筛选结果" title="导出当前筛选结果"><span class="material-icons-outlined" aria-hidden="true">download</span>导出</a>
|
||||
<a class="online-daifa-button" href="{{ route('business.pages.show', ['section' => $section['slug'], 'page' => $page['slug']]) }}"><span class="material-icons-outlined" aria-hidden="true">refresh</span>重置</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@ -1060,6 +1060,7 @@
|
||||
'biz-card mt-6',
|
||||
'business-blank-page' => ($page['slug'] ?? null) === 'store-receiving-bills',
|
||||
])
|
||||
@if (($page['slug'] ?? null) === 'store-receiving-bills') data-table-preferences-user="{{ user()->id }}" @endif
|
||||
aria-label="{{ $activeTab['title'] ?? ($page['title'] ?? $section['title']) }}"
|
||||
>
|
||||
<div class="biz-empty">
|
||||
|
||||
@ -118,6 +118,10 @@ Route::get('workspace/product-inventory/normal-products/export', 'Business\Pages
|
||||
->middleware('business.page:product-inventory,normal-products')
|
||||
->name('business.product-inventory.normal-products.export');
|
||||
|
||||
Route::get('workspace/product-inventory/online-daifa-price/export', 'Business\Pages@exportOnlineDaifaPrice')
|
||||
->middleware('business.page:product-inventory,online-daifa-price')
|
||||
->name('business.product-inventory.online-daifa-price.export');
|
||||
|
||||
Route::get('workspace/refunds/non-jingxi-refund-data/export', 'Business\Pages@exportNonJingxiRefunds')
|
||||
->middleware('business.page:refunds,non-jingxi-refund-data')
|
||||
->name('business.refunds.non-jingxi-refund-data.export');
|
||||
|
||||
54
scripts/deploy-auth.ps1
Normal file
54
scripts/deploy-auth.ps1
Normal file
@ -0,0 +1,54 @@
|
||||
function Start-CaiwuDeploymentAuth {
|
||||
param([string]$Server, [string]$SshUser, [string]$KeyPath, [Security.SecureString]$Password, [switch]$UpdatePassword)
|
||||
if ($Server -notmatch '^[A-Za-z0-9][A-Za-z0-9.-]*$' -or $SshUser -notmatch '^[A-Za-z_][A-Za-z0-9_-]*$') {
|
||||
throw '服务器地址或登录用户名格式无效。'
|
||||
}
|
||||
$options = @('-o', 'StrictHostKeyChecking=accept-new', '-o', 'ConnectTimeout=10')
|
||||
if (-not [string]::IsNullOrWhiteSpace($KeyPath)) {
|
||||
return @{ Options = $options + @('-i', (Resolve-Path -LiteralPath $KeyPath).Path, '-o', 'BatchMode=yes'); Directory = $null; Saved = @{} }
|
||||
}
|
||||
$directory = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) "CaiWuXiTong/deploy-credentials/${SshUser}@${Server}"
|
||||
[IO.Directory]::CreateDirectory($directory) | Out-Null
|
||||
$session = @{ Directory = $directory; Saved = @{}; Options = $options + @('-o', 'BatchMode=no', '-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1') }
|
||||
try {
|
||||
$acl = [Security.AccessControl.DirectorySecurity]::new()
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
$owner = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
||||
$acl.SetOwner($owner)
|
||||
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($owner, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
[IO.FileSystemAclExtensions]::SetAccessControl([IO.DirectoryInfo]::new($directory), $acl)
|
||||
$values = @{
|
||||
SSH_ASKPASS = (Join-Path $PSScriptRoot 'deploy-password-prompt.cmd')
|
||||
SSH_ASKPASS_REQUIRE = 'force'
|
||||
DISPLAY = 'caiwu-deploy'
|
||||
CAIWU_DEPLOY_LOGIN = "${SshUser}@${Server}"
|
||||
CAIWU_DEPLOY_PASSWORD_CACHE = (Join-Path $directory 'password.dpapi')
|
||||
CAIWU_DEPLOY_PASSWORD_UPDATE = $(if ($UpdatePassword) { '1' } else { $null })
|
||||
}
|
||||
foreach ($name in $values.Keys) {
|
||||
$session.Saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
|
||||
[Environment]::SetEnvironmentVariable($name, $values[$name], 'Process')
|
||||
}
|
||||
if ($Password) {
|
||||
$Password | ConvertFrom-SecureString | Set-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Encoding ASCII
|
||||
$env:CAIWU_DEPLOY_PASSWORD_UPDATE = $null
|
||||
}
|
||||
if (Test-Path -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE) {
|
||||
Write-Host '正在使用本机已保存的部署登录信息。'
|
||||
} else {
|
||||
Write-Host '首次部署:请在本机窗口输入服务器密码。此后自动使用已保存的登录信息。'
|
||||
}
|
||||
return $session
|
||||
} catch {
|
||||
Stop-CaiwuDeploymentAuth $session
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
function Stop-CaiwuDeploymentAuth {
|
||||
param($Session)
|
||||
if (-not $Session) { return }
|
||||
foreach ($name in $Session.Saved.Keys) {
|
||||
[Environment]::SetEnvironmentVariable($name, $Session.Saved[$name], 'Process')
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,10 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Server,
|
||||
[string]$Server = '218.93.190.75',
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$KeyPath,
|
||||
[Security.SecureString]$Password,
|
||||
[switch]$UpdatePassword,
|
||||
|
||||
[string]$SshUser = 'root',
|
||||
[string]$RemotePath = '/opt/caiwuxitong',
|
||||
@ -26,7 +26,9 @@ param(
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
$keyFullPath = (Resolve-Path $KeyPath).Path
|
||||
. (Join-Path $PSScriptRoot 'deploy-auth.ps1')
|
||||
$authSession = $null
|
||||
$sshOptions = @()
|
||||
$sshTarget = "${SshUser}@${Server}"
|
||||
$imageName = 'caiwu_akaunting'
|
||||
$tempRoot = Join-Path ([IO.Path]::GetTempPath()) ("caiwu-deploy-" + [Guid]::NewGuid().ToString('N'))
|
||||
@ -114,7 +116,7 @@ function Ensure-QiniuBusinessStorageRuntime {
|
||||
"grep -q '^QINIU_SECRET_KEY=.' '$remoteEnvironment'"
|
||||
) -join ' && '
|
||||
|
||||
& ssh -i $keyFullPath -o BatchMode=yes $sshTarget $remoteReadyCommand
|
||||
& ssh @sshOptions $sshTarget $remoteReadyCommand
|
||||
$remoteReady = $LASTEXITCODE -eq 0
|
||||
|
||||
if ($remoteReady) {
|
||||
@ -136,8 +138,7 @@ function Ensure-QiniuBusinessStorageRuntime {
|
||||
|
||||
$pendingEnvironment = "$remoteEnvironment.pending"
|
||||
$environmentContent | & ssh `
|
||||
-i $keyFullPath `
|
||||
-o BatchMode=yes `
|
||||
@sshOptions `
|
||||
$sshTarget `
|
||||
"umask 077; cat > '$pendingEnvironment'; chmod 600 '$pendingEnvironment'; mv '$pendingEnvironment' '$remoteEnvironment'"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
@ -249,17 +250,15 @@ function Start-RegistryTunnel {
|
||||
$startInfo.FileName = $sshPath
|
||||
$startInfo.UseShellExecute = $false
|
||||
$startInfo.CreateNoWindow = $true
|
||||
foreach ($argument in @(
|
||||
foreach ($argument in ($sshOptions + @(
|
||||
'-N',
|
||||
'-i', $keyFullPath,
|
||||
'-o', 'BatchMode=yes',
|
||||
'-o', 'ConnectTimeout=10',
|
||||
'-o', 'ExitOnForwardFailure=yes',
|
||||
'-o', 'ServerAliveInterval=15',
|
||||
'-o', 'ServerAliveCountMax=20',
|
||||
'-L', "127.0.0.1:${LocalPort}:127.0.0.1:5000",
|
||||
$sshTarget
|
||||
)) {
|
||||
))) {
|
||||
$startInfo.ArgumentList.Add($argument)
|
||||
}
|
||||
|
||||
@ -303,7 +302,6 @@ try {
|
||||
$deploySha = (git rev-parse HEAD).Trim()
|
||||
$imageTag = $deploySha.Substring(0, 12)
|
||||
$fullImage = "${imageName}:$imageTag"
|
||||
$remoteArchive = "$RemotePath/image-$imageTag.tar.gz"
|
||||
$buildDate = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
|
||||
|
||||
if (-not $AppUrl) {
|
||||
@ -317,6 +315,13 @@ try {
|
||||
|
||||
Invoke-Native { docker version | Out-Null } 'Docker Desktop 未启动或不可用。'
|
||||
|
||||
$authSession = Start-CaiwuDeploymentAuth -Server $Server -SshUser $SshUser -KeyPath $KeyPath -Password $Password -UpdatePassword:$UpdatePassword
|
||||
$sshOptions = $authSession.Options
|
||||
& ssh @sshOptions $sshTarget true
|
||||
if ($LASTEXITCODE -ne 0) { throw '服务器登录失败或已取消,已停止部署。若密码已变更,由 Codex 使用 -UpdatePassword 重新打开本机密码窗口。' }
|
||||
if ($authSession.Directory) { $env:CAIWU_DEPLOY_PASSWORD_UPDATE = $null }
|
||||
$remoteArchive = "$RemotePath/image-$imageTag.tar.gz"
|
||||
|
||||
& (Join-Path $PSScriptRoot 'build-frontend.ps1')
|
||||
|
||||
docker buildx inspect $BuilderName 2>$null | Out-Null
|
||||
@ -351,7 +356,7 @@ try {
|
||||
docker run --rm --network none --user www-data --entrypoint php $fullImage artisan --version
|
||||
} '发布镜像无法引导 Laravel。服务器未发生任何变更。'
|
||||
|
||||
$previousShaOutput = @(& ssh -i $keyFullPath -o BatchMode=yes -o StrictHostKeyChecking=accept-new $sshTarget "cat '$RemotePath/.deployed-sha' 2>/dev/null || true")
|
||||
$previousShaOutput = @(& ssh @sshOptions -o StrictHostKeyChecking=accept-new $sshTarget "cat '$RemotePath/.deployed-sha' 2>/dev/null || true")
|
||||
$previousSha = ($previousShaOutput -join "`n").Trim()
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw '无法连接服务器。'
|
||||
@ -364,7 +369,7 @@ try {
|
||||
}
|
||||
|
||||
if ($previousSha -and -not $previousShaExists -and -not $AllowMigrations) {
|
||||
throw "本地缺少服务器当前提交 $previousSha,无法安全比较数据库迁移。请先 git fetch,或在负责人授权后使用 -AllowMigrations。"
|
||||
throw "本地缺少服务器当前提交 $previousSha,无法安全比较数据库迁移。请先 git fetch 并核对全部待执行迁移,按 AGENTS.md 完成备份后使用 -AllowMigrations。"
|
||||
}
|
||||
|
||||
if ($previousSha -and $previousShaExists) {
|
||||
@ -372,7 +377,7 @@ try {
|
||||
database/migrations `
|
||||
':(glob)modules/*/Database/Migrations/*.php'
|
||||
if ($migrationChanges -and -not $AllowMigrations) {
|
||||
throw "检测到数据库迁移:$($migrationChanges -join ', ')。需负责人确认后添加 -AllowMigrations。"
|
||||
throw "检测到数据库迁移:$($migrationChanges -join ', ')。由 Codex 核对全部待执行迁移;本任务镜像迁移完成备份后可直接添加 -AllowMigrations,其他迁移按 AGENTS.md 执行。"
|
||||
}
|
||||
}
|
||||
|
||||
@ -381,22 +386,22 @@ try {
|
||||
if ($BootstrapServer) {
|
||||
$bootstrapRemote = "/tmp/caiwu-bootstrap-$imageTag.sh"
|
||||
Invoke-Native {
|
||||
scp -i $keyFullPath -o BatchMode=yes deploy/bootstrap-server.sh "${sshTarget}:$bootstrapRemote"
|
||||
scp @sshOptions deploy/bootstrap-server.sh "${sshTarget}:$bootstrapRemote"
|
||||
} '上传服务器初始化脚本失败。'
|
||||
Invoke-Native {
|
||||
ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$bootstrapRemote' && '$bootstrapRemote' '$AppUrl' '$RemotePath' && rm -f '$bootstrapRemote'"
|
||||
ssh @sshOptions $sshTarget "chmod 700 '$bootstrapRemote' && '$bootstrapRemote' '$AppUrl' '$RemotePath' && rm -f '$bootstrapRemote'"
|
||||
} '服务器初始化失败。'
|
||||
}
|
||||
|
||||
Invoke-Native {
|
||||
ssh -i $keyFullPath -o BatchMode=yes $sshTarget "docker version >/dev/null && docker compose version >/dev/null && install -d -m 700 '$RemotePath'"
|
||||
ssh @sshOptions $sshTarget "docker version >/dev/null && docker compose version >/dev/null && install -d -m 700 '$RemotePath'"
|
||||
} '服务器 Docker 未就绪;首次发布请添加 -BootstrapServer。'
|
||||
|
||||
Ensure-QiniuBusinessStorageRuntime
|
||||
|
||||
$migrationFlag = if ($AllowMigrations) { '1' } else { '0' }
|
||||
Invoke-Native {
|
||||
scp -i $keyFullPath -o BatchMode=yes `
|
||||
scp @sshOptions `
|
||||
compose.jiangling.yml `
|
||||
deploy/activate-release.sh `
|
||||
deploy/activate-incremental-release.sh `
|
||||
@ -410,7 +415,7 @@ try {
|
||||
} '上传运行配置失败。'
|
||||
|
||||
Invoke-Native {
|
||||
ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$RemotePath/update-runtime-url.sh' && '$RemotePath/update-runtime-url.sh' '$AppUrl' '$RemotePath'"
|
||||
ssh @sshOptions $sshTarget "chmod 700 '$RemotePath/update-runtime-url.sh' && '$RemotePath/update-runtime-url.sh' '$AppUrl' '$RemotePath'"
|
||||
} '更新服务器访问地址失败。'
|
||||
|
||||
if ($BootstrapServer) {
|
||||
@ -430,14 +435,14 @@ try {
|
||||
Remove-Item -LiteralPath $localTar -Force
|
||||
$archiveSizeMB = [math]::Round((Get-Item -LiteralPath $localArchive).Length / 1MB, 1)
|
||||
Write-Host "首次初始化全量包:$archiveSizeMB MiB"
|
||||
Invoke-Native { scp -i $keyFullPath -o BatchMode=yes $localArchive "${sshTarget}:$remoteArchive" } '上传镜像失败。'
|
||||
Invoke-Native { scp @sshOptions $localArchive "${sshTarget}:$remoteArchive" } '上传镜像失败。'
|
||||
Invoke-Native {
|
||||
ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && '$RemotePath/activate-release.sh' '$remoteArchive' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages' && '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml'"
|
||||
ssh @sshOptions $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && '$RemotePath/activate-release.sh' '$remoteArchive' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages' && '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml'"
|
||||
} '服务器激活、健康检查或增量仓库初始化失败。'
|
||||
}
|
||||
else {
|
||||
Invoke-NativeWithRetry {
|
||||
ssh -i $keyFullPath -o BatchMode=yes -o ConnectTimeout=10 -o ConnectionAttempts=1 $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && (curl -fsS -o /dev/null http://127.0.0.1:5000/v2/ || '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml')"
|
||||
ssh @sshOptions -o ConnectTimeout=10 -o ConnectionAttempts=1 $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && (curl -fsS -o /dev/null http://127.0.0.1:5000/v2/ || '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml')"
|
||||
} '服务器增量镜像仓库初始化失败。'
|
||||
|
||||
# docker save 导出未压缩层,每次导入重新压缩会改变摘要,导致 Registry 无法复用。
|
||||
@ -460,7 +465,7 @@ try {
|
||||
$registryImage = "127.0.0.1:${localRegistryPort}/caiwuxitong/app:$imageTag"
|
||||
$serverRegistryImage = "127.0.0.1:5000/caiwuxitong/app:$imageTag"
|
||||
|
||||
$beforeBytesOutput = @(& ssh -i $keyFullPath -o BatchMode=yes $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1")
|
||||
$beforeBytesOutput = @(& ssh @sshOptions $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1")
|
||||
$beforeBytes = [long](($beforeBytesOutput -join '').Trim())
|
||||
$uploadTimer = [Diagnostics.Stopwatch]::StartNew()
|
||||
$uploadSucceeded = $false
|
||||
@ -503,19 +508,19 @@ try {
|
||||
throw '增量镜像层上传失败。'
|
||||
}
|
||||
$uploadTimer.Stop()
|
||||
$afterBytesOutput = @(& ssh -i $keyFullPath -o BatchMode=yes $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1")
|
||||
$afterBytesOutput = @(& ssh @sshOptions $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1")
|
||||
$afterBytes = [long](($afterBytesOutput -join '').Trim())
|
||||
$incrementalMiB = [math]::Round([math]::Max(0, $afterBytes - $beforeBytes) / 1MB, 2)
|
||||
Write-Host "增量新增镜像层:$incrementalMiB MiB;传输耗时:$([math]::Round($uploadTimer.Elapsed.TotalSeconds, 1)) 秒"
|
||||
|
||||
Invoke-Native {
|
||||
ssh -i $keyFullPath -o BatchMode=yes $sshTarget "'$RemotePath/activate-incremental-release.sh' '$serverRegistryImage' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages'"
|
||||
ssh @sshOptions $sshTarget "'$RemotePath/activate-incremental-release.sh' '$serverRegistryImage' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages'"
|
||||
} '服务器增量激活或健康检查失败。'
|
||||
}
|
||||
|
||||
if ($ConfigureDingTalkCallback) {
|
||||
Invoke-Native {
|
||||
ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$RemotePath/configure-dingtalk-callback.sh' && '$RemotePath/configure-dingtalk-callback.sh' '$Server' '$RemotePath'"
|
||||
ssh @sshOptions $sshTarget "chmod 700 '$RemotePath/configure-dingtalk-callback.sh' && '$RemotePath/configure-dingtalk-callback.sh' '$Server' '$RemotePath'"
|
||||
} '钉钉 HTTP 回调 Nginx 配置失败。'
|
||||
}
|
||||
|
||||
@ -523,39 +528,43 @@ try {
|
||||
Write-Host "发布完成:$fullImage -> $AppUrl"
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
try {
|
||||
Pop-Location
|
||||
|
||||
if (Test-Path -LiteralPath $tempRoot) {
|
||||
Remove-Item -LiteralPath $tempRoot -Recurse -Force
|
||||
}
|
||||
|
||||
if ($sshTunnel) {
|
||||
if (-not $sshTunnel.HasExited) {
|
||||
$sshTunnel.Kill()
|
||||
if (Test-Path -LiteralPath $tempRoot) {
|
||||
Remove-Item -LiteralPath $tempRoot -Recurse -Force
|
||||
}
|
||||
$sshTunnel.Dispose()
|
||||
}
|
||||
|
||||
if ($remoteArchive) {
|
||||
ssh -i $keyFullPath -o BatchMode=yes -o ConnectTimeout=5 $sshTarget "rm -f '$remoteArchive'" 2>$null | Out-Null
|
||||
}
|
||||
if ($sshTunnel) {
|
||||
if (-not $sshTunnel.HasExited) {
|
||||
$sshTunnel.Kill()
|
||||
}
|
||||
$sshTunnel.Dispose()
|
||||
}
|
||||
|
||||
if ($bootstrapRemote) {
|
||||
ssh -i $keyFullPath -o BatchMode=yes -o ConnectTimeout=5 $sshTarget "rm -f '$bootstrapRemote'" 2>$null | Out-Null
|
||||
}
|
||||
if ($remoteArchive) {
|
||||
ssh @sshOptions -o ConnectTimeout=5 $sshTarget "rm -f '$remoteArchive'" 2>$null | Out-Null
|
||||
}
|
||||
|
||||
# Keep the compiled PHP base and Composer vendor layers between releases.
|
||||
# The production build cache is normally about 20 GB; pruning it to 3 GB made
|
||||
# every deployment rebuild PHP extensions and download all dependencies again.
|
||||
$pruneHelp = docker buildx prune --help 2>$null | Out-String
|
||||
$buildCacheMaxAge = "${BuildCacheMaxAgeHours}h"
|
||||
docker buildx prune --builder $BuilderName --filter "until=$buildCacheMaxAge" --force 2>$null | Out-Null
|
||||
if ($pruneHelp -match '--max-used-space') {
|
||||
docker buildx prune --builder $BuilderName --max-used-space $BuildCacheMaxUsedSpace --force 2>$null | Out-Null
|
||||
}
|
||||
elseif ($pruneHelp -match '--keep-storage') {
|
||||
docker buildx prune --builder $BuilderName --keep-storage $BuildCacheMaxUsedSpace --force 2>$null | Out-Null
|
||||
}
|
||||
if ($bootstrapRemote) {
|
||||
ssh @sshOptions -o ConnectTimeout=5 $sshTarget "rm -f '$bootstrapRemote'" 2>$null | Out-Null
|
||||
}
|
||||
|
||||
docker system df
|
||||
# Keep the compiled PHP base and Composer vendor layers between releases.
|
||||
# The production build cache is normally about 20 GB; pruning it to 3 GB made
|
||||
# every deployment rebuild PHP extensions and download all dependencies again.
|
||||
$pruneHelp = docker buildx prune --help 2>$null | Out-String
|
||||
$buildCacheMaxAge = "${BuildCacheMaxAgeHours}h"
|
||||
docker buildx prune --builder $BuilderName --filter "until=$buildCacheMaxAge" --force 2>$null | Out-Null
|
||||
if ($pruneHelp -match '--max-used-space') {
|
||||
docker buildx prune --builder $BuilderName --max-used-space $BuildCacheMaxUsedSpace --force 2>$null | Out-Null
|
||||
}
|
||||
elseif ($pruneHelp -match '--keep-storage') {
|
||||
docker buildx prune --builder $BuilderName --keep-storage $BuildCacheMaxUsedSpace --force 2>$null | Out-Null
|
||||
}
|
||||
|
||||
docker system df
|
||||
} finally {
|
||||
Stop-CaiwuDeploymentAuth $authSession
|
||||
}
|
||||
}
|
||||
|
||||
2
scripts/deploy-password-prompt.cmd
Normal file
2
scripts/deploy-password-prompt.cmd
Normal file
@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
powershell.exe -NoProfile -STA -ExecutionPolicy Bypass -File "%~dp0deploy-password-prompt.ps1"
|
||||
47
scripts/deploy-password-prompt.ps1
Normal file
47
scripts/deploy-password-prompt.ps1
Normal file
@ -0,0 +1,47 @@
|
||||
# OpenSSH invokes this through SSH_ASKPASS. stdout goes only to OpenSSH.
|
||||
# Never log or pass plaintext as a process argument. Persist only user-bound DPAPI ciphertext.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
||||
# A Codex PowerShell 7 parent may supply a different PSModulePath.
|
||||
Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1')
|
||||
Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1')
|
||||
if ($env:CAIWU_DEPLOY_PASSWORD_UPDATE -ne '1' -and (Test-Path -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE)) {
|
||||
$secure = (Get-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Raw).Trim() | ConvertTo-SecureString
|
||||
$credential = [Management.Automation.PSCredential]::new('deploy', $secure)
|
||||
[Console]::Out.WriteLine($credential.GetNetworkCredential().Password)
|
||||
exit 0
|
||||
}
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$form = New-Object Windows.Forms.Form
|
||||
$form.Text = '财务系统:部署登录'
|
||||
$form.ClientSize = New-Object Drawing.Size(430, 155)
|
||||
$form.StartPosition = 'CenterScreen'
|
||||
$form.TopMost = $true
|
||||
$label = New-Object Windows.Forms.Label
|
||||
$label.Text = "请输入服务器 $env:CAIWU_DEPLOY_LOGIN 的密码:"
|
||||
$label.SetBounds(15, 15, 400, 40)
|
||||
$inputBox = New-Object Windows.Forms.TextBox
|
||||
$inputBox.UseSystemPasswordChar = $true
|
||||
$inputBox.SetBounds(15, 60, 400, 25)
|
||||
$ok = New-Object Windows.Forms.Button
|
||||
$ok.Text = '登录'
|
||||
$ok.SetBounds(250, 105, 75, 30)
|
||||
$ok.DialogResult = [Windows.Forms.DialogResult]::OK
|
||||
$cancel = New-Object Windows.Forms.Button
|
||||
$cancel.Text = '取消'
|
||||
$cancel.SetBounds(335, 105, 75, 30)
|
||||
$cancel.DialogResult = [Windows.Forms.DialogResult]::Cancel
|
||||
$form.Controls.AddRange(@($label, $inputBox, $ok, $cancel))
|
||||
$form.AcceptButton = $ok
|
||||
$form.CancelButton = $cancel
|
||||
try {
|
||||
if ($form.ShowDialog() -ne [Windows.Forms.DialogResult]::OK) { exit 1 }
|
||||
# DPAPI ciphertext, restricted to this Windows user, reused by later deployments.
|
||||
$secure = ConvertTo-SecureString -String $inputBox.Text -AsPlainText -Force
|
||||
$secure | ConvertFrom-SecureString | Set-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Encoding ASCII
|
||||
[Console]::Out.WriteLine($inputBox.Text)
|
||||
} finally {
|
||||
$inputBox.Clear()
|
||||
$form.Dispose()
|
||||
}
|
||||
@ -99,6 +99,8 @@ class OnlineDaifaPricePageTest extends FeatureTestCase
|
||||
'keyword' => '6927049845766979458',
|
||||
'product_id' => '3821829253650055444',
|
||||
'shop_name' => '抖音-HX旗舰店101',
|
||||
'supplier_name' => '新北供应商',
|
||||
'material_no' => 'MAT-001',
|
||||
'status' => '',
|
||||
'created_from' => '2026-09-01',
|
||||
'created_to' => '2026-09-07',
|
||||
@ -120,12 +122,109 @@ class OnlineDaifaPricePageTest extends FeatureTestCase
|
||||
'keyword' => '6927049845766979458',
|
||||
'product_id' => '3821829253650055444',
|
||||
'shop_name' => '抖音-HX旗舰店101',
|
||||
'supplier_name' => '新北供应商',
|
||||
'material_no' => 'MAT-001',
|
||||
'created_from' => '2026-09-01',
|
||||
'created_to' => '2026-09-07',
|
||||
]))->assertOk()
|
||||
->assertSee('商品ID')
|
||||
->assertSee('店铺名称')
|
||||
->assertSee('供应商名称')
|
||||
->assertSee('新北供应商')
|
||||
->assertSee('料号')
|
||||
->assertSee('MAT-001')
|
||||
->assertSee('2026-09-01')
|
||||
->assertSee('2026-09-07');
|
||||
}
|
||||
|
||||
public function test_online_daifa_price_export_streams_all_currently_filtered_rows(): void
|
||||
{
|
||||
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||||
$filters = [
|
||||
'keyword' => 'DAIFA-001',
|
||||
'product_id' => 'PRODUCT-001',
|
||||
'shop_name' => '抖音旗舰店',
|
||||
'supplier_name' => '新北供应商',
|
||||
'material_no' => 'MAT-001',
|
||||
'status' => 'COMPLETED',
|
||||
'created_from' => '2026-09-01',
|
||||
'created_to' => '2026-09-07',
|
||||
];
|
||||
$repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class);
|
||||
$repository->shouldReceive('ready')->once()->andReturnTrue();
|
||||
$repository->shouldReceive('exportRows')->once()->with($filters)->andReturn((static function (): \Generator {
|
||||
yield [
|
||||
'process_instance_id' => 'PROCESS-001',
|
||||
'product_id' => '3821829253650055444',
|
||||
'daifa_trade_no' => '6927049845766979458',
|
||||
'shop_trade_no' => '6927049845766979459',
|
||||
'shop_name' => '抖音旗舰店',
|
||||
'payee_name' => '宁波顾家望业家居有限公司',
|
||||
'supplier_name' => '@新北供应商',
|
||||
'material_no' => 'MAT-001',
|
||||
'ship_qty' => 2,
|
||||
'paid_amount' => 616.61,
|
||||
'daifa_amount' => 375.0,
|
||||
'price_diff' => 241.61,
|
||||
'workflow' => [
|
||||
'businessId' => '=APPROVAL-001',
|
||||
'title' => '线上代发业务报销',
|
||||
'originatorUserName' => '+扬灵',
|
||||
],
|
||||
'status_label' => '已完成',
|
||||
'matched_product' => ['matched' => true, 'name' => '演示商品'],
|
||||
'workflow_created_at' => '2026-09-01 10:00:00',
|
||||
];
|
||||
})());
|
||||
$this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository);
|
||||
|
||||
$response = $this->loginAs()->get(route('business.product-inventory.online-daifa-price.export', $filters));
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertStringContainsString('attachment;', (string) $response->headers->get('content-disposition'));
|
||||
$this->assertStringContainsString('text/csv', (string) $response->headers->get('content-type'));
|
||||
$content = $response->streamedContent();
|
||||
$this->assertStringStartsWith(chr(0xEF) . chr(0xBB) . chr(0xBF), $content);
|
||||
$this->assertStringContainsString('供应商名称', $content);
|
||||
$this->assertStringContainsString('料号', $content);
|
||||
$this->assertStringContainsString("'=APPROVAL-001", $content);
|
||||
$this->assertStringContainsString("'+扬灵", $content);
|
||||
$this->assertStringContainsString("'@新北供应商", $content);
|
||||
$this->assertStringContainsString("'3821829253650055444", $content);
|
||||
$this->assertStringContainsString("'6927049845766979458", $content);
|
||||
$this->assertStringContainsString("'6927049845766979459", $content);
|
||||
$this->assertStringContainsString('MAT-001', $content);
|
||||
}
|
||||
|
||||
public function test_online_daifa_price_export_requires_a_ready_mirror(): void
|
||||
{
|
||||
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||||
$repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class);
|
||||
$repository->shouldReceive('ready')->once()->andReturnFalse();
|
||||
$repository->shouldNotReceive('exportRows');
|
||||
$this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository);
|
||||
|
||||
$this->withExceptionHandling()
|
||||
->loginAs()
|
||||
->get(route('business.product-inventory.online-daifa-price.export'))
|
||||
->assertServiceUnavailable();
|
||||
}
|
||||
|
||||
public function test_online_daifa_price_export_rejects_users_without_sidebar_permission(): void
|
||||
{
|
||||
$subject = 'user_' . $this->user->id;
|
||||
|
||||
$this->user->roles()->sync([\App\Models\Auth\Role::where('name', 'admin')->firstOrFail()->id]);
|
||||
setting()->set('system.sidebar_permissions', json_encode([
|
||||
'configured' => [$subject],
|
||||
'subjects' => [
|
||||
$subject => ['company-management/basic-information'],
|
||||
],
|
||||
], JSON_UNESCAPED_UNICODE));
|
||||
|
||||
$this->withExceptionHandling()
|
||||
->loginAs()
|
||||
->get(route('business.product-inventory.online-daifa-price.export'))
|
||||
->assertForbidden();
|
||||
}
|
||||
}
|
||||
|
||||
@ -207,6 +207,45 @@ class DingPayableWorkflowMirrorSynchronizerTest extends TestCase
|
||||
$this->assertContains('2026-08-02 00:00:00', array_values($queries)[0]['bindings']);
|
||||
}
|
||||
|
||||
public function test_daifa_repository_filters_supplier_and_material_no_for_page_and_export(): void
|
||||
{
|
||||
config(['upstream_mirrors.ding_online_daifa_price' => [
|
||||
'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price',
|
||||
'target_table' => 'ding_online_daifa_price_mirror',
|
||||
'source_key' => 'operations_replica', 'process_code' => 'PROC-TEST',
|
||||
'extend_columns' => true, 'column_map' => ['product_id' => '商品ID'],
|
||||
]]);
|
||||
$this->query->workflowBatches = [[
|
||||
$this->workflow('A', '2026-08-01 10:00:00'),
|
||||
$this->workflow('B', '2026-08-01 11:00:00'),
|
||||
$this->workflow('C', '2026-08-01 12:00:00'),
|
||||
]];
|
||||
$this->synchronizer->forConfigKey('ding_online_daifa_price')->sync(true, 10, 0);
|
||||
|
||||
$db = DB::connection('business_mirror');
|
||||
$db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'A')->update([
|
||||
'supplier_name' => '供应商%测试', 'material_no' => 'MAT-001',
|
||||
]);
|
||||
$db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'B')->update([
|
||||
'supplier_name' => '供应商X测试', 'material_no' => 'MAT-001',
|
||||
]);
|
||||
$db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'C')->update([
|
||||
'supplier_name' => '供应商%测试', 'material_no' => 'MAT-002',
|
||||
]);
|
||||
|
||||
$filters = ['supplier_name' => '供应商%测试', 'material_no' => 'MAT-001'];
|
||||
$repository = app(\Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository::class);
|
||||
|
||||
$page = $repository->paginate($filters, 1, 25);
|
||||
$this->assertSame(1, $page['total']);
|
||||
$this->assertSame(['A'], array_column($page['data'], 'process_instance_id'));
|
||||
|
||||
$exported = iterator_to_array($repository->exportRows($filters));
|
||||
$this->assertSame(['A'], array_column($exported, 'process_instance_id'));
|
||||
$this->assertSame('供应商%测试', $exported[0]['supplier_name']);
|
||||
$this->assertSame('MAT-001', $exported[0]['material_no']);
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function workflow(string $id, string $updateAt, string $status = 'COMPLETED'): array
|
||||
{
|
||||
|
||||
86
tests/scripts/deploy-auth-server.py
Normal file
86
tests/scripts/deploy-auth-server.py
Normal file
@ -0,0 +1,86 @@
|
||||
"""Loopback-only SSH/SFTP fixture; password arrives through stdin, never logs."""
|
||||
import io
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import paramiko
|
||||
|
||||
password = sys.stdin.readline().rstrip('\n')
|
||||
key = paramiko.RSAKey.generate(2048)
|
||||
|
||||
class Server(paramiko.ServerInterface):
|
||||
def __init__(self):
|
||||
self.direct = set()
|
||||
|
||||
def check_auth_password(self, username, supplied):
|
||||
return paramiko.AUTH_SUCCESSFUL if supplied == password else paramiko.AUTH_FAILED
|
||||
|
||||
def get_allowed_auths(self, username):
|
||||
return 'password'
|
||||
|
||||
def check_channel_request(self, kind, chanid):
|
||||
return paramiko.OPEN_SUCCEEDED if kind == 'session' else paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
|
||||
|
||||
def check_channel_direct_tcpip_request(self, chanid, origin, destination):
|
||||
self.direct.add(chanid)
|
||||
return paramiko.OPEN_SUCCEEDED
|
||||
|
||||
def check_channel_exec_request(self, channel, command):
|
||||
def finish():
|
||||
time.sleep(0.1)
|
||||
channel.send_exit_status(0)
|
||||
channel.close()
|
||||
threading.Thread(target=finish, daemon=True).start()
|
||||
return True
|
||||
|
||||
class SFTP(paramiko.SFTPServerInterface):
|
||||
def stat(self, path):
|
||||
return paramiko.SFTP_NO_SUCH_FILE
|
||||
|
||||
def open(self, path, flags, attr):
|
||||
class Handle(paramiko.SFTPHandle):
|
||||
def chattr(self, attr):
|
||||
return paramiko.SFTP_OK
|
||||
handle = Handle(flags)
|
||||
handle.writefile = io.BytesIO()
|
||||
return handle
|
||||
|
||||
def connection(client):
|
||||
transport = paramiko.Transport(client)
|
||||
transport.add_server_key(key)
|
||||
class SFTPSubsystem(paramiko.SFTPServer):
|
||||
def start_subsystem(self, name, transport, channel):
|
||||
super().start_subsystem(name, transport, channel)
|
||||
channel.send_exit_status(0)
|
||||
transport.set_subsystem_handler('sftp', SFTPSubsystem, SFTP)
|
||||
try:
|
||||
server = Server()
|
||||
channels = []
|
||||
transport.start_server(server=server)
|
||||
while transport.is_active():
|
||||
channel = transport.accept(0.5)
|
||||
if channel:
|
||||
channels.append(channel)
|
||||
if channel.chanid not in server.direct:
|
||||
continue
|
||||
def echo(c):
|
||||
while not c.closed:
|
||||
if c.recv_ready():
|
||||
data = c.recv(1024)
|
||||
if data:
|
||||
c.sendall(data)
|
||||
time.sleep(0.01)
|
||||
threading.Thread(target=echo, args=(channel,), daemon=True).start()
|
||||
except (EOFError, OSError, paramiko.SSHException):
|
||||
pass
|
||||
finally:
|
||||
transport.close()
|
||||
|
||||
listener = socket.socket()
|
||||
listener.bind(('127.0.0.1', 0))
|
||||
listener.listen(10)
|
||||
print(listener.getsockname()[1], flush=True)
|
||||
while True:
|
||||
client, _ = listener.accept()
|
||||
threading.Thread(target=connection, args=(client,), daemon=True).start()
|
||||
73
tests/scripts/deploy-password-auth.ps1
Normal file
73
tests/scripts/deploy-password-auth.ps1
Normal file
@ -0,0 +1,73 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
. (Join-Path $root 'scripts/deploy-auth.ps1')
|
||||
$session = $null
|
||||
$server = $null
|
||||
$tunnel = $null
|
||||
$username = 'test_' + [Guid]::NewGuid().ToString('N')
|
||||
try {
|
||||
$password = [Guid]::NewGuid().ToString('N') + '测试 !$`"'
|
||||
$session = Start-CaiwuDeploymentAuth -Server '127.0.0.1' -SshUser $username -Password (ConvertTo-SecureString $password -AsPlainText -Force)
|
||||
$info = [Diagnostics.ProcessStartInfo]::new()
|
||||
$info.FileName = (Get-Command python).Source
|
||||
$info.ArgumentList.Add((Join-Path $PSScriptRoot 'deploy-auth-server.py'))
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
$info.RedirectStandardInput = $true
|
||||
$info.StandardInputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
$info.Environment['PYTHONIOENCODING'] = 'utf-8'
|
||||
$info.RedirectStandardOutput = $true
|
||||
$info.RedirectStandardError = $true
|
||||
$server = [Diagnostics.Process]::Start($info)
|
||||
$server.StandardInput.WriteLine($password)
|
||||
$server.StandardInput.Flush()
|
||||
$port = $server.StandardOutput.ReadLine()
|
||||
if ($port -notmatch '^\d+$') { throw 'SSH fixture did not start' }
|
||||
$options = $session.Options + @('-o', "UserKnownHostsFile=$($session.Directory)/known_hosts")
|
||||
$target = "${username}@127.0.0.1"
|
||||
& ssh @options -p $port $target true
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Password SSH failed' }
|
||||
Stop-CaiwuDeploymentAuth $session
|
||||
$session = Start-CaiwuDeploymentAuth -Server '127.0.0.1' -SshUser $username
|
||||
& ssh @options -p $port $target true
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Saved password reuse failed' }
|
||||
$upload = Join-Path $session.Directory 'fixture.txt'
|
||||
'fixture' | Set-Content -LiteralPath $upload
|
||||
& scp @options -P $port $upload "${target}:/fixture.txt"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Password SFTP upload failed' }
|
||||
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
|
||||
$listener.Start(); $localPort = ([Net.IPEndPoint]$listener.LocalEndpoint).Port; $listener.Stop()
|
||||
$info = [Diagnostics.ProcessStartInfo]::new()
|
||||
$info.FileName = (Get-Command ssh).Source
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
foreach ($argument in ($options + @('-p', $port, '-N', '-o', 'ExitOnForwardFailure=yes', '-L', "127.0.0.1:${localPort}:127.0.0.1:1234", $target))) { $info.ArgumentList.Add($argument) }
|
||||
$tunnel = [Diagnostics.Process]::Start($info)
|
||||
Start-Sleep -Seconds 2
|
||||
$client = [Net.Sockets.TcpClient]::new('127.0.0.1', $localPort)
|
||||
$stream = $client.GetStream(); $stream.ReadTimeout = 5000
|
||||
$bytes = [Text.Encoding]::UTF8.GetBytes('probe'); $stream.Write($bytes, 0, $bytes.Length)
|
||||
$received = New-Object byte[] 5
|
||||
$count = $stream.Read($received, 0, 5)
|
||||
$client.Dispose()
|
||||
if ([Text.Encoding]::UTF8.GetString($received, 0, $count) -ne 'probe') { throw 'Password tunnel failed' }
|
||||
if ((Get-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Raw).Contains($password)) { throw 'Plaintext persisted' }
|
||||
'wrong-fixture-password' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE
|
||||
& ssh @options -p $port $target true 2>$null
|
||||
if ($LASTEXITCODE -eq 0) { throw 'Invalid password accepted' }
|
||||
$existingKey = Join-Path $session.Directory 'fake-key'
|
||||
'fixture' | Set-Content -LiteralPath $existingKey
|
||||
$keySession = Start-CaiwuDeploymentAuth -Server '127.0.0.1' -SshUser $username -KeyPath $existingKey
|
||||
if ($keySession.Options -notcontains 'BatchMode=yes' -or $keySession.Directory) { throw 'Key compatibility failed' }
|
||||
Write-Host 'PASS: supplied password SSH, saved-login reuse, SFTP upload, background tunnel, encrypted storage, rejected wrong password, optional key compatibility'
|
||||
} finally {
|
||||
if ($tunnel) { if (-not $tunnel.HasExited) { $tunnel.Kill() }; $tunnel.Dispose() }
|
||||
if ($server) { if (-not $server.HasExited) { $server.Kill() }; $server.Dispose() }
|
||||
Stop-CaiwuDeploymentAuth $session
|
||||
# Only this test-created identity directory may be removed.
|
||||
if ($session -and (Split-Path -Leaf $session.Directory) -eq "${username}@127.0.0.1") {
|
||||
$expected = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) "CaiWuXiTong/deploy-credentials/${username}@127.0.0.1"
|
||||
if ([IO.Path]::GetFullPath($session.Directory) -ne [IO.Path]::GetFullPath($expected)) { throw 'Unexpected test cleanup path' }
|
||||
Remove-Item -LiteralPath $session.Directory -Recurse -Force
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user