feat: scaffold supabase multi-tenant backend

This commit is contained in:
Codex
2026-06-21 21:54:43 +08:00
commit c9c767c7bd
99 changed files with 36660 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:54322/postgres
TENANT_ID=00000000-0000-0000-0000-000000000001
PB_SCHEMA_PATH=../../docs/pb_schema.json
PB_EXPORT_DIR=../../pb_export

View File

@@ -0,0 +1,729 @@
{
"name": "@tiku-saas/import-pocketbase",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@tiku-saas/import-pocketbase",
"version": "0.1.0",
"dependencies": {
"pg": "^8.16.3"
},
"devDependencies": {
"@types/node": "^24.0.4",
"@types/pg": "^8.15.4",
"tsx": "^4.20.3",
"typescript": "^5.8.3"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/node": {
"version": "24.13.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.2.tgz",
"integrity": "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
}
},
"node_modules/@types/pg": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz",
"integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/pg": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
"integrity": "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA==",
"license": "MIT",
"peer": true,
"dependencies": {
"pg-connection-string": "^2.14.0",
"pg-pool": "^3.14.0",
"pg-protocol": "^1.15.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.4.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
"integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.14.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
"integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.15.0.tgz",
"integrity": "sha512-cq9sECI5s0+uPUXjbz8ioyPJni6RzsRib0US67i5IoTZKw8fNeYlVE7u8F4dG7vEJJtc5wdD1K189lCCUwqWTQ==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/tsx": {
"version": "4.22.4",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz",
"integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
}
}
}

View File

@@ -0,0 +1,22 @@
{
"name": "@tiku-saas/import-pocketbase",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"schema:summary": "tsx src/analyze-schema.ts",
"schema:risk": "tsx src/risk-report.ts",
"import:json": "tsx src/import-json.ts",
"import:validate": "tsx src/validate-import.ts",
"check": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"pg": "^8.16.3"
},
"devDependencies": {
"@types/node": "^24.0.4",
"@types/pg": "^8.15.4",
"tsx": "^4.20.3",
"typescript": "^5.8.3"
}
}

View File

@@ -0,0 +1,30 @@
import { readPocketBaseSchema, fieldsOf } from './pb-schema.js';
const { absPath, collections, byId } = readPocketBaseSchema();
const businessCollections = collections.filter(c => !c.name.startsWith('_'));
const authCollections = collections.filter(c => c.type === 'auth');
const relationCount = collections.reduce(
(count, collection) => count + fieldsOf(collection).filter(field => field.type === 'relation').length,
0,
);
console.log(`PocketBase schema: ${absPath}`);
console.log(`Collections: ${collections.length}`);
console.log(`Business collections: ${businessCollections.length}`);
console.log(`Auth collections: ${authCollections.map(c => c.name).join(', ') || 'none'}`);
console.log(`Relation fields: ${relationCount}`);
console.log('');
for (const collection of businessCollections.sort((a, b) => a.name.localeCompare(b.name))) {
const fields = fieldsOf(collection);
const relationFields = fields.filter(field => field.type === 'relation');
const relationSummary = relationFields
.map(field => {
const target = field.collectionId ? byId.get(field.collectionId)?.name || field.collectionId : '?';
return `${field.name}->${target}`;
})
.join(', ');
console.log(`${collection.name.padEnd(24)} ${collection.type.padEnd(6)} fields=${String(fields.length).padStart(2)} relations=${relationSummary || '-'}`);
}

View File

@@ -0,0 +1,22 @@
import { DEFAULT_DATABASE_URL } from '../../../packages/config/src/index.js';
import { createPool, query as runQuery, queryOne as runQueryOne } from '../../../packages/db/src/index.js';
import { loadEnv } from './env.js';
loadEnv();
export const pool = createPool({
connectionString: process.env.DATABASE_URL || DEFAULT_DATABASE_URL,
max: 5,
});
export async function query<T = unknown>(sql: string, params: unknown[] = []): Promise<T[]> {
return runQuery<T>(pool, sql, params);
}
export async function queryOne<T = unknown>(sql: string, params: unknown[] = []): Promise<T | null> {
return runQueryOne<T>(pool, sql, params);
}
export async function closeDb() {
await pool.end();
}

View File

@@ -0,0 +1,5 @@
import { loadDotenv } from '../../../packages/config/src/index.js';
export function loadEnv() {
loadDotenv();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
import fs from 'node:fs';
import path from 'node:path';
export interface PocketBaseField {
name: string;
type: string;
required?: boolean;
hidden?: boolean;
values?: string[];
collectionId?: string;
maxSelect?: number;
}
export interface PocketBaseCollection {
id: string;
name: string;
type: string;
fields?: PocketBaseField[];
schema?: PocketBaseField[];
listRule?: string;
viewRule?: string;
createRule?: string;
updateRule?: string;
deleteRule?: string;
}
export function readPocketBaseSchema(schemaPath = process.env.PB_SCHEMA_PATH || '../../docs/pb_schema.json') {
const absPath = path.resolve(process.cwd(), schemaPath);
const raw = JSON.parse(fs.readFileSync(absPath, 'utf8'));
const collections = (Array.isArray(raw) ? raw : raw.collections || []) as PocketBaseCollection[];
const byId = new Map(collections.map(c => [c.id, c]));
const byName = new Map(collections.map(c => [c.name, c]));
return { absPath, collections, byId, byName };
}
export function fieldsOf(collection: PocketBaseCollection) {
return collection.fields || collection.schema || [];
}

View File

@@ -0,0 +1,80 @@
import { readPocketBaseSchema, fieldsOf } from './pb-schema.js';
const { collections, byId, absPath } = readPocketBaseSchema();
const sensitivePattern = /(password|token|secret|private|session|openid|unionid|accesskey|appkey|apikey|apiV3Key|notifyToken|aesKey|mchId|appSecret)/i;
const likelySafeKeyPattern = /(^key$|fieldKey|tokenKey)$/i;
const jsonRiskPattern = /(stats|progress|config|settings|raw|payload|metadata|fieldValues|svipRegions|recentActivities)/i;
interface Risk {
severity: 'critical' | 'high' | 'medium' | 'low';
collection: string;
field?: string;
message: string;
}
const risks: Risk[] = [];
for (const collection of collections.filter(c => !c.name.startsWith('_'))) {
const fields = fieldsOf(collection);
if (collection.name === 'settings') {
risks.push({
severity: 'critical',
collection: collection.name,
message: 'Monolithic settings table mixes public config and secrets. Split into tenant_settings, tenant_payment_accounts and app_private.tenant_secrets.',
});
}
if (collection.name === 'users') {
risks.push({
severity: 'high',
collection: collection.name,
message: 'Legacy users table mixes auth, profile, roles, learning stats, membership and referral data. Split before migration.',
});
}
for (const field of fields) {
if ((sensitivePattern.test(field.name) && !likelySafeKeyPattern.test(field.name)) || field.hidden) {
risks.push({
severity: field.hidden || sensitivePattern.test(field.name) ? 'critical' : 'high',
collection: collection.name,
field: field.name,
message: `Sensitive or hidden field "${field.name}" must not be copied into public normalized tables.`,
});
}
if (field.type === 'json' && jsonRiskPattern.test(field.name)) {
risks.push({
severity: 'medium',
collection: collection.name,
field: field.name,
message: `JSON field "${field.name}" needs explicit normalization or a documented reason to remain JSONB.`,
});
}
if (field.type === 'relation' && field.collectionId) {
const target = byId.get(field.collectionId);
if (!target) {
risks.push({
severity: 'high',
collection: collection.name,
field: field.name,
message: `Relation points to missing collection id "${field.collectionId}".`,
});
}
}
}
}
const order: Record<Risk['severity'], number> = { critical: 0, high: 1, medium: 2, low: 3 };
risks.sort((a, b) => order[a.severity] - order[b.severity] || a.collection.localeCompare(b.collection));
console.log(`PocketBase schema risk report: ${absPath}`);
console.log(`Risks: ${risks.length}`);
console.log('');
for (const risk of risks) {
const location = risk.field ? `${risk.collection}.${risk.field}` : risk.collection;
console.log(`[${risk.severity.toUpperCase()}] ${location} - ${risk.message}`);
}

View File

@@ -0,0 +1,354 @@
import { closeDb, query } from './db.js';
import { loadEnv } from './env.js';
loadEnv();
type CheckStatus = 'pass' | 'warn' | 'fail';
interface CheckResult {
name: string;
status: CheckStatus;
count?: number;
message: string;
}
const tenantId = process.env.TENANT_ID || '00000000-0000-0000-0000-000000000001';
const failOnWarnings = process.env.FAIL_ON_WARNINGS === 'true';
async function scalar(sql: string, params: unknown[] = []) {
const rows = await query<{ count: string }>(sql, params);
return Number(rows[0]?.count || 0);
}
function result(name: string, count: number, failMessage: string, passMessage: string, warnOnly = false): CheckResult {
if (count > 0) {
return {
name,
status: warnOnly ? 'warn' : 'fail',
count,
message: failMessage,
};
}
return { name, status: 'pass', count, message: passMessage };
}
async function tableCounts(): Promise<CheckResult[]> {
const tables = [
'platform_users',
'regions',
'region_modules',
'module_nodes',
'schools',
'majors',
'subjects',
'categories',
'questions',
'orders',
'svip_plans',
'activation_codes',
'vocabulary_units',
'vocabulary_words',
'handbook_subjects',
'handbook_chapters',
'handbook_entries',
'products',
];
const checks: CheckResult[] = [];
for (const table of tables) {
const count =
table === 'platform_users'
? await scalar('select count(*) from public.platform_users')
: await scalar(`select count(*) from public.${table} where tenant_id = $1`, [tenantId]);
checks.push({
name: `count:${table}`,
status: 'pass',
count,
message: `${table} rows: ${count}`,
});
}
return checks;
}
async function validationChecks(): Promise<CheckResult[]> {
const checks: CheckResult[] = [];
checks.push(
result(
'tenant_exists',
(await scalar('select count(*) from public.tenants where id = $1', [tenantId])) === 0 ? 1 : 0,
'Tenant seed is missing. Run Supabase seed or set TENANT_ID to an existing tenant.',
'Tenant exists.',
),
);
checks.push(
result(
'raw_records_not_normalized',
await scalar(
`
select count(*)
from public.pb_raw_records r
join public.pb_import_runs run on run.id = r.run_id
where r.tenant_id = $1
and run.id = (
select id from public.pb_import_runs
where tenant_id = $1
order by started_at desc
limit 1
)
and r.collection_name in (
'regions','region_modules','module_nodes','schools','majors','subjects',
'categories','questions','users','orders','svip_plans','codes',
'vocabulary_units','vocabulary','handbook_subjects','handbook_chapters',
'handbook_entries','banners','faqs','announcements'
)
and r.normalized = false
`,
[tenantId],
),
'Some core raw records from the latest run were not normalized.',
'All latest-run core raw records are marked normalized.',
),
);
checks.push(
result(
'questions_without_current_version',
await scalar(
`
select count(*)
from public.questions
where tenant_id = $1 and current_version_id is null
`,
[tenantId],
),
'Questions exist without a current version.',
'Every question has a current version.',
),
);
checks.push(
result(
'question_versions_wrong_tenant',
await scalar(
`
select count(*)
from public.questions q
join public.question_versions v on v.question_id = q.id
where q.tenant_id = $1 and v.tenant_id <> q.tenant_id
`,
[tenantId],
),
'Some question_versions have a different tenant_id from their question.',
'Question version tenant_id values match their questions.',
),
);
checks.push(
result(
'questions_unresolved_subjects',
await scalar(
`
select count(*)
from public.questions
where tenant_id = $1 and legacy_subject_id is not null and subject_id is null
`,
[tenantId],
),
'Some questions still have legacy_subject_id but no resolved subject_id.',
'Question subject references are resolved.',
true,
),
);
checks.push(
result(
'questions_unresolved_categories',
await scalar(
`
select count(*)
from public.questions
where tenant_id = $1 and legacy_category_id is not null and category_id is null
`,
[tenantId],
),
'Some questions still have legacy_category_id but no resolved category_id.',
'Question category references are resolved.',
true,
),
);
checks.push(
result(
'orders_unresolved_users',
await scalar(
`
select count(*)
from public.orders
where tenant_id = $1 and legacy_user_id is not null and user_id is null
`,
[tenantId],
),
'Some orders still have legacy_user_id but no resolved user_id.',
'Order user references are resolved.',
true,
),
);
checks.push(
result(
'orders_paid_without_payment',
await scalar(
`
select count(*)
from public.orders o
where o.tenant_id = $1
and o.status = 'paid'
and not exists (
select 1 from public.payments p
where p.tenant_id = o.tenant_id and p.order_id = o.id
)
`,
[tenantId],
),
'Paid orders exist without payment rows.',
'Paid orders have payment rows.',
),
);
checks.push(
result(
'entitlements_unresolved_user',
await scalar(
`
select count(*)
from public.entitlements e
left join public.platform_users u on u.id = e.user_id
where e.tenant_id = $1 and u.id is null
`,
[tenantId],
),
'Entitlements exist without a valid user.',
'Entitlements reference valid users.',
),
);
checks.push(
result(
'public_sensitive_profile_keys',
await scalar(
`
select count(*)
from public.platform_users
where raw_profile::text ~* '"(password|tokenKey|secret|sessionKey|openId|unionId|wechatSessionKey|qqOpenId|wechatOpenId|wechatUnionId)"'
`,
),
'Sensitive identity or credential keys remain in platform_users.raw_profile.',
'No sensitive identity or credential keys found in platform_users.raw_profile.',
),
);
checks.push(
result(
'student_stats_legacy_arrays',
await scalar(
`
select count(*)
from public.student_profiles
where tenant_id = $1 and (stats ? 'favorites' or stats ? 'wrongBook')
`,
[tenantId],
),
'student_profiles.stats still contains favorites/wrongBook legacy arrays.',
'student profile stats no longer contain favorites/wrongBook arrays.',
),
);
checks.push(
result(
'public_settings_sensitive_keys',
await scalar(
`
select count(*)
from public.tenant_settings
where tenant_id = $1
and public_config::text ~* '(secret|privatekey|sessionkey|accesskey|appkey|apikey|api_v3_key|notifytoken|aeskey)'
`,
[tenantId],
),
'Sensitive-looking keys remain in tenant_settings.public_config.',
'No sensitive-looking keys found in tenant public settings.',
),
);
checks.push(
result(
'public_crm_secret_leak',
await scalar(
`
select count(*)
from public.crm_config
where tenant_id = $1 and secret_ref is not null and secret_ref !~ '^app_private\\.tenant_secrets:'
`,
[tenantId],
),
'CRM config contains an unsafe secret_ref value.',
'CRM config stores only private secret references.',
),
);
checks.push(
result(
'critical_import_issues',
await scalar(
`
select count(*)
from public.pb_import_issues
where tenant_id = $1
and severity = 'critical'
and run_id = (
select id from public.pb_import_runs
where tenant_id = $1
order by started_at desc
limit 1
)
`,
[tenantId],
),
'Critical import issues exist in the latest run. Review pb_import_issues before launch.',
'No critical import issues in the latest run.',
true,
),
);
return checks;
}
async function main() {
const checks = [...(await tableCounts()), ...(await validationChecks())];
let failures = 0;
let warnings = 0;
for (const check of checks) {
const prefix = check.status === 'pass' ? 'PASS' : check.status === 'warn' ? 'WARN' : 'FAIL';
console.log(`[${prefix}] ${check.name}: ${check.message}${check.count === undefined ? '' : ` (${check.count})`}`);
if (check.status === 'fail') failures += 1;
if (check.status === 'warn') warnings += 1;
}
console.log(`Validation complete: ${failures} failures, ${warnings} warnings.`);
if (failures > 0 || (failOnWarnings && warnings > 0)) {
process.exitCode = 1;
}
}
main()
.catch(error => {
console.error(error);
process.exitCode = 1;
})
.finally(async () => {
await closeDb();
});

View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node"],
"outDir": "dist",
"rootDir": "../.."
},
"include": ["src/**/*.ts", "../../packages/**/*.ts"]
}

741
scripts/smoke-seed.js Normal file
View File

@@ -0,0 +1,741 @@
import pg from 'pg';
const { Pool } = pg;
const databaseUrl = process.env.DATABASE_URL || 'postgresql://postgres:postgres@127.0.0.1:54322/postgres';
const tenantId = process.env.TENANT_ID || '00000000-0000-0000-0000-000000000001';
const ids = {
user: '00000000-0000-0000-0000-000000000101',
tenantAdminUser: '00000000-0000-0000-0000-000000000102',
tenantOperatorUser: '00000000-0000-0000-0000-000000000103',
tenantSalesUser: '00000000-0000-0000-0000-000000000104',
tenantAgentUser: '00000000-0000-0000-0000-000000000105',
region: '00000000-0000-0000-0000-000000000301',
subject: '00000000-0000-0000-0000-000000000501',
category: '00000000-0000-0000-0000-000000000601',
questionBank: '00000000-0000-0000-0000-000000000400',
question: '00000000-0000-0000-0000-000000000401',
questionVersion: '00000000-0000-0000-0000-000000000402',
plan: '00000000-0000-0000-0000-000000000201',
order: '00000000-0000-0000-0000-000000000701',
payment: '00000000-0000-0000-0000-000000000702',
activationCode: '00000000-0000-0000-0000-000000000801',
vocabularyUnit: '00000000-0000-0000-0000-000000000811',
vocabularyWord: '00000000-0000-0000-0000-000000000812',
video: '00000000-0000-0000-0000-000000000821',
questionVideo: '00000000-0000-0000-0000-000000000822',
scorelineSchool: '00000000-0000-0000-0000-000000000831',
scorelineMajor: '00000000-0000-0000-0000-000000000832',
scorelineField: '00000000-0000-0000-0000-000000000833',
scorelineRecord: '00000000-0000-0000-0000-000000000834',
recentPractice: '00000000-0000-0000-0000-000000000841',
partnerTenant: '00000000-0000-0000-0000-000000000901',
partnerSubscription: '00000000-0000-0000-0000-000000000902',
partnerInvoice: '00000000-0000-0000-0000-000000000903',
partnerInvoiceItem: '00000000-0000-0000-0000-000000000904',
partnerInvoicePayment: '00000000-0000-0000-0000-000000000905',
};
const pool = new Pool({ connectionString: databaseUrl });
async function main() {
const client = await pool.connect();
try {
await client.query('begin');
await client.query(
`
delete from public.crm_webhook_queue
where tenant_id = $1
and (
record_id in ($2::text, $3::text, $4::text, $5::text)
or lead_id in (
select id::text
from public.referral_leads
where tenant_id = $1
and student_user_id in ($2::uuid, $3::uuid, $4::uuid, $5::uuid)
)
)
`,
[tenantId, ids.user, ids.tenantOperatorUser, ids.tenantSalesUser, ids.tenantAgentUser],
);
await client.query(
`
delete from public.referral_qrcodes
where tenant_id = $1
and user_id in ($2::uuid, $3::uuid, $4::uuid)
`,
[tenantId, ids.tenantOperatorUser, ids.tenantSalesUser, ids.tenantAgentUser],
);
await client.query(
`
delete from public.referral_tracks
where tenant_id = $1
and (
target_user_id in ($2::uuid, $3::uuid, $4::uuid, $5::uuid)
or ref_user_id in ($3::uuid, $4::uuid, $5::uuid)
)
`,
[tenantId, ids.user, ids.tenantOperatorUser, ids.tenantSalesUser, ids.tenantAgentUser],
);
await client.query(
`
delete from public.referral_leads
where tenant_id = $1
and student_user_id in ($2::uuid, $3::uuid, $4::uuid, $5::uuid)
`,
[tenantId, ids.user, ids.tenantOperatorUser, ids.tenantSalesUser, ids.tenantAgentUser],
);
await client.query(
`
delete from public.referral_team_edges
where tenant_id = $1
and (
member_user_id in ($2::uuid, $3::uuid, $4::uuid)
or leader_user_id in ($2::uuid, $3::uuid, $4::uuid)
)
`,
[tenantId, ids.tenantOperatorUser, ids.tenantSalesUser, ids.tenantAgentUser],
);
await client.query(
`
insert into public.platform_users (id, username, phone, name, primary_role, raw_profile)
values ($1, 'smoke_student', '13800000000', 'Smoke Student', 'student', '{"source":"smoke-seed"}'::jsonb)
on conflict (id)
do update set username = excluded.username,
phone = excluded.phone,
name = excluded.name,
updated_at = now()
`,
[ids.user],
);
await client.query(
`
insert into public.platform_users (id, username, phone, name, primary_role, raw_profile)
values ($1, 'smoke_tenant_admin', '13800000001', 'Smoke Tenant Admin', 'tenant_admin', '{"source":"smoke-seed"}'::jsonb)
on conflict (id)
do update set username = excluded.username,
phone = excluded.phone,
name = excluded.name,
primary_role = excluded.primary_role,
updated_at = now()
`,
[ids.tenantAdminUser],
);
await client.query(
`
insert into public.platform_users (id, username, phone, name, primary_role, raw_profile)
values
($1, 'smoke_tenant_operator', '13800000003', 'Smoke Tenant Operator', 'tenant_operator', '{"source":"smoke-seed"}'::jsonb),
($2, 'smoke_tenant_sales', '13800000004', 'Smoke Tenant Sales', 'sales', '{"source":"smoke-seed"}'::jsonb),
($3, 'smoke_tenant_agent', '13800000005', 'Smoke Tenant Agent', 'agent', '{"source":"smoke-seed"}'::jsonb)
on conflict (id)
do update set username = excluded.username,
phone = excluded.phone,
name = excluded.name,
primary_role = excluded.primary_role,
updated_at = now()
`,
[ids.tenantOperatorUser, ids.tenantSalesUser, ids.tenantAgentUser],
);
await client.query(
`
insert into public.user_identities (user_id, provider, provider_subject, phone)
values ($1, 'phone', '13800000000', '13800000000')
on conflict (provider, provider_subject)
do update set user_id = excluded.user_id,
phone = excluded.phone,
updated_at = now()
`,
[ids.user],
);
await client.query(
`
insert into public.tenant_memberships (tenant_id, user_id, role, status)
values ($1, $2, 'student', 'active')
on conflict (tenant_id, user_id, role)
do update set status = 'active', updated_at = now()
`,
[tenantId, ids.user],
);
await client.query(
`
insert into public.tenant_memberships (tenant_id, user_id, role, status, permissions)
values ($1, $2, 'tenant_admin', 'active', '{"content:*":true}'::jsonb)
on conflict (tenant_id, user_id, role)
do update set status = 'active',
permissions = excluded.permissions,
updated_at = now()
`,
[tenantId, ids.tenantAdminUser],
);
await client.query(
`
insert into public.student_profiles (tenant_id, user_id, stats, progress)
values ($1, $2, '{"totalAnswered":0,"correctCount":0,"wrongCount":0,"studyDays":1}'::jsonb, '{}'::jsonb)
on conflict (tenant_id, user_id) do nothing
`,
[tenantId, ids.user],
);
await client.query(
`
insert into public.regions (id, tenant_id, legacy_id, name, code, sort_order, is_active)
values ($1, $2, 'smoke-region', '烟测地区', 'SMOKE', 1, true)
on conflict (id)
do update set name = excluded.name,
code = excluded.code,
updated_at = now()
`,
[ids.region, tenantId],
);
await client.query(
`
insert into public.subjects (id, tenant_id, region_id, legacy_id, name, type, sort_order, is_active)
values ($1, $2, $3, 'smoke-subject', '烟测科目', 'cultural', 1, true)
on conflict (id)
do update set name = excluded.name,
region_id = excluded.region_id,
updated_at = now()
`,
[ids.subject, tenantId, ids.region],
);
await client.query(
`
insert into public.categories (id, tenant_id, subject_id, legacy_id, name, category_type, sort_order, is_active)
values ($1, $2, $3, 'smoke-category', '烟测章节', 'chapter', 1, true)
on conflict (id)
do update set name = excluded.name,
subject_id = excluded.subject_id,
updated_at = now()
`,
[ids.category, tenantId, ids.subject],
);
await client.query(
`
insert into public.question_banks (id, tenant_id, region_id, name, source_scope, status, metadata)
values ($1, $2, $3, '烟测题库', 'tenant', 'active', '{"source":"smoke-seed"}'::jsonb)
on conflict (id)
do update set name = excluded.name,
region_id = excluded.region_id,
updated_at = now()
`,
[ids.questionBank, tenantId, ids.region],
);
await client.query(
`
insert into public.questions (
id, tenant_id, question_bank_id, subject_id, category_id,
legacy_id, type, type_label, difficulty, status
)
values ($1, $2, $3, $4, $5, 'smoke-question', 'choice', '单选题', 1, 'published')
on conflict (id)
do update set question_bank_id = excluded.question_bank_id,
subject_id = excluded.subject_id,
category_id = excluded.category_id,
updated_at = now()
`,
[ids.question, tenantId, ids.questionBank, ids.subject, ids.category],
);
await client.query(
`
insert into public.question_versions (
id, tenant_id, question_id, version_no, content, options,
correct_option_index, correct_option_indices, answer_text, explanation
)
values (
$1, $2, $3, 1, '1 + 1 = ?',
'[{"label":"A","text":"1"},{"label":"B","text":"2"},{"label":"C","text":"3"}]'::jsonb,
1, '[1]'::jsonb, '2', '基础加法。'
)
on conflict (question_id, version_no)
do update set content = excluded.content,
options = excluded.options,
correct_option_index = excluded.correct_option_index,
correct_option_indices = excluded.correct_option_indices,
answer_text = excluded.answer_text,
explanation = excluded.explanation
`,
[ids.questionVersion, tenantId, ids.question],
);
await client.query(
`
update public.questions
set current_version_id = $3, has_video_explanation = true, updated_at = now()
where tenant_id = $1 and id = $2
`,
[tenantId, ids.question, ids.questionVersion],
);
await client.query(
`
insert into public.video_explanations (
id, tenant_id, legacy_id, title, description, video_url, thumbnail_url,
duration_seconds, knowledge_tags, is_general, subject_id, difficulty,
sort_order, is_active
)
values (
$1, $2, 'smoke-video', '烟测题目视频讲解', '用于验证题目视频 API',
'https://example.test/videos/smoke.mp4', 'https://example.test/videos/smoke.jpg',
180, '["基础加法","烟测"]'::jsonb, true, $3, 1, 1, true
)
on conflict (id)
do update set title = excluded.title,
video_url = excluded.video_url,
subject_id = excluded.subject_id,
is_active = true,
updated_at = now()
`,
[ids.video, tenantId, ids.subject],
);
await client.query(
`
insert into public.question_videos (
id, tenant_id, question_id, video_id, legacy_id, video_type, sort_order
)
values ($1, $2, $3, $4, 'smoke-question-video', 'specific', 1)
on conflict (id)
do update set question_id = excluded.question_id,
video_id = excluded.video_id,
updated_at = now()
`,
[ids.questionVideo, tenantId, ids.question, ids.video],
);
await client.query(
`
insert into public.svip_plans (
id, tenant_id, region_id, legacy_id, name, price_cents, original_price_cents,
days, description, per_day_label, badge, recommended, sort_order, is_active
)
values ($1, $2, $3, 'smoke-plan', '烟测月卡', 990, 1990, 30, '本地 smoke 套餐', '0.33/天', 'SMOKE', true, 1, true)
on conflict (id)
do update set name = excluded.name,
price_cents = excluded.price_cents,
days = excluded.days,
region_id = excluded.region_id,
updated_at = now()
`,
[ids.plan, tenantId, ids.region],
);
await client.query(
`
insert into public.orders (
id, tenant_id, user_id, legacy_id, order_no, status, product_type, product_name,
amount_cents, pay_method, pay_provider, plan_id, days, region_id, raw_payload
)
values ($1, $2, $3, 'smoke-order', 'SMOKE-ORDER-20260621', 'pending', 'svip', '烟测月卡', 990, 'manual', 'manual', $4, 30, $5, '{"source":"smoke-seed"}'::jsonb)
on conflict (id)
do update set status = excluded.status,
amount_cents = excluded.amount_cents,
updated_at = now()
`,
[ids.order, tenantId, ids.user, ids.plan, ids.region],
);
await client.query(
`
insert into public.payments (
id, tenant_id, order_id, provider, method, status, amount_cents, raw_payload
)
values ($1, $2, $3, 'manual', 'manual', 'pending', 990, '{"source":"smoke-seed"}'::jsonb)
on conflict (id)
do update set status = excluded.status,
amount_cents = excluded.amount_cents,
updated_at = now()
`,
[ids.payment, tenantId, ids.order],
);
await client.query(
`
insert into public.activation_codes (
id, tenant_id, legacy_id, code, days, is_used, sale_type, unit_price_cents, used_region_id, remark
)
values ($1, $2, 'smoke-code', 'SMOKE20260621', 30, false, 'smoke', 0, $3, '本地 smoke 激活码')
on conflict (id)
do update set is_used = false,
used_by = null,
used_at = null,
used_region_id = excluded.used_region_id,
updated_at = now()
`,
[ids.activationCode, tenantId, ids.region],
);
await client.query(
`
insert into public.vocabulary_units (
id, tenant_id, region_id, legacy_id, name, description, word_count, sort_order, is_active
)
values ($1, $2, $3, 'smoke-vocab-unit', '烟测单词单元', '本地 smoke 背单词单元', 1, 1, true)
on conflict (id)
do update set name = excluded.name,
region_id = excluded.region_id,
word_count = excluded.word_count,
updated_at = now()
`,
[ids.vocabularyUnit, tenantId, ids.region],
);
await client.query(
`
insert into public.vocabulary_words (
id, tenant_id, unit_id, legacy_id, word, phonetic, meaning,
example, example_translation, difficulty, tags, sort_order, is_active
)
values (
$1, $2, $3, 'smoke-word', 'abandon', '/əˈbændən/', '放弃',
'Do not abandon your plan.', '不要放弃你的计划。', 1,
'["smoke","basic"]'::jsonb, 1, true
)
on conflict (id)
do update set word = excluded.word,
unit_id = excluded.unit_id,
meaning = excluded.meaning,
updated_at = now()
`,
[ids.vocabularyWord, tenantId, ids.vocabularyUnit],
);
await client.query(
`
insert into public.user_word_progress (
tenant_id, user_id, word_id, status, correct_count, wrong_count,
last_review_date, next_review_date
)
values ($1, $2, $3, 'learning', 1, 0, now(), now() + interval '1 day')
on conflict (tenant_id, user_id, word_id)
do update set status = excluded.status,
correct_count = excluded.correct_count,
wrong_count = excluded.wrong_count,
last_review_date = excluded.last_review_date,
next_review_date = excluded.next_review_date,
updated_at = now()
`,
[tenantId, ids.user, ids.vocabularyWord],
);
await client.query(
`
insert into public.user_word_favorites (tenant_id, user_id, word_id, note, favorited_at)
values ($1, $2, $3, null, now())
on conflict (tenant_id, user_id, word_id)
do update set favorited_at = coalesce(public.user_word_favorites.favorited_at, now()),
updated_at = now()
`,
[tenantId, ids.user, ids.vocabularyWord],
);
await client.query(
`
insert into public.scoreline_schools (
id, tenant_id, region_id, legacy_id, name, short_name, type, is_hot, sort_order
)
values ($1, $2, $3, 'smoke-score-school', '烟测学院', '烟测学院', '普通', true, 1)
on conflict (id)
do update set name = excluded.name,
region_id = excluded.region_id,
updated_at = now()
`,
[ids.scorelineSchool, tenantId, ids.region],
);
await client.query(
`
insert into public.scoreline_majors (
id, tenant_id, region_id, school_id, legacy_id, name, sort_order
)
values ($1, $2, $3, $4, 'smoke-score-major', '计算机科学与技术', 1)
on conflict (id)
do update set name = excluded.name,
school_id = excluded.school_id,
updated_at = now()
`,
[ids.scorelineMajor, tenantId, ids.region, ids.scorelineSchool],
);
await client.query(
`
insert into public.scoreline_fields (
id, tenant_id, region_id, legacy_id, field_key, field_name, field_type,
unit, is_filter, is_required, is_visible, is_trend, sort_order
)
values ($1, $2, $3, 'smoke-score-field', 'minScore', '最低录取分', 'number', '分', true, false, true, true, 1)
on conflict (id)
do update set field_name = excluded.field_name,
is_trend = excluded.is_trend,
updated_at = now()
`,
[ids.scorelineField, tenantId, ids.region],
);
await client.query(
`
insert into public.scoreline_records (
id, tenant_id, region_id, school_id, major_id, legacy_id,
year, school_name, major_name, field_values
)
values (
$1, $2, $3, $4, $5, 'smoke-score-record',
2026, '烟测学院', '计算机科学与技术',
'{"minScore": 188, "enrollmentCount": 80}'::jsonb
)
on conflict (id)
do update set year = excluded.year,
field_values = excluded.field_values,
updated_at = now()
`,
[ids.scorelineRecord, tenantId, ids.region, ids.scorelineSchool, ids.scorelineMajor],
);
await client.query(
`
insert into public.recent_practices (
id, tenant_id, user_id, legacy_id, practice_type, target_legacy_id,
target_name, progress, color, last_access_at, last_practice_at, metadata
)
values (
$1, $2, $3, 'smoke-recent-practice', 'question',
'smoke-category', '烟测章节', 20, '#2563eb', now(), now(),
'{"source":"smoke-seed"}'::jsonb
)
on conflict (id)
do update set progress = excluded.progress,
last_access_at = excluded.last_access_at,
last_practice_at = excluded.last_practice_at,
updated_at = now()
`,
[ids.recentPractice, tenantId, ids.user],
);
await client.query(
`
insert into public.tenants (id, slug, name, legal_name, status, mode, billing_status, metadata)
values (
$1,
'smoke-partner',
'烟测合作商',
'烟测合作商有限公司',
'active',
'saas',
'active',
'{"source":"smoke-seed","contact":"partner"}'::jsonb
)
on conflict (id)
do update set name = excluded.name,
legal_name = excluded.legal_name,
status = excluded.status,
billing_status = excluded.billing_status,
updated_at = now()
`,
[ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_branding (tenant_id, brand_name, short_name, slogan)
values ($1, '烟测合作商题库', '合作商题库', '本地 SaaS 烟测租户')
on conflict (tenant_id)
do update set brand_name = excluded.brand_name,
short_name = excluded.short_name,
slogan = excluded.slogan,
updated_at = now()
`,
[ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_settings (tenant_id, feature_flags, admin_feature_flags, public_config)
values (
$1,
'{"enableStore":true,"enableVocabulary":true}'::jsonb,
'{"enableQuestionCRUD":true,"enableMarketing":true}'::jsonb,
'{"appUrl":"http://smoke-partner.localhost"}'::jsonb
)
on conflict (tenant_id)
do update set feature_flags = excluded.feature_flags,
admin_feature_flags = excluded.admin_feature_flags,
public_config = excluded.public_config,
updated_at = now()
`,
[ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_domains (tenant_id, host, domain_type, status, is_primary)
values ($1, 'smoke-partner.localhost', 'custom', 'active', true)
on conflict (host)
do update set tenant_id = excluded.tenant_id,
status = excluded.status,
is_primary = excluded.is_primary,
updated_at = now()
`,
[ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_billing_profiles (
tenant_id, billing_name, tax_id, contact_name, contact_phone,
contact_email, invoice_title, invoice_type
)
values (
$1,
'烟测合作商有限公司',
'91120000SMOKE',
'Smoke Partner',
'13900009999',
'partner@example.test',
'烟测合作商有限公司',
'normal_vat'
)
on conflict (tenant_id)
do update set billing_name = excluded.billing_name,
tax_id = excluded.tax_id,
contact_name = excluded.contact_name,
contact_phone = excluded.contact_phone,
contact_email = excluded.contact_email,
invoice_title = excluded.invoice_title,
invoice_type = excluded.invoice_type,
updated_at = now()
`,
[ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_subscriptions (
id, tenant_id, plan_code, status, starts_at, expires_at,
billing_cycle, amount_cents, metadata
)
values (
$1, $2, 'starter_yearly', 'active',
'2026-06-21T00:00:00Z', '2027-06-21T00:00:00Z',
'yearly', 980000, '{"source":"smoke-seed"}'::jsonb
)
on conflict (id)
do update set status = excluded.status,
expires_at = excluded.expires_at,
amount_cents = excluded.amount_cents,
updated_at = now()
`,
[ids.partnerSubscription, ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_invoices (
id, tenant_id, invoice_no, invoice_type, status, currency,
subtotal_cents, discount_cents, tax_cents, total_cents,
paid_cents, balance_cents, billing_period_start, billing_period_end,
due_date, issued_at, note, metadata
)
values (
$1, $2, 'BILL-SMOKE-20260621', 'subscription', 'paid', 'CNY',
980000, 0, 0, 980000, 980000, 0,
'2026-06-21', '2027-06-21', '2026-06-30',
'2026-06-21T00:00:00Z', '烟测合作商年费', '{"source":"smoke-seed"}'::jsonb
)
on conflict (id)
do update set status = excluded.status,
paid_cents = excluded.paid_cents,
balance_cents = excluded.balance_cents,
updated_at = now()
`,
[ids.partnerInvoice, ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_invoice_items (
id, tenant_id, invoice_id, item_type, description,
quantity, unit_amount_cents, amount_cents, metadata
)
values (
$1, $2, $3, 'subscription', '合作商基础版 starter_yearly',
1, 980000, 980000, '{"planCode":"starter_yearly"}'::jsonb
)
on conflict (id) do nothing
`,
[ids.partnerInvoiceItem, ids.partnerTenant, ids.partnerInvoice],
);
await client.query(
`
insert into public.tenant_invoice_payments (
id, tenant_id, invoice_id, payment_no, provider, method, status,
amount_cents, paid_at, provider_trade_no, raw_payload
)
values (
$1, $2, $3, 'PAY-SMOKE-20260621', 'manual', 'bank_transfer',
'paid', 980000, '2026-06-21T00:00:00Z', 'SMOKE-TRANSFER',
'{"source":"smoke-seed"}'::jsonb
)
on conflict (id)
do update set status = excluded.status,
amount_cents = excluded.amount_cents,
updated_at = now()
`,
[ids.partnerInvoicePayment, ids.partnerTenant, ids.partnerInvoice],
);
await client.query(
`
delete from public.tenant_usage_records
where tenant_id = $1
and period_start = '2026-06-01'
and period_end = '2026-06-30'
and metadata->>'source' = 'smoke-seed'
`,
[ids.partnerTenant],
);
await client.query(
`
insert into public.tenant_usage_records (tenant_id, metric_key, metric_value, period_start, period_end, metadata)
values
($1, 'students', 120, '2026-06-01', '2026-06-30', '{"source":"smoke-seed"}'::jsonb),
($1, 'questions', 860, '2026-06-01', '2026-06-30', '{"source":"smoke-seed"}'::jsonb),
($1, 'storage_gb', 3.5, '2026-06-01', '2026-06-30', '{"source":"smoke-seed"}'::jsonb)
`,
[ids.partnerTenant],
);
await client.query('commit');
console.log(`Smoke seed complete for tenant ${tenantId}`);
} catch (error) {
await client.query('rollback');
throw error;
} finally {
client.release();
await pool.end();
}
}
main().catch(error => {
console.error(error);
process.exitCode = 1;
});