提交开发分支未提交代码并修正配置

This commit is contained in:
2026-06-23 15:33:06 +08:00
parent a53b27ef20
commit 0fd96d150e
141 changed files with 3624 additions and 6048 deletions
@@ -0,0 +1,40 @@
# FingertipDesigner 配置整理说明
## 命名空间
- `YumiNail-Dev`:开发环境配置。
- `FingertipDesigner`:正式环境配置。
## 配置文件
- `core.yaml`:Core 服务独有配置,包括端口、业务缓存、慢请求、对象存储业务规则和 MessageHub 客户端参数。
- `gateway.yaml`:Gateway 服务独有配置,包括端口、路由、鉴权白名单和网关慢请求参数。
- `infra.yaml`:公共基础设施配置,包括数据库、Redis、MyBatis-Plus 和 RabbitMQ。
- `secret.yaml`:敏感配置,包括数据库密码、Redis 密码、RabbitMQ 密码、JWT、微信小程序和对象存储密钥。
- `logging.yaml`:公共日志配置。
## 本地启动配置
`FD-Core` 和 `FD-Gateway` 默认读取开发环境命名空间:
```powershell
$env:NACOS_SERVER_ADDR='192.168.5.103:8848'
$env:NACOS_NAMESPACE='YumiNail-Dev'
$env:NACOS_USERNAME='xiaowang'
$env:NACOS_PASSWORD='122503wcy....'
```
正式环境部署时设置:
```powershell
$env:NACOS_SERVER_ADDR='192.168.5.101:8848,192.168.5.102:8848,192.168.10.145:8848'
$env:NACOS_NAMESPACE='FingertipDesigner'
```
如 Nacos 地址、账号、密码发生变化,通过以下环境变量覆盖:
```powershell
$env:NACOS_SERVER_ADDR='192.168.5.103:8848'
$env:NACOS_USERNAME='nacos'
$env:NACOS_PASSWORD='122503wcy....'
```
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env node
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import { TextDecoder } from 'node:util'
const repoRoot = process.cwd()
const defaultTargets = [
'docx',
'scripts/sql',
'YumiNail-Core/src/main/resources/files/YumiNail.sql'
]
const includedExtensions = new Set(['.md', '.sql', '.txt'])
const excludedSegments = new Set(['.git', 'node_modules', 'target', 'dist'])
const utf8Decoder = new TextDecoder('utf-8', { fatal: true })
const latinMojibakePattern = /(?:Ã.|Â.|â[€\u0080-\u009F]?)/u
const gbkMojibakeTokens = [
'鏂', '鏄', '鐨', '璇', '鍙', '鎴', '閫', '绛', '锛', '銆',
'乂', '浠', '鍗', '灏', '涓', '闂', '妯', '瀹', '搴', '鐢',
'鍓', '鍚', '骞', '绾', '濡', '浜', '娴', '槑', '绋', '湪'
]
async function collectFiles(targets) {
const files = []
for (const target of targets) {
const absoluteTarget = path.resolve(repoRoot, target)
const stat = await fs.stat(absoluteTarget).catch(() => null)
if (!stat) {
continue
}
if (stat.isDirectory()) {
await walkDirectory(absoluteTarget, files)
} else if (shouldScanFile(absoluteTarget)) {
files.push(absoluteTarget)
}
}
return files
}
async function walkDirectory(directory, files) {
const entries = await fs.readdir(directory, { withFileTypes: true })
for (const entry of entries) {
const absolutePath = path.join(directory, entry.name)
const relativePath = path.relative(repoRoot, absolutePath).replaceAll('\\', '/')
if (isExcluded(relativePath)) {
continue
}
if (entry.isDirectory()) {
await walkDirectory(absolutePath, files)
} else if (entry.isFile() && shouldScanFile(absolutePath)) {
files.push(absolutePath)
}
}
}
function isExcluded(relativePath) {
return relativePath.split('/').some(segment => excludedSegments.has(segment))
}
function shouldScanFile(filePath) {
return includedExtensions.has(path.extname(filePath).toLowerCase())
}
async function checkFile(filePath) {
const bytes = await fs.readFile(filePath)
let text
try {
text = utf8Decoder.decode(bytes)
} catch (error) {
return [{
filePath,
line: 1,
reason: `not valid UTF-8: ${error.message}`
}]
}
const issues = []
const lines = text.split(/\r?\n/)
lines.forEach((lineText, index) => {
const reason = detectIssue(lineText)
if (reason) {
issues.push({
filePath,
line: index + 1,
reason
})
}
})
return issues
}
function detectIssue(lineText) {
if (lineText.includes('\uFFFD')) {
return 'contains replacement character'
}
if (latinMojibakePattern.test(lineText)) {
return 'contains Latin-1 mojibake fragment'
}
const gbkTokenHits = gbkMojibakeTokens.reduce(
(count, token) => count + countOccurrences(lineText, token),
0
)
if (gbkTokenHits >= 2) {
return 'contains likely GBK/UTF-8 mojibake fragments'
}
return null
}
function countOccurrences(text, token) {
let count = 0
let index = text.indexOf(token)
while (index !== -1) {
count += 1
index = text.indexOf(token, index + token.length)
}
return count
}
const targets = process.argv.slice(2)
const files = await collectFiles(targets.length > 0 ? targets : defaultTargets)
const issues = []
for (const filePath of files) {
issues.push(...await checkFile(filePath))
}
if (issues.length > 0) {
for (const issue of issues) {
const relativePath = path.relative(repoRoot, issue.filePath).replaceAll('\\', '/')
console.error(`${relativePath}:${issue.line}: ${issue.reason}`)
}
console.error(`Encoding check failed: ${issues.length} issue(s) in ${files.length} file(s).`)
process.exit(1)
}
console.log(`Encoding check passed: ${files.length} file(s) are valid UTF-8 without common mojibake.`)
-444
View File
@@ -1,444 +0,0 @@
#!/usr/bin/env node
/**
* Purpose: scan YumiNail business source files and report declaration-level
* comment coverage for classes, methods, fields, top-level constants, and mini
* program Page data/method entries.
* Usage: run `rtk node scripts/comment-coverage.mjs` from the repository root;
* pass `--json` to emit machine-readable output or `--fix` to insert comments
* for declarations that are safe to annotate mechanically.
*/
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
/**
* Purpose: absolute repository root used to resolve all scan targets.
* Usage: keep this derived from the current working directory so the script can
* be launched through `rtk node scripts/comment-coverage.mjs`.
*/
const repoRoot = process.cwd()
/**
* Purpose: source roots that contain hand-written business code.
* Usage: add new first-party source roots here when they should be part of the
* declaration coverage budget.
*/
const SOURCE_ROOTS = [
'YumiNail-Core/src/main/java',
'YumiNail-Frontend/src',
'WeChatProgram',
'YumiNail-Admin-Program'
]
/**
* Purpose: directory or file fragments that are generated, configuration-only,
* binary, or otherwise unsuitable for declaration comment coverage.
* Usage: keep exclusions narrow so real business code stays covered.
*/
const EXCLUDED_SEGMENTS = [
'node_modules',
'target',
'dist',
'.git',
'.idea',
'logs',
'assets/',
'assets\\',
'public/assets',
'public\\assets',
'components.d.ts',
'auto-import.d.ts',
'package-lock.json',
'project.config.json',
'project.private.config.json',
'sitemap.json'
]
/**
* Purpose: file extensions whose declarations can be statically detected by
* this lightweight scanner.
* Usage: update when introducing another hand-written source language.
*/
const INCLUDED_EXTENSIONS = new Set(['.java', '.ts', '.vue', '.js', '.wxml', '.wxss'])
/**
* Purpose: tiny names that represent framework keywords rather than business
* declarations.
* Usage: ignore these when scanning object methods in JavaScript-like files.
*/
const JS_KEYWORD_NAMES = new Set([
'if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'else', 'do'
])
/**
* Purpose: read command line output mode.
* Usage: `--json` prints the same coverage data without prose formatting.
*/
const outputJson = process.argv.includes('--json')
/**
* Purpose: read command line mutation mode.
* Usage: `--fix` inserts declaration comments, then the script can be run again
* without flags to verify the final percentage.
*/
const fixMode = process.argv.includes('--fix')
/**
* Purpose: determine whether a path should be skipped entirely.
* Usage: call before recursing into directories or scanning files.
*/
function isExcluded(relativePath) {
const normalized = relativePath.replaceAll('\\', '/')
return EXCLUDED_SEGMENTS.some(segment => normalized.includes(segment.replaceAll('\\', '/')))
}
/**
* Purpose: detect whether a file extension is part of the coverage scan.
* Usage: call for each discovered file before reading its content.
*/
function hasIncludedExtension(filePath) {
return INCLUDED_EXTENSIONS.has(path.extname(filePath))
}
/**
* Purpose: recursively list all source files under a directory.
* Usage: returns repository-relative paths using forward slashes for stable
* reports across Windows and Unix shells.
*/
async function listSourceFiles(relativeDir) {
const absoluteDir = path.join(repoRoot, relativeDir)
const results = []
async function walk(currentDir) {
const entries = await fs.readdir(currentDir, { withFileTypes: true }).catch(() => [])
for (const entry of entries) {
const absolutePath = path.join(currentDir, entry.name)
const relativePath = path.relative(repoRoot, absolutePath).replaceAll('\\', '/')
if (isExcluded(relativePath)) {
continue
}
if (entry.isDirectory()) {
await walk(absolutePath)
} else if (entry.isFile() && hasIncludedExtension(relativePath)) {
results.push(relativePath)
}
}
}
await walk(absoluteDir)
return results
}
/**
* Purpose: decide whether a declaration has a nearby leading comment.
* Usage: pass the full source lines and the zero-based declaration line index.
*/
function hasLeadingComment(lines, lineIndex) {
for (let cursor = lineIndex - 1; cursor >= 0; cursor -= 1) {
const text = lines[cursor].trim()
if (!text) {
continue
}
if (text.startsWith('@')) {
continue
}
if (text.endsWith('*/') || text.startsWith('*') || text.startsWith('//') || text.includes('<!--')) {
return true
}
return false
}
return false
}
/**
* Purpose: push a detected declaration into the coverage list.
* Usage: callers provide a stable type/name pair and the source line number.
*/
function addDeclaration(declarations, lines, lineIndex, type, name) {
if (!name || JS_KEYWORD_NAMES.has(name)) {
return
}
declarations.push({
type,
name,
line: lineIndex + 1,
commented: hasLeadingComment(lines, lineIndex)
})
}
/**
* Purpose: detect Java declarations in controllers, services, DTOs, entities,
* mappers, support classes, and tests when they live under source roots.
* Usage: returns declaration records with `commented` already computed.
*/
function scanJava(content) {
const lines = content.split(/\r?\n/)
const declarations = []
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('//') || text.startsWith('*') || text.startsWith('@')) {
return
}
const classMatch = text.match(/\b(public|protected|private)?\s*(abstract\s+|final\s+)?(class|interface|enum|record)\s+([A-Za-z_$][\w$]*)/)
if (classMatch) {
addDeclaration(declarations, lines, index, classMatch[3], classMatch[4])
return
}
const methodMatch = text.match(/\b(public|protected|private)\s+[\w<>\[\], ?]+\s+([A-Za-z_$][\w$]*)\s*\([^;]*\)\s*(throws\s+[\w, ]+)?\{?$/)
if (methodMatch && !text.includes(' class ')) {
addDeclaration(declarations, lines, index, 'method', methodMatch[2])
return
}
const fieldMatch = text.match(/\b(private|protected|public)\s+(static\s+)?(final\s+)?[\w<>\[\], ?]+\s+([A-Za-z_$][\w$]*)\s*(=|;)/)
if (fieldMatch && !text.includes('(')) {
addDeclaration(declarations, lines, index, 'field', fieldMatch[4])
}
})
return declarations
}
/**
* Purpose: detect TypeScript, Vue script, and mini-program JavaScript
* declarations including interfaces, exported functions, constants, Page data,
* and object methods.
* Usage: works best on source already stripped of template noise.
*/
function scanScriptLike(content) {
const lines = content.split(/\r?\n/)
const declarations = []
let insidePageData = false
let dataDepth = 0
let braceDepth = 0
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('//') || text.startsWith('*')) {
return
}
const typeMatch = text.match(/\b(export\s+)?(interface|type|class|enum)\s+([A-Za-z_$][\w$]*)/)
if (typeMatch && braceDepth === 0) {
addDeclaration(declarations, lines, index, typeMatch[2], typeMatch[3])
} else {
const functionMatch = text.match(/\b(export\s+)?(async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/)
if (functionMatch && braceDepth === 0) {
addDeclaration(declarations, lines, index, 'function', functionMatch[3])
} else {
const constMatch = text.match(/\b(export\s+)?(const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/)
if (constMatch && braceDepth === 0) {
addDeclaration(declarations, lines, index, constMatch[2], constMatch[3])
} else {
const methodMatch = text.match(/^([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/)
if (methodMatch && braceDepth <= 1) {
addDeclaration(declarations, lines, index, 'method', methodMatch[1])
} else if (/^data\s*:\s*\{/.test(text) && braceDepth <= 1) {
addDeclaration(declarations, lines, index, 'page-data', 'data')
insidePageData = true
dataDepth = 1
} else if (insidePageData) {
const dataFieldMatch = text.match(/^([A-Za-z_$][\w$]*)\s*:/)
if (dataFieldMatch) {
addDeclaration(declarations, lines, index, 'page-data-field', dataFieldMatch[1])
}
}
}
}
}
const openingBraces = (text.match(/\{/g) || []).length
const closingBraces = (text.match(/\}/g) || []).length
if (insidePageData) {
dataDepth += openingBraces
dataDepth -= closingBraces
if (dataDepth <= 0) {
insidePageData = false
}
}
braceDepth += openingBraces
braceDepth -= closingBraces
if (braceDepth < 0) {
braceDepth = 0
}
})
return declarations
}
/**
* Purpose: detect WXML class/id/event-bearing nodes as UI declarations.
* Usage: gives template files a lightweight coverage signal without trying to
* parse the full mini-program XML dialect.
*/
function scanMarkup(content) {
const lines = content.split(/\r?\n/)
const declarations = []
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('<!--')) {
return
}
const eventMatch = text.match(/\b(bindtap|catchtap|bindsubmit|bindchange|bindinput)="([^"]+)"/)
if (eventMatch) {
addDeclaration(declarations, lines, index, 'wxml-event', eventMatch[2])
return
}
const classMatch = text.match(/\bclass="([^"]+)"/)
if (classMatch) {
addDeclaration(declarations, lines, index, 'wxml-block', classMatch[1].split(/\s+/)[0])
}
})
return declarations
}
/**
* Purpose: detect named CSS/WXSS selectors as style declarations.
* Usage: styles count as covered when a nearby comment explains the block.
*/
function scanStyle(content) {
const lines = content.split(/\r?\n/)
const declarations = []
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('/*') || text.startsWith('*') || text.startsWith('@')) {
return
}
const selectorMatch = text.match(/^([.#][A-Za-z0-9_-]+)[\s,{:]/)
if (selectorMatch) {
addDeclaration(declarations, lines, index, 'style-selector', selectorMatch[1])
}
})
return declarations
}
/**
* Purpose: route a file to the proper declaration scanner.
* Usage: called once per included source file.
*/
function scanFile(relativePath, content) {
const ext = path.extname(relativePath)
if (ext === '.java') {
return scanJava(content)
}
if (ext === '.wxml' || ext === '.wxss') {
return []
}
return scanScriptLike(content)
}
/**
* Purpose: build a two-sentence declaration comment that explains intent and
* call/read/write usage without depending on source-specific business wording.
* Usage: the fixer inserts these lines immediately before a missing declaration.
*/
function createCommentLines(relativePath, declaration, indent) {
const moduleName = path.basename(relativePath)
const readableName = declaration.name
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/[_-]+/g, ' ')
.toLowerCase()
const subject = readableName || declaration.name
const ext = path.extname(relativePath)
if (ext === '.java') {
return [
`${indent}/**`,
`${indent} * Purpose: ${declaration.name} supports ${moduleName} by holding or executing the ${subject} business role.`,
`${indent} * Usage: reference this ${declaration.type} from the owning layer and pass validated inputs before reading or updating related state.`,
`${indent} */`
]
}
return [
`${indent}/**`,
`${indent} * Purpose: ${declaration.name} supports ${moduleName} by holding or executing the ${subject} page or API role.`,
`${indent} * Usage: import, call, read, or update this ${declaration.type} from the owning page/module while preserving the surrounding loading and permission flow.`,
`${indent} */`
]
}
/**
* Purpose: add missing comments to a source file using the same declaration
* coordinates that the coverage scanner reports.
* Usage: only called in `--fix` mode after reading a file from an included root.
*/
async function applyFixes(relativePath, declarations) {
const missing = declarations.filter(item => !item.commented)
if (!missing.length) {
return 0
}
const absolutePath = path.join(repoRoot, relativePath)
const lines = (await fs.readFile(absolutePath, 'utf8')).split(/\r?\n/)
for (const declaration of [...missing].sort((left, right) => right.line - left.line)) {
const lineIndex = declaration.line - 1
const indent = (lines[lineIndex].match(/^\s*/) || [''])[0]
lines.splice(lineIndex, 0, ...createCommentLines(relativePath, declaration, indent))
}
await fs.writeFile(absolutePath, lines.join('\n'), 'utf8')
return missing.length
}
/**
* Purpose: aggregate declarations into coverage totals and missing samples.
* Usage: main entry point for CLI execution.
*/
async function main() {
const files = (await Promise.all(SOURCE_ROOTS.map(listSourceFiles))).flat().sort()
const fileReports = []
let fixed = 0
for (const file of files) {
const content = await fs.readFile(path.join(repoRoot, file), 'utf8')
const declarations = scanFile(file, content)
if (fixMode) {
fixed += await applyFixes(file, declarations)
}
if (!declarations.length) {
continue
}
const covered = declarations.filter(item => item.commented).length
fileReports.push({
file,
total: declarations.length,
covered,
missing: declarations.filter(item => !item.commented)
})
}
const total = fileReports.reduce((sum, file) => sum + file.total, 0)
const covered = fileReports.reduce((sum, file) => sum + file.covered, 0)
const coverage = total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))
const report = {
coverage,
total,
covered,
missing: total - covered,
files: fileReports,
missingTop: fileReports
.filter(file => file.missing.length)
.sort((left, right) => right.missing.length - left.missing.length)
.slice(0, 30)
.map(file => ({
file: file.file,
missing: file.missing.slice(0, 20)
}))
}
if (fixMode) {
console.log(`Inserted comments for ${fixed} declarations. Re-run without --fix to verify coverage.`)
return
}
if (outputJson) {
console.log(JSON.stringify(report, null, 2))
return
}
console.log(`Comment coverage: ${coverage}% (${covered}/${total})`)
console.log(`Missing declarations: ${report.missing}`)
for (const file of report.missingTop) {
console.log(`\n${file.file}`)
for (const item of file.missing) {
console.log(` line ${item.line}: ${item.type} ${item.name}`)
}
}
if (report.coverage < 99) {
process.exitCode = 1
}
}
await main()
-283
View File
@@ -1,283 +0,0 @@
#!/usr/bin/env python3
"""
Promote manually uploaded YumiNail jars on production hosts.
Recommended manual upload location:
/opt/app/upload/YumiNail-Core.jar
/opt/app/upload/YumiNail-Gateway.jar
The script keeps the server-side convention:
current: /opt/app/<App>.jar
backup: /opt/app/backups/<App>.jar.bak-YYYYMMDD-HHMMSS
release: /opt/app/releases/<App>-YYYYMMDD-HHMMSS.jar
"""
import argparse
import glob
import re
import sys
import time
import zipfile
import xml.etree.ElementTree as ET
import paramiko
NS = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
SERVICES = {
"core": {
"app": "YumiNail-Core",
"pattern": re.compile(r"^YumiNail-Core0[1-3]$", re.I),
},
"gateway": {
"app": "YumiNail-Gateway",
"pattern": re.compile(r"^YumiNail-Gateway0[1-3]$", re.I),
},
}
def cell_index(ref):
match = re.match(r"[A-Z]+", ref or "A1")
if not match:
return 0
value = 0
for letter in match.group(0):
value = value * 26 + ord(letter) - ord("A") + 1
return value - 1
def default_workbook():
candidates = glob.glob("Y:/code/*.xlsx")
if not candidates:
candidates = glob.glob("E:/code/xiaowang/*.xlsx")
if not candidates:
raise RuntimeError("No server workbook found. Pass --server-info explicitly.")
return sorted(candidates)[0]
def workbook_rows(path):
with zipfile.ZipFile(path) as archive:
shared = []
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
for item in root.findall("m:si", NS):
shared.append("".join(node.text or "" for node in item.findall(".//m:t", NS)))
workbook = ET.fromstring(archive.read("xl/workbook.xml"))
relationships = ET.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
relmap = {rel.attrib["Id"]: rel.attrib["Target"] for rel in relationships}
sheet = workbook.find(
"{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheets/"
"{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet"
)
sheet_id = sheet.attrib["{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"]
sheet_root = ET.fromstring(archive.read("xl/" + relmap[sheet_id].lstrip("/")))
for row in sheet_root.findall(".//m:row", NS):
values = []
for cell in row.findall("m:c", NS):
index = cell_index(cell.attrib.get("r", "A1"))
while len(values) <= index:
values.append("")
node = cell.find("m:v", NS)
value = "" if node is None or node.text is None else node.text
if cell.attrib.get("t") == "s" and value:
value = shared[int(value)]
values[index] = value
values += [""] * 8
if values[0].strip():
try:
port = int(values[2] or 22)
except ValueError:
continue
yield {
"name": values[0].strip(),
"host": values[1].strip(),
"port": port,
"user": values[3].strip(),
"password": values[4],
}
def select_targets(rows, service, target_names):
wanted = set()
if target_names:
wanted = {item.strip().lower() for item in ",".join(target_names).split(",") if item.strip()}
selected = []
pattern = SERVICES[service]["pattern"]
for row in rows:
name = row["name"]
if wanted:
if name.lower() in wanted:
selected.append(row)
elif pattern.match(name):
selected.append(row)
if not selected:
raise RuntimeError("No matching targets found.")
return selected
def shell_quote(value):
return "'" + str(value).replace("'", "'\"'\"'") + "'"
def open_ssh(server):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
hostname=server["host"],
port=server["port"],
username=server["user"],
password=server["password"],
timeout=20,
banner_timeout=20,
auth_timeout=20,
)
return client
def run_remote(server, command, dry_run=False):
print(f"==> {server['name']} ({server['host']})")
if dry_run:
print(command)
return 0
client = open_ssh(server)
try:
_, stdout, stderr = client.exec_command(command, timeout=240)
out = stdout.read().decode(errors="replace")
err = stderr.read().decode(errors="replace")
code = stdout.channel.recv_exit_status()
if out:
print(out, end="" if out.endswith("\n") else "\n")
if err:
print(err, end="" if err.endswith("\n") else "\n", file=sys.stderr)
if code != 0:
print(f"remote command failed with exit code {code}", file=sys.stderr)
return code
finally:
client.close()
def promote_command(app, remote_app_dir, upload_dir, uploaded_jar_name, timestamp, restart):
app_q = shell_quote(app)
app_dir_q = shell_quote(remote_app_dir)
upload_dir_q = shell_quote(upload_dir)
upload_name_q = shell_quote(uploaded_jar_name)
ts_q = shell_quote(timestamp)
restart_part = ""
if restart:
restart_part = """
echo "-- restart --"
cd "$APP_DIR"
NO_TAIL=1 ./start.sh restart
"""
return f"""set -e
APP={app_q}
APP_DIR={app_dir_q}
UPLOAD_DIR={upload_dir_q}
UPLOAD_NAME={upload_name_q}
TS={ts_q}
CURRENT="$APP_DIR/$APP.jar"
UPLOADED="$UPLOAD_DIR/$UPLOAD_NAME"
BACKUP="$APP_DIR/backups/$APP.jar.bak-$TS"
RELEASE="$APP_DIR/releases/$APP-$TS.jar"
mkdir -p "$APP_DIR/backups" "$APP_DIR/releases" "$UPLOAD_DIR"
if [ ! -f "$UPLOADED" ]; then
echo "Uploaded jar not found: $UPLOADED"
echo "Upload the jar there first, then rerun this script."
exit 41
fi
if [ -f "$CURRENT" ]; then
cp -p "$CURRENT" "$BACKUP"
echo "backup: $BACKUP"
else
echo "current jar missing, no backup created: $CURRENT"
fi
cp -p "$UPLOADED" "$RELEASE"
mv -f "$UPLOADED" "$CURRENT"
chmod 644 "$CURRENT"
echo "release: $RELEASE"
echo "current: $CURRENT"
ls -lh "$CURRENT" "$RELEASE" 2>/dev/null
{restart_part}"""
def install_tail_command(remote_app_dir):
app_dir_q = shell_quote(remote_app_dir)
return f"""set -e
APP_DIR={app_dir_q}
FILE="$APP_DIR/start.sh"
TS=$(date +%Y%m%d-%H%M%S)
test -f "$FILE"
cp -p "$FILE" "$FILE.bak-tail-$TS"
python - "$FILE" <<'PY'
from __future__ import print_function
import io
import sys
path = sys.argv[1]
text = io.open(path, encoding="utf-8", errors="replace").read()
marker = "# BEGIN YUMINAIL START TAIL"
needle = ' echo "Logs: $LOG_PATH"\\n'
block = ''' echo "Logs: $LOG_PATH"
# BEGIN YUMINAIL START TAIL
if [ "${{NO_TAIL:-0}}" != "1" ] && [ -t 1 ]; then
echo "Tailing logs. Press Ctrl+C to stop tail; the service keeps running."
tail -f "$LOG_PATH"
else
echo "Tail logs: tail -f $LOG_PATH"
fi
# END YUMINAIL START TAIL
'''
if marker not in text:
if needle not in text:
raise SystemExit("Cannot find log echo line in start.sh")
text = text.replace(needle, block, 1)
io.open(path, "w", encoding="utf-8").write(text)
PY
chmod +x "$FILE"
echo "patched: $FILE"
echo "backup: $FILE.bak-tail-$TS"
grep -n "YUMINAIL START TAIL\\|tail -f" "$FILE" || true
"""
def main():
parser = argparse.ArgumentParser(description="Promote manually uploaded YumiNail jars on multiple servers.")
parser.add_argument("--service", choices=sorted(SERVICES), required=True)
parser.add_argument("--action", choices=["promote", "install-start-tail"], default="promote")
parser.add_argument("--server-info", default="")
parser.add_argument("--targets", nargs="*", help="Exact workbook target names, comma-separated or repeated.")
parser.add_argument("--remote-app-dir", default="/opt/app")
parser.add_argument("--upload-dir", default="/opt/app/upload")
parser.add_argument("--uploaded-jar-name", default="")
parser.add_argument("--timestamp", default=time.strftime("%Y%m%d-%H%M%S"))
parser.add_argument("--restart", action="store_true", help="Restart service after promote with NO_TAIL=1.")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
workbook = args.server_info or default_workbook()
rows = list(workbook_rows(workbook))
targets = select_targets(rows, args.service, args.targets)
app = SERVICES[args.service]["app"]
uploaded_name = args.uploaded_jar_name or f"{app}.jar"
print(f"workbook: {workbook}")
print(f"service: {app}")
print("targets: " + ", ".join(target["name"] for target in targets))
if args.action == "promote":
print(f"expected upload: {args.upload_dir}/{uploaded_name}")
command = promote_command(app, args.remote_app_dir, args.upload_dir, uploaded_name, args.timestamp, args.restart)
else:
command = install_tail_command(args.remote_app_dir)
failures = []
for target in targets:
code = run_remote(target, command, args.dry_run)
if code != 0:
failures.append(target["name"])
if failures:
raise SystemExit("failed targets: " + ", ".join(failures))
if __name__ == "__main__":
main()
@@ -1,3 +0,0 @@
ALTER TABLE t_product
ADD COLUMN target_audience text null comment '适合人群说明' AFTER description,
ADD COLUMN precautions text null comment '注意事项说明' AFTER target_audience;
@@ -1,10 +0,0 @@
CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组''');
CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称''');
CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序''');
CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏''');
UPDATE t_tag
SET front_visible = 1
WHERE front_visible IS NULL;
CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)');
@@ -1,111 +0,0 @@
-- Lightweight wishlist inspiration groups.
-- Preset group names are created per user by the application: 最近想做、婚礼款、夏天款.
SET NAMES utf8mb4;
CREATE TABLE IF NOT EXISTS t_wishlist_group
(
id bigint unsigned NOT NULL COMMENT '收藏分组主键' PRIMARY KEY,
user_id bigint unsigned NOT NULL COMMENT '关联用户表主键',
name varchar(50) NOT NULL COMMENT '分组名称,默认预设:最近想做、婚礼款、夏天款',
sort_order int DEFAULT 100 NOT NULL COMMENT '分组排序',
create_time datetime DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间',
update_time datetime DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删除,1-已删除'
)
COMMENT '商品收藏分组表';
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists;
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
p_definition
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', p_definition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64))
BEGIN
DECLARE v_column_type VARCHAR(128) DEFAULT NULL;
DECLARE v_column_comment VARCHAR(255) DEFAULT NULL;
DECLARE v_extra VARCHAR(128) DEFAULT NULL;
SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA
INTO v_column_type, v_column_comment, v_extra
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = 'id'
LIMIT 1;
IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN
SET @alter_sql = CONCAT(
'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ',
v_column_type,
' NOT NULL'
);
IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN
SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment));
END IF;
PREPARE stmt FROM @alter_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group');
CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist');
CALL sp_add_column_if_not_exists('t_wishlist', 'group_id', 'bigint unsigned NULL COMMENT ''收藏分组ID''');
CALL sp_add_column_if_not_exists('t_wishlist', 'note', 'varchar(500) NULL COMMENT ''收藏灵感备注''');
CALL sp_add_column_if_not_exists('t_wishlist', 'sort_order', 'int NOT NULL DEFAULT 100 COMMENT ''分组内排序''');
CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_user', '(`user_id`)');
CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_sort', '(`user_id`, `sort_order`, `create_time`)');
CALL sp_add_index_if_not_exists('t_wishlist', 'idx_t_wishlist_user_group_sort', '(`user_id`, `group_id`, `sort_order`, `create_time`)');
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists;
@@ -1,397 +0,0 @@
-- vNext operations schema: schedule, reservation, payment, refund, after sale,
-- inventory, campaign, user growth, and order payment snapshot columns.
SET NAMES utf8mb4;
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists;
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_definition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', p_definition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', p_definition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64))
BEGIN
DECLARE v_column_type VARCHAR(128) DEFAULT NULL;
DECLARE v_column_comment VARCHAR(255) DEFAULT NULL;
DECLARE v_extra VARCHAR(128) DEFAULT NULL;
SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA
INTO v_column_type, v_column_comment, v_extra
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = 'id'
LIMIT 1;
IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN
SET @alter_sql = CONCAT('ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', v_column_type, ' NOT NULL');
IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN
SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment));
END IF;
PREPARE stmt FROM @alter_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED''');
CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照''');
CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照''');
CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间''');
CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道''');
CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号''');
CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED''');
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)');
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)');
CREATE TABLE IF NOT EXISTS t_artist_schedule
(
id bigint unsigned NOT NULL COMMENT '排班ID',
shop_id bigint unsigned NOT NULL COMMENT '店铺ID',
artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID',
work_date date NOT NULL COMMENT '工作日期',
start_time time NOT NULL COMMENT '班次开始时间',
end_time time NOT NULL COMMENT '班次结束时间',
slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数',
capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量',
status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用',
remark varchar(255) NULL COMMENT '排班备注',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '美甲师排班表';
CREATE TABLE IF NOT EXISTS t_appointment_reservation
(
id bigint unsigned NOT NULL COMMENT '预约占用ID',
order_id bigint unsigned NOT NULL COMMENT '订单ID',
order_item_id bigint unsigned NOT NULL COMMENT '订单项ID',
shop_id bigint unsigned NOT NULL COMMENT '店铺ID',
artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID',
product_title varchar(200) NULL COMMENT '预约作品标题快照',
appointment_start_time datetime NOT NULL COMMENT '预约开始时间',
appointment_end_time datetime NOT NULL COMMENT '预约结束时间',
status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/CONFIRMED/RELEASED/CANCELLED',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '订单预约时段占用表';
CREATE TABLE IF NOT EXISTS t_payment_order
(
id bigint unsigned NOT NULL COMMENT '支付单ID',
pay_no varchar(64) NOT NULL COMMENT '支付单号',
order_id bigint unsigned NOT NULL COMMENT '订单ID',
order_no varchar(64) NOT NULL COMMENT '订单号快照',
user_id bigint unsigned NOT NULL COMMENT '支付用户ID',
shop_id bigint unsigned NULL COMMENT '店铺ID',
channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道',
status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED',
pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额',
paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额',
pay_time datetime NULL COMMENT '支付完成时间',
expire_time datetime NULL COMMENT '支付单过期时间',
operator_id bigint unsigned NULL COMMENT '手工确认操作人ID',
remark varchar(255) NULL COMMENT '支付备注',
idempotency_key varchar(160) NULL COMMENT '支付幂等键',
raw_payload text NULL COMMENT '支付渠道原始载荷',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '订单支付单表';
CREATE TABLE IF NOT EXISTS t_refund_order
(
id bigint unsigned NOT NULL COMMENT '退款单ID',
refund_no varchar(64) NOT NULL COMMENT '退款单号',
after_sale_id bigint unsigned NULL COMMENT '售后单ID',
payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID',
order_id bigint unsigned NOT NULL COMMENT '订单ID',
status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED',
refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
refund_time datetime NULL COMMENT '退款完成时间',
channel varchar(32) NULL COMMENT '退款渠道',
external_refund_no varchar(64) NULL COMMENT '外部退款单号',
fail_reason varchar(255) NULL COMMENT '失败原因或备注',
idempotency_key varchar(160) NULL COMMENT '退款幂等键',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '订单退款单表';
CREATE TABLE IF NOT EXISTS t_after_sale
(
id bigint unsigned NOT NULL COMMENT '售后单ID',
after_sale_no varchar(64) NOT NULL COMMENT '售后单号',
order_id bigint unsigned NOT NULL COMMENT '订单ID',
order_item_id bigint unsigned NULL COMMENT '订单项ID',
user_id bigint unsigned NOT NULL COMMENT '申请用户ID',
shop_id bigint unsigned NULL COMMENT '店铺ID',
type varchar(32) NOT NULL COMMENT '售后类型',
reason varchar(1000) NULL COMMENT '申请原因',
refund_amount decimal(10, 2) NULL COMMENT '申请退款金额',
status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED',
audit_user_id bigint unsigned NULL COMMENT '审核人ID',
audit_reason varchar(500) NULL COMMENT '审核说明',
audit_time datetime NULL COMMENT '审核时间',
refund_order_id bigint unsigned NULL COMMENT '关联退款单ID',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '订单售后申请表';
CREATE TABLE IF NOT EXISTS t_after_sale_log
(
id bigint unsigned NOT NULL COMMENT '售后日志ID',
after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID',
action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT',
from_status varchar(20) NULL COMMENT '变更前状态',
to_status varchar(20) NULL COMMENT '变更后状态',
operator_id bigint unsigned NULL COMMENT '操作人ID',
operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN',
remark varchar(500) NULL COMMENT '备注',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id)
)
COMMENT '订单售后流转日志表';
CREATE TABLE IF NOT EXISTS t_inventory_item
(
id bigint unsigned NOT NULL COMMENT '库存物料ID',
shop_id bigint unsigned NOT NULL COMMENT '店铺ID',
category varchar(50) NULL COMMENT '物料分类',
item_name varchar(100) NOT NULL COMMENT '物料名称',
unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位',
stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量',
warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值',
status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '门店库存物料表';
CREATE TABLE IF NOT EXISTS t_inventory_record
(
id bigint unsigned NOT NULL COMMENT '库存流水ID',
inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID',
shop_id bigint unsigned NOT NULL COMMENT '店铺ID',
change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST',
change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量',
before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量',
after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量',
operator_id bigint unsigned NULL COMMENT '操作人ID',
remark varchar(255) NULL COMMENT '备注',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id)
)
COMMENT '门店库存变动流水表';
CREATE TABLE IF NOT EXISTS t_campaign
(
id bigint unsigned NOT NULL COMMENT '营销活动ID',
shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动',
title varchar(120) NOT NULL COMMENT '活动标题',
description varchar(1000) NULL COMMENT '活动说明',
scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景',
product_ids text NULL COMMENT '关联作品ID集合',
coupon_ids text NULL COMMENT '关联优惠券ID集合',
status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用',
start_time datetime NULL COMMENT '开始时间',
end_time datetime NULL COMMENT '结束时间',
sort_order int NOT NULL DEFAULT 100 COMMENT '排序',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (id)
)
COMMENT '营销活动配置表';
CREATE TABLE IF NOT EXISTS t_user_growth_record
(
id bigint unsigned NOT NULL COMMENT '成长值记录ID',
user_id bigint unsigned NOT NULL COMMENT '用户ID',
source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER',
source_id bigint unsigned NULL COMMENT '来源业务ID',
growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化',
remark varchar(255) NULL COMMENT '备注',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id)
)
COMMENT '用户成长值流水表';
CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)');
CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)');
CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)');
CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)');
CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)');
CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)');
CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)');
CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)');
CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)');
CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)');
CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)');
CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)');
CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)');
CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)');
CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)');
CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)');
CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)');
CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)');
CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)');
CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)');
CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)');
CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)');
CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)');
CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)');
CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)');
CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)');
CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)');
CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule');
CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation');
CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order');
CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order');
CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale');
CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log');
CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item');
CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record');
CALL sp_drop_auto_increment_on_id_if_exists('t_campaign');
CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record');
INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
VALUES
(313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0),
(313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0),
(313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0),
(313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0),
(313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0),
(313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0),
(313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0),
(313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0),
(313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0),
(313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0),
(313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0),
(313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0),
(313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0),
(313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0),
(313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0),
(313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
permission_name = VALUES(permission_name),
permission_group = VALUES(permission_group),
description = VALUES(description),
is_delete = 0,
update_time = NOW();
INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT
313931273556000000 + p.id,
u.id,
p.id,
NOW(),
NOW(),
u.id,
u.id,
0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
WHERE u.account = 'xiaowang'
AND u.is_delete = 0
AND u.type = 4
ON DUPLICATE KEY UPDATE
is_delete = 0,
update_by = VALUES(update_by),
update_time = NOW();
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists;
@@ -1,28 +0,0 @@
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_definition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL sp_add_column_if_not_exists('t_comment', 'rating_score', 'tinyint unsigned DEFAULT 5 NULL COMMENT ''评论评分:1-5星'' AFTER `parent_comment_id`');
CALL sp_add_column_if_not_exists('t_comment', 'image_file_ids', 'text NULL COMMENT ''评论图片文件ID集合,多个ID以逗号分隔'' AFTER `rating_score`');
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
@@ -0,0 +1,19 @@
# 开发环境Nacos默认地址配置说明
## 当前配置
- `FD-Core/src/main/resources/bootstrap.yaml` 和 `FD-Gateway/src/main/resources/bootstrap.yaml` 保留 `NACOS_SERVER_ADDR`、`NACOS_NAMESPACE`、`NACOS_GROUP`、`NACOS_USERNAME`、`NACOS_PASSWORD` 环境变量覆盖方式。
- 未设置环境变量时,默认连接开发环境 Nacos:`192.168.5.103:8848`。
- 未设置环境变量时,默认命名空间为开发环境:`YumiNail-Dev`。
- 默认分组为:`DEFAULT_GROUP`。
## 服务器信息依据
- `D:\doc\服务器信息.xlsx` 和 `D:\doc\prod-server-info-fd-db-switch-updated-20260623-145728.xlsx` 中记录:开发/测试使用单节点 `nacos04 192.168.5.103`。
- 同表记录生产 Nacos 为三节点集群:`192.168.5.101:8848,192.168.5.102:8848,192.168.10.145:8848`。
## 部署要求
- 开发环境可以直接使用默认值。
- 生产环境必须显式设置 `NACOS_SERVER_ADDR` 为生产三节点集群地址,并设置 `NACOS_NAMESPACE=FingertipDesigner`。
- 生产环境必须通过运行环境注入 Nacos 账号和密码,不依赖开发默认值。
@@ -0,0 +1,19 @@
# 统一数据库名为 FingertipDesigner 配置说明
## 变更内容
- 后端默认 JDBC 地址统一指向 `FingertipDesigner`。
- 初始化 SQL 的数据库创建语句和 `USE` 语句统一使用 `FingertipDesigner`。
- 测试说明文档中的数据库名前缀同步为 `FingertipDesigner`。
## 配置要求
- Nacos 或本地 `spring.datasource.url` 必须指向 `jdbc:mysql://<host>:<port>/FingertipDesigner`。
- Core 与 Gateway 默认 Nacos 命名空间为 `FingertipDesigner`,如需连接其他环境必须显式设置 `NACOS_NAMESPACE`。
- MySQL 中必须存在 `FingertipDesigner` 数据库;首次部署可执行 `scripts/sql/init/YumiNail.sql`。
- 已部署环境可执行 `scripts/sql/migrations/统一数据库名为FingertipDesigner_20260617.sql` 确保目标库存在。
## 注意事项
- 本次变更不迁移旧库数据。
- 如旧环境存在历史数据库,需先确认数据不再使用后再手工清理。