diff --git a/.gitea/scripts/assert-nacos-release.mjs b/.gitea/scripts/assert-nacos-release.mjs new file mode 100644 index 00000000..491edcf3 --- /dev/null +++ b/.gitea/scripts/assert-nacos-release.mjs @@ -0,0 +1,18 @@ +import { createHash } from 'node:crypto'; +import { access, readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { envName, latestSuccess, recordsRoot, snapshotRoot } from './release-store.mjs'; + +const environment = envName(process.env.RELEASE_ENVIRONMENT); +const commitSha = process.env.RELEASE_SHA; +const record = await latestSuccess(environment, 'nacos'); +if (!commitSha || record.commitSha !== commitSha || record.status !== 'success') throw new Error(`没有提交 ${commitSha} 对应的成功 Nacos 发布`); +if (!record.activeSnapshotId || !record.snapshotId || !Array.isArray(record.files) || record.files.length === 0 || record.files.some((file) => !file.sha256 || !file.dataId || !file.namespace)) throw new Error('Nacos 发布记录不完整'); +const destinations = environment === 'prod' ? ['prod-center1', 'prod-center2'] : [environment]; +for (const destination of destinations) for (const file of record.files) { + const path = join(snapshotRoot(environment, record.activeSnapshotId), destination, file.namespace, 'DEFAULT_GROUP', file.dataId); + const content = await readFile(path, 'utf8'); + if (createHash('sha256').update(content, 'utf8').digest('hex') !== file.sha256) throw new Error(`Nacos 发布快照摘要不匹配:${destination}/${file.namespace}/${file.dataId}`); +} +await access(join(recordsRoot(environment), 'latest-success-nacos.json')); +console.log(JSON.stringify(record)); diff --git a/.gitea/scripts/dispatch-workflow.mjs b/.gitea/scripts/dispatch-workflow.mjs new file mode 100644 index 00000000..c8ba2d07 --- /dev/null +++ b/.gitea/scripts/dispatch-workflow.mjs @@ -0,0 +1,20 @@ +const workflow = process.argv[2]; +const ref = process.argv[3] || process.env.GITHUB_REF_NAME; +if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs '); +const token = process.env.GITHUB_TOKEN; +if (!token) throw new Error('缺少 GITHUB_TOKEN'); +const server = process.env.GITHUB_SERVER_URL || 'http://192.168.5.15:3000'; +const repository = process.env.GITHUB_REPOSITORY || 'xiaowang/JayuCloud'; +const inputs = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('DISPATCH_INPUT_')).map(([key, value]) => [key.slice('DISPATCH_INPUT_'.length).toLowerCase(), value])); +if (process.env.AUTO_ROLLBACK === 'true') inputs.auto_rollback = 'true'; +const isNacosRollback = /^rollback-(dev|sit|prod)-nacos\.yml$/.test(workflow); +if (isNacosRollback && !inputs.snapshot_id && process.env.RELEASE_STORE_ROOT && (process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT)) { + try { inputs.snapshot_id = JSON.parse(await (await import('node:fs/promises')).readFile(`${process.env.RELEASE_STORE_ROOT}/records/${process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT}/pending-nacos.json`, 'utf8')).snapshotId; } catch {} +} +if (isNacosRollback && process.env.AUTO_ROLLBACK === 'true' && !inputs.snapshot_id) { + console.log('没有待处理的 Nacos 发布快照,无需触发 Nacos 回退'); + process.exit(0); +} +const response = await fetch(`${server}/api/v1/repos/${repository}/actions/workflows/${workflow}/dispatches`, { method: 'POST', headers: { Authorization: `token ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ ref, inputs }) }); +if (!response.ok && response.status !== 204) throw new Error(`触发 ${workflow} 失败:HTTP ${response.status} ${await response.text()}`); +console.log(`已触发 ${workflow} @ ${ref}`); diff --git a/.gitea/scripts/publish-nacos.mjs b/.gitea/scripts/publish-nacos.mjs index 04f73f5a..684a2d50 100644 --- a/.gitea/scripts/publish-nacos.mjs +++ b/.gitea/scripts/publish-nacos.mjs @@ -1,133 +1,75 @@ import { createHash } from 'node:crypto'; -import { readFile, readdir } from 'node:fs/promises'; +import { mkdir, readFile, readdir, rm } from 'node:fs/promises'; import { join, relative, sep } from 'node:path'; +import { atomicWrite, envName, listYamlFiles, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs'; -const repositoryRoot = process.cwd(); -const target = requiredNacosTarget('NACOS_ENVIRONMENT'); +const environment = envName(process.env.NACOS_ENVIRONMENT); const group = 'DEFAULT_GROUP'; -const configRoot = join(repositoryRoot, 'nacos', 'namespaces', target.environment); -const configFiles = await collectYamlFiles(configRoot); - -if (configFiles.length === 0) { - throw new Error(`nacos/namespaces/${target.environment} 下没有可发布的 YAML 配置`); -} - -for (const destination of target.destinations) { - await publishDestination(destination, configFiles); -} - -async function publishDestination(destination, files) { - const nacosUrls = requiredEnvironment(`${destination.prefix}_URLS`).split(',').map((value) => normalizeNacosBaseUrl(value.trim())).filter(Boolean); - if (nacosUrls.length < destination.verificationNodeCount) { - throw new Error(`${destination.name} 至少需要 ${destination.verificationNodeCount} 个 Nacos 地址用于发布校验`); - } - const username = requiredEnvironment(`${destination.prefix}_USERNAME`); - const password = requiredEnvironment(`${destination.prefix}_PASSWORD`); - const token = await login(nacosUrls[0], username, password); - for (const filePath of files) { - const root = join(repositoryRoot, 'nacos', 'namespaces', destination.environment); - const relativePath = relative(root, filePath).split(sep); - if (relativePath.length !== 3 || relativePath[1] !== group) { - throw new Error(`配置路径必须是 /${group}/.yaml:${relativePath.join('/')}`); - } - const [namespace, , dataId] = relativePath; - const content = await readFile(filePath, 'utf8'); - await publish(nacosUrls[0], token, namespace, group, dataId, content); - await verify(nacosUrls.slice(0, destination.verificationNodeCount), token, namespace, group, dataId, content); - console.log(`已发布并校验 ${destination.name}/${namespace}/${group}/${dataId}`); +const root = process.cwd(); +const configRoot = join(root, 'nacos', 'namespaces', environment); +const files = await listYamlFiles(configRoot); +if (!files.length) throw new Error(`没有可发布的 ${environment} YAML 配置`); +const destinations = (environment === 'prod' ? [['NACOS_PROD', 'prod-center1', 2], ['NACOS_DR', 'prod-center2', 1]] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment, 1]]).map(([prefix, id, nodes]) => { + const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean); + if (urls.length < nodes) throw new Error(`${prefix} Nacos 地址不足`); + return { prefix, id, urls, token: null, nodes }; +}); +for (const destination of destinations) destination.token = await login(destination.urls[0], required(`${destination.prefix}_USERNAME`), required(`${destination.prefix}_PASSWORD`)); +const groupName = group; +const runId = process.env.GITHUB_RUN_ID || 'manual'; +const commitSha = process.env.GITHUB_SHA || 'unknown'; +const recordRoot = recordsRoot(environment); +const snapshotId = `${new Date().toISOString().replaceAll(/[:.]/g, '-')}-${runId}`; +const releaseId = `${environment}-${commitSha.slice(0, 12)}-${runId}`; +const snapshot = snapshotRoot(environment, snapshotId); +const activeSnapshotId = `active-${releaseId}`; +const activeSnapshot = snapshotRoot(environment, activeSnapshotId); +await mkdir(snapshot, { recursive: true }); +await mkdir(activeSnapshot, { recursive: true }); +const entries = []; +for (const file of files) { + const { namespace, dataId } = info(file); + const content = await readFile(file, 'utf8'); + const entry = { namespace, dataId, sha256: sha256(content), previousSha256: {}, previousExists: {} }; + entries.push(entry); + for (const destination of destinations) { + const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`); + if (!response.ok && response.status !== 404) throw new Error(`读取当前 Nacos 配置失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`); + const oldContent = await response.text(); + entry.previousExists[destination.id] = response.status !== 404; + entry.previousSha256[destination.id] = sha256(oldContent); + await atomicWrite(join(snapshot, destination.id, namespace, groupName, dataId), oldContent); + await atomicWrite(join(activeSnapshot, destination.id, namespace, groupName, dataId), content); } } - -function requiredEnvironment(name) { - const value = process.env[name]; - if (!value) { - throw new Error(`缺少环境变量 ${name}`); - } - return value; -} - -function normalizeNacosBaseUrl(value) { - return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); -} - -function requiredNacosTarget(name) { - const value = requiredEnvironment(name); - const destinations = { - dev: [{ name: 'dev', environment: 'dev', prefix: 'NACOS_DEV', verificationNodeCount: 1 }], - sit: [{ name: 'sit', environment: 'sit', prefix: 'NACOS_SIT', verificationNodeCount: 1 }], - 'prod-center1': [{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 }], - 'prod-center2': [{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 }], - 'prod-both': [ - { name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 }, - { name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 }, - ], - }[value]; - if (!destinations) { - throw new Error(`不支持的 Nacos 发布目标:${value}`); - } - return { environment: destinations[0].environment, destinations }; -} - -async function collectYamlFiles(directory) { - const entries = await readdir(directory, { withFileTypes: true }); - const files = []; - for (const entry of entries) { - const entryPath = join(directory, entry.name); - if (entry.isDirectory()) { - files.push(...await collectYamlFiles(entryPath)); - } else if (entry.isFile() && entry.name.endsWith('.yaml')) { - files.push(entryPath); +await writeJson(join(recordRoot, 'pending-nacos.json'), { environment, snapshotId, activeSnapshotId, commitSha, runId, releaseId, files: entries, createdAt: new Date().toISOString() }); +try { + for (const file of files) { + const { namespace, dataId } = info(file); + const content = await readFile(file, 'utf8'); + for (const destination of destinations) { + const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(destination.token)}`, { method: 'POST', body: new URLSearchParams({ dataId, group: groupName, tenant: namespace, type: 'yaml', content }) }); + const result = await response.text(); + if (!response.ok || result.trim() !== 'true') throw new Error(`发布失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`); + await verify(destination, namespace, dataId, content); } } - return files.sort(); + const previous = await optionalJson(join(recordRoot, 'latest-success-nacos.json')); + const record = { environment, status: 'success', commitSha, runId, releaseId, snapshotId, activeSnapshotId, previousReleaseId: previous?.releaseId || null, files: entries, publishedAt: new Date().toISOString() }; + await writeJson(join(recordRoot, 'latest-success-nacos.json'), record); + await writeJson(join(recordRoot, 'nacos', `${releaseId}.json`), record); + await rm(join(recordRoot, 'pending-nacos.json'), { force: true }); + console.log(`已发布并校验 ${environment} Nacos,回退快照 ${snapshotId}`); +} catch (error) { + console.error(error.message); + console.error(`AUTO_ROLLBACK_SNAPSHOT_ID=${snapshotId}`); + throw error; } -async function login(baseUrl, user, secret) { - const body = new URLSearchParams({ username: user, password: secret }); - const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body }); - if (!response.ok) { - throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`); - } - const payload = await response.json(); - if (!payload.accessToken) { - throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`); - } - return payload.accessToken; -} - -async function publish(baseUrl, token, namespace, configGroup, dataId, content) { - const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content }); - const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body }); - const result = await response.text(); - if (!response.ok || result.trim() !== 'true') { - throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`); - } -} - -async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) { - const expectedHash = sha256(expectedContent); - for (const baseUrl of baseUrls) { - const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace }); - let lastStatus = 0; - let lastContent = ''; - for (let attempt = 1; attempt <= 3; attempt += 1) { - const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`); - const content = await response.text(); - lastStatus = response.status; - lastContent = content; - if (response.ok && sha256(content) === expectedHash) { - break; - } - if (attempt < 3) { - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - } - if (lastStatus !== 200 || sha256(lastContent) !== expectedHash) { - throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${lastStatus} ${lastContent.slice(0, 200)}`); - } - } -} - -function sha256(value) { - return createHash('sha256').update(value, 'utf8').digest('hex'); -} +function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; } +function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); } +function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); } +function info(file) { const parts = relative(configRoot, file).split(sep); if (parts.length !== 2) throw new Error(`配置路径无效:${file}`); return { namespace: parts[0], dataId: parts[1] }; } +async function optionalJson(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } } +async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; } +async function verify(destination, namespace, dataId, expected) { const expectedHash = sha256(expected); for (const base of destination.urls) { let status = 0; let content = ''; for (let attempt = 0; attempt < 3; attempt += 1) { const response = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`); status = response.status; content = await response.text(); if (status === 200 && sha256(content) === expectedHash) break; await new Promise((resolve) => setTimeout(resolve, 1000)); } if (status !== 200 || sha256(content) !== expectedHash) throw new Error(`Nacos 校验失败:${destination.prefix}/${base}/${namespace}/${dataId}`); } } diff --git a/.gitea/scripts/record-deploy.mjs b/.gitea/scripts/record-deploy.mjs new file mode 100644 index 00000000..a614cd4d --- /dev/null +++ b/.gitea/scripts/record-deploy.mjs @@ -0,0 +1,37 @@ +import { createHash } from 'node:crypto'; +import { readFile, readdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { envName, latestSuccess, recordsRoot, writeJson } from './release-store.mjs'; + +const environment = envName(process.env.RELEASE_ENVIRONMENT); +const commitSha = process.env.RELEASE_SHA; +const nacos = await latestSuccess(environment, 'nacos'); +const packageDir = process.env.PACKAGE_DIRECTORY; +if (!commitSha || nacos.commitSha !== commitSha || !packageDir) throw new Error('部署记录参数不完整'); +if (nacos.status !== 'success' || !nacos.files?.length || !nacos.activeSnapshotId) throw new Error('Nacos 发布已回退或发布记录不完整'); +const manifestPath = await findFile(packageDir, 'manifest.json'); +const manifest = JSON.parse(await readFile(manifestPath, 'utf8')); +const artifactPaths = {}; +for (const [name, fileName] of Object.entries({ core: 'JC-Salon-Core.jar', gateway: 'JC-Salon-Gateway.jar', frontend: 'jc-salon-frontend-dist.tar.gz' })) { + const artifactPath = await findFile(packageDir, fileName); + const sha256 = createHash('sha256').update(await readFile(artifactPath)).digest('hex'); + const expected = manifest.artifacts?.find((item) => item.Path?.endsWith(fileName))?.Sha256?.toLowerCase(); + if (!expected || expected !== sha256) throw new Error(`发布包摘要不匹配:${fileName}`); + artifactPaths[name] = { path: artifactPath, sha256 }; +} +const previous = await optional(join(recordsRoot(environment), 'latest-success-deploy.json')); +const releaseId = `${environment}-${commitSha.slice(0, 12)}-${process.env.GITHUB_RUN_ID || 'manual'}`; +const record = { environment, status: 'success', commitSha, releaseId, nacosReleaseId: nacos.releaseId, snapshotId: nacos.snapshotId, activeSnapshotId: nacos.activeSnapshotId, packageDir, manifestPath, artifacts: artifactPaths, previousReleaseId: previous?.releaseId || null, runId: process.env.GITHUB_RUN_ID || 'manual', deployedAt: new Date().toISOString() }; +await writeJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`), record); +await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), record); +console.log(JSON.stringify(record)); +async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } } +async function findFile(root, name) { + for (const entry of await readdir(root, { withFileTypes: true })) { + const path = join(root, entry.name); + if (entry.isDirectory()) { const nested = await optionalFind(path, name); if (nested) return nested; } + else if (entry.name === name) return path; + } + throw new Error(`发布包缺少 ${name}`); +} +async function optionalFind(root, name) { try { return await findFile(root, name); } catch { return null; } } diff --git a/.gitea/scripts/record-rollback.mjs b/.gitea/scripts/record-rollback.mjs new file mode 100644 index 00000000..c6ba64d4 --- /dev/null +++ b/.gitea/scripts/record-rollback.mjs @@ -0,0 +1,10 @@ +import { join } from 'node:path'; +import { envName, recordsRoot, readJson, writeJson } from './release-store.mjs'; + +const environment = envName(process.env.RELEASE_ENVIRONMENT); +const releaseId = process.env.ROLLBACK_RELEASE_ID; +if (!releaseId) throw new Error('缺少 ROLLBACK_RELEASE_ID'); +const record = await readJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`)); +if (record.status !== 'success' || !record.packageDir || !record.activeSnapshotId) throw new Error('目标回退版本记录不完整'); +await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), { ...record, restoredAt: new Date().toISOString() }); +console.log(`已将 ${environment} 成功版本指针更新到 ${releaseId}`); diff --git a/.gitea/scripts/release-store.mjs b/.gitea/scripts/release-store.mjs new file mode 100644 index 00000000..d10b8343 --- /dev/null +++ b/.gitea/scripts/release-store.mjs @@ -0,0 +1,62 @@ +import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; + +export const storeRoot = process.env.RELEASE_STORE_ROOT || '/salon-release'; + +export function envName(value = process.env.NACOS_ENVIRONMENT) { + if (!['dev', 'sit', 'prod'].includes(value)) throw new Error(`不支持的环境:${value}`); + return value; +} + +export function environmentRoot(environment = envName()) { + return join(storeRoot, environment); +} + +export function snapshotRoot(environment = envName(), snapshotId) { + return join(storeRoot, 'nacos-snapshots', environment, snapshotId); +} + +export function recordsRoot(environment = envName()) { + return join(storeRoot, 'records', environment); +} + +export async function atomicWrite(path, content) { + await mkdir(dirname(path), { recursive: true }); + const temp = `${path}.tmp-${process.pid}-${Date.now()}`; + await writeFile(temp, content, 'utf8'); + await rename(temp, path); +} + +export async function readJson(path) { + return JSON.parse(await readFile(path, 'utf8')); +} + +export async function writeJson(path, value) { + await atomicWrite(path, `${JSON.stringify(value, null, 2)}\n`); +} + +export async function latestSuccess(environment = envName(), kind = 'nacos') { + const path = join(recordsRoot(environment), `latest-success-${kind}.json`); + return readJson(path); +} + +export async function releaseRecord(environment, kind, releaseId) { + return readJson(join(recordsRoot(environment), kind, `${releaseId}.json`)); +} + +export async function listYamlFiles(root) { + const result = []; + for (const entry of await readdir(root, { withFileTypes: true })) { + const path = join(root, entry.name); + if (entry.isDirectory()) result.push(...await listYamlFiles(path)); + else if (entry.isFile() && entry.name.endsWith('.yaml')) result.push(path); + } + return result.sort(); +} + +export function safeRelative(root, path) { + const value = resolve(path); + const base = resolve(root); + if (!value.startsWith(`${base}/`) && !value.startsWith(`${base}\\`)) throw new Error(`路径越界:${path}`); + return value.slice(base.length + 1).replaceAll('\\', '/'); +} diff --git a/.gitea/scripts/rollback-nacos.mjs b/.gitea/scripts/rollback-nacos.mjs new file mode 100644 index 00000000..a990da6f --- /dev/null +++ b/.gitea/scripts/rollback-nacos.mjs @@ -0,0 +1,67 @@ +import { createHash } from 'node:crypto'; +import { readFile, readdir, rm } from 'node:fs/promises'; +import { join } from 'node:path'; +import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs'; + +const environment = envName(process.env.NACOS_ENVIRONMENT); +const group = 'DEFAULT_GROUP'; +const destinations = environment === 'prod' ? [['NACOS_PROD', 'prod-center1'], ['NACOS_DR', 'prod-center2']] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment]]; +const targets = []; +for (const [prefix, id] of destinations) { + const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean); + if (!urls.length) throw new Error(`${prefix}_URLS 为空`); + targets.push({ prefix, id, urls, token: await login(urls[0], required(`${prefix}_USERNAME`), required(`${prefix}_PASSWORD`)) }); +} +const root = recordsRoot(environment); +const pending = await optional(join(root, 'pending-nacos.json')); +const latest = await optional(join(root, 'latest-success-nacos.json')); +let selected = process.env.NACOS_RELEASE_ID + ? await optional(join(root, 'nacos', `${process.env.NACOS_RELEASE_ID}.json`)) + : null; +if (process.env.NACOS_RELEASE_ID && !selected) throw new Error(`找不到 Nacos 发布记录:${process.env.NACOS_RELEASE_ID}`); +if (!process.env.NACOS_SNAPSHOT_ID && !pending && !selected && latest?.previousReleaseId) selected = await optional(join(root, 'nacos', `${latest.previousReleaseId}.json`)); +const snapshotId = process.env.NACOS_SNAPSHOT_ID || (selected ? selected.activeSnapshotId : pending?.snapshotId || latest?.snapshotId); +if (!snapshotId) throw new Error(`没有 ${environment} Nacos 回退快照`); +if (!selected && !pending) selected = await findSnapshotRecord(join(root, 'nacos'), snapshotId); +const snapshot = snapshotRoot(environment, snapshotId); +const entries = selected?.files || pending?.files || latest?.files || []; +const selectedIsActive = selected?.activeSnapshotId === snapshotId; +if (!entries.length) throw new Error('回退记录缺少配置清单'); +for (const target of targets) { + for (const entry of entries) { + for (const base of target.urls) { + const exists = selectedIsActive || entry.previousExists?.[target.id] !== false; + const path = join(snapshot, target.id, entry.namespace, group, entry.dataId); + const content = exists ? await readFile(path, 'utf8') : ''; + const expectedHash = selectedIsActive ? entry.sha256 : entry.previousSha256?.[target.id]; + if (exists && (!expectedHash || sha256(content) !== expectedHash)) throw new Error(`回退快照摘要不匹配:${target.id}/${entry.namespace}/${entry.dataId}`); + const query = new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token }); + const response = exists + ? await fetch(`${base}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(target.token)}`, { method: 'POST', body: new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, type: 'yaml', content }) }) + : await fetch(`${base}/nacos/v1/cs/configs?${query}`, { method: 'DELETE' }); + if (!response.ok || (exists && (await response.text()).trim() !== 'true')) throw new Error(`回退失败:${target.id}/${entry.namespace}/${entry.dataId}`); + const check = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`); + const actual = await check.text(); + if (exists ? (!check.ok || sha256(actual) !== sha256(content)) : check.status !== 404) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`); + } + } +} +await writeJson(join(root, 'last-rollback.json'), { environment, snapshotId, source: process.env.AUTO_ROLLBACK === 'true' ? 'automatic' : 'manual', rollbackAt: new Date().toISOString() }); +if (selectedIsActive && selected) await writeJson(join(root, 'latest-success-nacos.json'), selected); +await rm(join(root, 'pending-nacos.json'), { force: true }); +console.log(`已回退 ${environment} Nacos:${snapshotId}`); +function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; } +function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); } +function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); } +async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } } +async function findSnapshotRecord(directory, id) { + try { + for (const file of await readdir(directory)) { + if (!file.endsWith('.json')) continue; + const record = await optional(join(directory, file)); + if (record?.snapshotId === id || record?.activeSnapshotId === id) return record; + } + } catch {} + return null; +} +async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; } diff --git a/.gitea/workflows/auto-publish-dev-nacos.yml b/.gitea/workflows/auto-publish-dev-nacos.yml new file mode 100644 index 00000000..15c74e73 --- /dev/null +++ b/.gitea/workflows/auto-publish-dev-nacos.yml @@ -0,0 +1,39 @@ +name: 自动发布dev环境nacos配置 + +on: + push: + branches: [dev] + +concurrency: + group: release-dev + cancel-in-progress: false + +jobs: + publish: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + NACOS_ENVIRONMENT: dev + RELEASE_STORE_ROOT: /salon-release + RELEASE_ENVIRONMENT: dev + NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }} + NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }} + NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }} + steps: + - name: 检出提交 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + test -n "$GITEA_TOKEN" + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 发布并校验 Nacos + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=dev node .gitea/scripts/dispatch-workflow.mjs rollback-dev-nacos.yml refs/heads/dev || true' ERR + node .gitea/scripts/publish-nacos.mjs diff --git a/.gitea/workflows/auto-publish-prod-nacos.yml b/.gitea/workflows/auto-publish-prod-nacos.yml new file mode 100644 index 00000000..50bb8beb --- /dev/null +++ b/.gitea/workflows/auto-publish-prod-nacos.yml @@ -0,0 +1,47 @@ +name: 自动发布prod环境nacos + +on: + push: + branches: [prod] + +concurrency: + group: release-prod + cancel-in-progress: false + +jobs: + publish: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + NACOS_ENVIRONMENT: prod + RELEASE_STORE_ROOT: /salon-release + RELEASE_ENVIRONMENT: prod + NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }} + NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }} + NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }} + NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }} + NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} + NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} + steps: + - name: 检出提交 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 发布并校验 Nacos + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=prod node .gitea/scripts/dispatch-workflow.mjs rollback-prod-nacos.yml refs/heads/prod || true' ERR + node .gitea/scripts/publish-nacos.mjs + - name: 触发生产部署 + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DISPATCH_INPUT_RELEASE_SHA: ${{ github.sha }} + run: node .gitea/scripts/dispatch-workflow.mjs deploy-prod.yml refs/heads/prod diff --git a/.gitea/workflows/auto-publish-sit-nacos.yml b/.gitea/workflows/auto-publish-sit-nacos.yml new file mode 100644 index 00000000..dc29024a --- /dev/null +++ b/.gitea/workflows/auto-publish-sit-nacos.yml @@ -0,0 +1,44 @@ +name: 自动发布sit环境nacos配置 + +on: + push: + branches: [sit] + +concurrency: + group: release-sit + cancel-in-progress: false + +jobs: + publish: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + NACOS_ENVIRONMENT: sit + RELEASE_STORE_ROOT: /salon-release + RELEASE_ENVIRONMENT: sit + NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }} + NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} + NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} + steps: + - name: 检出提交 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 发布并校验 Nacos + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=sit node .gitea/scripts/dispatch-workflow.mjs rollback-sit-nacos.yml refs/heads/sit || true' ERR + node .gitea/scripts/publish-nacos.mjs + - name: 触发 SIT 部署 + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DISPATCH_INPUT_RELEASE_SHA: ${{ github.sha }} + run: node .gitea/scripts/dispatch-workflow.mjs deploy-sit.yml refs/heads/sit diff --git a/.gitea/workflows/deploy-prod.yml b/.gitea/workflows/deploy-prod.yml new file mode 100644 index 00000000..48587117 --- /dev/null +++ b/.gitea/workflows/deploy-prod.yml @@ -0,0 +1,72 @@ +name: 自动部署prod环境 + +on: + workflow_dispatch: + inputs: + release_sha: { description: 已成功发布 PROD Nacos 的提交 SHA, required: true, type: string } + +concurrency: { group: release-prod, cancel-in-progress: false } + +jobs: + deploy: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + RELEASE_ENVIRONMENT: prod + RELEASE_SHA: ${{ inputs.release_sha || github.sha }} + RELEASE_STORE_ROOT: /salon-release + WEB_TARGET_HOST: 10.66.0.3 + WEB_TARGET_PORT: 22 + WEB_TARGET_USER: root + WEB_REMOTE_DIR: /opt/jc-salon-frontend + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} + NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }} + NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }} + NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }} + NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }} + NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} + NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} + steps: + - name: 检出发布提交 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$RELEASE_SHA" + git checkout --detach "$RELEASE_SHA" + - name: 校验 PROD Nacos 发布记录 + shell: bash + run: node .gitea/scripts/assert-nacos-release.mjs + - name: 构建并固化 PROD 发布包 + shell: pwsh + env: { VITE_API_BASE_URL: https://salon.yunail.art/api, VITE_ADMIN_API_BASE_URL: https://salon.yunail.art/admin/api } + run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit + - name: 保存发布包 + shell: bash + run: | + set -euo pipefail + package_dir="/salon-release/packages/prod/${RELEASE_SHA}-${GITHUB_RUN_ID}" + mkdir -p "$package_dir" + cp -a artifacts/release/. "$package_dir/" + echo "PACKAGE_DIRECTORY=$package_dir" >> "$GITHUB_ENV" + - name: 安装 SSH 密码工具 + shell: bash + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass + - name: 写入 PROD 目标清单 + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/salon-prod" + printf '[{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Environment":"prod"},{"Name":"salon-web","Host":"%s","Port":%s,"User":"%s","Environment":"prod"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-prod/servers.json" + - name: 执行 PROD 部署 + shell: pwsh + run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-prod/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core -GatewayRemoteAppDir /opt/jc-salon-gateway -CorePattern '^core01-' -GatewayPattern '^gateway01-' -CoreServiceName jc-salon-core -GatewayServiceName jc-salon-gateway -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://salon.yunail.art + - name: 记录成功部署 + shell: bash + run: node .gitea/scripts/record-deploy.mjs + - name: 部署失败自动回退 + if: failure() + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}, AUTO_ROLLBACK: 'true' } + run: node .gitea/scripts/dispatch-workflow.mjs rollback-prod.yml refs/heads/prod diff --git a/.gitea/workflows/deploy-sit.yml b/.gitea/workflows/deploy-sit.yml new file mode 100644 index 00000000..b91a294b --- /dev/null +++ b/.gitea/workflows/deploy-sit.yml @@ -0,0 +1,69 @@ +name: 自动部署sit环境 + +on: + workflow_dispatch: + inputs: + release_sha: { description: 已成功发布 SIT Nacos 的提交 SHA, required: true, type: string } + +concurrency: { group: release-sit, cancel-in-progress: false } + +jobs: + deploy: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + RELEASE_ENVIRONMENT: sit + RELEASE_SHA: ${{ inputs.release_sha || github.sha }} + RELEASE_STORE_ROOT: /salon-release + WEB_TARGET_HOST: 10.66.0.3 + WEB_TARGET_PORT: 22 + WEB_TARGET_USER: root + WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} + NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }} + NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} + NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} + steps: + - name: 检出发布提交 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$RELEASE_SHA" + git checkout --detach "$RELEASE_SHA" + - name: 校验 SIT Nacos 发布记录 + shell: bash + run: node .gitea/scripts/assert-nacos-release.mjs + - name: 构建 SIT 发布包 + shell: pwsh + env: { VITE_API_BASE_URL: https://sit.yunail.art/api, VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api } + run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit + - name: 持久化已校验发布包 + shell: bash + run: | + set -euo pipefail + package_dir="/salon-release/packages/sit/${RELEASE_SHA}-${GITHUB_RUN_ID}" + mkdir -p "$package_dir" + cp -a artifacts/release/. "$package_dir/" + echo "PACKAGE_DIRECTORY=$package_dir" >> "$GITHUB_ENV" + - name: 安装 SSH 密码工具 + shell: bash + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass + - name: 写入 SIT 目标清单 + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/salon-sit" + printf '[{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},{"Name":"salon-web-sit","Host":"%s","Port":%s,"User":"%s","Purpose":"Salon SIT NGINX","Environment":"sit"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-sit/servers.json" + - name: 执行 SIT 部署 + shell: pwsh + run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.yunail.art + - name: 记录成功部署 + shell: bash + run: node .gitea/scripts/record-deploy.mjs + - name: 部署失败自动回退 + if: failure() + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}, AUTO_ROLLBACK: 'true' } + run: node .gitea/scripts/dispatch-workflow.mjs rollback-sit.yml refs/heads/sit diff --git a/.gitea/workflows/environment-promotion-guard.yml b/.gitea/workflows/environment-promotion-guard.yml new file mode 100644 index 00000000..57f26035 --- /dev/null +++ b/.gitea/workflows/environment-promotion-guard.yml @@ -0,0 +1,43 @@ +name: 环境分支晋级检查 + +on: + pull_request_target: + branches: + - sit + - prod + +jobs: + validate-source: + name: environment-promotion-source + runs-on: jayucloud + steps: + - name: 校验环境分支晋级链路 + shell: bash + env: + TARGET_BRANCH: ${{ gitea.base_ref }} + SOURCE_BRANCH: ${{ gitea.head_ref }} + SOURCE_REPOSITORY: ${{ gitea.event.pull_request.head.repo.full_name }} + TARGET_REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + + test -n "$TARGET_BRANCH" + test -n "$SOURCE_BRANCH" + test -n "$SOURCE_REPOSITORY" + test -n "$TARGET_REPOSITORY" + + if [[ "$SOURCE_REPOSITORY" != "$TARGET_REPOSITORY" ]]; then + echo "拒绝跨仓库环境晋级:$SOURCE_REPOSITORY -> $TARGET_REPOSITORY" + exit 1 + fi + + case "$TARGET_BRANCH:$SOURCE_BRANCH" in + sit:dev|prod:sit) + echo "允许环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH" + ;; + *) + echo "拒绝环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH" + echo "允许链路仅为 dev -> sit -> prod" + exit 1 + ;; + esac diff --git a/.gitea/workflows/publish-nacos.yml b/.gitea/workflows/publish-nacos.yml deleted file mode 100644 index 10b7c5a5..00000000 --- a/.gitea/workflows/publish-nacos.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: 发布 Nacos 配置 - -on: - push: - branches: - - dev - - sit - workflow_dispatch: - inputs: - environment: - description: 发布目标 - required: true - type: choice - options: - - dev - - sit - - prod-center1 - - prod-center2 - - prod-both - -jobs: - publish: - runs-on: jayucloud - env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 - steps: - - name: 检出配置源 - uses: actions/checkout@v4 - - name: 准备 Node.js 运行时 - uses: actions/setup-node@v4 - with: - node-version: 20 - - name: 发布并校验配置 - env: - NACOS_ENVIRONMENT: ${{ inputs.environment || github.ref_name }} - NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }} - NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }} - NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }} - NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }} - NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} - NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} - NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }} - NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} - NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} - NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }} - NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }} - NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }} - run: node .gitea/scripts/publish-nacos.mjs diff --git a/.gitea/workflows/rollback-dev-nacos.yml b/.gitea/workflows/rollback-dev-nacos.yml new file mode 100644 index 00000000..2fb82e7c --- /dev/null +++ b/.gitea/workflows/rollback-dev-nacos.yml @@ -0,0 +1,33 @@ +name: 回退dev环境nacos配置 + +on: + workflow_dispatch: + inputs: + snapshot_id: { description: 可选快照 ID,留空使用待回退快照, required: false, type: string } + auto_rollback: { description: 是否由自动失败流程触发, required: false, type: boolean } + +concurrency: { group: release-dev, cancel-in-progress: false } + +jobs: + rollback: + runs-on: jayucloud + env: + NACOS_ENVIRONMENT: dev + RELEASE_STORE_ROOT: /salon-release + NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }} + NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }} + NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }} + NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }} + AUTO_ROLLBACK: ${{ inputs.auto_rollback }} + steps: + - name: 检出回退脚本 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}, GITHUB_SERVER_URL: http://192.168.5.15:3000 } + run: | + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 恢复并校验 Nacos + shell: bash + run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs diff --git a/.gitea/workflows/rollback-prod-nacos.yml b/.gitea/workflows/rollback-prod-nacos.yml new file mode 100644 index 00000000..57ea3c10 --- /dev/null +++ b/.gitea/workflows/rollback-prod-nacos.yml @@ -0,0 +1,42 @@ +name: 回退prod环境nacos配置 + +on: + workflow_dispatch: + inputs: + snapshot_id: { description: 可选快照 ID,留空使用待回退快照, required: false, type: string } + auto_rollback: { description: 是否由自动失败流程触发, required: false, type: boolean } + +concurrency: { group: release-prod, cancel-in-progress: false } + +jobs: + rollback: + runs-on: jayucloud + env: + NACOS_ENVIRONMENT: prod + RELEASE_STORE_ROOT: /salon-release + NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }} + NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }} + NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }} + NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }} + NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }} + NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} + NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} + AUTO_ROLLBACK: ${{ inputs.auto_rollback }} + GITHUB_SERVER_URL: http://192.168.5.15:3000 + steps: + - name: 检出回退脚本 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}, GITHUB_SERVER_URL: http://192.168.5.15:3000 } + run: | + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 恢复并校验 Nacos + shell: bash + run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs + - name: 触发 PROD 应用恢复 + if: inputs.auto_rollback == true + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}, AUTO_ROLLBACK: 'true' } + run: node .gitea/scripts/dispatch-workflow.mjs rollback-prod.yml refs/heads/prod diff --git a/.gitea/workflows/rollback-prod.yml b/.gitea/workflows/rollback-prod.yml new file mode 100644 index 00000000..81c352bd --- /dev/null +++ b/.gitea/workflows/rollback-prod.yml @@ -0,0 +1,78 @@ +name: prod环境回退上一个版本 + +on: + workflow_dispatch: + inputs: + auto_rollback: { description: 是否由自动失败流程触发, required: false, type: boolean } + +concurrency: { group: release-prod, cancel-in-progress: false } + +jobs: + rollback: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + RELEASE_ENVIRONMENT: prod + RELEASE_STORE_ROOT: /salon-release + NACOS_ENVIRONMENT: prod + AUTO_ROLLBACK: ${{ inputs.auto_rollback }} + WEB_TARGET_HOST: 10.66.0.3 + WEB_TARGET_PORT: 22 + WEB_TARGET_USER: root + WEB_REMOTE_DIR: /opt/jc-salon-frontend + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} + NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }} + NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }} + NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }} + NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }} + NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} + NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} + steps: + - name: 检出回退脚本 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} } + run: | + set -euo pipefail + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 读取上一成功版本 + shell: bash + run: | + set -euo pipefail + current=/salon-release/records/prod/latest-success-deploy.json + test -f "$current" + node - <<'NODE' >> "$GITHUB_ENV" + const fs = require('fs'); + const latest = JSON.parse(fs.readFileSync('/salon-release/records/prod/latest-success-deploy.json')); + const id = process.env.AUTO_ROLLBACK === 'true' ? latest.releaseId : latest.previousReleaseId; + if (!id) throw new Error('没有可回退的 PROD 成功版本'); + const target = JSON.parse(fs.readFileSync(`/salon-release/records/prod/deploy/${id}.json`)); + console.log(`PACKAGE_DIRECTORY=${target.packageDir}`); + console.log(`ROLLBACK_SNAPSHOT_ID=${target.activeSnapshotId}`); + console.log(`ROLLBACK_RELEASE_ID=${target.releaseId}`); + console.log(`NACOS_RELEASE_ID=${target.nacosReleaseId}`); + NODE + - name: 安装 SSH 密码工具 + shell: bash + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass + - name: 写入 PROD 目标清单 + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/salon-prod" + printf '[{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Environment":"prod"},{"Name":"salon-web","Host":"%s","Port":%s,"User":"%s","Environment":"prod"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-prod/servers.json" + - name: 恢复 PROD Nacos + shell: bash + env: + NACOS_SNAPSHOT_ID: ${{ env.ROLLBACK_SNAPSHOT_ID }} + NACOS_RELEASE_ID: ${{ env.NACOS_RELEASE_ID }} + AUTO_ROLLBACK: 'true' + NACOS_ROLLBACK_INVALIDATE: 'true' + run: node .gitea/scripts/rollback-nacos.mjs + - name: 恢复 PROD 应用 + shell: pwsh + run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-prod/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core -GatewayRemoteAppDir /opt/jc-salon-gateway -CorePattern '^core01-' -GatewayPattern '^gateway01-' -CoreServiceName jc-salon-core -GatewayServiceName jc-salon-gateway -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://salon.yunail.art + - name: 记录回退后的成功版本 + shell: bash + run: node .gitea/scripts/record-rollback.mjs diff --git a/.gitea/workflows/rollback-sit-nacos.yml b/.gitea/workflows/rollback-sit-nacos.yml new file mode 100644 index 00000000..b0138480 --- /dev/null +++ b/.gitea/workflows/rollback-sit-nacos.yml @@ -0,0 +1,39 @@ +name: 回退sit环境nacos配置 + +on: + workflow_dispatch: + inputs: + snapshot_id: { description: 可选快照 ID,留空使用待回退快照, required: false, type: string } + auto_rollback: { description: 是否由自动失败流程触发, required: false, type: boolean } + +concurrency: { group: release-sit, cancel-in-progress: false } + +jobs: + rollback: + runs-on: jayucloud + env: + NACOS_ENVIRONMENT: sit + RELEASE_STORE_ROOT: /salon-release + NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }} + NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }} + NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} + NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} + AUTO_ROLLBACK: ${{ inputs.auto_rollback }} + GITHUB_SERVER_URL: http://192.168.5.15:3000 + steps: + - name: 检出回退脚本 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}, GITHUB_SERVER_URL: http://192.168.5.15:3000 } + run: | + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 恢复并校验 Nacos + shell: bash + run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs + - name: 触发 SIT 应用恢复 + if: inputs.auto_rollback == true + shell: bash + env: { GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}, AUTO_ROLLBACK: 'true' } + run: node .gitea/scripts/dispatch-workflow.mjs rollback-sit.yml refs/heads/sit diff --git a/.gitea/workflows/rollback-sit.yml b/.gitea/workflows/rollback-sit.yml new file mode 100644 index 00000000..b9d194ae --- /dev/null +++ b/.gitea/workflows/rollback-sit.yml @@ -0,0 +1,68 @@ +name: sit环境回退上一个版本 + +on: + workflow_dispatch: + inputs: + auto_rollback: { description: 是否由自动失败流程触发, required: false, type: boolean } + +concurrency: { group: release-sit, cancel-in-progress: false } + +jobs: + rollback: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + RELEASE_ENVIRONMENT: sit + RELEASE_STORE_ROOT: /salon-release + NACOS_ENVIRONMENT: sit + AUTO_ROLLBACK: ${{ inputs.auto_rollback }} + WEB_TARGET_HOST: 10.66.0.3 + WEB_TARGET_PORT: 22 + WEB_TARGET_USER: root + WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} + NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }} + NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }} + NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }} + steps: + - name: 检出回退脚本 + shell: bash + env: { GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}, GITHUB_SERVER_URL: http://192.168.5.15:3000 } + run: | + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 读取最近成功版本 + shell: bash + run: | + set -euo pipefail + test -f /salon-release/records/sit/latest-success-deploy.json + node - <<'NODE' >> "$GITHUB_ENV" + const fs = require('fs'); + const latest = JSON.parse(fs.readFileSync('/salon-release/records/sit/latest-success-deploy.json')); + const id = process.env.AUTO_ROLLBACK === 'true' ? latest.releaseId : latest.previousReleaseId; + if (!id) throw new Error('没有可回退的 SIT 成功版本'); + const target = JSON.parse(fs.readFileSync(`/salon-release/records/sit/deploy/${id}.json`)); + console.log(`PACKAGE_DIRECTORY=${target.packageDir}`); + console.log(`ROLLBACK_SNAPSHOT_ID=${target.activeSnapshotId}`); + console.log(`ROLLBACK_RELEASE_ID=${target.releaseId}`); + console.log(`NACOS_RELEASE_ID=${target.nacosReleaseId}`); + NODE + - name: 安装 SSH 密码工具 + shell: bash + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass + - name: 恢复 SIT Nacos + shell: bash + env: + NACOS_SNAPSHOT_ID: ${{ env.ROLLBACK_SNAPSHOT_ID }} + NACOS_RELEASE_ID: ${{ env.NACOS_RELEASE_ID }} + AUTO_ROLLBACK: 'true' + NACOS_ROLLBACK_INVALIDATE: 'true' + run: node .gitea/scripts/rollback-nacos.mjs + - name: 执行 SIT 应用回退 + shell: pwsh + run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.yunail.art + - name: 记录回退后的成功版本 + shell: bash + run: node .gitea/scripts/record-rollback.mjs diff --git a/.gitea/workflows/salon-prod-deploy.yml b/.gitea/workflows/salon-prod-deploy.yml deleted file mode 100644 index edf960ac..00000000 --- a/.gitea/workflows/salon-prod-deploy.yml +++ /dev/null @@ -1,139 +0,0 @@ -name: Salon 生产发布 - -on: - workflow_dispatch: - inputs: - prepare_run_id: - description: 自动准备工作流的运行 ID - required: true - type: string - release_sha: - description: prod 合并提交 SHA - required: true - type: string - -jobs: - deploy: - runs-on: jayucloud - env: - GITHUB_SERVER_URL: http://192.168.5.15:3000 - WEB_TARGET_HOST: ${{ secrets.SALON_PROD_WEB_HOST }} - WEB_TARGET_PORT: ${{ secrets.SALON_PROD_WEB_PORT }} - WEB_TARGET_USER: ${{ secrets.SALON_PROD_WEB_USER }} - WEB_REMOTE_DIR: ${{ secrets.SALON_PROD_WEB_DIR }} - steps: - - name: 从内网 Gitea 检出发布脚本 - shell: bash - env: - GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - CHECKOUT_SHA: ${{ inputs.release_sha }} - run: | - set -euo pipefail - test -n "$GITEA_TOKEN" - test -n "$CHECKOUT_SHA" - git init . - git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" - git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$CHECKOUT_SHA" - git checkout --detach "$CHECKOUT_SHA" - - name: 检查发布工具链 - shell: bash - run: | - set -euo pipefail - java -version 2>&1 | grep -q '17\.' - node --version | grep -q '^v20\.' - pwsh --version - - name: 下载已审核发布包 - shell: bash - env: - GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PREPARE_RUN_ID: ${{ inputs.prepare_run_id }} - ARTIFACT_NAME: salon-prod-${{ inputs.release_sha }} - run: | - set -euo pipefail - test -n "$GITEA_TOKEN" - test -n "$PREPARE_RUN_ID" - test -n "$ARTIFACT_NAME" - api_base="$GITHUB_SERVER_URL/api/actions_pipeline/_apis/pipelines/workflows/$PREPARE_RUN_ID/artifacts?api-version=6.0-preview" - response_file="$RUNNER_TEMP/salon-prod-artifacts.json" - curl --fail-with-body --silent --show-error --retry 3 --retry-all-errors \ - -H "Authorization: Bearer $GITEA_TOKEN" "$api_base" > "$response_file" - artifact_id=$(node -e 'const fs=require("fs"); const name=process.argv[1]; const data=JSON.parse(fs.readFileSync(process.argv[2],"utf8")); const item=(data.value||[]).find(v=>v.name===name); if(!item||!item.fileContainerResourceUrl) process.exit(2); const m=item.fileContainerResourceUrl.match(/\\/(\\d+)\\/path$/); if(!m) process.exit(3); process.stdout.write(m[1]);' "$ARTIFACT_NAME" "$response_file") - path_url="$GITHUB_SERVER_URL/api/actions_pipeline/_apis/pipelines/workflows/$PREPARE_RUN_ID/artifacts/$artifact_id/path?api-version=6.0-preview" - curl --fail-with-body --silent --show-error --retry 3 --retry-all-errors \ - -H "Authorization: Bearer $GITEA_TOKEN" "$path_url" > "$RUNNER_TEMP/salon-prod-artifact-path.json" - mkdir -p artifacts/release - node - "$RUNNER_TEMP/salon-prod-artifact-path.json" "$GITHUB_SERVER_URL" "$PREPARE_RUN_ID" "$artifact_id" "$GITEA_TOKEN" <<'NODE' - const fs = require('fs'); - const { execFileSync } = require('child_process'); - const [pathFile, server, runId, artifactId, token] = process.argv.slice(2); - const data = JSON.parse(fs.readFileSync(pathFile, 'utf8')); - const files = data.value || []; - if (files.length === 0) throw new Error('Artifact 未返回任何文件'); - for (const file of files) { - if (!file.contentLocation || !file.path) throw new Error('Artifact 文件项缺少下载地址或路径'); - const relativePath = file.path.split('/').slice(1).join('/'); - if (!relativePath || relativePath.includes('..')) throw new Error(`非法 Artifact 路径: ${file.path}`); - const output = `artifacts/release/${relativePath}`; - fs.mkdirSync(require('path').dirname(output), { recursive: true }); - execFileSync('curl', ['--fail-with-body', '--silent', '--show-error', '--retry', '3', '--retry-all-errors', '-H', `Authorization: Bearer ${token}`, `${server}${file.contentLocation}?itemPath=${encodeURIComponent(file.path)}`, '-o', output], { stdio: 'inherit' }); - } - NODE - test -f artifacts/release/manifest.json - test -f artifacts/release/backend/JC-Salon-Core.jar || find artifacts/release -name 'JC-Salon-Core.jar' -exec cp {} artifacts/release/backend/JC-Salon-Core.jar \; - test -f artifacts/release/backend/JC-Salon-Gateway.jar || find artifacts/release -name 'JC-Salon-Gateway.jar' -exec cp {} artifacts/release/backend/JC-Salon-Gateway.jar \; - - name: 发布并校验 Salon 生产 Nacos - shell: bash - env: - NACOS_ENVIRONMENT: prod-both - NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }} - NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }} - NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }} - NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }} - NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }} - NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }} - run: node .gitea/scripts/publish-nacos.mjs - - name: 写入临时 SSH 配置和目标清单 - shell: bash - env: - SALON_PROD_SSH_PRIVATE_KEY: ${{ secrets.SALON_PROD_SSH_PRIVATE_KEY }} - SALON_PROD_KNOWN_HOSTS: ${{ secrets.SALON_PROD_KNOWN_HOSTS }} - run: | - set -euo pipefail - test -n "$SALON_PROD_SSH_PRIVATE_KEY" - test -n "$SALON_PROD_KNOWN_HOSTS" - test -n "$WEB_TARGET_HOST" - test -n "$WEB_TARGET_PORT" - test -n "$WEB_TARGET_USER" - test -n "$WEB_REMOTE_DIR" - mkdir -p "$RUNNER_TEMP/salon-prod" - printf '%s\n' "$SALON_PROD_SSH_PRIVATE_KEY" > "$RUNNER_TEMP/salon-prod/id_ed25519" - printf '%s\n' "$SALON_PROD_KNOWN_HOSTS" > "$RUNNER_TEMP/salon-prod/known_hosts" - chmod 600 "$RUNNER_TEMP/salon-prod/id_ed25519" "$RUNNER_TEMP/salon-prod/known_hosts" - cat > "$RUNNER_TEMP/salon-prod/servers.json" <- - ./docs/scripts/deploy-jayucloud-salon-production.ps1 - -Deploy - -SkipDatabaseInit - -RequireSystemd - -PackageDirectory "artifacts/release" - -ServerInfoJsonPath "$env:SERVER_INFO_JSON" - -SshKeyPath "$env:SSH_KEY_PATH" - -KnownHostsPath "$env:KNOWN_HOSTS_PATH" - -WebTargetName salon-web - -WebRemoteDir "$env:WEB_REMOTE_DIR" diff --git a/.gitea/workflows/salon-prod-prepare.yml b/.gitea/workflows/salon-prod-prepare.yml deleted file mode 100644 index 27f91778..00000000 --- a/.gitea/workflows/salon-prod-prepare.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Salon 生产发布准备 - -on: - pull_request: - types: - - closed - branches: - - prod - -jobs: - prepare: - if: >- - github.event.pull_request.merged == true && - github.event.pull_request.base.ref == 'prod' && - github.event.pull_request.head.ref == 'sit' - runs-on: jayucloud - env: - GITHUB_REF_NAME: prod - GITHUB_SERVER_URL: http://192.168.5.15:3000 - steps: - - name: 从内网 Gitea 检出合并提交 - shell: bash - env: - GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - CHECKOUT_SHA: ${{ github.event.pull_request.merge_commit_sha }} - run: | - set -euo pipefail - test -n "$GITEA_TOKEN" - test -n "$CHECKOUT_SHA" - git init . - git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" - git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$CHECKOUT_SHA" - git checkout --detach "$CHECKOUT_SHA" - - name: 检查构建工具链 - shell: bash - run: | - set -euo pipefail - java -version 2>&1 | grep -q '17\.' - node --version | grep -q '^v20\.' - mvn --version > "$RUNNER_TEMP/maven-version.txt" - grep -q 'Java version: 17\.' "$RUNNER_TEMP/maven-version.txt" - pwsh --version - - name: 构建 Salon 发布包 - shell: pwsh - run: >- - ./docs/scripts/deploy-jayucloud-salon-production.ps1 - -PackageOnly - -SkipTests - -SkipDatabaseInit - - name: 上传发布包 - uses: actions/upload-artifact@v3 - with: - name: salon-prod-${{ github.event.pull_request.merge_commit_sha }} - path: artifacts/release/* - if-no-files-found: error - retention-days: 30 - - name: 输出部署参数 - shell: bash - env: - RELEASE_SHA: ${{ github.event.pull_request.merge_commit_sha }} - run: | - { - echo "## Salon 生产部署参数" - echo "" - echo "**prepare_run_id**: \`${{ github.run_id }}\`" - echo "" - echo "**release_sha**: \`$RELEASE_SHA\`" - echo "" - echo "**Artifact**: \`salon-prod-$RELEASE_SHA\`" - } >> "$GITHUB_STEP_SUMMARY" - - echo "prepare_run_id=${{ github.run_id }}" - echo "release_sha=$RELEASE_SHA" - echo "artifact_name=salon-prod-$RELEASE_SHA" diff --git a/.gitignore b/.gitignore index 09bc4c66..d2da9ad8 100644 --- a/.gitignore +++ b/.gitignore @@ -268,7 +268,7 @@ jspm_packages/ # Mini program local overrides WeChatProgram/utils/config.local.js -FingertipDesigner-Admin-Program/utils/config.local.js +JayuCloudArtList-Admin-Program/utils/config.local.js FM-Wechat-Fronted/utils/config.local.js # 本地敏感服务器信息 diff --git a/AGENTS.md b/AGENTS.md index de918b91..cee9ecb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,10 +45,10 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat ## Project Workflow Rules - 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。 -- 后端修改如果涉及 SQL,不要修改初始化 SQL;必须新增版本变更 SQL。 +- 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。 - 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。 - 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。 -- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;`scripts/sql/init/FingertipDesigner.sql` 从该版本起冻结为仅空库首次初始化使用,后续 SQL、脚本和配置都必须通过版本迭代文件新增或调整。 +- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。 - 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `scripts/0.0.1版本基线与后续迭代规则_20260628.md`,并在任务记录中写明新增或调整的版本化文件。 - 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。 diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/FingertipDesignerCoreApplication.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/FingertipDesignerCoreApplication.java deleted file mode 100644 index bf1c1b40..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/FingertipDesignerCoreApplication.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.scheduling.annotation.EnableScheduling; - -@EnableDiscoveryClient -@EnableScheduling -@SpringBootApplication -/** - * Purpose: FingertipDesignerCoreApplication supports FingertipDesignerCoreApplication.java by holding or executing the fingertip designer core application business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class FingertipDesignerCoreApplication { - - /** - * Purpose: main supports FingertipDesignerCoreApplication.java by holding or executing the main business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static void main(String[] args) { - SpringApplication.run(FingertipDesignerCoreApplication.class, args); - } - -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/annotation/OperationGuard.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/annotation/OperationGuard.java deleted file mode 100644 index b90c56c7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/annotation/OperationGuard.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.annotation; - -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -/** - * Purpose: OperationGuard supports OperationGuard.java by holding or executing the operation guard business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public @interface OperationGuard { - - String action(); - - OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING; - - int ttlSeconds() default 10; - - String message() default "操作进行中,请勿重复点击"; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/annotation/RequirePermission.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/annotation/RequirePermission.java deleted file mode 100644 index 19257442..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/annotation/RequirePermission.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -/** - * Purpose: RequirePermission supports RequirePermission.java by holding or executing the require permission business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public @interface RequirePermission { - - String value() default ""; - - int requireUserType() default -1; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/aspect/OperationGuardAspect.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/aspect/OperationGuardAspect.java deleted file mode 100644 index 1350f4f7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/aspect/OperationGuardAspect.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.aspect; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardService; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; -import lombok.RequiredArgsConstructor; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; -import java.time.Duration; - -@Aspect -@Component -@Order(100) -@RequiredArgsConstructor -/** - * Purpose: OperationGuardAspect supports OperationGuardAspect.java by holding or executing the operation guard aspect business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OperationGuardAspect { - - /** - * Purpose: operationGuardService supports OperationGuardAspect.java by holding or executing the operation guard service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final OperationGuardService operationGuardService; - - @Around("@annotation(operationGuard)") - /** - * Purpose: guardOperation supports OperationGuardAspect.java by holding or executing the guard operation business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - if (attributes == null) { - return Result.error(500, "无法获取请求信息"); - } - - HttpServletRequest request = attributes.getRequest(); - OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire( - request, - operationGuard.action(), - Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds())) - ); - if (!handle.acquired()) { - if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) { - return Result.success(); - } - return Result.error(409, operationGuard.message()); - } - - try { - return joinPoint.proceed(); - } finally { - operationGuardService.release(handle); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/aspect/PermissionAspect.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/aspect/PermissionAspect.java deleted file mode 100644 index 2c94c8c3..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/aspect/PermissionAspect.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.aspect; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.PermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.PermissionService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionCatalog; -import lombok.RequiredArgsConstructor; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; -import java.lang.reflect.Method; - -@Aspect -@Component -@Order(Ordered.HIGHEST_PRECEDENCE) -@RequiredArgsConstructor -/** - * Purpose: PermissionAspect supports PermissionAspect.java by holding or executing the permission aspect business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class PermissionAspect { - - /** - * Purpose: permissionService supports PermissionAspect.java by holding or executing the permission service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final PermissionService permissionService; - /** - * Purpose: permissionMapper supports PermissionAspect.java by holding or executing the permission mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final PermissionMapper permissionMapper; - /** - * Purpose: userMapper supports PermissionAspect.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserMapper userMapper; - - @Around("@annotation(com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission)") - /** - * Purpose: checkPermission supports PermissionAspect.java by holding or executing the check permission business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - if (attributes == null) { - return Result.error(403, "无法获取请求信息"); - } - - HttpServletRequest request = attributes.getRequest(); - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - return Result.error(401, "未登录"); - } - - MethodSignature signature = (MethodSignature) joinPoint.getSignature(); - Method method = signature.getMethod(); - RequirePermission requirePermission = method.getAnnotation(RequirePermission.class); - if (requirePermission == null) { - return joinPoint.proceed(); - } - - UserDO userDO = userMapper.selectById(userId); - if (userDO == null) { - return Result.error(404, "用户不存在"); - } - - String permissionCode = requirePermission.value(); - Long currentShopId = parseShopId(request.getAttribute("currentShopId")); - if (Integer.valueOf(4).equals(userDO.getType()) - && currentShopId == null - && StringUtils.hasText(permissionCode) - && !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) { - return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作"); - } - - if (Integer.valueOf(4).equals(userDO.getType()) - && currentShopId == null - && StringUtils.hasText(permissionCode) - && PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) { - return joinPoint.proceed(); - } - - boolean hasPermission = !StringUtils.hasText(permissionCode) - || permissionService.hasPermission(userId, permissionCode); - if (!hasPermission) { - return Result.error(403, buildPermissionDeniedMessage(permissionCode)); - } - - return joinPoint.proceed(); - } - - /** - * Purpose: buildPermissionDeniedMessage supports PermissionAspect.java by holding or executing the build permission denied message business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildPermissionDeniedMessage(String permissionCode) { - if (!StringUtils.hasText(permissionCode)) { - return "权限不足"; - } - - PermissionDO permissionDO = permissionMapper.selectOne( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getPermissionCode, permissionCode) - .eq(PermissionDO::getIsDelete, 0) - .last("limit 1") - ); - if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) { - return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")"; - } - return "权限不足:缺少权限代码 " + permissionCode; - } - - /** - * Purpose: parseShopId supports PermissionAspect.java by holding or executing the parse shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long parseShopId(Object value) { - if (value instanceof Number number) { - long shopId = number.longValue(); - return shopId > 0 ? shopId : null; - } - if (value instanceof String text && StringUtils.hasText(text)) { - try { - long shopId = Long.parseLong(text.trim()); - return shopId > 0 ? shopId : null; - } catch (NumberFormatException ignored) { - return null; - } - } - return null; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/BusinessException.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/BusinessException.java deleted file mode 100644 index e65b07c5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/BusinessException.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.common; - -/** - * 业务异常。 - */ -public class BusinessException extends RuntimeException { - - /** - * Purpose: code supports BusinessException.java by holding or executing the code business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final Integer code; - - public BusinessException(String message) { - this(500, message); - } - - public BusinessException(Integer code, String message) { - super(message); - this.code = code; - } - - public BusinessException(String message, Throwable cause) { - this(500, message, cause); - } - - public BusinessException(Integer code, String message, Throwable cause) { - super(message, cause); - this.code = code; - } - - /** - * Purpose: getCode supports BusinessException.java by holding or executing the get code business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Integer getCode() { - return code; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/GlobalExceptionHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/GlobalExceptionHandler.java deleted file mode 100644 index ace901f1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/GlobalExceptionHandler.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.common; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.context.support.DefaultMessageSourceResolvable; -import org.springframework.validation.BindException; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.multipart.MaxUploadSizeExceededException; -import org.springframework.web.multipart.MultipartException; - -import javax.validation.ConstraintViolationException; - -/** - * 全局异常处理器。 - */ -@Slf4j -@RestControllerAdvice -public class GlobalExceptionHandler { - - /** - * Purpose: MAX_UPLOAD_SIZE_BYTES supports GlobalExceptionHandler.java by holding or executing the max upload size bytes business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024; - - @ExceptionHandler(MethodArgumentNotValidException.class) - /** - * Purpose: handleMethodArgumentNotValidException supports GlobalExceptionHandler.java by holding or executing the handle method argument not valid exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - String message = e.getBindingResult().getAllErrors().stream() - .map(DefaultMessageSourceResolvable::getDefaultMessage) - .findFirst() - .orElse("请求参数不合法"); - return Result.error(message); - } - - @ExceptionHandler(BindException.class) - /** - * Purpose: handleBindException supports GlobalExceptionHandler.java by holding or executing the handle bind exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleBindException(BindException e) { - String message = e.getBindingResult().getAllErrors().stream() - .map(DefaultMessageSourceResolvable::getDefaultMessage) - .findFirst() - .orElse("请求参数不合法"); - return Result.error(message); - } - - @ExceptionHandler(ConstraintViolationException.class) - /** - * Purpose: handleConstraintViolationException supports GlobalExceptionHandler.java by holding or executing the handle constraint violation exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleConstraintViolationException(ConstraintViolationException e) { - String message = e.getConstraintViolations().stream() - .map(violation -> violation.getMessage()) - .findFirst() - .orElse("请求参数不合法"); - return Result.error(message); - } - - @ExceptionHandler(MaxUploadSizeExceededException.class) - /** - * Purpose: handleMaxUploadSizeExceededException supports GlobalExceptionHandler.java by holding or executing the handle max upload size exceeded exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) { - log.warn("上传文件超过限制: {}", e.getMessage()); - return Result.error(buildUploadLimitMessage()); - } - - @ExceptionHandler(MultipartException.class) - /** - * Purpose: handleMultipartException supports GlobalExceptionHandler.java by holding or executing the handle multipart exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleMultipartException(MultipartException e) { - log.warn("文件上传请求异常: {}", e.getMessage()); - return Result.error(buildUploadLimitMessage()); - } - - @ExceptionHandler(IllegalStateException.class) - /** - * Purpose: handleIllegalStateException supports GlobalExceptionHandler.java by holding or executing the handle illegal state exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleIllegalStateException(IllegalStateException e) { - if (isUploadLimitException(e)) { - log.warn("上传文件超过限制: {}", e.getMessage()); - return Result.error(buildUploadLimitMessage()); - } - log.error("非法状态异常", e); - return Result.error(e.getMessage()); - } - - @ExceptionHandler(BusinessException.class) - /** - * Purpose: handleBusinessException supports GlobalExceptionHandler.java by holding or executing the handle business exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleBusinessException(BusinessException e) { - log.warn("业务异常: {}", e.getMessage()); - return Result.error(e.getCode(), e.getMessage()); - } - - @ExceptionHandler(RuntimeException.class) - /** - * Purpose: handleRuntimeException supports GlobalExceptionHandler.java by holding or executing the handle runtime exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleRuntimeException(RuntimeException e) { - log.error("运行时异常", e); - return Result.error(e.getMessage()); - } - - @ExceptionHandler(Exception.class) - /** - * Purpose: handleException supports GlobalExceptionHandler.java by holding or executing the handle exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result handleException(Exception e) { - log.error("系统异常", e); - return Result.error("系统繁忙,请稍后再试"); - } - - /** - * Purpose: buildUploadLimitMessage supports GlobalExceptionHandler.java by holding or executing the build upload limit message business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildUploadLimitMessage() { - return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB"; - } - - /** - * Purpose: isUploadLimitException supports GlobalExceptionHandler.java by holding or executing the is upload limit exception business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isUploadLimitException(Throwable throwable) { - Throwable current = throwable; - while (current != null) { - String message = current.getMessage(); - if (message != null && (message.contains("maximum permitted size") - || message.contains("FileSizeLimitExceededException") - || message.contains("exceeds its maximum permitted size"))) { - return true; - } - current = current.getCause(); - } - return false; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/Result.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/Result.java deleted file mode 100644 index b8f5bfb4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/Result.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.common; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * 统一响应结果类 - * - * @param 数据类型 - * @author xiaowang - * @date 2026-02-12 - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class Result implements Serializable { - - /** - * Purpose: code supports Result.java by holding or executing the code business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer code; - /** - * Purpose: message supports Result.java by holding or executing the message business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String message; - /** - * Purpose: data supports Result.java by holding or executing the data business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private T data; - - /** - * Purpose: success supports Result.java by holding or executing the success business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Result success() { - return new Result<>(200, "操作成功", null); - } - - /** - * Purpose: success supports Result.java by holding or executing the success business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Result success(T data) { - return new Result<>(200, "操作成功", data); - } - - /** - * Purpose: error supports Result.java by holding or executing the error business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Result error(String message) { - return new Result<>(500, message, null); - } - - /** - * Purpose: error supports Result.java by holding or executing the error business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Result error(Integer code, String message) { - return new Result<>(code, message, null); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/dto/AgreementAwareRequest.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/dto/AgreementAwareRequest.java deleted file mode 100644 index c5d5e73c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/dto/AgreementAwareRequest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.common.dto; - -import java.util.Map; - -/** - * Purpose: AgreementAwareRequest supports AgreementAwareRequest.java by holding or executing the agreement aware request business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface AgreementAwareRequest { - - Boolean getAgreementAccepted(); - - Map getAgreementVersions(); - - String getClientType(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/entity/BaseEntity.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/entity/BaseEntity.java deleted file mode 100644 index 260a6a94..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/entity/BaseEntity.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.common.entity; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 实体类基类 - * 提取公共字段,方便后续实体类扩展 - * - * @author xiaowang - * @date 2026-02-12 - */ -@Data -public abstract class BaseEntity { - - /** - * 主键ID - */ - @TableId(type = IdType.ASSIGN_ID) - private Long id; - - /** - * 创建时间 - */ - @TableField(fill = FieldFill.INSERT) - private LocalDateTime createTime; - - /** - * 更新时间 - */ - @TableField(fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/vo/PageResultVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/vo/PageResultVO.java deleted file mode 100644 index b0ca34a7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/common/vo/PageResultVO.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.common.vo; - -import lombok.Data; - -import java.util.List; - -@Data -/** - * PageResultVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class PageResultVO { - /** - * Field `list` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List list; - /** - * Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long total; - /** - * Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer page; - /** - * Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer size; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/AppCacheProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/AppCacheProperties.java deleted file mode 100644 index 2e3c9d53..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/AppCacheProperties.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 多级缓存配置。 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.cache") -public class AppCacheProperties { - - /** - * Purpose: localMaxSize supports AppCacheProperties.java by holding or executing the local max size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long localMaxSize = 2048; - - private CacheSpec productDetail = new CacheSpec(120, 900); - - private CacheSpec productList = new CacheSpec(60, 300); - - private CacheSpec productSearch = new CacheSpec(60, 300); - - private CacheSpec shop = new CacheSpec(180, 900); - - private CacheSpec tag = new CacheSpec(300, 1200); - - private CacheSpec objectStorageFile = new CacheSpec(300, 1800); - - private CacheSpec dashboard = new CacheSpec(30, 90); - - @Data - /** - * Purpose: CacheSpec supports AppCacheProperties.java by holding or executing the cache spec business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class CacheSpec { - /** - * Purpose: localTtlSeconds supports AppCacheProperties.java by holding or executing the local ttl seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long localTtlSeconds; - /** - * Purpose: redisTtlSeconds supports AppCacheProperties.java by holding or executing the redis ttl seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long redisTtlSeconds; - - public CacheSpec() { - } - - public CacheSpec(long localTtlSeconds, long redisTtlSeconds) { - this.localTtlSeconds = localTtlSeconds; - this.redisTtlSeconds = redisTtlSeconds; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/AuthInterceptor.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/AuthInterceptor.java deleted file mode 100644 index e35a1e74..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/AuthInterceptor.java +++ /dev/null @@ -1,230 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.support.RequestShopContext; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestSignatureService; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestThrottleService; -import com.xiaowang.jacyucloudsalon.core.support.security.UserSessionService; -import com.xiaowang.jacyucloudsalon.core.utils.JwtUtil; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.springframework.web.servlet.HandlerInterceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -@Component -@RequiredArgsConstructor -/** - * Purpose: AuthInterceptor supports AuthInterceptor.java by holding or executing the auth interceptor business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class AuthInterceptor implements HandlerInterceptor { - - /** - * Purpose: jwtUtil supports AuthInterceptor.java by holding or executing the jwt util business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final JwtUtil jwtUtil; - /** - * Purpose: userMapper supports AuthInterceptor.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserMapper userMapper; - /** - * Purpose: userShopBindingSupport supports AuthInterceptor.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserShopBindingSupport userShopBindingSupport; - /** - * Purpose: userSessionService supports AuthInterceptor.java by holding or executing the user session service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserSessionService userSessionService; - /** - * Purpose: requestSignatureService supports AuthInterceptor.java by holding or executing the request signature service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final RequestSignatureService requestSignatureService; - /** - * Purpose: requestThrottleService supports AuthInterceptor.java by holding or executing the request throttle service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final RequestThrottleService requestThrottleService; - - /** - * Purpose: AUTHORIZATION_HEADER supports AuthInterceptor.java by holding or executing the authorization header business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String AUTHORIZATION_HEADER = "Authorization"; - /** - * Purpose: BEARER_PREFIX supports AuthInterceptor.java by holding or executing the bearer prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String BEARER_PREFIX = "Bearer "; - - @Override - /** - * Purpose: preHandle supports AuthInterceptor.java by holding or executing the pre handle business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - String path = request.getRequestURI(); - - String authHeader = request.getHeader(AUTHORIZATION_HEADER); - - if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write("{\"code\":401,\"message\":\"未提供认证Token\"}"); - return false; - } - - String token = authHeader.substring(BEARER_PREFIX.length()); - - if (!jwtUtil.validateToken(token)) { - writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期"); - return false; - } - - if (!jwtUtil.isAccessToken(token)) { - writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误"); - return false; - } - - Long userId = jwtUtil.getUserIdFromToken(token); - String account = jwtUtil.getAccountFromToken(token); - Long currentShopId = jwtUtil.getShopIdFromToken(token); - String sessionId = jwtUtil.getSessionIdFromToken(token); - String jti = jwtUtil.getJtiFromToken(token); - if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { - writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录"); - return false; - } - - UserDO currentUser = userMapper.selectById(userId); - if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { - writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效"); - return false; - } - - if (currentUser.getStatus() != null && !Integer.valueOf(1).equals(currentUser.getStatus())) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "账号已被禁用"); - return false; - } - - boolean adminPath = isAdminPath(path); - if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限"); - return false; - } - - boolean canAccessShop = userShopBindingSupport.canUserAccessShop( - userId, - currentShopId, - adminPath, - currentUser.getType() - ); - if (!canAccessShop) { - String message = currentShopId == null || currentShopId <= 0 - ? "当前登录未选择可用店铺,请重新登录" - : (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId) - && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) - ? "店铺已被冻结" - : "当前登录店铺已停用或账号已失去该店铺访问权限"); - writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message); - return false; - } - - if (adminPath - && !Integer.valueOf(4).equals(currentUser.getType()) - && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) - && !isExpiredAdminAllowedPath(path)) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员"); - return false; - } - - if (requiresSignature(request)) { - try { - requestSignatureService.validateRequest(request, token, userId); - } catch (RuntimeException exception) { - writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); - return false; - } - } - - if (requiresWriteRateLimit(request)) { - try { - requestThrottleService.checkAuthenticatedWrite(request, userId); - } catch (RuntimeException exception) { - writeJsonResponse(response, 429, exception.getMessage()); - return false; - } - } - - request.setAttribute("userId", userId); - request.setAttribute("account", account); - request.setAttribute("userType", currentUser.getType()); - request.setAttribute("accessToken", token); - request.setAttribute("sessionId", sessionId); - request.setAttribute("tokenJti", jti); - request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId); - - return true; - } - - /** - * Purpose: requiresSignature supports AuthInterceptor.java by holding or executing the requires signature business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean requiresSignature(HttpServletRequest request) { - return requiresWriteRateLimit(request); - } - - /** - * Purpose: requiresWriteRateLimit supports AuthInterceptor.java by holding or executing the requires write rate limit business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean requiresWriteRateLimit(HttpServletRequest request) { - String method = request.getMethod(); - if (!StringUtils.hasText(method)) { - return false; - } - String normalized = method.toUpperCase(); - return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized)); - } - - /** - * Purpose: isAdminPath supports AuthInterceptor.java by holding or executing the is admin path business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isAdminPath(String path) { - return path.startsWith("/admin/") || path.startsWith("/order/admin/"); - } - - /** - * Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isExpiredAdminAllowedPath(String path) { - return path.startsWith("/admin/auth/") - || path.equals("/admin/user/info") - || path.equals("/permission/list/user/current") - || path.equals("/api/permission/list/user/current") - || path.startsWith("/admin/planning/") - || path.startsWith("/admin/shops/"); - } - - /** - * Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception { - response.setStatus(status); - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}"); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/BrandProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/BrandProperties.java deleted file mode 100644 index 3512596e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/BrandProperties.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 平台品牌文案配置。 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.brand") -public class BrandProperties { - - /** - * 短信模板中的平台名称。 - */ - private String messageTemplateName = "FingertipDesigner"; - - /** - * 管理师注册店铺的默认描述。 - */ - private String managerRegisterShopDescription = "甲屿店务注册店铺"; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/HttpClientConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/HttpClientConfig.java deleted file mode 100644 index 22dbf72f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/HttpClientConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -import java.util.concurrent.TimeUnit; - -@Configuration -/** - * Purpose: HttpClientConfig supports HttpClientConfig.java by holding or executing the http client config business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class HttpClientConfig { - - @Bean - /** - * Purpose: poolingHttpClientConnectionManager supports HttpClientConfig.java by holding or executing the pooling http client connection manager business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(HttpClientProperties properties) { - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setMaxTotal(properties.getMaxTotalConnections()); - connectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute()); - return connectionManager; - } - - @Bean - public RestTemplate restTemplate(HttpClientProperties properties, - PoolingHttpClientConnectionManager connectionManager) { - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(properties.getConnectTimeoutMs()) - .setSocketTimeout(properties.getReadTimeoutMs()) - .setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs()) - .build(); - CloseableHttpClient httpClient = HttpClients.custom() - .setConnectionManager(connectionManager) - .setDefaultRequestConfig(requestConfig) - .disableCookieManagement() - .evictIdleConnections(30, TimeUnit.SECONDS) - .build(); - - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - requestFactory.setConnectTimeout(properties.getConnectTimeoutMs()); - requestFactory.setReadTimeout(properties.getReadTimeoutMs()); - requestFactory.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs()); - return new RestTemplate(requestFactory); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/HttpClientProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/HttpClientProperties.java deleted file mode 100644 index b4a58230..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/HttpClientProperties.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.http-client") -/** - * Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class HttpClientProperties { - - /** - * Purpose: connectTimeoutMs supports HttpClientProperties.java by holding or executing the connect timeout ms business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int connectTimeoutMs = 3000; - - /** - * Purpose: readTimeoutMs supports HttpClientProperties.java by holding or executing the read timeout ms business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int readTimeoutMs = 5000; - - /** - * Purpose: connectionRequestTimeoutMs supports HttpClientProperties.java by holding or executing the connection request timeout ms business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int connectionRequestTimeoutMs = 1000; - - /** - * Purpose: maxTotalConnections supports HttpClientProperties.java by holding or executing the max total connections business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int maxTotalConnections = 200; - - /** - * Purpose: maxConnectionsPerRoute supports HttpClientProperties.java by holding or executing the max connections per route business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int maxConnectionsPerRoute = 50; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/JacksonConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/JacksonConfig.java deleted file mode 100644 index 1e5c3b4b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/JacksonConfig.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.time.LocalDateTime; -import java.io.IOException; -import java.time.format.DateTimeFormatter; - -@Configuration -/** - * Purpose: JacksonConfig supports JacksonConfig.java by holding or executing the jackson config business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class JacksonConfig { - - @Bean - /** - * Purpose: longToStringJacksonCustomizer supports JacksonConfig.java by holding or executing the long to string jackson customizer business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() { - return builder -> { - // Snowflake IDs are serialized as strings so the web and mini program do not lose precision. - builder.serializerByType(Long.class, ToStringSerializer.instance); - builder.serializerByType(Long.TYPE, ToStringSerializer.instance); - - JavaTimeModule javaTimeModule = new JavaTimeModule(); - javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer()); - builder.modules(javaTimeModule); - }; - } - - /** - * Purpose: FlexibleLocalDateTimeDeserializer supports JacksonConfig.java by holding or executing the flexible local date time deserializer business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer { - private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - @Override - /** - * Purpose: deserialize supports JacksonConfig.java by holding or executing the deserialize business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { - String value = parser.getValueAsString(); - if (value == null || value.trim().isEmpty()) { - return null; - } - String normalized = value.trim(); - if (normalized.contains("T")) { - return LocalDateTime.parse(normalized); - } - return LocalDateTime.parse(normalized, SPACE_FORMATTER); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/JwtProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/JwtProperties.java deleted file mode 100644 index 76970366..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/JwtProperties.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * JWT 配置。 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.security.jwt") -public class JwtProperties { - - /** - * HS512 密钥,生产环境请通过 Nacos 覆盖。 - */ - private String secret = "fingertip-designer-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; - - /** - * Token 发行者。 - */ - private String issuer = "fingertip-designer"; - - /** - * AccessToken 有效期,单位秒。 - */ - private long accessTokenExpirationSeconds = 2 * 60 * 60; - - /** - * 记住登录 AccessToken 有效期,单位秒。 - */ - private long rememberMeAccessTokenExpirationSeconds = 7 * 24 * 60 * 60; - - /** - * RefreshToken 有效期,单位秒。 - */ - private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60; - - /** - * 时钟偏移容忍,单位秒。 - */ - private long clockSkewSeconds = 30; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/LoginLockProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/LoginLockProperties.java deleted file mode 100644 index 1756b80b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/LoginLockProperties.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.security.login-lock") -/** - * Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class LoginLockProperties { - - /** - * Purpose: maxFailures supports LoginLockProperties.java by holding or executing the max failures business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int maxFailures = 5; - - /** - * Purpose: windowSeconds supports LoginLockProperties.java by holding or executing the window seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long windowSeconds = 600; - - /** - * Purpose: lockSeconds supports LoginLockProperties.java by holding or executing the lock seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long lockSeconds = 900; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java deleted file mode 100644 index 3eb3b8c6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import com.baomidou.mybatisplus.annotation.DbType; -import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; -import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; -import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * MyBatis-Plus配置类 - * 配置分页、乐观锁和防止全表更新等插件 - * - * @author xiaowang - * @date 2026-02-12 - */ -@Configuration -@MapperScan({ - "com.xiaowang.fingertipdesigner.core.modules.artist.mapper", - "com.xiaowang.fingertipdesigner.core.modules.auth.mapper", - "com.xiaowang.fingertipdesigner.core.modules.content.mapper", - "com.xiaowang.fingertipdesigner.core.modules.file.mapper", - "com.xiaowang.fingertipdesigner.core.modules.integration.mapper", - "com.xiaowang.fingertipdesigner.core.modules.inventory.mapper", - "com.xiaowang.fingertipdesigner.core.modules.marketing.mapper", - "com.xiaowang.fingertipdesigner.core.modules.message.mapper", - "com.xiaowang.fingertipdesigner.core.modules.order.mapper", - "com.xiaowang.fingertipdesigner.core.modules.payment.mapper", - "com.xiaowang.fingertipdesigner.core.modules.planning.mapper", - "com.xiaowang.fingertipdesigner.core.modules.product.mapper", - "com.xiaowang.fingertipdesigner.core.modules.security.mapper", - "com.xiaowang.fingertipdesigner.core.modules.shop.mapper", - "com.xiaowang.fingertipdesigner.core.modules.system.mapper", - "com.xiaowang.fingertipdesigner.core.modules.user.mapper" -}) -public class MyBatisPlusConfig { - - /** - * 配置MyBatis-Plus插件 - */ - @Bean - public MybatisPlusInterceptor mybatisPlusInterceptor() { - MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); - - // 1. 分页插件 - interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); - - // 2. 乐观锁插件 - interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); - - // 3. 防止全表更新与删除插件 - interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); - - return interceptor; - } - - @Bean - /** - * Purpose: identifierGenerator supports MyBatisPlusConfig.java by holding or executing the identifier generator business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) { - return new IdentifierGenerator() { - @Override - /** - * Purpose: nextId supports MyBatisPlusConfig.java by holding or executing the next id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Number nextId(Object entity) { - return snowflakeIdGenerator.nextId(); - } - - @Override - /** - * Purpose: nextUUID supports MyBatisPlusConfig.java by holding or executing the next uuid business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String nextUUID(Object entity) { - return snowflakeIdGenerator.nextIdString(); - } - }; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyMetaObjectHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyMetaObjectHandler.java deleted file mode 100644 index b6225ff8..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyMetaObjectHandler.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; -import lombok.extern.slf4j.Slf4j; -import org.apache.ibatis.reflection.MetaObject; -import org.springframework.stereotype.Component; - -import java.time.LocalDateTime; - -/** - * MyBatis-Plus 自动填充配置 - * 用于自动填充实体类中的创建时间、更新时间等字段 - * - * @author xiaowang - * @date 2026-02-12 - */ -@Slf4j -@Component -public class MyMetaObjectHandler implements MetaObjectHandler { - - @Override - /** - * Purpose: insertFill supports MyMetaObjectHandler.java by holding or executing the insert fill business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void insertFill(MetaObject metaObject) { - log.info("start insert fill ...."); - this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); - this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); - } - - @Override - /** - * Purpose: updateFill supports MyMetaObjectHandler.java by holding or executing the update fill business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void updateFill(MetaObject metaObject) { - log.info("start update fill ...."); - this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/ObjectStorageProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/ObjectStorageProperties.java deleted file mode 100644 index 3aef97eb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/ObjectStorageProperties.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; -import org.springframework.validation.annotation.Validated; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; -import java.util.Arrays; -import java.util.List; - -@Data -@Component -@Validated -@ConfigurationProperties(prefix = "object-storage") -public class ObjectStorageProperties { - - @NotEmpty - private List providerOrder = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS"); - - @NotEmpty - private List replicaRequiredProviders = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS"); - - private String primaryProvider; - - private String backupProvider; - - @NotNull - @Min(1) - private Integer signedUrlExpireMinutes; - - @NotBlank - private String backupQueueName; - - @NotBlank - private String backupExchangeName; - - @NotBlank - private String backupRoutingKey; - - @NotNull - @Min(1) - private Integer backupRetryBatchLimit; - - @NotBlank - private String backupRetryCron; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RabbitMQConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RabbitMQConfig.java deleted file mode 100644 index 661e2064..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RabbitMQConfig.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.RequiredArgsConstructor; -import org.springframework.amqp.core.Binding; -import org.springframework.amqp.core.BindingBuilder; -import org.springframework.amqp.core.DirectExchange; -import org.springframework.amqp.core.Queue; -import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; -import org.springframework.amqp.support.converter.MessageConverter; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -@RequiredArgsConstructor -public class RabbitMQConfig { - - public static final String EXAMPLE_QUEUE = "fingertip-designer.example.queue"; - public static final String EXAMPLE_EXCHANGE = "fingertip-designer.example.exchange"; - public static final String EXAMPLE_ROUTING_KEY = "fingertip-designer.example.routing.key"; - - private final ObjectStorageProperties objectStorageProperties; - - @Bean - public MessageConverter jsonMessageConverter() { - return new Jackson2JsonMessageConverter(); - } - - @Bean - public Queue exampleQueue() { - return new Queue(EXAMPLE_QUEUE, true); - } - - @Bean - public DirectExchange exampleExchange() { - return new DirectExchange(EXAMPLE_EXCHANGE); - } - - @Bean - public Binding exampleBinding() { - return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY); - } - - @Bean - public Queue objectStorageBackupQueue() { - return new Queue(objectStorageProperties.getBackupQueueName(), true); - } - - @Bean - public DirectExchange objectStorageBackupExchange() { - return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false); - } - - @Bean - public Binding objectStorageBackupBinding() { - return BindingBuilder.bind(objectStorageBackupQueue()) - .to(objectStorageBackupExchange()) - .with(objectStorageProperties.getBackupRoutingKey()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RateLimitProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RateLimitProperties.java deleted file mode 100644 index 76aa68c5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RateLimitProperties.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 限流配置。 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.security.rate-limit") -public class RateLimitProperties { - - private LimitRule login = new LimitRule(10, 60); - - private LimitRule register = new LimitRule(5, 300); - - private LimitRule sendCode = new LimitRule(5, 60); - - private LimitRule resetPassword = new LimitRule(5, 600); - - private LimitRule wechatMiniLogin = new LimitRule(10, 60); - - private LimitRule agreementRead = new LimitRule(60, 60); - - private LimitRule authenticatedWrite = new LimitRule(80, 60); - - private LimitRule orderCreate = new LimitRule(10, 60); - - @Data - /** - * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class LimitRule { - /** - * Purpose: limit supports RateLimitProperties.java by holding or executing the limit business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private int limit; - /** - * Purpose: windowSeconds supports RateLimitProperties.java by holding or executing the window seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long windowSeconds; - - public LimitRule() { - } - - public LimitRule(int limit, long windowSeconds) { - this.limit = limit; - this.windowSeconds = windowSeconds; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RedisConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RedisConfig.java deleted file mode 100644 index d960534e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RedisConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; -import org.springframework.cache.annotation.CachingConfigurerSupport; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -/** - * Redis配置类 - * - * @author xiaowang - * @date 2026-02-12 - */ -@Configuration -@EnableCaching -public class RedisConfig extends CachingConfigurerSupport { - - @Bean - /** - * Purpose: redisTemplate supports RedisConfig.java by holding or executing the redis template business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(factory); - - // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 - Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); - ObjectMapper om = new ObjectMapper(); - om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); - om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); - jackson2JsonRedisSerializer.setObjectMapper(om); - - StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); - - // key采用String的序列化方式 - template.setKeySerializer(stringRedisSerializer); - // hash的key也采用String的序列化方式 - template.setHashKeySerializer(stringRedisSerializer); - // value序列化方式采用jackson - template.setValueSerializer(jackson2JsonRedisSerializer); - // hash的value序列化方式采用jackson - template.setHashValueSerializer(jackson2JsonRedisSerializer); - template.afterPropertiesSet(); - - return template; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RequestSignatureProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RequestSignatureProperties.java deleted file mode 100644 index 3456831b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/RequestSignatureProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 请求签名配置。 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.security.signature") -public class RequestSignatureProperties { - - /** - * 是否启用签名校验。 - */ - private boolean enabled = true; - - /** - * 时间窗口,单位秒。 - */ - private long windowSeconds = 300; - - /** - * nonce 额外保留时间,单位秒。 - */ - private long nonceRetentionSeconds = 600; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SecurityHeadersFilter.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SecurityHeadersFilter.java deleted file mode 100644 index e2be5fc3..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SecurityHeadersFilter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import org.springframework.stereotype.Component; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@Component -/** - * Purpose: SecurityHeadersFilter supports SecurityHeadersFilter.java by holding or executing the security headers filter business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SecurityHeadersFilter implements Filter { - - @Override - /** - * Purpose: doFilter supports SecurityHeadersFilter.java by holding or executing the do filter business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (response instanceof HttpServletResponse httpResponse) { - httpResponse.setHeader("X-Content-Type-Options", "nosniff"); - httpResponse.setHeader("X-Frame-Options", "DENY"); - httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin"); - httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:"); - } - chain.doFilter(request, response); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SlowRequestLogProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SlowRequestLogProperties.java deleted file mode 100644 index ce39acc2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SlowRequestLogProperties.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.slow-request") -/** - * Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SlowRequestLogProperties { - - /** - * Purpose: enabled supports SlowRequestLogProperties.java by holding or executing the enabled business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean enabled = true; - - /** - * Purpose: thresholdMs supports SlowRequestLogProperties.java by holding or executing the threshold ms business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long thresholdMs = 300; - - /** - * Purpose: logResponseHeaderRequestId supports SlowRequestLogProperties.java by holding or executing the log response header request id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean logResponseHeaderRequestId = true; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SlowRequestLoggingInterceptor.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SlowRequestLoggingInterceptor.java deleted file mode 100644 index 17df4c5c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/SlowRequestLoggingInterceptor.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.HandlerMapping; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.UUID; - -@Component -/** - * Purpose: SlowRequestLoggingInterceptor supports SlowRequestLoggingInterceptor.java by holding or executing the slow request logging interceptor business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SlowRequestLoggingInterceptor implements HandlerInterceptor { - - /** - * Purpose: REQUEST_ID_HEADER supports SlowRequestLoggingInterceptor.java by holding or executing the request id header business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String REQUEST_ID_HEADER = "X-Request-Id"; - - private static final String START_TIME_ATTRIBUTE = SlowRequestLoggingInterceptor.class.getName() + ".startTime"; - private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("core-slow"); - - /** - * Purpose: properties supports SlowRequestLoggingInterceptor.java by holding or executing the properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SlowRequestLogProperties properties; - - public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) { - this.properties = properties; - } - - @Override - /** - * Purpose: preHandle supports SlowRequestLoggingInterceptor.java by holding or executing the pre handle business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { - String requestId = resolveRequestId(request); - request.setAttribute(REQUEST_ID_HEADER, requestId); - if (properties.isLogResponseHeaderRequestId()) { - response.setHeader(REQUEST_ID_HEADER, requestId); - } - if (properties.isEnabled()) { - request.setAttribute(START_TIME_ATTRIBUTE, System.nanoTime()); - } - return true; - } - - @Override - /** - * Purpose: afterCompletion supports SlowRequestLoggingInterceptor.java by holding or executing the after completion business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) { - if (!properties.isEnabled()) { - return; - } - Object startTimeValue = request.getAttribute(START_TIME_ATTRIBUTE); - if (!(startTimeValue instanceof Long)) { - return; - } - - long durationMs = Math.max(0L, (System.nanoTime() - (Long) startTimeValue) / 1_000_000L); - if (durationMs < properties.getThresholdMs()) { - return; - } - - String requestId = (String) request.getAttribute(REQUEST_ID_HEADER); - String bestMatchingPattern = toStringValue(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); - String controllerMethod = resolveControllerMethod(handler); - String exceptionClass = ex == null ? "" : ex.getClass().getSimpleName(); - - SLOW_REQUEST_LOGGER.warn( - "requestId={} method={} uri={} query={} bestMatchingPattern={} controllerMethod={} status={} durationMs={} userId={} userType={} shopId={} clientIp={} contentLength={} exceptionClass={}", - sanitize(requestId), - request.getMethod(), - request.getRequestURI(), - sanitize(request.getQueryString()), - sanitize(bestMatchingPattern), - sanitize(controllerMethod), - response.getStatus(), - durationMs, - castLong(request.getAttribute("userId")), - castInteger(request.getAttribute("userType")), - castLong(request.getAttribute("currentShopId")), - resolveClientIp(request), - request.getContentLengthLong(), - sanitize(exceptionClass) - ); - } - - /** - * Purpose: resolveRequestId supports SlowRequestLoggingInterceptor.java by holding or executing the resolve request id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveRequestId(HttpServletRequest request) { - String requestId = request.getHeader(REQUEST_ID_HEADER); - return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", ""); - } - - /** - * Purpose: resolveControllerMethod supports SlowRequestLoggingInterceptor.java by holding or executing the resolve controller method business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveControllerMethod(Object handler) { - if (handler instanceof HandlerMethod handlerMethod) { - return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName(); - } - return ""; - } - - /** - * Purpose: resolveClientIp supports SlowRequestLoggingInterceptor.java by holding or executing the resolve client ip business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveClientIp(HttpServletRequest request) { - String forwarded = request.getHeader("X-Forwarded-For"); - if (StringUtils.hasText(forwarded)) { - return forwarded.split(",")[0].trim(); - } - String realIp = request.getHeader("X-Real-IP"); - if (StringUtils.hasText(realIp)) { - return realIp.trim(); - } - return request.getRemoteAddr(); - } - - /** - * Purpose: sanitize supports SlowRequestLoggingInterceptor.java by holding or executing the sanitize business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sanitize(String value) { - if (!StringUtils.hasText(value)) { - return ""; - } - return value.replace('\n', '_').replace('\r', '_'); - } - - /** - * Purpose: toStringValue supports SlowRequestLoggingInterceptor.java by holding or executing the to string value business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String toStringValue(Object value) { - return value == null ? "" : value.toString(); - } - - /** - * Purpose: castLong supports SlowRequestLoggingInterceptor.java by holding or executing the cast long business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long castLong(Object value) { - return value instanceof Long ? (Long) value : null; - } - - /** - * Purpose: castInteger supports SlowRequestLoggingInterceptor.java by holding or executing the cast integer business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer castInteger(Object value) { - return value instanceof Integer ? (Integer) value : null; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/UploadSecurityProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/UploadSecurityProperties.java deleted file mode 100644 index 7d210582..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/UploadSecurityProperties.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -import java.util.ArrayList; -import java.util.List; - -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.security.upload") -/** - * Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class UploadSecurityProperties { - - /** - * Purpose: maxSize supports UploadSecurityProperties.java by holding or executing the max size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long maxSize = 10 * 1024 * 1024; - - private long maxTotalSize = 500L * 1024 * 1024; - - private List allowedMimeTypes = new ArrayList<>(List.of( - "image/jpeg", - "image/png", - "image/webp", - "image/gif" - )); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java deleted file mode 100644 index 86988c63..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@RequiredArgsConstructor -/** - * Purpose: WebMvcConfig supports WebMvcConfig.java by holding or executing the web mvc config business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class WebMvcConfig implements WebMvcConfigurer { - - /** - * Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final AuthInterceptor authInterceptor; - /** - * Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor; - - @Override - /** - * Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(slowRequestLoggingInterceptor) - .addPathPatterns("/**") - .order(-100); - - registry.addInterceptor(authInterceptor) - .addPathPatterns("/**") - .order(0) - .excludePathPatterns( - "/user/login", - "/user/register", - "/user/check/**", - "/user/refresh-token", - "/user/send-verification-code", - "/user/phone-login", - "/user/wechat-mini/**", - "/user/reset-password-by-phone", - "/legal-agreement/current", - "/legal-agreement/current/**", - "/api/legal-agreement/current", - "/api/legal-agreement/current/**", - "/product/get/**", - "/product/list/**", - "/comment/list/product/**", - "/api/comment/list/product/**", - "/nail-artist/profile/**", - "/nail-artist/*/availability", - "/nail-artist/*/reviews", - "/shop/get/**", - "/shop/trust-profile/**", - "/shop/list", - "/shop/list/public", - "/shop/list/simple", - "/tag/list/all", - "/tag/list/filter-options", - "/file/get-signed-url/**", - "/admin/auth/login", - "/admin/auth/login-shops/**", - "/admin/auth/refresh", - "/error", - "/health/**" - ); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WechatMiniProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WechatMiniProperties.java deleted file mode 100644 index 22091b4d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WechatMiniProperties.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * 微信小程序登录配置。 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "fingertip-designer.wechat.mini") -public class WechatMiniProperties { - - /** - * Purpose: appId supports WechatMiniProperties.java by holding or executing the app id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String appId; - /** - * Purpose: appSecret supports WechatMiniProperties.java by holding or executing the app secret business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String appSecret; - /** - * Purpose: code2sessionUrl supports WechatMiniProperties.java by holding or executing the code2session url business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session"; - /** - * Purpose: phoneNumberUrl supports WechatMiniProperties.java by holding or executing the phone number url business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"; - /** - * Purpose: accessTokenBufferSeconds supports WechatMiniProperties.java by holding or executing the access token buffer seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer accessTokenBufferSeconds = 60; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/filter/RequestBodyCacheFilter.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/filter/RequestBodyCacheFilter.java deleted file mode 100644 index 2f24b2d5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/filter/RequestBodyCacheFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.filter; - -import com.xiaowang.jacyucloudsalon.core.support.security.CachedBodyHttpServletRequest; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestSignatureService; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; -import org.springframework.util.StreamUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * 缓存 JSON 请求体,供签名校验复用。 - */ -@Component -@Order(Ordered.HIGHEST_PRECEDENCE) -public class RequestBodyCacheFilter extends OncePerRequestFilter { - - @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { - if (!shouldWrap(request)) { - filterChain.doFilter(request, response); - return; - } - - byte[] body = StreamUtils.copyToByteArray(request.getInputStream()); - CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body); - wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body); - filterChain.doFilter(wrappedRequest, response); - } - - /** - * Purpose: shouldWrap supports RequestBodyCacheFilter.java by holding or executing the should wrap business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean shouldWrap(HttpServletRequest request) { - String method = request.getMethod(); - if (!StringUtils.hasText(method)) { - return false; - } - String normalizedMethod = method.toUpperCase(); - if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) { - return false; - } - String contentType = request.getContentType(); - if (!StringUtils.hasText(contentType)) { - return false; - } - String normalizedType = contentType.toLowerCase(); - return normalizedType.contains("application/json"); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/controller/front/DashboardController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/controller/front/DashboardController.java deleted file mode 100644 index aaedbb4e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/controller/front/DashboardController.java +++ /dev/null @@ -1,450 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.controller.front; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.fasterxml.jackson.core.type.TypeReference; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties; -import com.xiaowang.jacyucloudsalon.core.modules.content.entity.CommentDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.content.mapper.CommentMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.service.OperationsAnalyticsService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.support.cache.MultiLevelCacheService; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.DashboardStatsVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.HotProductVO; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.OperationsAnalyticsVO; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.RecentActivityVO; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.math.BigDecimal; -import java.time.Duration; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -@RestController -@RequestMapping("/admin/dashboard") -@RequiredArgsConstructor -/** - * DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class DashboardController { - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductMapper productMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CommentMapper commentMapper; - /** - * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final OrderMapper orderMapper; - /** - * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final OrderItemMapper orderItemMapper; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - /** - * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MultiLevelCacheService multiLevelCacheService; - /** - * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AppCacheProperties appCacheProperties; - private final OperationsAnalyticsService operationsAnalyticsService; - - @GetMapping("/stats") - @RequirePermission("dashboard:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getDashboardStats(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long shopIdScope = resolveShopScope(currentUser); - String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope); - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard(); - DashboardStatsVO stats = multiLevelCacheService.getOrLoad( - "cache:dashboard:stats:" + cacheScope, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference() { - }, - () -> buildDashboardStats(currentUser, shopIdScope) - ); - return Result.success(stats); - } - - @GetMapping("/analytics") - @RequirePermission("analytics:view") - public Result getAnalytics(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long shopIdScope = resolveShopScope(currentUser); - Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; - return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope)); - } - - /** - * Run business method `buildDashboardStats`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopIdScope parameter `shopIdScope` supplied by the caller - * @return private DashboardStatsVO result consumed by the caller or returned to the frontend - */ - private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) { - DashboardStatsVO stats = new DashboardStatsVO(); - Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; - - if (currentUser != null) { - // 根据用户类型显示不同的数据 - if (currentUser.getType() == 4) { // 管理员 - stats.setTotalUsers(userMapper.selectCount(null)); - stats.setTotalProducts(productMapper.selectCount(null)); - stats.setTotalShops(shopMapper.selectCount(null)); - stats.setTodayOrders(getTodayOrders(null)); - stats.setTotalCustomers(countUsers(null, 0, null, null)); - stats.setTotalArtists(countUsers(null, 3, null, null)); - } else { // 店长或美甲师 - Long shopId = currentUser.getShopId(); - if (shopId != null) { - shopIdScope = shopId; - // 只显示当前店铺的数据 - stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false)); - stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper().eq(ProductDO::getShopId, shopId))); - stats.setTotalShops(0L); // 非管理员不显示店铺数量 - stats.setTodayOrders(getTodayOrders(shopId)); - stats.setTotalCustomers(countUsers(shopId, 0, null, null)); - stats.setTotalArtists(countUsers(shopId, 3, null, null)); - } else { - // 没有店铺ID的情况 - stats.setTotalUsers(0L); - stats.setTotalProducts(0L); - stats.setTotalShops(0L); - stats.setTodayOrders(0L); - stats.setTotalCustomers(0L); - stats.setTotalArtists(0L); - } - } - } else { - // 无法获取用户信息的情况 - stats.setTotalUsers(0L); - stats.setTotalProducts(0L); - stats.setTotalShops(0L); - stats.setTodayOrders(0L); - stats.setTotalCustomers(0L); - stats.setTotalArtists(0L); - } - - LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); - LocalDateTime weekStart = todayStart.minusDays(6); - stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null)); - stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null)); - stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null)); - stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null)); - stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null)); - stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null)); - long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null); - long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null); - stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders); - stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null)); - - stats.setHotProducts(getHotProducts(shopIdScope)); - stats.setRecentActivities(getRecentActivities(shopIdScope)); - - return stats; - } - - /** - * Run business method `resolveShopScope`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolveShopScope(UserDO currentUser) { - if (currentUser == null || currentUser.getType() == 4) { - return null; - } - return currentUser.getShopId(); - } - - /** - * Purpose: countUsers supports DashboardController.java by holding or executing the count users business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - if (type != null) { - wrapper.eq(UserDO::getType, type); - } - if (from != null) { - wrapper.ge(UserDO::getCreateTime, from); - } - if (to != null) { - wrapper.le(UserDO::getCreateTime, to); - } - if (shopId != null) { - List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false); - if (userIds.isEmpty()) { - return 0L; - } - wrapper.in(UserDO::getId, userIds); - } - return userMapper.selectCount(wrapper); - } - - /** - * Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { - return (long) listScopedOrders(shopId, artistId, status, from, to).size(); - } - - /** - * Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) { - return listScopedOrders(shopId, artistId, null, from, to).stream() - .map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount()) - .filter(amount -> amount != null) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } - - /** - * Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - wrapper.eq(OrderDO::getShopId, shopId); - } - if (status != null) { - wrapper.eq(OrderDO::getStatus, status); - } - if (from != null) { - wrapper.ge(OrderDO::getCreateTime, from); - } - if (to != null) { - wrapper.le(OrderDO::getCreateTime, to); - } - if (artistId != null) { - Set orderIds = listOrderIdsByArtist(artistId); - if (orderIds.isEmpty()) { - return Collections.emptyList(); - } - wrapper.in(OrderDO::getId, orderIds); - } - return orderMapper.selectList(wrapper); - } - - /** - * Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Set listOrderIdsByArtist(Long artistId) { - List items = orderItemMapper.selectList(new LambdaQueryWrapper() - .select(OrderItemDO::getOrderId) - .eq(OrderItemDO::getArtistId, artistId)); - return items.stream() - .map(OrderItemDO::getOrderId) - .filter(id -> id != null) - .collect(Collectors.toCollection(HashSet::new)); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long getTodayOrders(Long shopId) { - // 获取今天的开始时间 - LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); - String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - - if (shopId != null) { - // 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺 - java.util.Map result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr); - return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; - } else { - // 管理员查询所有订单 - java.util.Map result = orderItemMapper.countTodayOrders(todayStartStr); - return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; - } - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List getHotProducts(Long shopId) { - // 通过订单商品表统计每个商品的订单数量,按订单数量排序 - // 使用SQL查询获取商品及其订单数量 - List> productOrderCounts = orderItemMapper.selectMaps( - new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper() - .select("product_id, COUNT(*) as order_count") - .groupBy("product_id") - .orderByDesc("order_count") - .last("LIMIT 5") - ); - - List hotProducts = new ArrayList<>(); - - // 遍历查询结果,获取商品详情 - for (Map map : productOrderCounts) { - Long productId = Long.valueOf(map.get("product_id").toString()); - ProductDO product = productMapper.selectById(productId); - - if (product != null && (shopId == null || shopId.equals(product.getShopId()))) { - HotProductVO vo = new HotProductVO(); - BeanUtils.copyProperties(product, vo); - vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0); - hotProducts.add(vo); - } - } - - // 如果按订单数量查询没有结果,使用点赞数作为备选 - if (hotProducts.isEmpty()) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - wrapper.eq(ProductDO::getShopId, shopId); - } - wrapper.orderByDesc(ProductDO::getLikeCount) - .last("LIMIT 5"); - List products = productMapper.selectList(wrapper); - - hotProducts = products.stream().map(product -> { - HotProductVO vo = new HotProductVO(); - BeanUtils.copyProperties(product, vo); - vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0); - return vo; - }).collect(Collectors.toList()); - } - - return hotProducts; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List getRecentActivities(Long shopId) { - List activities = new ArrayList<>(); - - LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false); - if (userIds.isEmpty()) { - userWrapper.eq(UserDO::getId, -1L); - } else { - userWrapper.in(UserDO::getId, userIds); - } - } - userWrapper.orderByDesc(UserDO::getCreateTime) - .last("LIMIT 3"); - List recentUsers = userMapper.selectList(userWrapper); - - for (UserDO user : recentUsers) { - RecentActivityVO vo = new RecentActivityVO(); - vo.setId(user.getId()); - vo.setType("user"); - vo.setTitle("新用户注册"); - vo.setDescription("用户\"" + user.getNickname() + "\"注册成功"); - vo.setTime(user.getCreateTime()); - vo.setColor(""); - activities.add(vo); - } - - LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - productWrapper.eq(ProductDO::getShopId, shopId); - } - productWrapper.orderByDesc(ProductDO::getCreateTime) - .last("LIMIT 2"); - List recentProducts = productMapper.selectList(productWrapper); - - for (ProductDO product : recentProducts) { - RecentActivityVO vo = new RecentActivityVO(); - vo.setId(product.getId()); - vo.setType("product"); - vo.setTitle("新品上架"); - vo.setDescription("新品\"" + product.getTitle() + "\"已上架"); - vo.setTime(product.getCreateTime()); - vo.setColor("blue"); - activities.add(vo); - } - - LambdaQueryWrapper commentWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - commentWrapper.eq(CommentDO::getShopId, shopId); - } - commentWrapper.orderByDesc(CommentDO::getCreateTime) - .last("LIMIT 2"); - List recentComments = commentMapper.selectList(commentWrapper); - - for (CommentDO comment : recentComments) { - RecentActivityVO vo = new RecentActivityVO(); - vo.setId(comment.getId()); - vo.setType("comment"); - vo.setTitle("用户评论"); - String content = comment.getCommentContent(); - if (content != null && content.length() > 20) { - content = content.substring(0, 20) + "..."; - } - vo.setDescription(content != null ? content : "用户发表了评论"); - vo.setTime(comment.getCreateTime()); - vo.setColor("green"); - activities.add(vo); - } - - activities.sort((a, b) -> b.getTime().compareTo(a.getTime())); - - return activities.stream().limit(5).collect(Collectors.toList()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/OperationsAnalyticsService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/OperationsAnalyticsService.java deleted file mode 100644 index bc5b9b1d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/OperationsAnalyticsService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.service; - -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.OperationsAnalyticsVO; - -public interface OperationsAnalyticsService { - OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/WorkbenchService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/WorkbenchService.java deleted file mode 100644 index 85f8031c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/WorkbenchService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.service; - -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.StoreWorkbenchVO; - -public interface WorkbenchService { - StoreWorkbenchVO getWorkbench(Long shopId, Long artistId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java deleted file mode 100644 index d4b0036c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserGrowthRecordDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserGrowthRecordMapper; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.service.OperationsAnalyticsService; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.OperationsAnalyticsVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.math.BigDecimal; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -@Service -@RequiredArgsConstructor -public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService { - - private final OrderMapper orderMapper; - private final OrderItemMapper orderItemMapper; - private final ProductMapper productMapper; - private final UserGrowthRecordMapper userGrowthRecordMapper; - - @Override - public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) { - List orders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, OrderDO::getShopId, shopId) - .eq(OrderDO::getIsDelete, 0)); - if (artistId != null) { - Set orderIds = new HashSet<>(); - orderItemMapper.selectList(new LambdaQueryWrapper() - .eq(OrderItemDO::getArtistId, artistId) - .eq(OrderItemDO::getIsDelete, 0)) - .forEach(item -> orderIds.add(item.getOrderId())); - orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList(); - } - OperationsAnalyticsVO vo = new OperationsAnalyticsVO(); - vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0)) - .stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum()); - vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0)) - .stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum()); - vo.setCartCount(0L); - vo.setOrderCount((long) orders.size()); - vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count()); - vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); - vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() - .eq(UserGrowthRecordDO::getSourceType, "REVIEW"))); - vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() - .eq(UserGrowthRecordDO::getSourceType, "REBOOK"))); - vo.setTotalAmount(orders.stream() - .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java deleted file mode 100644 index 1f0d5599..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.AfterSaleDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.entity.InventoryItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistChangeRequestDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.AfterSaleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.mapper.InventoryItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistChangeRequestMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistReviewMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.service.WorkbenchService; -import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus; -import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.StoreWorkbenchVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -@Service -@RequiredArgsConstructor -public class WorkbenchServiceImpl implements WorkbenchService { - - private final OrderMapper orderMapper; - private final OrderItemMapper orderItemMapper; - private final AfterSaleMapper afterSaleMapper; - private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; - private final InventoryItemMapper inventoryItemMapper; - private final ArtistScheduleMapper artistScheduleMapper; - private final OrderArtistReviewMapper orderArtistReviewMapper; - - @Override - public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) { - LocalDateTime todayStart = LocalDate.now().atStartOfDay(); - LocalDateTime tomorrowStart = todayStart.plusDays(1); - List orders = scopedOrders(shopId, artistId); - StoreWorkbenchVO vo = new StoreWorkbenchVO(); - vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count()); - vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count()); - vo.setPendingAfterSaleCount(countAfterSales(shopId)); - vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId)); - vo.setLowStockItemCount(countLowStock(shopId)); - vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate())); - vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart)); - vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); - vo.setServiceAmount(orders.stream() - .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - vo.setAverageRating(resolveRating(artistId)); - return vo; - } - - private boolean isActionableOrder(OrderDO order) { - if (order == null || order.getStatus() == null) { - return false; - } - return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) - || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); - } - - private List scopedOrders(Long shopId, Long artistId) { - List orders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, OrderDO::getShopId, shopId) - .eq(OrderDO::getIsDelete, 0)); - if (artistId == null) { - return orders; - } - Set orderIds = new HashSet<>(); - orderItemMapper.selectList(new LambdaQueryWrapper() - .eq(OrderItemDO::getArtistId, artistId) - .eq(OrderItemDO::getIsDelete, 0)) - .forEach(item -> orderIds.add(item.getOrderId())); - return orders.stream().filter(order -> orderIds.contains(order.getId())).toList(); - } - - private long countAfterSales(Long shopId) { - return afterSaleMapper.selectCount(new LambdaQueryWrapper() - .eq(shopId != null, AfterSaleDO::getShopId, shopId) - .eq(AfterSaleDO::getStatus, "PENDING") - .eq(AfterSaleDO::getIsDelete, 0)); - } - - private long countArtistChanges(Long shopId, Long artistId) { - return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper() - .eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId) - .eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId) - .eq(OrderArtistChangeRequestDO::getStatus, "PENDING") - .eq(OrderArtistChangeRequestDO::getIsDelete, 0)); - } - - private long countLowStock(Long shopId) { - return inventoryItemMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, InventoryItemDO::getShopId, shopId) - .eq(InventoryItemDO::getIsDelete, 0)) - .stream() - .filter(item -> item.getStockQuantity() != null - && item.getWarningThreshold() != null - && item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0) - .count(); - } - - private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) { - return artistScheduleMapper.selectCount(new LambdaQueryWrapper() - .eq(shopId != null, ArtistScheduleDO::getShopId, shopId) - .eq(artistId != null, ArtistScheduleDO::getArtistId, artistId) - .ge(ArtistScheduleDO::getWorkDate, today) - .lt(ArtistScheduleDO::getWorkDate, today.plusDays(3)) - .eq(ArtistScheduleDO::getIsDelete, 0)); - } - - private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) { - if (artistId == null) { - return 0L; - } - return orderItemMapper.selectList(new LambdaQueryWrapper() - .eq(OrderItemDO::getArtistId, artistId) - .ge(OrderItemDO::getAppointmentTime, todayStart) - .lt(OrderItemDO::getAppointmentTime, tomorrowStart) - .eq(OrderItemDO::getIsDelete, 0)) - .size(); - } - - private BigDecimal resolveRating(Long artistId) { - if (artistId == null) { - return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); - } - BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); - return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP); - } - - private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) { - return value != null && !value.isBefore(start) && value.isBefore(end); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/DashboardStatsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/DashboardStatsVO.java deleted file mode 100644 index b9c6b87c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/DashboardStatsVO.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.util.List; - -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.HotProductVO; -@Data -/** - * DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class DashboardStatsVO { - /** - * Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long totalUsers; - /** - * Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long totalProducts; - /** - * Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long totalShops; - /** - * Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long todayOrders; - /** - * Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal totalOrderAmount; - /** - * Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal todayOrderAmount; - /** - * Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal weekOrderAmount; - /** - * Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long totalCustomers; - /** - * Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long totalArtists; - /** - * Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long newCustomersToday; - /** - * Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long newCustomers7Days; - /** - * Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long newOrders7Days; - /** - * Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long pendingOrders; - /** - * Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long completedOrders; - /** - * Field `hotProducts` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List hotProducts; - /** - * Field `recentActivities` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List recentActivities; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/OperationsAnalyticsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/OperationsAnalyticsVO.java deleted file mode 100644 index 0bdc638e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/OperationsAnalyticsVO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class OperationsAnalyticsVO { - private Long viewCount; - private Long favoriteCount; - private Long cartCount; - private Long orderCount; - private Long paidOrderCount; - private Long completedOrderCount; - private Long reviewCount; - private Long rebookCount; - private BigDecimal totalAmount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/RecentActivityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/RecentActivityVO.java deleted file mode 100644 index 90fc7aea..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/RecentActivityVO.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -/** - * RecentActivityVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class RecentActivityVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String type; - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - /** - * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String description; - /** - * Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime time; - /** - * Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String color; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/StoreWorkbenchVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/StoreWorkbenchVO.java deleted file mode 100644 index b916c2f9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/vo/StoreWorkbenchVO.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class StoreWorkbenchVO { - private Long todayOrderCount; - private Long pendingOrderCount; - private Long pendingAfterSaleCount; - private Long pendingArtistChangeCount; - private Long lowStockItemCount; - private Long scheduleReminderCount; - private Long todayServiceCount; - private Long completedServiceCount; - private BigDecimal serviceAmount; - private BigDecimal averageRating; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/controller/front/NailArtistController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/controller/front/NailArtistController.java deleted file mode 100644 index 5a5a06a5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/controller/front/NailArtistController.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.service.NailArtistInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistAvailabilityVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistProfileVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistReviewVO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -/** - * 美甲师信息Controller(前台) - */ -@RestController -@RequestMapping("/nail-artist") -public class NailArtistController { - - @Autowired - /** - * Purpose: nailArtistInfoService supports NailArtistController.java by holding or executing the nail artist info service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private NailArtistInfoService nailArtistInfoService; - - /** - * 获取所有可用的美甲师信息(前台使用) - */ - @GetMapping("/list") - public Result> getAllAvailableNailArtists() { - List nailArtistInfoDTOList = nailArtistInfoService.getAllAvailableNailArtists(); - return Result.success(nailArtistInfoDTOList); - } - - @GetMapping("/list/shop/{shopId}") - public Result> listByShopId(@PathVariable Long shopId) { - return Result.success(nailArtistInfoService.getByShopId(shopId)); - } - - /** - * 根据用户ID获取美甲师信息(前台使用) - */ - @GetMapping("/get/{userId}") - public Result getNailArtistInfo(@PathVariable Long userId) { - NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); - return Result.success(nailArtistInfoDTO); - } - - @GetMapping("/profile/{artistId}") - public Result getPublicProfile(@PathVariable Long artistId) { - return Result.success(nailArtistInfoService.getPublicProfile(artistId)); - } - - @GetMapping("/{artistId}/availability") - public Result> getAvailability(@PathVariable Long artistId) { - return Result.success(nailArtistInfoService.getAvailability(artistId)); - } - - @GetMapping("/{artistId}/reviews") - public Result> listPublicReviews(@PathVariable Long artistId) { - return Result.success(nailArtistInfoService.listPublicReviews(artistId)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleDTO.java deleted file mode 100644 index 1f1755e7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleDTO.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.dto; - -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalTime; - -@Data -public class ArtistScheduleDTO { - private Long shopId; - private Long artistId; - private LocalDate workDate; - private LocalTime startTime; - private LocalTime endTime; - private Integer slotMinutes; - private Integer capacity; - private Integer status; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleExceptionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleExceptionDTO.java deleted file mode 100644 index e5f8c3e9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleExceptionDTO.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.dto; - -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalTime; - -@Data -public class ArtistScheduleExceptionDTO { - private Long shopId; - private Long artistId; - private LocalDate workDate; - private String exceptionType; - private LocalTime startTime; - private LocalTime endTime; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleRuleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleRuleDTO.java deleted file mode 100644 index 5d3b3a07..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/ArtistScheduleRuleDTO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.dto; - -import lombok.Data; - -import java.time.LocalTime; -import java.util.List; - -@Data -public class ArtistScheduleRuleDTO { - private Long shopId; - private Long artistId; - private String presetType; - private List workDays; - private LocalTime startTime; - private LocalTime endTime; - private Integer status; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/NailArtistInfoDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/NailArtistInfoDTO.java deleted file mode 100644 index 35fd72a1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/dto/NailArtistInfoDTO.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.dto; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalTime; - -/** - * 美甲师信息DTO - */ -@Data -public class NailArtistInfoDTO { - /** - * 主键ID - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long id; - - /** - * 关联用户表主键(美甲师用户) - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long userId; - - /** - * 身份 - */ - private String identity; - - /** - * 从业年限 - */ - private Integer experience; - - /** - * 技能标签ID集合,多个ID以逗号分隔 - */ - private String skills; - - /** - * 评分 - */ - private BigDecimal rating; - - /** - * 状态:1-营业中,0-休息中 - */ - private Integer status; - - /** - * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer participateProduction; - - /** - * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalTime workStartTime; - - /** - * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalTime workEndTime; - - /** - * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer userType; - - /** - * Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String userTypeName; - - /** - * 作品集商品ID集合,多个ID以逗号分隔 - */ - private String portfolio; - - /** - * 美甲师姓名(从用户表获取) - */ - private String nickname; - - /** - * 所属店铺ID - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long shopId; - - /** - * 店铺名称 - */ - private String shopName; - - /** - * 用户签名 - */ - private String signature; - - /** - * 头像访问地址 - */ - private String avatar; - - /** - * 排班模式摘要 - */ - private String scheduleModeSummary; - - /** - * 排班时间摘要 - */ - private String scheduleTimeSummary; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleDO.java deleted file mode 100644 index d648426a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleDO.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDate; -import java.time.LocalTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_artist_schedule") -public class ArtistScheduleDO extends BaseEntity { - @TableField("shop_id") - private Long shopId; - @TableField("artist_id") - private Long artistId; - @TableField("work_date") - private LocalDate workDate; - @TableField("start_time") - private LocalTime startTime; - @TableField("end_time") - private LocalTime endTime; - @TableField("slot_minutes") - private Integer slotMinutes; - @TableField("capacity") - private Integer capacity; - @TableField("status") - private Integer status; - @TableField("remark") - private String remark; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleExceptionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleExceptionDO.java deleted file mode 100644 index 210e9822..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleExceptionDO.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDate; -import java.time.LocalTime; - -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_artist_schedule_exception") -public class ArtistScheduleExceptionDO extends BaseEntity { - @TableField("shop_id") - private Long shopId; - @TableField("artist_id") - private Long artistId; - @TableField("work_date") - private LocalDate workDate; - @TableField("exception_type") - private String exceptionType; - @TableField("start_time") - private LocalTime startTime; - @TableField("end_time") - private LocalTime endTime; - @TableField("slot_minutes") - private Integer slotMinutes; - @TableField("capacity") - private Integer capacity; - @TableField("remark") - private String remark; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleRuleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleRuleDO.java deleted file mode 100644 index b7986316..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/ArtistScheduleRuleDO.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalTime; - -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_artist_schedule_rule") -public class ArtistScheduleRuleDO extends BaseEntity { - @TableField("shop_id") - private Long shopId; - @TableField("artist_id") - private Long artistId; - @TableField("preset_type") - private String presetType; - @TableField("work_days") - private String workDays; - @TableField("start_time") - private LocalTime startTime; - @TableField("end_time") - private LocalTime endTime; - @TableField("slot_minutes") - private Integer slotMinutes; - @TableField("capacity") - private Integer capacity; - @TableField("status") - private Integer status; - @TableField("remark") - private String remark; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/NailArtistInfoDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/NailArtistInfoDO.java deleted file mode 100644 index 3c8f459a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/entity/NailArtistInfoDO.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 美甲师信息实体类 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_nail_artist_info") -public class NailArtistInfoDO extends BaseEntity { - /** - * 关联用户表主键(美甲师用户) - */ - private Long userId; - - /** - * 身份 - */ - private String identity; - - /** - * 从业年限 - */ - private Integer experience; - - /** - * 技能标签ID集合,多个ID以逗号分隔 - */ - private String skills; - - /** - * 评分 - */ - private BigDecimal rating; - - /** - * 状态:1-营业中,0-休息中 - */ - private Integer status; - - @TableField("participate_production") - /** - * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer participateProduction; - - @TableField("work_start_time") - /** - * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalTime workStartTime; - - @TableField("work_end_time") - /** - * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalTime workEndTime; - - /** - * 作品集商品ID集合,多个ID以逗号分隔 - */ - private String portfolio; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java deleted file mode 100644 index 7c932e53..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleExceptionDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface ArtistScheduleExceptionMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleMapper.java deleted file mode 100644 index 1a79e71b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleMapper.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -import java.time.LocalDate; -import java.time.LocalTime; - -@Mapper -public interface ArtistScheduleMapper extends BaseMapper { - @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + - "AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " + - "AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE") - ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("workDate") LocalDate workDate, - @Param("startTime") LocalTime startTime, - @Param("endTime") LocalTime endTime); - - @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + - "AND work_date = #{workDate} AND is_delete = 0 ORDER BY start_time ASC LIMIT 1 FOR UPDATE") - ArtistScheduleDO selectDayScheduleForUpdate(@Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("workDate") LocalDate workDate); - - @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + - "AND work_date = #{workDate} AND start_time = #{startTime} AND is_delete = 0 LIMIT 1 FOR UPDATE") - ArtistScheduleDO selectSlotScheduleForUpdate(@Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("workDate") LocalDate workDate, - @Param("startTime") LocalTime startTime); - - @Update("UPDATE t_artist_schedule SET start_time = #{startTime}, end_time = #{endTime}, " + - "slot_minutes = #{slotMinutes}, capacity = #{capacity}, status = #{status}, remark = #{remark}, " + - "update_time = NOW() WHERE id = #{id} AND is_delete = 0") - int updateGeneratedSchedule(@Param("id") Long id, - @Param("startTime") LocalTime startTime, - @Param("endTime") LocalTime endTime, - @Param("slotMinutes") Integer slotMinutes, - @Param("capacity") Integer capacity, - @Param("status") Integer status, - @Param("remark") String remark); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleRuleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleRuleMapper.java deleted file mode 100644 index af65744b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/ArtistScheduleRuleMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleRuleDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface ArtistScheduleRuleMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/NailArtistInfoMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/NailArtistInfoMapper.java deleted file mode 100644 index 0cba9e10..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/mapper/NailArtistInfoMapper.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO; -import org.apache.ibatis.annotations.Mapper; - -/** - * 美甲师信息Mapper - */ -@Mapper -public interface NailArtistInfoMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/ArtistScheduleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/ArtistScheduleService.java deleted file mode 100644 index ac77b81a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/ArtistScheduleService.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.service; - -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleExceptionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleRuleDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleExceptionVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleSettingVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleVO; - -import java.time.LocalDate; -import java.util.List; - -public interface ArtistScheduleService { - ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto); - - List listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate); - - ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId); - - ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto); - - ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/NailArtistInfoService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/NailArtistInfoService.java deleted file mode 100644 index 77834597..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/NailArtistInfoService.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistAvailabilityVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistProfileVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistReviewVO; - -import java.util.List; - -/** - * 美甲师信息服务 - */ -public interface NailArtistInfoService extends IService { - /** - * 根据用户ID获取美甲师信息 - * @param userId 用户ID - * @return 美甲师信息 - */ - NailArtistInfoDTO getByUserId(Long userId); - - /** - * 获取所有美甲师信息 - * @return 美甲师信息列表 - */ - List getAllNailArtists(); - - /** - * 根据店铺ID获取美甲师信息 - * @param shopId 店铺ID - * @return 美甲师信息列表 - */ - List getByShopId(Long shopId); - - /** - * 保存或更新美甲师信息 - * @param nailArtistInfoDTO 美甲师信息DTO - * @return 保存后的美甲师信息 - */ - NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO); - - /** - * 获取所有可用的美甲师信息(前台使用) - * @return 美甲师信息列表 - */ - List getAllAvailableNailArtists(); - - NailArtistProfileVO getPublicProfile(Long artistId); - - List getAvailability(Long artistId); - - List listPublicReviews(Long artistId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java deleted file mode 100644 index c6c36fb5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java +++ /dev/null @@ -1,423 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleExceptionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleRuleDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleExceptionDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleRuleDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleExceptionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleRuleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.service.ArtistScheduleService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleExceptionVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleSettingVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -public class ArtistScheduleServiceImpl implements ArtistScheduleService { - - private static final int GENERATED_DAYS = 60; - private static final int DEFAULT_SLOT_MINUTES = 60; - private static final int DEFAULT_CAPACITY = 1; - private static final String PRESET_SINGLE_REST = "SINGLE_REST"; - private static final String PRESET_DOUBLE_REST = "DOUBLE_REST"; - private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE"; - private static final String PRESET_LATE_SHIFT = "LATE_SHIFT"; - private static final String PRESET_CUSTOM = "CUSTOM"; - private static final String EXCEPTION_REST = "REST"; - private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK"; - private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT"; - - private final ArtistScheduleMapper artistScheduleMapper; - private final ArtistScheduleRuleMapper ruleMapper; - private final ArtistScheduleExceptionMapper exceptionMapper; - private final AppointmentReservationMapper reservationMapper; - - @Override - @Transactional - public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) { - if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null - || dto.getStartTime() == null || dto.getEndTime() == null) { - throw new RuntimeException("排班信息不完整"); - } - ArtistScheduleDO schedule = new ArtistScheduleDO(); - BeanUtils.copyProperties(dto, schedule); - schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes()); - schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity()); - schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); - schedule.setIsDelete(0); - ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime()); - if (existing == null) { - artistScheduleMapper.insert(schedule); - } else { - schedule.setId(existing.getId()); - artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(), - schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark()); - } - return toVO(schedule); - } - - @Override - public List listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(ArtistScheduleDO::getIsDelete, 0) - .orderByAsc(ArtistScheduleDO::getWorkDate) - .orderByAsc(ArtistScheduleDO::getStartTime); - if (shopId != null) { - wrapper.eq(ArtistScheduleDO::getShopId, shopId); - } - if (artistId != null) { - wrapper.eq(ArtistScheduleDO::getArtistId, artistId); - } - if (startDate != null) { - wrapper.ge(ArtistScheduleDO::getWorkDate, startDate); - } - if (endDate != null) { - wrapper.le(ArtistScheduleDO::getWorkDate, endDate); - } - return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList(); - } - - private ArtistScheduleVO toVO(ArtistScheduleDO schedule) { - ArtistScheduleVO vo = new ArtistScheduleVO(); - BeanUtils.copyProperties(schedule, vo); - return vo; - } - - @Override - public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) { - if (shopId == null || artistId == null) { - throw new RuntimeException("排班规则查询参数不完整"); - } - ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO(); - ArtistScheduleRuleDO rule = selectRule(shopId, artistId); - setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule)); - setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L)) - .stream() - .map(this::toExceptionVO) - .toList()); - return setting; - } - - @Override - @Transactional - public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) { - ArtistScheduleRuleDO normalized = normalizeRule(dto); - ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId()); - if (existing == null) { - ruleMapper.insert(normalized); - } else { - normalized.setId(existing.getId()); - ruleMapper.updateById(normalized); - } - refreshGeneratedSchedules(normalized); - return toRuleVO(normalized); - } - - @Override - @Transactional - public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) { - ArtistScheduleExceptionDO normalized = normalizeException(dto); - ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId()); - if (rule == null) { - rule = defaultRule(normalized.getShopId(), normalized.getArtistId()); - } - ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate()); - if (existing == null) { - exceptionMapper.insert(normalized); - } else { - normalized.setId(existing.getId()); - exceptionMapper.updateById(normalized); - } - refreshScheduleForDate(rule, normalized, normalized.getWorkDate()); - return toExceptionVO(normalized); - } - - private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) { - if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) { - throw new RuntimeException("排班规则信息不完整"); - } - String presetType = normalizePresetType(dto.getPresetType()); - LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime(); - LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime(); - validateTimeRange(startTime, endTime); - ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO(); - rule.setShopId(dto.getShopId()); - rule.setArtistId(dto.getArtistId()); - rule.setPresetType(presetType); - rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType))); - rule.setStartTime(startTime); - rule.setEndTime(endTime); - rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); - rule.setCapacity(DEFAULT_CAPACITY); - rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); - rule.setRemark(trimText(dto.getRemark())); - rule.setIsDelete(0); - return rule; - } - - private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) { - if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) { - throw new RuntimeException("排班例外信息不完整"); - } - String exceptionType = normalizeExceptionType(dto.getExceptionType()); - LocalTime startTime = dto.getStartTime(); - LocalTime endTime = dto.getEndTime(); - if (!EXCEPTION_REST.equals(exceptionType)) { - if (startTime == null || endTime == null) { - throw new RuntimeException("临时上班或改班必须填写开始和结束时间"); - } - validateTimeRange(startTime, endTime); - } - ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO(); - exception.setShopId(dto.getShopId()); - exception.setArtistId(dto.getArtistId()); - exception.setWorkDate(dto.getWorkDate()); - exception.setExceptionType(exceptionType); - exception.setStartTime(startTime); - exception.setEndTime(endTime); - exception.setSlotMinutes(DEFAULT_SLOT_MINUTES); - exception.setCapacity(DEFAULT_CAPACITY); - exception.setRemark(trimText(dto.getRemark())); - exception.setIsDelete(0); - return exception; - } - - private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) { - return ruleMapper.selectOne(new LambdaQueryWrapper() - .eq(ArtistScheduleRuleDO::getShopId, shopId) - .eq(ArtistScheduleRuleDO::getArtistId, artistId) - .eq(ArtistScheduleRuleDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) { - return exceptionMapper.selectOne(new LambdaQueryWrapper() - .eq(ArtistScheduleExceptionDO::getShopId, shopId) - .eq(ArtistScheduleExceptionDO::getArtistId, artistId) - .eq(ArtistScheduleExceptionDO::getWorkDate, workDate) - .eq(ArtistScheduleExceptionDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - private List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { - return exceptionMapper.selectList(new LambdaQueryWrapper() - .eq(ArtistScheduleExceptionDO::getShopId, shopId) - .eq(ArtistScheduleExceptionDO::getArtistId, artistId) - .eq(ArtistScheduleExceptionDO::getIsDelete, 0) - .between(ArtistScheduleExceptionDO::getWorkDate, start, end) - .orderByAsc(ArtistScheduleExceptionDO::getWorkDate)); - } - - private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) { - LocalDate start = LocalDate.now(); - LocalDate end = start.plusDays(GENERATED_DAYS - 1L); - Map exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end) - .stream() - .collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a)); - LocalDate cursor = start; - while (!cursor.isAfter(end)) { - refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor); - cursor = cursor.plusDays(1L); - } - } - - private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) { - GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate); - if (!generated.working()) { - assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate); - upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark()); - return; - } - assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime()); - upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark()); - } - - private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) { - if (exception != null) { - if (EXCEPTION_REST.equals(exception.getExceptionType())) { - return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception)); - } - if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) { - return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception)); - } - } - boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue()); - return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班"); - } - - private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime, - Integer slotMinutes, Integer capacity, Integer status, String remark) { - ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate); - if (schedule == null) { - schedule = new ArtistScheduleDO(); - schedule.setShopId(rule.getShopId()); - schedule.setArtistId(rule.getArtistId()); - schedule.setWorkDate(workDate); - schedule.setStartTime(startTime); - schedule.setEndTime(endTime); - schedule.setSlotMinutes(slotMinutes); - schedule.setCapacity(capacity); - schedule.setStatus(status); - schedule.setRemark(remark); - schedule.setIsDelete(0); - artistScheduleMapper.insert(schedule); - return; - } - artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark); - } - - private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) { - int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate); - if (count > 0) { - throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count); - } - } - - private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) { - int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime); - if (count > 0) { - throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count); - } - } - - private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) { - return toRuleVO(defaultRule(shopId, artistId)); - } - - private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) { - ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO(); - rule.setShopId(shopId); - rule.setArtistId(artistId); - rule.setPresetType(PRESET_DOUBLE_REST); - rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5))); - rule.setStartTime(LocalTime.of(9, 0)); - rule.setEndTime(LocalTime.of(17, 0)); - rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); - rule.setCapacity(DEFAULT_CAPACITY); - rule.setStatus(1); - rule.setIsDelete(0); - return rule; - } - - private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) { - ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO(); - BeanUtils.copyProperties(rule, vo); - vo.setWorkDays(decodeWorkDays(rule.getWorkDays())); - return vo; - } - - private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) { - ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO(); - BeanUtils.copyProperties(exception, vo); - return vo; - } - - private String normalizePresetType(String presetType) { - String value = trimText(presetType); - if (value == null || value.isBlank()) { - return PRESET_CUSTOM; - } - return value; - } - - private String normalizeExceptionType(String exceptionType) { - String value = trimText(exceptionType); - if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) { - return value; - } - throw new RuntimeException("不支持的排班例外类型:" + value); - } - - private List resolveWorkDays(List inputWorkDays, String presetType) { - List presetDays = switch (presetType) { - case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5); - case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6); - default -> inputWorkDays; - }; - Set normalized = new LinkedHashSet<>(); - for (Integer day : presetDays == null ? List.of() : presetDays) { - if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) { - normalized.add(day); - } - } - if (normalized.isEmpty()) { - throw new RuntimeException("请至少选择一个工作日"); - } - return normalized.stream().sorted().toList(); - } - - private String encodeWorkDays(List workDays) { - return workDays.stream() - .sorted() - .map(String::valueOf) - .collect(Collectors.joining(",")); - } - - private List decodeWorkDays(String workDays) { - if (workDays == null || workDays.isBlank()) { - return new ArrayList<>(); - } - return List.of(workDays.split(",")).stream() - .map(String::trim) - .filter(value -> !value.isBlank()) - .map(Integer::valueOf) - .sorted() - .toList(); - } - - private LocalTime presetStartTime(String presetType) { - if (PRESET_NINE_TO_FIVE.equals(presetType)) { - return LocalTime.of(9, 0); - } - return LocalTime.of(10, 0); - } - - private LocalTime presetEndTime(String presetType) { - if (PRESET_NINE_TO_FIVE.equals(presetType)) { - return LocalTime.of(17, 0); - } - return LocalTime.of(22, 0); - } - - private void validateTimeRange(LocalTime startTime, LocalTime endTime) { - if (startTime == null || endTime == null || !startTime.isBefore(endTime)) { - throw new RuntimeException("排班开始时间必须早于结束时间"); - } - } - - private String trimText(String value) { - return value == null ? null : value.trim(); - } - - private String exceptionRemark(ArtistScheduleExceptionDO exception) { - if (exception.getRemark() != null && !exception.getRemark().isBlank()) { - return exception.getRemark(); - } - return "例外排班:" + exception.getExceptionType(); - } - - private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes, - Integer capacity, String remark) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java deleted file mode 100644 index 7c3ef932..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java +++ /dev/null @@ -1,831 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleRuleDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistReviewDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleRuleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistReviewMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.service.NailArtistInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistAvailabilityVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistProfileVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistReviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistWorkVO; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -/** - * NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class NailArtistInfoServiceImpl extends ServiceImpl implements NailArtistInfoService { - - private static final int REVIEW_STATUS_SUBMITTED = 1; - private static final int ORDER_STATUS_COMPLETED = 2; - private static final int AVAILABILITY_DAYS = 7; - private static final int SLOT_MINUTES = 60; - private static final int MAX_AVAILABILITY_SLOTS = 16; - private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; - private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm"); - private static final String PRESET_DOUBLE_REST = "DOUBLE_REST"; - private static final String PRESET_SINGLE_REST = "SINGLE_REST"; - - @Autowired - /** - * Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserMapper userMapper; - - @Autowired - /** - * Purpose: shopMapper supports NailArtistInfoServiceImpl.java by holding or executing the shop mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ShopMapper shopMapper; - - @Autowired - /** - * Purpose: userShopBindingSupport supports NailArtistInfoServiceImpl.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserShopBindingSupport userShopBindingSupport; - - @Autowired - private ProductMapper productMapper; - - @Autowired - private OrderMapper orderMapper; - - @Autowired - private OrderItemMapper orderItemMapper; - - @Autowired - private OrderArtistReviewMapper orderArtistReviewMapper; - - @Autowired - private ObjectStorageFileService objectStorageFileService; - - @Autowired - private ObjectStorageUrlSupport objectStorageUrlSupport; - - @Autowired(required = false) - private ArtistScheduleMapper artistScheduleMapper; - - @Autowired(required = false) - private ArtistScheduleRuleMapper artistScheduleRuleMapper; - - @Autowired(required = false) - private AppointmentReservationMapper appointmentReservationMapper; - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend - */ - public NailArtistInfoDTO getByUserId(Long userId) { - NailArtistInfoDO info = getOne(new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getUserId, userId) - .eq(NailArtistInfoDO::getIsDelete, 0) - .last("LIMIT 1")); - return info == null ? null : convertToDTO(info); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List getAllNailArtists() { - List result = new ArrayList<>(); - List records = list(new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getIsDelete, 0)); - for (NailArtistInfoDO record : records) { - NailArtistInfoDTO dto = convertToDTO(record); - if (isVisibleServiceUser(dto)) { - result.add(dto); - } - } - enrichScheduleSummaries(result, null); - return result; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getByShopId(Long shopId) { - List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); - if (serviceUserIds.isEmpty()) { - return new ArrayList<>(); - } - - List users = userMapper.selectList(new LambdaQueryWrapper() - .in(UserDO::getId, serviceUserIds) - .eq(UserDO::getType, 3) - .eq(UserDO::getStatus, 1) - .eq(UserDO::getIsDelete, 0) - .orderByAsc(UserDO::getCreateTime) - .orderByAsc(UserDO::getId)); - List result = new ArrayList<>(); - ShopDO shop = shopMapper.selectById(shopId); - for (UserDO user : users) { - NailArtistInfoDTO dto = getByUserId(user.getId()); - if (dto == null) { - dto = buildFallbackArtistInfo(user); - } - dto.setShopId(shopId); - dto.setShopName(shop == null ? null : shop.getShopName()); - result.add(dto); - } - enrichScheduleSummaries(result, shopId); - return result; - } - - @Override - /** - * Save submitted data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param dto parameter `dto` supplied by the caller - * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend - */ - public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) { - NailArtistInfoDO entity = new NailArtistInfoDO(); - BeanUtils.copyProperties(dto, entity); - - NailArtistInfoDO existing = getOne(new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getUserId, dto.getUserId()) - .eq(NailArtistInfoDO::getIsDelete, 0) - .last("LIMIT 1")); - if (existing != null) { - entity.setId(existing.getId()); - } - if (entity.getStatus() == null) { - entity.setStatus(1); - } - if (entity.getParticipateProduction() == null) { - UserDO user = userMapper.selectById(dto.getUserId()); - entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0); - } - - /** - * Save submitted data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param entity parameter `entity` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - saveOrUpdate(entity); - /** - * Run business method `convertToDTO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param entity parameter `entity` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToDTO(entity); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List getAllAvailableNailArtists() { - List result = new ArrayList<>(); - List records = list(new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getStatus, 1) - .eq(NailArtistInfoDO::getIsDelete, 0)); - for (NailArtistInfoDO record : records) { - NailArtistInfoDTO dto = convertToDTO(record); - if (isBookableServiceUser(dto)) { - result.add(dto); - } - } - return result; - } - - @Override - public NailArtistProfileVO getPublicProfile(Long artistId) { - NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); - UserDO artist = userMapper.selectById(artistId); - if (artist == null || isDeleted(artist.getIsDelete())) { - throw new RuntimeException("美甲师信息不存在"); - } - - List servedItems = loadArtistOrderItems(artistId, true); - List reviews = listPublicReviews(artistId); - NailArtistProfileVO profile = new NailArtistProfileVO(); - profile.setArtistId(artistId); - profile.setArtistName(resolveArtistName(artistInfo, artist)); - profile.setAvatar(artist.getAvatar()); - profile.setIdentity(artistInfo.getIdentity()); - profile.setSignature(artistInfo.getSignature()); - profile.setExperience(artistInfo.getExperience()); - profile.setStatus(artistInfo.getStatus()); - profile.setShopId(artistInfo.getShopId()); - profile.setShopName(artistInfo.getShopName()); - profile.setRating(resolvePublicRating(artistId, artistInfo)); - profile.setServiceCount(countServiceQuantity(servedItems)); - profile.setWorkStartTime(artistInfo.getWorkStartTime()); - profile.setWorkEndTime(artistInfo.getWorkEndTime()); - profile.setStyleTags(parseTextTokens(artistInfo.getSkills())); - profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 24)); - profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList())); - profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList())); - return profile; - } - - @Override - public List getAvailability(Long artistId) { - NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); - if (!Integer.valueOf(1).equals(artistInfo.getStatus())) { - return new ArrayList<>(); - } - - List scheduleSlots = buildScheduleAvailabilitySlots(artistId, artistInfo); - if (!scheduleSlots.isEmpty()) { - return scheduleSlots; - } - - LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime(); - LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime(); - if (!workEnd.isAfter(workStart)) { - workStart = LocalTime.of(10, 0); - workEnd = LocalTime.of(20, 0); - } - - LocalDate today = LocalDate.now(); - LocalDateTime rangeStart = today.atStartOfDay(); - LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay(); - Set bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd); - LocalDateTime now = LocalDateTime.now(); - List slots = new ArrayList<>(); - - for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) { - LocalDate date = today.plusDays(dayOffset); - LocalTime cursor = workStart; - while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) { - LocalDateTime slotStart = date.atTime(cursor); - LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES); - if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) { - slots.add(buildAvailabilitySlot(slotStart, slotEnd)); - } - cursor = cursor.plusMinutes(SLOT_MINUTES); - } - } - return slots; - } - - private List buildScheduleAvailabilitySlots(Long artistId, NailArtistInfoDTO artistInfo) { - if (artistScheduleMapper == null || artistInfo.getShopId() == null) { - return new ArrayList<>(); - } - LocalDate today = LocalDate.now(); - List schedules = artistScheduleMapper.selectList(new LambdaQueryWrapper() - .eq(ArtistScheduleDO::getShopId, artistInfo.getShopId()) - .eq(ArtistScheduleDO::getArtistId, artistId) - .eq(ArtistScheduleDO::getStatus, 1) - .eq(ArtistScheduleDO::getIsDelete, 0) - .ge(ArtistScheduleDO::getWorkDate, today) - .lt(ArtistScheduleDO::getWorkDate, today.plusDays(AVAILABILITY_DAYS)) - .orderByAsc(ArtistScheduleDO::getWorkDate) - .orderByAsc(ArtistScheduleDO::getStartTime)); - if (schedules == null || schedules.isEmpty()) { - return new ArrayList<>(); - } - LocalDateTime minStart = LocalDateTime.now().plusMinutes(30); - List slots = new ArrayList<>(); - for (ArtistScheduleDO schedule : schedules) { - int slotMinutes = schedule.getSlotMinutes() == null || schedule.getSlotMinutes() < 15 ? SLOT_MINUTES : schedule.getSlotMinutes(); - int capacity = schedule.getCapacity() == null || schedule.getCapacity() < 1 ? 1 : schedule.getCapacity(); - LocalTime cursor = schedule.getStartTime(); - while (cursor != null && schedule.getEndTime() != null - && !cursor.plusMinutes(slotMinutes).isAfter(schedule.getEndTime()) - && slots.size() < MAX_AVAILABILITY_SLOTS) { - LocalDateTime slotStart = schedule.getWorkDate().atTime(cursor); - LocalDateTime slotEnd = slotStart.plusMinutes(slotMinutes); - int used = appointmentReservationMapper == null ? 0 - : appointmentReservationMapper.countOverlappingActive(artistId, slotStart, slotEnd); - if (slotStart.isAfter(minStart) && used < capacity) { - slots.add(buildAvailabilitySlot(slotStart, slotEnd)); - } - cursor = cursor.plusMinutes(slotMinutes); - } - if (slots.size() >= MAX_AVAILABILITY_SLOTS) { - break; - } - } - return slots; - } - - @Override - public List listPublicReviews(Long artistId) { - if (artistId == null) { - return new ArrayList<>(); - } - List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() - .eq(OrderArtistReviewDO::getArtistId, artistId) - .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) - .eq(OrderArtistReviewDO::getIsDelete, 0) - .orderByDesc(OrderArtistReviewDO::getSubmittedAt) - .orderByDesc(OrderArtistReviewDO::getId)); - if (reviews == null || reviews.isEmpty()) { - return new ArrayList<>(); - } - - List limitedReviews = reviews.stream().limit(20).collect(Collectors.toList()); - Map customerMap = loadUsers(limitedReviews.stream() - .map(OrderArtistReviewDO::getCustomerId) - .collect(Collectors.toCollection(LinkedHashSet::new))); - Map productMap = loadProducts(limitedReviews.stream() - .map(OrderArtistReviewDO::getProductId) - .collect(Collectors.toCollection(LinkedHashSet::new))); - Set imageIds = new LinkedHashSet<>(); - for (OrderArtistReviewDO review : limitedReviews) { - imageIds.addAll(parseLongTokens(review.getImageFileIds())); - } - Map fileMap = loadFiles(imageIds); - - List result = new ArrayList<>(); - for (OrderArtistReviewDO review : limitedReviews) { - result.add(buildReviewVO(review, customerMap, productMap, fileMap)); - } - return result; - } - - /** - * Run business method `convertToDTO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param entity parameter `entity` supplied by the caller - * @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend - */ - private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) { - NailArtistInfoDTO dto = new NailArtistInfoDTO(); - BeanUtils.copyProperties(entity, dto); - - UserDO user = userMapper.selectById(entity.getUserId()); - if (user != null) { - dto.setNickname(user.getNickname()); - dto.setSignature(user.getSignature()); - dto.setAvatar(resolveAccessibleAvatar(user.getAvatar())); - dto.setUserType(user.getType()); - dto.setUserTypeName(resolveUserTypeName(user.getType())); - if (dto.getParticipateProduction() == null) { - dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0); - } - - List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); - if (!shopOptions.isEmpty()) { - ShopSimpleVO primaryShop = shopOptions.get(0); - dto.setShopId(primaryShop.getId()); - dto.setShopName(primaryShop.getShopName()); - } else if (user.getShopId() != null && user.getShopId() > 0) { - ShopDO shop = shopMapper.selectById(user.getShopId()); - if (shop != null) { - dto.setShopId(shop.getId()); - dto.setShopName(shop.getShopName()); - } - } - } - return dto; - } - - private NailArtistInfoDTO buildFallbackArtistInfo(UserDO user) { - NailArtistInfoDTO dto = new NailArtistInfoDTO(); - dto.setUserId(user.getId()); - dto.setNickname(user.getNickname()); - dto.setSignature(user.getSignature()); - dto.setAvatar(resolveAccessibleAvatar(user.getAvatar())); - dto.setUserType(user.getType()); - dto.setUserTypeName(resolveUserTypeName(user.getType())); - dto.setIdentity("美甲师"); - dto.setStatus(1); - dto.setParticipateProduction(1); - dto.setShopId(user.getShopId()); - List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); - if (!shopOptions.isEmpty()) { - ShopSimpleVO primaryShop = shopOptions.get(0); - dto.setShopId(primaryShop.getId()); - dto.setShopName(primaryShop.getShopName()); - } else if (user.getShopId() != null && user.getShopId() > 0) { - ShopDO shop = shopMapper.selectById(user.getShopId()); - if (shop != null) { - dto.setShopId(shop.getId()); - dto.setShopName(shop.getShopName()); - } - } - return dto; - } - - private void enrichScheduleSummaries(List artists, Long shopId) { - if (artistScheduleRuleMapper == null || artists == null || artists.isEmpty()) { - return; - } - Set artistIds = artists.stream() - .map(NailArtistInfoDTO::getUserId) - .filter(userId -> userId != null && userId > 0) - .collect(Collectors.toCollection(LinkedHashSet::new)); - if (artistIds.isEmpty()) { - return; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .in(ArtistScheduleRuleDO::getArtistId, artistIds) - .eq(ArtistScheduleRuleDO::getIsDelete, 0); - if (shopId != null && shopId > 0) { - wrapper.eq(ArtistScheduleRuleDO::getShopId, shopId); - } - Map ruleByArtistId = artistScheduleRuleMapper.selectList(wrapper).stream() - .collect(Collectors.toMap(ArtistScheduleRuleDO::getArtistId, rule -> rule, (left, right) -> left)); - artists.forEach(artist -> applyScheduleSummary(artist, ruleByArtistId.get(artist.getUserId()))); - } - - private void applyScheduleSummary(NailArtistInfoDTO artist, ArtistScheduleRuleDO rule) { - if (artist == null) { - return; - } - if (rule == null || !Integer.valueOf(1).equals(rule.getStatus())) { - artist.setScheduleModeSummary("未设置"); - artist.setScheduleTimeSummary(""); - return; - } - artist.setScheduleModeSummary(resolveScheduleModeSummary(rule.getPresetType())); - artist.setScheduleTimeSummary(formatScheduleTimeSummary(rule.getStartTime(), rule.getEndTime())); - } - - private String resolveScheduleModeSummary(String presetType) { - if (PRESET_DOUBLE_REST.equals(presetType)) { - return "双休"; - } - if (PRESET_SINGLE_REST.equals(presetType)) { - return "单休"; - } - return "自定义"; - } - - private String formatScheduleTimeSummary(LocalTime startTime, LocalTime endTime) { - if (startTime == null || endTime == null) { - return ""; - } - return TIME_TEXT_FORMATTER.format(startTime) + "-" + TIME_TEXT_FORMATTER.format(endTime); - } - - private String resolveAccessibleAvatar(String avatar) { - if (!StringUtils.hasText(avatar)) { - return null; - } - String accessibleUrl = objectStorageUrlSupport.toAccessibleUrl(avatar); - return StringUtils.hasText(accessibleUrl) ? accessibleUrl : avatar; - } - - /** - * Run business method `isVisibleServiceUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param dto parameter `dto` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isVisibleServiceUser(NailArtistInfoDTO dto) { - if (dto == null || dto.getUserType() == null) { - return false; - } - return Integer.valueOf(3).equals(dto.getUserType()) - || Integer.valueOf(2).equals(dto.getUserType()); - } - - /** - * Run business method `isBookableServiceUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param dto parameter `dto` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isBookableServiceUser(NailArtistInfoDTO dto) { - return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus()); - } - - /** - * Run business method `resolveUserTypeName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param type parameter `type` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveUserTypeName(Integer type) { - if (Integer.valueOf(2).equals(type)) { - return "店长"; - } - if (Integer.valueOf(3).equals(type)) { - return "美甲师"; - } - return "用户"; - } - - private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) { - if (artistId == null) { - throw new RuntimeException("美甲师信息不存在"); - } - NailArtistInfoDTO artistInfo = getByUserId(artistId); - if (artistInfo != null && isVisibleServiceUser(artistInfo)) { - return artistInfo; - } - UserDO artist = userMapper.selectById(artistId); - if (artist == null - || isDeleted(artist.getIsDelete()) - || !Integer.valueOf(3).equals(artist.getType()) - || !Integer.valueOf(1).equals(artist.getStatus())) { - throw new RuntimeException("美甲师信息不存在"); - } - return buildFallbackArtistInfo(artist); - } - - private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) { - BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); - BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating; - if (rating == null) { - return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); - } - return rating.setScale(1, RoundingMode.HALF_UP); - } - - private List loadArtistOrderItems(Long artistId, boolean completedOnly) { - List orders = orderMapper.selectByArtistId(artistId); - if (orders == null || orders.isEmpty()) { - return new ArrayList<>(); - } - - Set allowedOrderIds = orders.stream() - .filter(order -> !isDeleted(order.getIsDelete())) - .filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus())) - .map(OrderDO::getId) - .collect(Collectors.toCollection(LinkedHashSet::new)); - if (allowedOrderIds.isEmpty()) { - return new ArrayList<>(); - } - - List items = new ArrayList<>(); - for (Long orderId : allowedOrderIds) { - List orderItems = orderItemMapper.selectByOrderId(orderId); - if (orderItems == null) { - continue; - } - for (OrderItemDO item : orderItems) { - if (item != null - && artistId.equals(item.getArtistId()) - && !isDeleted(item.getIsDelete())) { - items.add(item); - } - } - } - return items; - } - - private long countServiceQuantity(List items) { - if (items == null || items.isEmpty()) { - return 0L; - } - long count = 0L; - for (OrderItemDO item : items) { - if (item == null) { - continue; - } - count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity(); - } - return count; - } - - private List buildWorks(String portfolio, List servedItems, int limit) { - LinkedHashSet productIds = new LinkedHashSet<>(parseLongTokens(portfolio)); - if (servedItems != null) { - servedItems.stream() - .sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) - .map(OrderItemDO::getProductId) - .filter(productId -> productId != null && productId > 0) - .forEach(productIds::add); - } - if (productIds.isEmpty()) { - return new ArrayList<>(); - } - - List limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList()); - Map productMap = loadProducts(new LinkedHashSet<>(limitedIds)); - Set fileIds = new LinkedHashSet<>(); - for (ProductDO product : productMap.values()) { - fileIds.addAll(parseLongTokens(product.getImageFileIds())); - } - Map fileMap = loadFiles(fileIds); - - List works = new ArrayList<>(); - for (Long productId : limitedIds) { - ProductDO product = productMap.get(productId); - if (product == null || isDeleted(product.getIsDelete()) || !isFrontVisible(product)) { - continue; - } - works.add(buildWorkVO(product, fileMap)); - } - return works; - } - - private NailArtistWorkVO buildWorkVO(ProductDO product, Map fileMap) { - NailArtistWorkVO work = new NailArtistWorkVO(); - work.setId(product.getId()); - work.setTitle(product.getTitle()); - work.setDescription(product.getDescription()); - work.setPrice(product.getPrice()); - work.setTags(parseTextTokens(product.getTags())); - work.setLikeCount(product.getLikeCount()); - work.setCollectCount(product.getCollectCount()); - List imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap); - work.setImageUrls(imageUrls); - work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0)); - return work; - } - - private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review, - Map customerMap, - Map productMap, - Map fileMap) { - NailArtistReviewVO vo = new NailArtistReviewVO(); - vo.setId(review.getId()); - vo.setArtistId(review.getArtistId()); - vo.setCustomerId(review.getCustomerId()); - UserDO customer = customerMap.get(review.getCustomerId()); - vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname()); - vo.setCustomerAvatar(customer == null ? null : customer.getAvatar()); - vo.setProductId(review.getProductId()); - ProductDO product = productMap.get(review.getProductId()); - vo.setProductTitle(product == null ? null : product.getTitle()); - vo.setRating(review.getRatingScore()); - vo.setContent(review.getContent()); - List imageFileIds = parseLongTokens(review.getImageFileIds()); - vo.setImageFileIds(imageFileIds); - vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap)); - vo.setSubmittedAt(review.getSubmittedAt()); - return vo; - } - - private Set loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) { - List bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd); - if (bookedItems == null || bookedItems.isEmpty()) { - return new HashSet<>(); - } - return bookedItems.stream() - .map(OrderItemDO::getAppointmentTime) - .filter(appointmentTime -> appointmentTime != null) - .map(this::truncateToMinute) - .collect(Collectors.toSet()); - } - - private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) { - NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO(); - slot.setStartTime(startTime); - slot.setEndTime(endTime); - slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate())); - slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime())); - slot.setAvailable(true); - return slot; - } - - private Map loadProducts(Set productIds) { - if (productIds == null || productIds.isEmpty()) { - return new HashMap<>(); - } - List products = productMapper.selectBatchIds(productIds); - if (products == null || products.isEmpty()) { - return new HashMap<>(); - } - return products.stream() - .filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete()) && isFrontVisible(product)) - .collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new)); - } - - private Map loadUsers(Set userIds) { - if (userIds == null || userIds.isEmpty()) { - return new HashMap<>(); - } - List users = userMapper.selectBatchIds(new ArrayList<>(userIds)); - if (users == null || users.isEmpty()) { - return new HashMap<>(); - } - return users.stream() - .filter(user -> user != null && user.getId() != null) - .collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new)); - } - - private Map loadFiles(Set fileIds) { - if (fileIds == null || fileIds.isEmpty()) { - return new HashMap<>(); - } - Map files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); - return files == null ? new HashMap<>() : files; - } - - private List resolveImageUrls(List fileIds, Map fileMap) { - if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { - return new ArrayList<>(); - } - List urls = new ArrayList<>(); - for (Long fileId : fileIds) { - ObjectStorageFileVO file = fileMap.get(fileId); - if (file != null && StringUtils.hasText(file.getFileUrl())) { - urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); - } - } - return urls; - } - - private List parseLongTokens(String raw) { - if (!StringUtils.hasText(raw)) { - return new ArrayList<>(); - } - LinkedHashSet ids = new LinkedHashSet<>(); - for (String token : raw.split("[,;,;\\s]+")) { - if (!StringUtils.hasText(token)) { - continue; - } - try { - ids.add(Long.parseLong(token.trim())); - } catch (NumberFormatException ignored) { - // Some legacy fields store tag names instead of ids. - } - } - return new ArrayList<>(ids); - } - - private List parseTextTokens(String raw) { - if (!StringUtils.hasText(raw)) { - return new ArrayList<>(); - } - LinkedHashSet tokens = new LinkedHashSet<>(); - for (String token : raw.split("[,;,;、\\s]+")) { - if (StringUtils.hasText(token)) { - tokens.add(token.trim()); - } - } - return new ArrayList<>(tokens); - } - - private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) { - if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) { - return artistInfo.getNickname(); - } - if (artist != null && StringUtils.hasText(artist.getNickname())) { - return artist.getNickname(); - } - return "美甲师"; - } - - private boolean isDeleted(Integer isDelete) { - return Integer.valueOf(1).equals(isDelete); - } - - private boolean isFrontVisible(ProductDO product) { - return product != null && Integer.valueOf(1).equals(product.getFrontVisible()); - } - - private LocalDateTime truncateToMinute(LocalDateTime value) { - return value == null ? null : value.withSecond(0).withNano(0); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/support/BookableArtistSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/support/BookableArtistSupport.java deleted file mode 100644 index 2db833da..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/support/BookableArtistSupport.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.support; - -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; - -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.stream.Collectors; - -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -@Component -@RequiredArgsConstructor -/** - * Purpose: BookableArtistSupport supports BookableArtistSupport.java by holding or executing the bookable artist support business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class BookableArtistSupport { - - /** - * Purpose: userMapper supports BookableArtistSupport.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserMapper userMapper; - /** - * Purpose: nailArtistInfoMapper supports BookableArtistSupport.java by holding or executing the nail artist info mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final NailArtistInfoMapper nailArtistInfoMapper; - /** - * Purpose: userShopBindingSupport supports BookableArtistSupport.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserShopBindingSupport userShopBindingSupport; - - /** - * Purpose: isValidBookableArtist supports BookableArtistSupport.java by holding or executing the is valid bookable artist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isValidBookableArtist(Long shopId, Long artistId) { - if (artistId == null || artistId <= 0) { - return false; - } - - UserDO artist = userMapper.selectById(artistId); - if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { - return false; - } - if (!isBookableServiceUser(artist)) { - return false; - } - if (!Integer.valueOf(1).equals(artist.getStatus())) { - return false; - } - return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId); - } - - /** - * Purpose: isBookableServiceUser supports BookableArtistSupport.java by holding or executing the is bookable service user business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isBookableServiceUser(UserDO user) { - if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { - return false; - } - if (Integer.valueOf(3).equals(user.getType())) { - return true; - } - if (!Integer.valueOf(2).equals(user.getType())) { - return false; - } - NailArtistInfoDO info = nailArtistInfoMapper.selectOne( - new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getUserId, user.getId()) - .eq(NailArtistInfoDO::getIsDelete, 0) - .last("LIMIT 1") - ); - return info != null - && Integer.valueOf(1).equals(info.getStatus()) - && Integer.valueOf(1).equals(info.getParticipateProduction()); - } - - /** - * Purpose: filterValidBookableArtists supports BookableArtistSupport.java by holding or executing the filter valid bookable artists business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String filterValidBookableArtists(Long shopId, String rawBookableArtists) { - if (!StringUtils.hasText(rawBookableArtists)) { - return ""; - } - - Set validArtistIds = new LinkedHashSet<>(); - for (String artistIdText : rawBookableArtists.split(",")) { - if (!StringUtils.hasText(artistIdText)) { - continue; - } - try { - Long artistId = Long.parseLong(artistIdText.trim()); - if (isValidBookableArtist(shopId, artistId)) { - validArtistIds.add(artistId); - } - } catch (NumberFormatException ignored) { - // Ignore invalid configured IDs and only expose currently valid artists. - } - } - - return validArtistIds.stream() - .map(String::valueOf) - .collect(Collectors.joining(",")); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistCalendarAppointmentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistCalendarAppointmentVO.java deleted file mode 100644 index 8350718b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistCalendarAppointmentVO.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -/** - * ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ArtistCalendarAppointmentVO { - /** - * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long orderId; - /** - * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String orderNo; - /** - * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalAmount; - /** - * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal actualAmount; - /** - * Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer orderStatus; - /** - * Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String orderStatusText; - /** - * Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long orderItemId; - /** - * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long productId; - /** - * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String productTitle; - /** - * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long artistId; - /** - * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String artistName; - /** - * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String customerNickname; - /** - * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String customerPhoneMasked; - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - /** - * Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime appointmentStartTime; - /** - * Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime appointmentEndTime; - /** - * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer quantity; - /** - * Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long durationMinutes; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleExceptionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleExceptionVO.java deleted file mode 100644 index 07ad5090..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleExceptionVO.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - -@Data -public class ArtistScheduleExceptionVO { - private Long id; - private Long shopId; - private Long artistId; - private LocalDate workDate; - private String exceptionType; - private LocalTime startTime; - private LocalTime endTime; - private String remark; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java deleted file mode 100644 index 2b71aeef..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import lombok.Data; - -import java.util.List; - -@Data -public class ArtistScheduleRuleSettingVO { - private ArtistScheduleRuleVO rule; - private List exceptions; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleRuleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleRuleVO.java deleted file mode 100644 index 8cf821a8..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleRuleVO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import lombok.Data; - -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.List; - -@Data -public class ArtistScheduleRuleVO { - private Long id; - private Long shopId; - private Long artistId; - private String presetType; - private List workDays; - private LocalTime startTime; - private LocalTime endTime; - private Integer status; - private String remark; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleVO.java deleted file mode 100644 index 11d4f557..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/ArtistScheduleVO.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - -@Data -public class ArtistScheduleVO { - private Long id; - private Long shopId; - private Long artistId; - private LocalDate workDate; - private LocalTime startTime; - private LocalTime endTime; - private Integer slotMinutes; - private Integer capacity; - private Integer status; - private String remark; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistAvailabilityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistAvailabilityVO.java deleted file mode 100644 index 8597347e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistAvailabilityVO.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -public class NailArtistAvailabilityVO { - private LocalDateTime startTime; - private LocalDateTime endTime; - private String dateText; - private String timeText; - private Boolean available; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistProfileVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistProfileVO.java deleted file mode 100644 index d8d31c7e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistProfileVO.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.List; - -@Data -public class NailArtistProfileVO { - @JsonSerialize(using = ToStringSerializer.class) - private Long artistId; - private String artistName; - private String avatar; - private String identity; - private String signature; - private Integer experience; - private Integer status; - @JsonSerialize(using = ToStringSerializer.class) - private Long shopId; - private String shopName; - private BigDecimal rating; - private Long serviceCount; - private LocalTime workStartTime; - private LocalTime workEndTime; - private List styleTags = new ArrayList<>(); - private List works = new ArrayList<>(); - private List reviews = new ArrayList<>(); - private List availability = new ArrayList<>(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistReviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistReviewVO.java deleted file mode 100644 index 941d1f0f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistReviewVO.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -@Data -public class NailArtistReviewVO { - @JsonSerialize(using = ToStringSerializer.class) - private Long id; - @JsonSerialize(using = ToStringSerializer.class) - private Long artistId; - @JsonSerialize(using = ToStringSerializer.class) - private Long customerId; - private String customerName; - private String customerAvatar; - @JsonSerialize(using = ToStringSerializer.class) - private Long productId; - private String productTitle; - private BigDecimal rating; - private String content; - private List imageFileIds = new ArrayList<>(); - private List imageUrls = new ArrayList<>(); - private LocalDateTime submittedAt; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistWorkVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistWorkVO.java deleted file mode 100644 index 44005f1c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/artist/vo/NailArtistWorkVO.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.artist.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -@Data -public class NailArtistWorkVO { - @JsonSerialize(using = ToStringSerializer.class) - private Long id; - private String title; - private String description; - private BigDecimal price; - private String coverImageUrl; - private List imageUrls = new ArrayList<>(); - private List tags = new ArrayList<>(); - private Integer likeCount; - private Integer collectCount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/controller/front/LoginIdentityController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/controller/front/LoginIdentityController.java deleted file mode 100644 index 86ba2c29..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/controller/front/LoginIdentityController.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginIdentityDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginIdentityVO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.service.LoginIdentityService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户登录标识信息表 Controller - * 对应数据库表 t_login_identity - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/login-identity", "/api/login-identity"}) -@RequiredArgsConstructor -public class LoginIdentityController { - /** - * Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final LoginIdentityService loginIdentityService; - - /** - * 创建登录标识 - * - * @param loginIdentityDTO 登录标识DTO - * @return 登录标识ID - */ - @PostMapping("/create") - public Result createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) { - Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO); - return Result.success(id); - } - - /** - * 更新登录标识 - * - * @param id 登录标识ID - * @param loginIdentityDTO 登录标识DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) { - boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO); - return Result.success(success); - } - - /** - * 删除登录标识 - * - * @param id 登录标识ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteLoginIdentity(@PathVariable Long id) { - boolean success = loginIdentityService.deleteLoginIdentity(id); - return Result.success(success); - } - - /** - * 根据ID查询登录标识 - * - * @param id 登录标识ID - * @return 登录标识VO - */ - @GetMapping("/get/{id}") - public Result getLoginIdentityById(@PathVariable Long id) { - LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id); - return Result.success(loginIdentityVO); - } - - /** - * 查询所有登录标识 - * - * @return 登录标识VO列表 - */ - @GetMapping("/list/all") - public Result> listAllLoginIdentities() { - List loginIdentityVOs = loginIdentityService.listAllLoginIdentities(); - return Result.success(loginIdentityVOs); - } - - /** - * 根据用户ID查询登录标识 - * - * @param userId 用户ID - * @return 登录标识VO列表 - */ - @GetMapping("/list/user/{userId}") - public Result> listLoginIdentitiesByUserId(@PathVariable Long userId) { - List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId); - return Result.success(loginIdentityVOs); - } - - /** - * 根据登录方式查询登录标识 - * - * @param loginMethod 登录方式 - * @return 登录标识VO列表 - */ - @GetMapping("/list/loginMethod/{loginMethod}") - public Result> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) { - List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod); - return Result.success(loginIdentityVOs); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/BindEmailRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/BindEmailRequestDTO.java deleted file mode 100644 index 85033910..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/BindEmailRequestDTO.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -/** - * 绑定邮箱请求 DTO - * 用于用户绑定邮箱账号 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class BindEmailRequestDTO { - - /** - * 邮箱地址 - */ - private String email; - - /** - * 验证码 - */ - private String code; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/BindPhoneRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/BindPhoneRequestDTO.java deleted file mode 100644 index df8e75d2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/BindPhoneRequestDTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import com.fasterxml.jackson.annotation.JsonAlias; -import lombok.Data; - -/** - * 绑定手机号请求 DTO - * 用于用户绑定手机号 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class BindPhoneRequestDTO { - - /** - * 手机号 - */ - private String phone; - - /** - * 验证码 - */ - @JsonAlias("code") - private String verificationCode; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/LoginIdentityDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/LoginIdentityDTO.java deleted file mode 100644 index b8c14027..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/LoginIdentityDTO.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 用户登录标识信息表 DTO - * 用于登录标识信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class LoginIdentityDTO { - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 登录方式(0-手机号、1-账号、2-邮箱) - */ - private String loginMethod; - - /** - * 前端输入的具体值(如手机号、账号、邮箱) - */ - private String inputValue; - - /** - * 输入时间 - */ - private LocalDateTime inputTime; - - /** - * 状态:1-有效,0-无效 - */ - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/LoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/LoginRequestDTO.java deleted file mode 100644 index 40764a1d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/LoginRequestDTO.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import com.xiaowang.jacyucloudsalon.core.utils.AccountValidationUtils; -import lombok.Getter; -import lombok.Setter; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; -import java.util.Map; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -/** - * 登录请求 DTO - * 用于用户账号密码登录 - * - * @author xiaowang - * @date 2026-02-14 - */ -@Getter -@Setter -public class LoginRequestDTO implements AgreementAwareRequest { - - /** - * 账号 - */ - @NotBlank(message = "账号不能为空") - @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") - private String account; - - /** - * 密码 - */ - private String password; - - /** - * 记住我标志 - */ - private Boolean rememberMe; - - /** - * 店铺ID - */ - private Long shopId; - - /** - * Purpose: agreementAccepted supports LoginRequestDTO.java by holding or executing the agreement accepted business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean agreementAccepted; - - /** - * Purpose: agreementVersions supports LoginRequestDTO.java by holding or executing the agreement versions business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map agreementVersions; - - /** - * Purpose: clientType supports LoginRequestDTO.java by holding or executing the client type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String clientType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/PhoneLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/PhoneLoginRequestDTO.java deleted file mode 100644 index 826bac1f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/PhoneLoginRequestDTO.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; -import java.util.Map; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -/** - * 手机号验证码登录请求 DTO - * - * @author xiaowang - * @date 2026-03-03 - */ -@Data -public class PhoneLoginRequestDTO implements AgreementAwareRequest { - - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") - /** - * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String phone; - - @NotBlank(message = "验证码不能为空") - @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") - /** - * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String verificationCode; - - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - /** - * 记住登录标志 - */ - private Boolean rememberMe; - - /** - * Purpose: agreementAccepted supports PhoneLoginRequestDTO.java by holding or executing the agreement accepted business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean agreementAccepted; - - /** - * Purpose: agreementVersions supports PhoneLoginRequestDTO.java by holding or executing the agreement versions business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map agreementVersions; - - /** - * Purpose: clientType supports PhoneLoginRequestDTO.java by holding or executing the client type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String clientType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/RefreshTokenRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/RefreshTokenRequestDTO.java deleted file mode 100644 index 9a78d205..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/RefreshTokenRequestDTO.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -/** - * 刷新Token请求 DTO - * 用于刷新访问令牌 - * - * @author xiaowang - * @date 2026-02-14 - */ -@Data -public class RefreshTokenRequestDTO { - - /** - * 刷新令牌 - */ - private String refreshToken; -} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/RegisterRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/RegisterRequestDTO.java deleted file mode 100644 index 906618b9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/RegisterRequestDTO.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import com.xiaowang.jacyucloudsalon.core.utils.AccountValidationUtils; -import lombok.Data; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; -import java.util.Map; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -/** - * 注册请求 DTO - * - * @author xiaowang - * @date 2026-02-14 - */ -@Data -public class RegisterRequestDTO implements AgreementAwareRequest { - - @NotBlank(message = "账号不能为空") - @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") - /** - * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String account; - - @NotBlank(message = "密码不能为空") - /** - * Field `password` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String password; - - /** - * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String nickname; - - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - /** - * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String inviteCode; - - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") - /** - * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String phone; - - @NotBlank(message = "验证码不能为空") - @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") - /** - * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String verificationCode; - - /** - * Purpose: agreementAccepted supports RegisterRequestDTO.java by holding or executing the agreement accepted business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean agreementAccepted; - - /** - * Purpose: agreementVersions supports RegisterRequestDTO.java by holding or executing the agreement versions business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map agreementVersions; - - /** - * Purpose: clientType supports RegisterRequestDTO.java by holding or executing the client type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String clientType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/ResetPasswordRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/ResetPasswordRequestDTO.java deleted file mode 100644 index 3fd922c0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/ResetPasswordRequestDTO.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -/** - * 重置密码请求 DTO - * 用于用户重置密码 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class ResetPasswordRequestDTO { - - /** - * 手机号 - */ - private String phone; - - /** - * 验证码 - */ - private String verificationCode; - - /** - * 新密码 - */ - private String newPassword; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/SendVerificationCodeRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/SendVerificationCodeRequestDTO.java deleted file mode 100644 index dda92f8a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/SendVerificationCodeRequestDTO.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; - -/** - * 发送验证码请求 DTO。 - */ -@Data -public class SendVerificationCodeRequestDTO { - - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") - /** - * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String phone; - - /** - * 业务场景编码,用来选择 FingertipDesigner 投递 MessageHub 时的配置。 - */ - private String sceneCode; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/SwitchShopRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/SwitchShopRequestDTO.java deleted file mode 100644 index 52c1782b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/SwitchShopRequestDTO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -@Data -/** - * SwitchShopRequestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class SwitchShopRequestDTO { - - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/UpdatePhoneRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/UpdatePhoneRequestDTO.java deleted file mode 100644 index 706bfec2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/dto/UpdatePhoneRequestDTO.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.dto; - -import lombok.Data; - -/** - * 更换手机号请求 DTO - * 用于用户更换绑定的手机号 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class UpdatePhoneRequestDTO { - - /** - * 原手机号 - */ - private String oldPhone; - - /** - * 新手机号 - */ - private String newPhone; - - /** - * 验证码 - */ - private String verificationCode; -} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/entity/LoginIdentityDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/entity/LoginIdentityDO.java deleted file mode 100644 index 304f2f41..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/entity/LoginIdentityDO.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 用户登录标识信息表 DO - * 对应数据库表 t_login_identity - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_login_identity") -public class LoginIdentityDO extends BaseEntity { - - /** - * 关联用户表主键 - */ - @TableField("user_id") - private Long userId; - - /** - * 登录方式(0-手机号、1-账号、2-邮箱) - */ - @TableField("login_method") - private String loginMethod; - - /** - * 前端输入的具体值(如手机号、账号、邮箱) - */ - @TableField("input_value") - private String inputValue; - - /** - * 输入时间 - */ - @TableField("input_time") - private LocalDateTime inputTime; - - /** - * 状态:1-有效,0-无效 - */ - @TableField("status") - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/mapper/LoginIdentityMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/mapper/LoginIdentityMapper.java deleted file mode 100644 index 16cc6a3c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/mapper/LoginIdentityMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.auth.entity.LoginIdentityDO; - -/** - * 用户登录标识信息表 Mapper - * 对应数据库表 t_login_identity - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface LoginIdentityMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/LoginIdentityService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/LoginIdentityService.java deleted file mode 100644 index 7c3631b4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/LoginIdentityService.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.auth.entity.LoginIdentityDO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginIdentityDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginIdentityVO; - -import java.util.List; - -/** - * 用户登录标识信息表 Service - * 对应数据库表 t_login_identity - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface LoginIdentityService extends IService { - - /** - * 创建登录标识 - * - * @param loginIdentityDTO 登录标识DTO - * @return 登录标识ID - */ - Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO); - - /** - * 更新登录标识 - * - * @param id 登录标识ID - * @param loginIdentityDTO 登录标识DTO - * @return 是否更新成功 - */ - boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO); - - /** - * 删除登录标识 - * - * @param id 登录标识ID - * @return 是否删除成功 - */ - boolean deleteLoginIdentity(Long id); - - /** - * 根据ID查询登录标识 - * - * @param id 登录标识ID - * @return 登录标识VO - */ - LoginIdentityVO getLoginIdentityById(Long id); - - /** - * 查询所有登录标识 - * - * @return 登录标识VO列表 - */ - List listAllLoginIdentities(); - - /** - * 根据用户ID查询登录标识 - * - * @param userId 用户ID - * @return 登录标识VO列表 - */ - List listLoginIdentitiesByUserId(Long userId); - - /** - * 根据登录方式查询登录标识 - * - * @param loginMethod 登录方式 - * @return 登录标识VO列表 - */ - List listLoginIdentitiesByLoginMethod(String loginMethod); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/VerificationCodeService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/VerificationCodeService.java deleted file mode 100644 index 9eae8546..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/VerificationCodeService.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.service; - - -/** - * 验证码服务接口 - * - * @author xiaowang - * @date 2026-03-03 - */ -public interface VerificationCodeService { - - /** - * Run business method `generateVerificationCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - String generateVerificationCode(); - - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - */ - void sendVerificationCode(String phone); - - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - */ - void sendVerificationCode(String phone, String sceneCode); - - /** - * Run business method `verifyCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean verifyCode(String phone, String code); - - /** - * Run business method `canResend`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean canResend(String phone); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/LoginIdentityServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/LoginIdentityServiceImpl.java deleted file mode 100644 index 71088fc7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/LoginIdentityServiceImpl.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginIdentityDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.entity.LoginIdentityDO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.mapper.LoginIdentityMapper; -import com.xiaowang.jacyucloudsalon.core.modules.auth.service.LoginIdentityService; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginIdentityVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * 用户登录标识信息表 Service 实现 - * 对应数据库表 t_login_identity - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class LoginIdentityServiceImpl extends ServiceImpl implements LoginIdentityService { - /** - * Variable `loginIdentityMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final LoginIdentityMapper loginIdentityMapper; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO) { - LoginIdentityDO loginIdentityDO = new LoginIdentityDO(); - loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); - loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod()); - loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue()); - loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime()); - loginIdentityDO.setStatus(loginIdentityDTO.getStatus()); - loginIdentityMapper.insert(loginIdentityDO); - return loginIdentityDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO) { - LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); - if (loginIdentityDO == null) { - return false; - } - loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); - loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod()); - loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue()); - loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime()); - loginIdentityDO.setStatus(loginIdentityDTO.getStatus()); - return loginIdentityMapper.updateById(loginIdentityDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteLoginIdentity(Long id) { - return loginIdentityMapper.deleteById(id) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return LoginIdentityVO result consumed by the caller or returned to the frontend - */ - public LoginIdentityVO getLoginIdentityById(Long id) { - LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); - if (loginIdentityDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginIdentityDO parameter `loginIdentityDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(loginIdentityDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllLoginIdentities() { - List loginIdentityDOs = loginIdentityMapper.selectList(null); - return loginIdentityDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listLoginIdentitiesByUserId(Long userId) { - List loginIdentityDOs = loginIdentityMapper.selectList( - Wrappers.lambdaQuery(LoginIdentityDO.class) - .eq(LoginIdentityDO::getUserId, userId) - ); - return loginIdentityDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginMethod parameter `loginMethod` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listLoginIdentitiesByLoginMethod(String loginMethod) { - List loginIdentityDOs = loginIdentityMapper.selectList( - Wrappers.lambdaQuery(LoginIdentityDO.class) - .eq(LoginIdentityDO::getLoginMethod, loginMethod) - ); - return loginIdentityDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param loginIdentityDO 登录标识DO - * @return 登录标识VO - */ - private LoginIdentityVO convertToVO(LoginIdentityDO loginIdentityDO) { - LoginIdentityVO loginIdentityVO = new LoginIdentityVO(); - loginIdentityVO.setId(loginIdentityDO.getId()); - loginIdentityVO.setUserId(loginIdentityDO.getUserId()); - loginIdentityVO.setLoginMethod(loginIdentityDO.getLoginMethod()); - loginIdentityVO.setInputValue(loginIdentityDO.getInputValue()); - loginIdentityVO.setInputTime(loginIdentityDO.getInputTime()); - loginIdentityVO.setUpdateTime(loginIdentityDO.getUpdateTime()); - loginIdentityVO.setStatus(loginIdentityDO.getStatus()); - return loginIdentityVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java deleted file mode 100644 index 37017c0c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubClientService; -import com.xiaowang.jacyucloudsalon.core.modules.auth.service.VerificationCodeService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; - -import java.security.SecureRandom; -import java.time.Duration; - -/** - * 验证码服务实现。 - */ -@Slf4j -@Service -@RequiredArgsConstructor -public class VerificationCodeServiceImpl implements VerificationCodeService { - - /** - * Purpose: CODE_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the code prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CODE_PREFIX = "verification:code:"; - /** - * Purpose: SEND_TIME_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the send time prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SEND_TIME_PREFIX = "verification:send_time:"; - /** - * Purpose: CODE_LENGTH supports VerificationCodeServiceImpl.java by holding or executing the code length business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int CODE_LENGTH = 6; - /** - * Purpose: CODE_EXPIRE_MINUTES supports VerificationCodeServiceImpl.java by holding or executing the code expire minutes business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int CODE_EXPIRE_MINUTES = 5; - /** - * Purpose: RESEND_INTERVAL_SECONDS supports VerificationCodeServiceImpl.java by holding or executing the resend interval seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int RESEND_INTERVAL_SECONDS = 60; - /** - * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final StringRedisTemplate redisTemplate; - /** - * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MessageHubClientService messageHubClientService; - - @Override - /** - * Run business method `generateVerificationCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - public String generateVerificationCode() { - SecureRandom random = new SecureRandom(); - StringBuilder code = new StringBuilder(); - for (int i = 0; i < CODE_LENGTH; i++) { - code.append(random.nextInt(10)); - } - return code.toString(); - } - - @Override - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - */ - public void sendVerificationCode(String phone) { - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - sendVerificationCode(phone, "USER_LOGIN_SMS_CODE"); - } - - @Override - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - */ - public void sendVerificationCode(String phone, String sceneCode) { - String code = generateVerificationCode(); - - String codeKey = CODE_PREFIX + phone; - String sendTimeKey = SEND_TIME_PREFIX + phone; - - redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); - redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), - Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); - - messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); - log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); - } - - @Override - /** - * Run business method `verifyCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean verifyCode(String phone, String code) { - String codeKey = CODE_PREFIX + phone; - String storedCode = redisTemplate.opsForValue().get(codeKey); - - if (storedCode == null) { - log.warn("验证码不存在或已过期,手机号: {}", phone); - return false; - } - - if (!storedCode.equals(code)) { - log.warn("验证码错误,手机号: {}", phone); - return false; - } - - redisTemplate.delete(codeKey); - log.info("验证码验证成功,手机号: {}", phone); - return true; - } - - @Override - /** - * Run business method `canResend`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean canResend(String phone) { - String sendTimeKey = SEND_TIME_PREFIX + phone; - String sendTime = redisTemplate.opsForValue().get(sendTimeKey); - return sendTime == null; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginIdentityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginIdentityVO.java deleted file mode 100644 index 920268af..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginIdentityVO.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 用户登录标识信息表 VO - * 用于前端展示登录标识信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class LoginIdentityVO { - - /** - * 登录标识唯一主键ID(雪花id) - */ - private Long id; - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 用户昵称 - */ - private String userNickname; - - /** - * 登录方式(0-手机号、1-账号、2-邮箱) - */ - private String loginMethod; - - /** - * 登录方式名称 - */ - private String loginMethodName; - - /** - * 前端输入的具体值(如手机号、账号、邮箱) - */ - private String inputValue; - - /** - * 输入时间 - */ - private LocalDateTime inputTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; - - /** - * 状态:1-有效,0-无效 - */ - private Integer status; - - /** - * 状态名称 - */ - private String statusName; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java deleted file mode 100644 index 814d58da..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -/** - * 登录响应 VO - * - * @author xiaowang - * @date 2026-02-14 - */ -@Data -public class LoginResponseVO { - - /** - * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String accessToken; - - /** - * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String refreshToken; - - /** - * Field `userInfo` (UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private UserInfo userInfo; - - /** - * Field `needSetPassword` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private boolean needSetPassword; // 是否需要设置密码 - - @Data - /** - * Purpose: UserInfo supports LoginResponseVO.java by holding or executing the user info business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class UserInfo { - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String account; - /** - * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String nickname; - /** - * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String avatar; - /** - * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer type; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - /** - * Field `shopAuthorizationExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime shopAuthorizationExpireTime; - /** - * Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean shopAuthorizationExpired; - @JsonSerialize(contentUsing = ToStringSerializer.class) - /** - * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shopIds; - /** - * Field `shopNames` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shopNames; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginShopSelectionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginShopSelectionVO.java deleted file mode 100644 index ebaadde5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginShopSelectionVO.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.auth.vo; - -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -/** - * 登录页可选店铺结果。 - */ -@Data -public class LoginShopSelectionVO { - - /** - * Field `allowShoplessLogin` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private boolean allowShoplessLogin; - - /** - * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String message; - - /** - * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shops = new ArrayList<>(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/controller/front/CommentController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/controller/front/CommentController.java deleted file mode 100644 index add1ce20..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/controller/front/CommentController.java +++ /dev/null @@ -1,215 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.modules.content.dto.CommentDTO; -import com.xiaowang.jacyucloudsalon.core.modules.content.service.CommentService; -import com.xiaowang.jacyucloudsalon.core.modules.content.vo.CommentVO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadCompleteRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadInitRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageFileDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ChunkUploadService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.PrimaryObjectStorageService; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.support.security.UploadSecurityValidator; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.io.FileInputStream; -import java.util.List; - -@RestController -@RequestMapping({"/comment", "/api/comment"}) -@RequiredArgsConstructor -public class CommentController { - - private final CommentService commentService; - private final ObjectStorageFileService objectStorageFileService; - private final PrimaryObjectStorageService primaryObjectStorageService; - private final ChunkUploadService chunkUploadService; - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - private final UploadSecurityValidator uploadSecurityValidator; - private final ObjectStorageProperties objectStorageProperties; - - @PostMapping("/create") - public Result createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) { - Long userId = (Long) request.getAttribute("userId"); - Long id = commentService.createComment(userId, commentDTO); - return Result.success(id); - } - - @PostMapping("/upload-image") - @OperationGuard(action = "comment-image-upload", ttlSeconds = 15, message = "图片正在上传中,请勿重复操作") - public Result uploadCommentImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - return Result.error("请先登录后再上传评价图片"); - } - try { - uploadSecurityValidator.validate(file); - String originalFilename = normalizeOriginalFilename(file.getOriginalFilename()); - String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); - String fileUrl = primaryObjectStorageService.uploadFile(file, objectName); - return Result.success(createCommentImageRecord(originalFilename, fileUrl, objectName, file.getContentType(), file.getSize())); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("评价图片上传失败: " + e.getMessage()); - } - } - - @PostMapping("/upload-image/init") - @OperationGuard(action = "comment-image-upload-init", ttlSeconds = 10, message = "图片正在上传中,请勿重复操作") - public Result initCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - return Result.error("请先登录后再上传评价图片"); - } - uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); - return Result.success(chunkUploadService.initCommentImageUpload(userId, requestDTO)); - } - - @PostMapping("/upload-image/chunk") - @OperationGuard(action = "comment-image-upload-chunk", ttlSeconds = 20) - public Result uploadCommentImageChunk(HttpServletRequest request, - @RequestParam("uploadId") String uploadId, - @RequestParam("chunkIndex") Integer chunkIndex, - @RequestParam("totalChunks") Integer totalChunks, - @RequestParam("chunk") MultipartFile chunkFile) { - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - return Result.error("请先登录后再上传评价图片"); - } - uploadSecurityValidator.validateChunk(chunkFile); - chunkUploadService.uploadCommentImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); - return Result.success(true); - } - - @PostMapping("/upload-image/complete") - @OperationGuard(action = "comment-image-upload-complete", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") - public Result completeCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - return Result.error("请先登录后再上传评价图片"); - } - try (ChunkUploadService.PreparedUploadFile preparedUploadFile = - chunkUploadService.prepareCommentImageFile(userId, requestDTO.getUploadId()); - FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { - String originalFilename = normalizeOriginalFilename(preparedUploadFile.getFileName()); - String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); - String fileUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); - ObjectStorageFileVO fileVO = createCommentImageRecord(originalFilename, fileUrl, objectName, preparedUploadFile.getContentType(), preparedUploadFile.getFileSize()); - chunkUploadService.clearCommentImageUpload(userId, requestDTO.getUploadId()); - return Result.success(fileVO); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("评价图片上传失败: " + e.getMessage()); - } - } - - @DeleteMapping("/upload-image/{uploadId}") - @OperationGuard(action = "comment-image-upload-cancel", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") - public Result cancelCommentImageUpload(HttpServletRequest request, @PathVariable String uploadId) { - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - return Result.error("请先登录后再取消上传"); - } - chunkUploadService.clearCommentImageUpload(userId, uploadId); - return Result.success(true); - } - - @PutMapping("/update/{id}") - public Result updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = commentService.updateComment(id, userId, commentDTO); - return Result.success(success); - } - - @DeleteMapping("/delete/{id}") - public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = commentService.deleteComment(id, userId); - return Result.success(success); - } - - @GetMapping("/get/{id}") - public Result getCommentById(@PathVariable Long id) { - CommentVO commentVO = commentService.getCommentById(id); - return Result.success(commentVO); - } - - @GetMapping("/list/all") - public Result> listAllComments() { - List commentVOs = commentService.listAllComments(); - return Result.success(commentVOs); - } - - @GetMapping("/list/user/{userId}") - public Result> listCommentsByUserId(@PathVariable Long userId) { - List commentVOs = commentService.listCommentsByUserId(userId); - return Result.success(commentVOs); - } - - @GetMapping("/list/shop/{shopId}") - public Result> listCommentsByShopId(@PathVariable Long shopId) { - List commentVOs = commentService.listCommentsByShopId(shopId); - return Result.success(commentVOs); - } - - @GetMapping("/list/product/{productId}") - public Result> listCommentsByProductId(@PathVariable Long productId) { - List commentVOs = commentService.listCommentsByProductId(productId); - return Result.success(commentVOs); - } - - @GetMapping("/list/parent/{parentCommentId}") - public Result> listCommentsByParentCommentId(@PathVariable Long parentCommentId) { - List commentVOs = commentService.listCommentsByParentCommentId(parentCommentId); - return Result.success(commentVOs); - } - - private ObjectStorageFileVO createCommentImageRecord(String originalFilename, String fileUrl, String objectName, String contentType, Long fileSize) { - ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); - dto.setFileName(originalFilename); - dto.setFileUrl(fileUrl); - dto.setObjectName(objectName); - dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider()); - dto.setPrimaryUrl(fileUrl); - dto.setBackupProvider(objectStorageProperties.getBackupProvider()); - dto.setContentType(contentType); - dto.setFileSize(fileSize); - dto.setPrimaryUploadStatus(1); - dto.setBackupUploadStatus(0); - dto.setBackupRetryCount(0); - dto.setStatus(1); - Long fileId = objectStorageFileService.createObjectStorageFile(dto); - return objectStorageFileService.getObjectStorageFileById(fileId); - } - - private String normalizeOriginalFilename(String originalFilename) { - if (originalFilename == null || originalFilename.isBlank()) { - return "comment-image"; - } - return originalFilename; - } - - private String resolveFileExtension(String originalFilename) { - if (originalFilename == null || !originalFilename.contains(".")) { - return ""; - } - return originalFilename.substring(originalFilename.lastIndexOf(".")); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/dto/CommentDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/dto/CommentDTO.java deleted file mode 100644 index 10a768ac..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/dto/CommentDTO.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.dto; - -import lombok.Data; - -import java.util.List; - -/** - * 用户评论信息表 DTO - * 用于评论信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class CommentDTO { - - /** - * 评论用户ID,关联用户表主键 - */ - private Long userId; - - /** - * 关联店铺表主键(0表示非店铺评论) - */ - private Long shopId; - - /** - * 关联商品表主键(0表示非商品评论) - */ - private Long productId; - - /** - * 评论内容 - */ - private String commentContent; - - /** - * 父级评论ID(0表示为根评论) - */ - private Long parentCommentId; - - /** - * 评论评分:1-5星,根评论使用 - */ - private Integer ratingScore; - - /** - * 评论图片文件ID集合,根评论使用 - */ - private List imageFileIds; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/entity/CommentDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/entity/CommentDO.java deleted file mode 100644 index 193516ef..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/entity/CommentDO.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 用户评论信息表 DO - * 对应数据库表 t_comment - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_comment") -public class CommentDO extends BaseEntity { - - /** - * 评论用户ID,关联用户表主键 - */ - @TableField("user_id") - private Long userId; - - /** - * 关联店铺表主键(0表示非店铺评论) - */ - @TableField("shop_id") - private Long shopId; - - /** - * 关联商品表主键(0表示非商品评论) - */ - @TableField("product_id") - private Long productId; - - /** - * 评论内容 - */ - @TableField("comment_content") - private String commentContent; - - /** - * 父级评论ID(0表示为根评论) - */ - @TableField("parent_comment_id") - private Long parentCommentId; - - /** - * 评论评分:1-5星 - */ - @TableField("rating_score") - private Integer ratingScore; - - /** - * 评论图片文件ID集合,多个ID以逗号分隔 - */ - @TableField("image_file_ids") - private String imageFileIds; - - /** - * 评论点赞数 - */ - @TableField("like_count") - private Integer likeCount; - - /** - * 逻辑删除标识:0-未删除,1-已删除 - */ - @TableField("is_delete") - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/mapper/CommentMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/mapper/CommentMapper.java deleted file mode 100644 index 32dba72b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/mapper/CommentMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.content.entity.CommentDO; - -/** - * 用户评论信息表 Mapper - * 对应数据库表 t_comment - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface CommentMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/service/CommentService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/service/CommentService.java deleted file mode 100644 index 321a1222..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/service/CommentService.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.content.entity.CommentDO; -import com.xiaowang.jacyucloudsalon.core.modules.content.dto.CommentDTO; -import com.xiaowang.jacyucloudsalon.core.modules.content.vo.CommentVO; - -import java.util.List; - -/** - * 用户评论信息表 Service - * 对应数据库表 t_comment - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface CommentService extends IService { - - /** - * 创建评论 - * - * @param commentDTO 评论DTO - * @return 评论ID - */ - Long createComment(CommentDTO commentDTO); - - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUserId parameter `currentUserId` supplied by the caller - * @param commentDTO parameter `commentDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long createComment(Long currentUserId, CommentDTO commentDTO); - - /** - * 更新评论 - * - * @param id 评论ID - * @param commentDTO 评论DTO - * @return 是否更新成功 - */ - boolean updateComment(Long id, CommentDTO commentDTO); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @param commentDTO parameter `commentDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO); - - /** - * 删除评论 - * - * @param id 评论ID - * @return 是否删除成功 - */ - boolean deleteComment(Long id); - - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean deleteComment(Long id, Long currentUserId); - - /** - * Run business method `adminDeleteComment`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param managedShopId parameter `managedShopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean adminDeleteComment(Long id, Long managedShopId); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listAdminComments(Long productId, Long userId, Long shopId, String keyword); - - /** - * 根据ID查询评论 - * - * @param id 评论ID - * @return 评论VO - */ - CommentVO getCommentById(Long id); - - /** - * 查询所有评论 - * - * @return 评论VO列表 - */ - List listAllComments(); - - /** - * 根据用户ID查询评论 - * - * @param userId 用户ID - * @return 评论VO列表 - */ - List listCommentsByUserId(Long userId); - - /** - * 根据店铺ID查询评论 - * - * @param shopId 店铺ID - * @return 评论VO列表 - */ - List listCommentsByShopId(Long shopId); - - /** - * 根据商品ID查询评论 - * - * @param productId 商品ID - * @return 评论VO列表 - */ - List listCommentsByProductId(Long productId); - - /** - * 根据父级评论ID查询回复 - * - * @param parentCommentId 父级评论ID - * @return 评论VO列表 - */ - List listCommentsByParentCommentId(Long parentCommentId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/service/impl/CommentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/service/impl/CommentServiceImpl.java deleted file mode 100644 index 61680847..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/service/impl/CommentServiceImpl.java +++ /dev/null @@ -1,620 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.content.dto.CommentDTO; -import com.xiaowang.jacyucloudsalon.core.modules.content.entity.CommentDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.content.mapper.CommentMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.content.service.CommentService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.content.vo.CommentVO; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * 用户评论信息表 Service 实现 - * 对应数据库表 t_comment - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class CommentServiceImpl extends ServiceImpl implements CommentService { - /** - * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CommentMapper commentMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductMapper productMapper; - private final ObjectStorageFileService objectStorageFileService; - private final ObjectStorageUrlSupport objectStorageUrlSupport; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param commentDTO parameter `commentDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createComment(CommentDTO commentDTO) { - if (commentDTO == null || commentDTO.getUserId() == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请先登录后再评论"); - } - return createComment(commentDTO.getUserId(), commentDTO); - } - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUserId parameter `currentUserId` supplied by the caller - * @param commentDTO parameter `commentDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createComment(Long currentUserId, CommentDTO commentDTO) { - if (currentUserId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请先登录后再评论"); - } - if (commentDTO == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("评论内容不能为空"); - } - String content = sanitizeContent(commentDTO.getCommentContent()); - Long productId = normalizeId(commentDTO.getProductId()); - Long parentCommentId = normalizeId(commentDTO.getParentCommentId()); - if (productId == null && parentCommentId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择要评论的作品"); - } - CommentDO parentComment = null; - if (parentCommentId != null) { - parentComment = commentMapper.selectById(parentCommentId); - if (parentComment == null || Integer.valueOf(1).equals(parentComment.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("回复的评论不存在"); - } - if (productId == null) { - productId = parentComment.getProductId(); - } else if (parentComment.getProductId() != null && !productId.equals(parentComment.getProductId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("回复内容与作品不匹配"); - } - } - Long shopId = normalizeId(commentDTO.getShopId()); - if (shopId == null && productId != null) { - ProductDO product = productMapper.selectById(productId); - if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) { - shopId = product.getShopId(); - } - } - CommentDO commentDO = new CommentDO(); - boolean rootComment = parentCommentId == null; - commentDO.setUserId(currentUserId); - commentDO.setShopId(shopId); - commentDO.setProductId(productId); - commentDO.setCommentContent(content); - commentDO.setParentCommentId(parentCommentId); - if (rootComment) { - commentDO.setRatingScore(normalizeRatingScore(commentDTO.getRatingScore())); - commentDO.setImageFileIds(joinImageFileIds(commentDTO.getImageFileIds())); - } - commentDO.setLikeCount(0); - commentDO.setIsDelete(0); - commentMapper.insert(commentDO); - return commentDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param commentDTO parameter `commentDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateComment(Long id, CommentDTO commentDTO) { - CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null) { - return false; - } - commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); - commentDO.setUpdateTime(LocalDateTime.now()); - return commentMapper.updateById(commentDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteComment(Long id) { - CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null) { - return false; - } - commentDO.setIsDelete(1); - return commentMapper.updateById(commentDO) > 0; - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @param commentDTO parameter `commentDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) { - CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { - return false; - } - if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只能修改自己的评论"); - } - commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); - commentDO.setUpdateTime(LocalDateTime.now()); - return commentMapper.updateById(commentDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteComment(Long id, Long currentUserId) { - CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { - return false; - } - if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只能删除自己的评论"); - } - commentDO.setIsDelete(1); - commentDO.setUpdateTime(LocalDateTime.now()); - return commentMapper.updateById(commentDO) > 0; - } - - @Override - /** - * Run business method `adminDeleteComment`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param managedShopId parameter `managedShopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean adminDeleteComment(Long id, Long managedShopId) { - CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { - return false; - } - if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权删除其他门店评论"); - } - commentDO.setIsDelete(1); - commentDO.setUpdateTime(LocalDateTime.now()); - return commentMapper.updateById(commentDO) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return CommentVO result consumed by the caller or returned to the frontend - */ - public CommentVO getCommentById(Long id) { - CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param commentDO parameter `commentDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(commentDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllComments() { - return toCommentVOList(activeQuery().orderByDesc(CommentDO::getCreateTime)); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listCommentsByUserId(Long userId) { - List commentDOs = commentMapper.selectList( - Wrappers.lambdaQuery(CommentDO.class) - .eq(CommentDO::getUserId, userId) - .eq(CommentDO::getIsDelete, 0) - .orderByDesc(CommentDO::getCreateTime) - ); - return commentDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listCommentsByShopId(Long shopId) { - List commentDOs = commentMapper.selectList( - Wrappers.lambdaQuery(CommentDO.class) - .eq(CommentDO::getShopId, shopId) - .eq(CommentDO::getIsDelete, 0) - .orderByDesc(CommentDO::getCreateTime) - ); - return commentDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listCommentsByProductId(Long productId) { - List commentDOs = commentMapper.selectList( - Wrappers.lambdaQuery(CommentDO.class) - .eq(CommentDO::getProductId, productId) - .eq(CommentDO::getIsDelete, 0) - .orderByDesc(CommentDO::getCreateTime) - ); - /** - * Run business method `buildTree`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param commentDOs parameter `commentDOs` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildTree(commentDOs); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param parentCommentId parameter `parentCommentId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listCommentsByParentCommentId(Long parentCommentId) { - List commentDOs = commentMapper.selectList( - Wrappers.lambdaQuery(CommentDO.class) - .eq(CommentDO::getParentCommentId, parentCommentId) - .eq(CommentDO::getIsDelete, 0) - .orderByAsc(CommentDO::getCreateTime) - ); - return commentDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listAdminComments(Long productId, Long userId, Long shopId, String keyword) { - List commentDOs = commentMapper.selectList( - Wrappers.lambdaQuery(CommentDO.class) - .eq(CommentDO::getIsDelete, 0) - .eq(productId != null && productId > 0, CommentDO::getProductId, productId) - .eq(userId != null && userId > 0, CommentDO::getUserId, userId) - .eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId) - .like(StringUtils.hasText(keyword), CommentDO::getCommentContent, keyword) - .orderByDesc(CommentDO::getCreateTime) - ); - return commentDOs.stream().map(this::convertToVO).collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param commentDO 评论DO - * @return 评论VO - */ - private CommentVO convertToVO(CommentDO commentDO) { - CommentVO commentVO = new CommentVO(); - commentVO.setId(commentDO.getId()); - commentVO.setUserId(commentDO.getUserId()); - commentVO.setShopId(commentDO.getShopId()); - commentVO.setProductId(commentDO.getProductId()); - commentVO.setCommentContent(commentDO.getCommentContent()); - commentVO.setParentCommentId(commentDO.getParentCommentId()); - commentVO.setLikeCount(commentDO.getLikeCount()); - commentVO.setRatingScore(commentDO.getRatingScore()); - List imageFileIds = parseImageFileIds(commentDO.getImageFileIds()); - commentVO.setImageFileIds(imageFileIds); - commentVO.setImageUrls(resolveImageUrls(imageFileIds)); - commentVO.setCreateTime(commentDO.getCreateTime()); - commentVO.setUpdateTime(commentDO.getUpdateTime()); - /** - * Run business method `fillDisplayFields`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param commentVO parameter `commentVO` supplied by the caller - * @param commentDO parameter `commentDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - fillDisplayFields(commentVO, commentDO); - return commentVO; - } - - /** - * Run business method `toCommentVOList`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper) { - return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList()); - } - - /** - * Run business method `buildTree`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param commentDOs parameter `commentDOs` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List buildTree(List commentDOs) { - Map rootMap = new HashMap<>(); - List roots = new ArrayList<>(); - List replies = new ArrayList<>(); - for (CommentDO commentDO : commentDOs) { - CommentVO vo = convertToVO(commentDO); - if (commentDO.getParentCommentId() == null || commentDO.getParentCommentId() <= 0) { - vo.setReplies(new ArrayList<>()); - rootMap.put(commentDO.getId(), vo); - roots.add(vo); - } else { - replies.add(vo); - } - } - replies.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder()))); - for (CommentVO reply : replies) { - CommentVO root = rootMap.get(reply.getParentCommentId()); - if (root != null) { - root.getReplies().add(reply); - } - } - roots.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed()); - return roots; - } - - /** - * Run business method `fillDisplayFields`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param commentVO parameter `commentVO` supplied by the caller - * @param commentDO parameter `commentDO` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { - UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); - if (user != null) { - commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); - } - ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId()); - if (shop != null) { - commentVO.setShopName(shop.getShopName()); - } - ProductDO product = commentDO.getProductId() == null ? null : productMapper.selectById(commentDO.getProductId()); - if (product != null) { - commentVO.setProductTitle(product.getTitle()); - } - if (commentDO.getParentCommentId() != null && commentDO.getParentCommentId() > 0) { - CommentDO parent = commentMapper.selectById(commentDO.getParentCommentId()); - if (parent != null && !Integer.valueOf(1).equals(parent.getIsDelete())) { - commentVO.setParentCommentContent(parent.getCommentContent()); - } - } - } - - private Integer normalizeRatingScore(Integer ratingScore) { - if (ratingScore == null) { - return 5; - } - return Math.max(1, Math.min(5, ratingScore)); - } - - private String joinImageFileIds(List imageFileIds) { - if (imageFileIds == null || imageFileIds.isEmpty()) { - return null; - } - return imageFileIds.stream() - .filter(id -> id != null && id > 0) - .distinct() - .limit(6) - .map(String::valueOf) - .collect(Collectors.joining(",")); - } - - private List parseImageFileIds(String imageFileIds) { - List result = new ArrayList<>(); - if (!StringUtils.hasText(imageFileIds)) { - return result; - } - for (String token : imageFileIds.split(",")) { - if (!StringUtils.hasText(token)) { - continue; - } - try { - Long id = Long.valueOf(token.trim()); - if (id > 0) { - result.add(id); - } - } catch (NumberFormatException ignored) { - // Ignore malformed legacy tokens. - } - } - return new ArrayList<>(new LinkedHashSet<>(result)); - } - - private List resolveImageUrls(List imageFileIds) { - if (imageFileIds == null || imageFileIds.isEmpty()) { - return new ArrayList<>(); - } - Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(new LinkedHashSet<>(imageFileIds)); - List urls = new ArrayList<>(); - for (Long imageFileId : imageFileIds) { - ObjectStorageFileVO fileVO = fileMap.get(imageFileId); - if (fileVO == null || !StringUtils.hasText(fileVO.getFileUrl())) { - continue; - } - urls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); - } - return urls; - } - - /** - * Run business method `activeQuery`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper result consumed by the caller or returned to the frontend - */ - private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { - return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0); - } - - /** - * Run business method `normalizeId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long normalizeId(Long id) { - return id == null || id <= 0 ? null : id; - } - - /** - * Run business method `sanitizeContent`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param content parameter `content` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String sanitizeContent(String content) { - if (!StringUtils.hasText(content)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("评论内容不能为空"); - } - String sanitized = content.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim(); - sanitized = sanitized.replaceAll("<[^>]*>", ""); - if (!StringUtils.hasText(sanitized)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("评论内容不能为空"); - } - if (sanitized.length() > 300) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("评论最多输入 300 个字"); - } - return sanitized; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/vo/CommentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/vo/CommentVO.java deleted file mode 100644 index e21be40d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/content/vo/CommentVO.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.content.vo; - -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -/** - * 用户评论信息表 VO - * 用于前端展示评论信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class CommentVO { - - /** - * 评论唯一主键ID(雪花ID) - */ - private Long id; - - /** - * 评论用户ID,关联用户表主键 - */ - private Long userId; - - /** - * 用户昵称 - */ - private String userNickname; - - /** - * 关联店铺表主键(0表示非店铺评论) - */ - private Long shopId; - - /** - * 店铺名称 - */ - private String shopName; - - /** - * 关联商品表主键(0表示非商品评论) - */ - private Long productId; - - /** - * 商品标题 - */ - private String productTitle; - - /** - * 评论内容 - */ - private String commentContent; - - /** - * 父级评论ID(0表示为根评论) - */ - private Long parentCommentId; - - /** - * 父级评论内容 - */ - private String parentCommentContent; - - /** - * 评论点赞数 - */ - private Integer likeCount; - - /** - * 评论评分:1-5星 - */ - private Integer ratingScore; - - /** - * 评论图片文件ID集合 - */ - private List imageFileIds; - - /** - * 评论图片展示链接 - */ - private List imageUrls; - - /** - * 评论创建时间 - */ - private LocalDateTime createTime; - - /** - * 评论更新时间 - */ - private LocalDateTime updateTime; - - /** - * 回复列表 - */ - private List replies; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/AliyunOssConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/AliyunOssConfig.java deleted file mode 100644 index ad6bffe1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/AliyunOssConfig.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.config; - -import com.aliyun.oss.OSS; -import com.aliyun.oss.OSSClientBuilder; -import lombok.Data; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; -import org.springframework.validation.annotation.Validated; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; - -@Data -@Configuration -@Validated -@ConfigurationProperties(prefix = "aliyun.oss") -public class AliyunOssConfig { - - @NotNull - private Boolean enabled; - @NotBlank - private String endpoint; - @NotBlank - private String region; - @NotBlank - private String bucketName; - @NotBlank - private String accessKeyId; - @NotBlank - private String accessKeySecret; - @NotNull - @Min(1) - private Integer signedUrlExpireMinutes; - - @Bean(destroyMethod = "shutdown") - @ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true") - public OSS aliyunOssClient() { - if (!StringUtils.hasText(endpoint) - || !StringUtils.hasText(accessKeyId) - || !StringUtils.hasText(accessKeySecret)) { - throw new IllegalStateException("Aliyun OSS is enabled but endpoint/accessKeyId/accessKeySecret is incomplete"); - } - return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/MinioStorageConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/MinioStorageConfig.java deleted file mode 100644 index 917b7d67..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/MinioStorageConfig.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.config; - -import io.minio.MinioClient; -import lombok.Data; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; -import org.springframework.validation.annotation.Validated; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; - -@Data -@Configuration -@Validated -@ConfigurationProperties(prefix = "minio") -public class MinioStorageConfig { - - @NotNull - private Boolean enabled; - - private String endpoint; - - private String bucketName; - - private String accessKey; - - private String secretKey; - - @NotNull - private Boolean privateBucket; - - @NotNull - @Min(1) - private Integer signedUrlExpireMinutes; - - @Bean - @ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true") - public MinioClient minioClient() { - if (!StringUtils.hasText(endpoint) - || !StringUtils.hasText(accessKey) - || !StringUtils.hasText(secretKey)) { - throw new IllegalStateException("MinIO is enabled but endpoint/accessKey/secretKey is incomplete"); - } - return MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .build(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/QiniuKodoConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/QiniuKodoConfig.java deleted file mode 100644 index 8b51b927..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/config/QiniuKodoConfig.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.config; - -import com.qiniu.common.Zone; -import com.qiniu.storage.BucketManager; -import com.qiniu.storage.UploadManager; -import com.qiniu.util.Auth; -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.validation.annotation.Validated; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; - -@Data -@Configuration -@Validated -@ConfigurationProperties(prefix = "qiniu.kodo") -public class QiniuKodoConfig { - - @NotBlank - private String accessKey; - - @NotBlank - private String secretKey; - - @NotBlank - private String bucketName; - - @NotBlank - private String domain; - - @NotBlank - private String zone; - - @NotNull - private Boolean privateBucket; - - @NotNull - @Min(1) - private Integer signedUrlExpireMinutes; - - @Bean - public Auth qiniuAuth() { - return Auth.create(accessKey, secretKey); - } - - @Bean - public com.qiniu.storage.Configuration qiniuConfiguration() { - return new com.qiniu.storage.Configuration(resolveZone()); - } - - @Bean - public UploadManager qiniuUploadManager(com.qiniu.storage.Configuration qiniuConfiguration) { - return new UploadManager(qiniuConfiguration); - } - - @Bean - public BucketManager qiniuBucketManager(com.qiniu.storage.Configuration qiniuConfiguration, Auth qiniuAuth) { - return new BucketManager(qiniuAuth, qiniuConfiguration); - } - - private Zone resolveZone() { - String normalizedZone = zone.trim().toLowerCase(); - switch (normalizedZone) { - case "z0": - return Zone.zone0(); - case "z1": - return Zone.zone1(); - case "z2": - return Zone.zone2(); - case "na0": - return Zone.zoneNa0(); - case "as0": - return Zone.zoneAs0(); - default: - throw new IllegalStateException("Unsupported Qiniu zone: " + zone); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/controller/front/FrontendFileController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/controller/front/FrontendFileController.java deleted file mode 100644 index 8a0c5de4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/controller/front/FrontendFileController.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.EffectDiagramMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import lombok.RequiredArgsConstructor; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * Purpose: FrontendFileController exposes signed-file access only for public frontend references. - * Usage: anonymous clients call /file/get-signed-url/{fileId}; the controller verifies the file is referenced by public content before returning a URL. - */ -@RestController -@RequestMapping("/file") -@RequiredArgsConstructor -public class FrontendFileController { - private final ObjectStorageFileService objectStorageFileService; - private final ObjectStorageUrlSupport objectStorageUrlSupport; - private final ProductMapper productMapper; - private final ShopMapper shopMapper; - private final EffectDiagramMapper effectDiagramMapper; - - /** - * Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public. - * Usage: pass a public file id and optional expiry minutes; private or unreferenced files are rejected. - */ - @GetMapping("/get-signed-url/{fileId}") - public Result getSignedUrl(@PathVariable Long fileId, - @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { - try { - ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); - if (fileVO == null) { - return Result.error("文件不存在"); - } - if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) { - return Result.error("文件不可公开访问"); - } - - String signedUrl = hasObjectStorageReference(fileVO) - ? objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes) - : fileVO.getFileUrl(); - return Result.success(signedUrl); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("获取签名链接失败: " + e.getMessage()); - } - } - - private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) { - return StringUtils.hasText(fileVO.getObjectName()) - || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getPrimaryUrl())) - || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl())); - } - - /** - * Purpose: isPublicFileReference prevents arbitrary uploaded files from being exposed through the public signing endpoint. - * Usage: call with a file id and keep mapper checks in sync with public content tables. - */ - private boolean isPublicFileReference(Long fileId) { - if (fileId == null) { - return false; - } - return positive(productMapper.countPublicImageReference(fileId)) - || positive(shopMapper.countPublicImageReference(fileId)) - || positive(effectDiagramMapper.countPublicImageReference(fileId)); - } - - /** - * Purpose: positive normalizes nullable mapper counts. - * Usage: use for COUNT(*) results where null should behave like zero. - */ - private boolean positive(Long count) { - return count != null && count > 0; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/controller/front/ObjectStorageFileController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/controller/front/ObjectStorageFileController.java deleted file mode 100644 index a03a4f32..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/controller/front/ObjectStorageFileController.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadCompleteRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadInitRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageFileDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageUploadOutcome; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ChunkUploadService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageOrchestrationService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jacyucloudsalon.core.support.security.UploadSecurityValidator; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ChunkUploadSessionVO; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import lombok.RequiredArgsConstructor; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.io.FileInputStream; -import java.util.List; - -/** - * 对象存储文件控制器,对应表 t_object_storage_file。 - */ -@RestController -@RequestMapping("/admin/object-storage-file") -@RequiredArgsConstructor -@Validated -public class ObjectStorageFileController { - /** - * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageFileService objectStorageFileService; - /** - * Variable `objectStorageOrchestrationService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageOrchestrationService objectStorageOrchestrationService; - /** - * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ChunkUploadService chunkUploadService; - /** - * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageUrlSupport objectStorageUrlSupport; - /** - * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - /** - * Purpose: uploadSecurityValidator supports ObjectStorageFileController.java by holding or executing the upload security validator business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UploadSecurityValidator uploadSecurityValidator; - private final ObjectStorageProperties objectStorageProperties; - - @PostMapping("/upload/init") - @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") - public Result initChunkUpload(HttpServletRequest request, - @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); - return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO)); - } - - @PostMapping("/upload/chunk") - @OperationGuard(action = "admin-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) - public Result uploadChunk(HttpServletRequest request, - @RequestParam("uploadId") String uploadId, - @RequestParam("chunkIndex") Integer chunkIndex, - @RequestParam("totalChunks") Integer totalChunks, - @RequestParam("chunk") MultipartFile chunkFile) { - Long userId = (Long) request.getAttribute("userId"); - uploadSecurityValidator.validateChunk(chunkFile); - chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); - return Result.success(true); - } - - @PostMapping("/upload/complete") - @OperationGuard(action = "admin-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result completeChunkUpload(HttpServletRequest request, - @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - try (ChunkUploadService.PreparedUploadFile preparedUploadFile = - chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId()); - FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { - String originalFilename = preparedUploadFile.getFileName(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - - ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( - inputStream, - preparedUploadFile.getFileSize(), - preparedUploadFile.getContentType(), - objectName - ); - - ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); - dto.setFileName(originalFilename); - dto.setFileUrl(uploadOutcome.getPrimaryUrl()); - dto.setObjectName(objectName); - dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); - dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); - dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); - dto.setContentType(preparedUploadFile.getContentType()); - dto.setFileSize(preparedUploadFile.getFileSize()); - dto.setPrimaryUploadStatus(1); - dto.setBackupUploadStatus(0); - dto.setBackupRetryCount(0); - dto.setUploadAttempts(uploadOutcome.getAttempts()); - dto.setStatus(1); - - Long fileId = objectStorageFileService.createObjectStorageFile(dto); - chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId()); - return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("文件上传失败: " + e.getMessage()); - } - } - - @DeleteMapping("/upload/{uploadId}") - @OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - /** - * Run business method `cancelChunkUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) { - Long userId = (Long) request.getAttribute("userId"); - chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId); - return Result.success(true); - } - - /** - * 上传文件。 - */ - @PostMapping("/upload") - @OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result uploadFile(@RequestParam("file") MultipartFile file) { - try { - uploadSecurityValidator.validate(file); - String originalFilename = file.getOriginalFilename(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - - ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( - file.getInputStream(), - file.getSize(), - file.getContentType(), - objectName - ); - - ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); - dto.setFileName(originalFilename); - dto.setFileUrl(uploadOutcome.getPrimaryUrl()); - dto.setObjectName(objectName); - dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); - dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); - dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); - dto.setContentType(file.getContentType()); - dto.setFileSize(file.getSize()); - dto.setPrimaryUploadStatus(1); - dto.setBackupUploadStatus(0); - dto.setBackupRetryCount(0); - dto.setUploadAttempts(uploadOutcome.getAttempts()); - dto.setStatus(1); - - Long fileId = objectStorageFileService.createObjectStorageFile(dto); - return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("文件上传失败: " + e.getMessage()); - } - } - - /** - * 获取带签名的图片链接。 - */ - @GetMapping("/get-signed-url/{fileId}") - public Result getSignedUrl(@PathVariable Long fileId, - @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { - try { - ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); - if (fileVO == null) { - return Result.error("文件不存在"); - } - - String signedUrl = objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes); - return Result.success(signedUrl); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("获取签名链接失败: " + e.getMessage()); - } - } - - @PostMapping("/create") - @OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) { - Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO); - return Result.success(id); - } - - @PutMapping("/update/{id}") - @OperationGuard(action = "admin-file-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updateObjectStorageFile(@PathVariable Long id, - @RequestBody ObjectStorageFileDTO objectStorageFileDTO) { - boolean success = objectStorageFileService.updateObjectStorageFile(id, objectStorageFileDTO); - return Result.success(success); - } - - @DeleteMapping("/delete/{id}") - @OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result deleteObjectStorageFile(@PathVariable Long id) { - boolean success = objectStorageFileService.deleteObjectStorageFile(id); - return Result.success(success); - } - - @GetMapping("/get/{id}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getObjectStorageFileById(@PathVariable Long id) { - ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id); - return Result.success(objectStorageFileVO); - } - - @GetMapping("/list/all") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listAllObjectStorageFiles() { - List objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles(); - return Result.success(objectStorageFileVOs); - } - - @GetMapping("/list/status/{status}") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param status parameter `status` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listObjectStorageFilesByStatus(@PathVariable Integer status) { - List objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status); - return Result.success(objectStorageFileVOs); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java deleted file mode 100644 index 628b527f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; - -/** - * 分片上传完成请求 - */ -@Data -public class ChunkUploadCompleteRequestDTO { - - @NotBlank(message = "上传标识不能为空") - /** - * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String uploadId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ChunkUploadInitRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ChunkUploadInitRequestDTO.java deleted file mode 100644 index 3e83b8fc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ChunkUploadInitRequestDTO.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.Data; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; - -/** - * 分片上传初始化请求 - */ -@Data -public class ChunkUploadInitRequestDTO { - - @NotBlank(message = "文件名不能为空") - /** - * Field `fileName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String fileName; - - @NotNull(message = "文件大小不能为空") - @Min(value = 1, message = "文件大小不合法") - /** - * Field `fileSize` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long fileSize; - - @NotBlank(message = "文件类型不能为空") - /** - * Field `contentType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String contentType; - - @NotBlank(message = "文件指纹不能为空") - /** - * Field `fileFingerprint` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String fileFingerprint; - - @NotBlank(message = "上传场景不能为空") - /** - * Field `scene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String scene; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageBackupMessage.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageBackupMessage.java deleted file mode 100644 index cf6bfe32..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageBackupMessage.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class ObjectStorageBackupMessage { - - private Long fileId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageFileDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageFileDTO.java deleted file mode 100644 index 8c803650..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageFileDTO.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -/** - * 对象存储文件信息表 DTO - * 用于文件信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class ObjectStorageFileDTO { - - /** - * 文件名称 - */ - private String fileName; - - /** - * 文件访问链接 - */ - private String fileUrl; - - private String objectName; - - private String primaryProvider; - - private String primaryUrl; - - private String backupProvider; - - private String backupUrl; - - private String contentType; - - private Long fileSize; - - private Integer primaryUploadStatus; - - private Integer backupUploadStatus; - - private Integer backupRetryCount; - - private String backupLastError; - - private LocalDateTime backupUploadedAt; - - private LocalDateTime backupLastRetryTime; - - private List uploadAttempts; - - /** - * 文件状态:1-可用,0-不可用,2-回收站 - */ - private Integer status; - - /** - * 文件删除时间(NULL表示未删除) - */ - private LocalDateTime deleteTime; - - /** - * 文件移入回收站时间(NULL表示未移入) - */ - private LocalDateTime recycleTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageReplicaDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageReplicaDTO.java deleted file mode 100644 index 0deee58d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageReplicaDTO.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -public class ObjectStorageReplicaDTO { - - private String provider; - - private String objectName; - - private String objectUrl; - - private Integer uploadStatus; - - private Integer retryCount; - - private String lastError; - - private LocalDateTime uploadedAt; - - private LocalDateTime lastRetryTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageUploadAttempt.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageUploadAttempt.java deleted file mode 100644 index e0888f70..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageUploadAttempt.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class ObjectStorageUploadAttempt { - - private String provider; - - private String objectName; - - private String objectUrl; - - private Integer uploadStatus; - - private Integer retryCount; - - private String lastError; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageUploadOutcome.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageUploadOutcome.java deleted file mode 100644 index f5cb32e5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/dto/ObjectStorageUploadOutcome.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.List; - -@Data -@AllArgsConstructor -public class ObjectStorageUploadOutcome { - - private String primaryProvider; - - private String primaryUrl; - - private List attempts; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/entity/ObjectStorageFileDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/entity/ObjectStorageFileDO.java deleted file mode 100644 index 6d9dafcd..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/entity/ObjectStorageFileDO.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 对象存储文件信息表 DO - * 对应数据库表 t_object_storage_file - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_object_storage_file") -public class ObjectStorageFileDO extends BaseEntity { - - /** - * 文件名称 - */ - @TableField("file_name") - private String fileName; - - /** - * 文件访问链接 - */ - @TableField("file_url") - private String fileUrl; - - @TableField("object_name") - private String objectName; - - @TableField("primary_provider") - private String primaryProvider; - - @TableField("primary_url") - private String primaryUrl; - - @TableField("backup_provider") - private String backupProvider; - - @TableField("backup_url") - private String backupUrl; - - @TableField("content_type") - private String contentType; - - @TableField("file_size") - private Long fileSize; - - @TableField("primary_upload_status") - private Integer primaryUploadStatus; - - @TableField("backup_upload_status") - private Integer backupUploadStatus; - - @TableField("backup_retry_count") - private Integer backupRetryCount; - - @TableField("backup_last_error") - private String backupLastError; - - @TableField("backup_uploaded_at") - private LocalDateTime backupUploadedAt; - - @TableField("backup_last_retry_time") - private LocalDateTime backupLastRetryTime; - - /** - * 文件状态:1-可用,0-不可用,2-回收站 - */ - @TableField("status") - private Integer status; - - /** - * 文件删除时间(NULL表示未删除) - */ - @TableField("delete_time") - private LocalDateTime deleteTime; - - /** - * 文件移入回收站时间(NULL表示未移入) - */ - @TableField("recycle_time") - private LocalDateTime recycleTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/entity/ObjectStorageReplicaDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/entity/ObjectStorageReplicaDO.java deleted file mode 100644 index e86aa283..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/entity/ObjectStorageReplicaDO.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_object_storage_file_replica") -public class ObjectStorageReplicaDO extends BaseEntity { - - @TableField("file_id") - private Long fileId; - - @TableField("provider") - private String provider; - - @TableField("object_name") - private String objectName; - - @TableField("object_url") - private String objectUrl; - - @TableField("upload_status") - private Integer uploadStatus; - - @TableField("retry_count") - private Integer retryCount; - - @TableField("last_error") - private String lastError; - - @TableField("uploaded_at") - private LocalDateTime uploadedAt; - - @TableField("last_retry_time") - private LocalDateTime lastRetryTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mapper/ObjectStorageFileMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mapper/ObjectStorageFileMapper.java deleted file mode 100644 index 0310dc5e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mapper/ObjectStorageFileMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageFileDO; - -/** - * 对象存储文件信息表 Mapper - * 对应数据库表 t_object_storage_file - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface ObjectStorageFileMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mapper/ObjectStorageReplicaMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mapper/ObjectStorageReplicaMapper.java deleted file mode 100644 index 545c0102..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mapper/ObjectStorageReplicaMapper.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageReplicaDO; - -public interface ObjectStorageReplicaMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mq/ObjectStorageBackupMessageListener.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mq/ObjectStorageBackupMessageListener.java deleted file mode 100644 index 970f5198..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mq/ObjectStorageBackupMessageListener.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.mq; - -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageBackupMessage; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageBackupService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.amqp.rabbit.annotation.RabbitListener; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -@RequiredArgsConstructor -public class ObjectStorageBackupMessageListener { - - private final ObjectStorageBackupService objectStorageBackupService; - - @RabbitListener(queues = "#{objectStorageProperties.backupQueueName}") - public void handle(ObjectStorageBackupMessage message) { - if (message == null || message.getFileId() == null) { - return; - } - try { - objectStorageBackupService.backupFile(message.getFileId()); - } catch (Exception e) { - log.warn("Handle object storage backup message failed, fileId={}", message.getFileId(), e); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java deleted file mode 100644 index 64d034ba..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.mq; - -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageBackupMessage; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -@RequiredArgsConstructor -public class ObjectStorageBackupMessagePublisher { - - private final RabbitTemplate rabbitTemplate; - private final ObjectStorageProperties objectStorageProperties; - - public void publish(Long fileId) { - if (fileId == null || fileId <= 0) { - return; - } - try { - rabbitTemplate.convertAndSend( - objectStorageProperties.getBackupExchangeName(), - objectStorageProperties.getBackupRoutingKey(), - new ObjectStorageBackupMessage(fileId) - ); - } catch (Exception e) { - log.warn("Publish object storage backup message failed, fileId={}", fileId, e); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java deleted file mode 100644 index b6da5408..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.scheduler; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageReplicaDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.mapper.ObjectStorageReplicaMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageBackupService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.impl.ObjectStorageBackupServiceImpl; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.util.List; - -@Slf4j -@Component -@RequiredArgsConstructor -public class ObjectStorageBackupRetryScheduler { - - private final ObjectStorageReplicaMapper objectStorageReplicaMapper; - private final ObjectStorageBackupService objectStorageBackupService; - private final ObjectStorageProperties objectStorageProperties; - - @Scheduled(cron = "${object-storage.backup-retry-cron}", zone = "Asia/Shanghai") - public void retryPendingOrFailedBackups() { - List replicas = objectStorageReplicaMapper.selectList( - Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) - .in(ObjectStorageReplicaDO::getProvider, objectStorageProperties.getReplicaRequiredProviders()) - .in(ObjectStorageReplicaDO::getUploadStatus, - ObjectStorageBackupServiceImpl.UPLOAD_STATUS_PENDING, - ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED) - .last("LIMIT " + objectStorageProperties.getBackupRetryBatchLimit()) - ); - for (ObjectStorageReplicaDO replica : replicas) { - try { - objectStorageBackupService.backupFile(replica.getFileId()); - } catch (Exception e) { - log.warn("Retry object storage replica failed, fileId={}, provider={}", replica.getFileId(), replica.getProvider(), e); - } - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/AliyunOssService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/AliyunOssService.java deleted file mode 100644 index cb3b438c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/AliyunOssService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import java.io.InputStream; - -public interface AliyunOssService { - - String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType); - - String getPresignedUrl(String objectName); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ChunkUploadService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ChunkUploadService.java deleted file mode 100644 index 9cd7ce16..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ChunkUploadService.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadInitRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ChunkUploadSessionVO; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; - -/** - * ChunkUploadService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface ChunkUploadService { - - /** - * Run business method `initAdminObjectStorageUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend - */ - ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); - - /** - * Run business method `initUserAvatarUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend - */ - ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); - - ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); - - ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); - - /** - * Run business method `uploadAdminObjectStorageChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - */ - void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); - - /** - * Run business method `uploadUserAvatarChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - */ - void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); - - void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); - - void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); - - /** - * Run business method `prepareAdminObjectStorageFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return PreparedUploadFile result consumed by the caller or returned to the frontend - */ - PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId); - - /** - * Run business method `prepareUserAvatarFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return PreparedUploadFile result consumed by the caller or returned to the frontend - */ - PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId); - - PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId); - - PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId); - - /** - * Run business method `clearAdminObjectStorageUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - */ - void clearAdminObjectStorageUpload(Long ownerId, String uploadId); - - /** - * Run business method `clearUserAvatarUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - */ - void clearUserAvatarUpload(Long ownerId, String uploadId); - - void clearUserProfileImageUpload(Long ownerId, String uploadId); - - void clearCommentImageUpload(Long ownerId, String uploadId); -/** - * PreparedUploadFile declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ - interface PreparedUploadFile extends AutoCloseable { - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return File result consumed by the caller or returned to the frontend - */ - File getFile(); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - String getFileName(); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - String getContentType(); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return long result consumed by the caller or returned to the frontend - */ - long getFileSize(); - - @Override - /** - * Run business method `close`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - */ - void close(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageBackupService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageBackupService.java deleted file mode 100644 index 53b8ab8e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageBackupService.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -public interface ObjectStorageBackupService { - - void backupFile(Long fileId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageFileService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageFileService.java deleted file mode 100644 index e149402b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageFileService.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageFileDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageFileDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * 对象存储文件信息表 Service - * 对应数据库表 t_object_storage_file - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface ObjectStorageFileService extends IService { - - /** - * 创建文件 - * - * @param objectStorageFileDTO 文件DTO - * @return 文件ID - */ - Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO); - - /** - * 更新文件 - * - * @param id 文件ID - * @param objectStorageFileDTO 文件DTO - * @return 是否更新成功 - */ - boolean updateObjectStorageFile(Long id, ObjectStorageFileDTO objectStorageFileDTO); - - /** - * 删除文件 - * - * @param id 文件ID - * @return 是否删除成功 - */ - boolean deleteObjectStorageFile(Long id); - - /** - * 根据ID查询文件 - * - * @param id 文件ID - * @return 文件VO - */ - ObjectStorageFileVO getObjectStorageFileById(Long id); - - /** - * 鎵归噺鏌ヨ鏂囦欢锛岃繑鍥瀒D -> 鏂囦欢淇℃伅鏄犲皠 - * - * @param ids 鏂囦欢ID闆嗗悎 - * @return 鏂囦欢鏄犲皠 - */ - Map getObjectStorageFileMapByIds(Collection ids); - - /** - * 查询所有文件 - * - * @return 文件VO列表 - */ - List listAllObjectStorageFiles(); - - /** - * 根据状态查询文件 - * - * @param status 文件状态 - * @return 文件VO列表 - */ - List listObjectStorageFilesByStatus(Integer status); - - void evictObjectStorageFileCache(Long id); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageOrchestrationService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageOrchestrationService.java deleted file mode 100644 index ed0f900c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageOrchestrationService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageUploadOutcome; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageFileDO; - -import java.io.InputStream; - -public interface ObjectStorageOrchestrationService { - - ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; - - void completeReplicas(ObjectStorageFileDO file); - - String getPresignedUrl(Long fileId, String objectName, Integer expiryTimeInMinutes); - - String getPresignedUrl(String objectName, Integer expiryTimeInMinutes); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageProvider.java deleted file mode 100644 index deb322ea..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageProvider.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import java.io.InputStream; - -public interface ObjectStorageProvider { - - String providerCode(); - - boolean isEnabled(); - - String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; - - InputStream downloadFile(String objectName) throws Exception; - - void deleteFile(String objectName) throws Exception; - - String getFileUrl(String objectName); - - String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageReplicaService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageReplicaService.java deleted file mode 100644 index b0b0efbb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/ObjectStorageReplicaService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageReplicaDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageUploadAttempt; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageReplicaDO; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -public interface ObjectStorageReplicaService { - - List listByFileId(Long fileId); - - Map> listMapByFileIds(Collection fileIds); - - void saveInitialReplicas(Long fileId, List attempts); - - void saveOrUpdateReplica(Long fileId, ObjectStorageReplicaDTO replicaDTO); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/PrimaryObjectStorageService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/PrimaryObjectStorageService.java deleted file mode 100644 index 821f6a09..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/PrimaryObjectStorageService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service; - -import org.springframework.web.multipart.MultipartFile; - -import java.io.InputStream; - -public interface PrimaryObjectStorageService { - - String uploadFile(MultipartFile file, String objectName) throws Exception; - - String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; - - InputStream downloadFile(String objectName) throws Exception; - - void deleteFile(String objectName) throws Exception; - - String getFileUrl(String objectName); - - String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/AliyunOssServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/AliyunOssServiceImpl.java deleted file mode 100644 index e5157167..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/AliyunOssServiceImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.aliyun.oss.HttpMethod; -import com.aliyun.oss.OSS; -import com.aliyun.oss.model.GeneratePresignedUrlRequest; -import com.aliyun.oss.model.ObjectMetadata; -import com.aliyun.oss.model.PutObjectRequest; -import com.xiaowang.jacyucloudsalon.core.modules.file.config.AliyunOssConfig; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.AliyunOssService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageProvider; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.io.InputStream; -import java.net.URL; -import java.util.Date; - -@Slf4j -@Service -@RequiredArgsConstructor -public class AliyunOssServiceImpl implements AliyunOssService, ObjectStorageProvider { - - private final ObjectProvider ossClientProvider; - private final AliyunOssConfig aliyunOssConfig; - - @Override - public String providerCode() { - return "ALIYUN_OSS"; - } - - @Override - public boolean isEnabled() { - return Boolean.TRUE.equals(aliyunOssConfig.getEnabled()) - && ossClientProvider.getIfAvailable() != null - && StringUtils.hasText(aliyunOssConfig.getBucketName()); - } - - @Override - public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) { - return uploadStream(objectName, inputStream, fileSize, contentType); - } - - @Override - public String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType) { - OSS ossClient = requireClient(); - ObjectMetadata metadata = new ObjectMetadata(); - if (fileSize >= 0) { - metadata.setContentLength(fileSize); - } - if (StringUtils.hasText(contentType)) { - metadata.setContentType(contentType); - } - ossClient.putObject(new PutObjectRequest(aliyunOssConfig.getBucketName(), objectName, inputStream, metadata)); - log.info("Aliyun OSS backup uploaded: {}", objectName); - return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; - } - - @Override - public InputStream downloadFile(String objectName) { - OSS ossClient = requireClient(); - return ossClient.getObject(aliyunOssConfig.getBucketName(), objectName).getObjectContent(); - } - - @Override - public void deleteFile(String objectName) { - OSS ossClient = requireClient(); - ossClient.deleteObject(aliyunOssConfig.getBucketName(), objectName); - } - - @Override - public String getFileUrl(String objectName) { - return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; - } - - @Override - public String getPresignedUrl(String objectName) { - return getPresignedUrl(objectName, aliyunOssConfig.getSignedUrlExpireMinutes()); - } - - @Override - public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { - OSS ossClient = requireClient(); - Date expiration = new Date(System.currentTimeMillis() - + resolveExpireMinutes(expiryTimeInMinutes) * 60L * 1000L); - GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest( - aliyunOssConfig.getBucketName(), - objectName, - HttpMethod.GET - ); - request.setExpiration(expiration); - URL url = ossClient.generatePresignedUrl(request); - return url.toString(); - } - - private int resolveExpireMinutes(Integer expiryTimeInMinutes) { - if (expiryTimeInMinutes != null && expiryTimeInMinutes > 0) { - return expiryTimeInMinutes; - } - return aliyunOssConfig.getSignedUrlExpireMinutes(); - } - - private OSS requireClient() { - OSS ossClient = ossClientProvider.getIfAvailable(); - if (ossClient == null) { - throw new IllegalStateException("Aliyun OSS is not enabled or not configured"); - } - return ossClient; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ChunkUploadServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ChunkUploadServiceImpl.java deleted file mode 100644 index 37eb9471..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ChunkUploadServiceImpl.java +++ /dev/null @@ -1,995 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadInitRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ChunkUploadService; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ChunkUploadSessionVO; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.util.DigestUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; - -@Slf4j -@Service -@RequiredArgsConstructor -/** - * ChunkUploadServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ChunkUploadServiceImpl implements ChunkUploadService { - - // Keep each chunk comfortably below the common 1 MB gateway/body limit. - private static final int CHUNK_SIZE = 512 * 1024; - /** - * Purpose: SESSION_EXPIRE_HOURS supports ChunkUploadServiceImpl.java by holding or executing the session expire hours business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long SESSION_EXPIRE_HOURS = 24; - /** - * Purpose: METADATA_FILE_NAME supports ChunkUploadServiceImpl.java by holding or executing the metadata file name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String METADATA_FILE_NAME = "metadata.json"; - /** - * Purpose: CHUNK_FILE_PREFIX supports ChunkUploadServiceImpl.java by holding or executing the chunk file prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHUNK_FILE_PREFIX = "chunk-"; - /** - * Purpose: CHUNK_FILE_SUFFIX supports ChunkUploadServiceImpl.java by holding or executing the chunk file suffix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHUNK_FILE_SUFFIX = ".part"; - /** - * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectMapper objectMapper; - - @Override - /** - * Run business method `initAdminObjectStorageUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend - */ - public ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - /** - * Run business method `initUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return initUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, requestDTO); - } - - @Override - /** - * Run business method `initUserAvatarUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend - */ - public ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - /** - * Run business method `initUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO); - } - - @Override - public ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - return initUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, requestDTO); - } - - @Override - public ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - return initUpload(UploadTargetType.COMMENT_IMAGE, ownerId, requestDTO); - } - - @Override - /** - * Run business method `uploadAdminObjectStorageChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - */ - public void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { - /** - * Run business method `uploadChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - uploadChunk(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); - } - - @Override - /** - * Run business method `uploadUserAvatarChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - */ - public void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { - /** - * Run business method `uploadChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); - } - - @Override - public void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { - uploadChunk(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); - } - - @Override - public void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { - uploadChunk(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); - } - - @Override - /** - * Run business method `prepareAdminObjectStorageFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return PreparedUploadFile result consumed by the caller or returned to the frontend - */ - public PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId) { - /** - * Run business method `prepareMergedFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return prepareMergedFile(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); - } - - @Override - /** - * Run business method `prepareUserAvatarFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return PreparedUploadFile result consumed by the caller or returned to the frontend - */ - public PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId) { - /** - * Run business method `prepareMergedFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId); - } - - @Override - public PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId) { - return prepareMergedFile(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); - } - - @Override - public PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId) { - return prepareMergedFile(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); - } - - @Override - /** - * Run business method `clearAdminObjectStorageUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - */ - public void clearAdminObjectStorageUpload(Long ownerId, String uploadId) { - /** - * Run business method `clearUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - clearUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); - } - - @Override - /** - * Run business method `clearUserAvatarUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - */ - public void clearUserAvatarUpload(Long ownerId, String uploadId) { - /** - * Run business method `clearUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId); - } - - @Override - public void clearUserProfileImageUpload(Long ownerId, String uploadId) { - clearUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); - } - - @Override - public void clearCommentImageUpload(Long ownerId, String uploadId) { - clearUpload(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); - } - - /** - * Run business method `initUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return private ChunkUploadSessionVO result consumed by the caller or returned to the frontend - */ - private ChunkUploadSessionVO initUpload(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - /** - * Run business method `validateInitRequest`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateInitRequest(ownerId, requestDTO); - /** - * Run business method `cleanupExpiredSessionsQuietly`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return result consumed by the caller or returned to the frontend - */ - cleanupExpiredSessionsQuietly(); - - String uploadId = buildUploadId(targetType, ownerId, requestDTO); - Path sessionDir = getSessionDir(uploadId); - int totalChunks = (int) Math.ceil((double) requestDTO.getFileSize() / CHUNK_SIZE); - - try { - Files.createDirectories(sessionDir); - - UploadMetadata metadata = readMetadataIfExists(sessionDir); - if (metadata != null && !isCompatible(metadata, targetType, ownerId, requestDTO, totalChunks)) { - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - deleteDirectory(sessionDir); - Files.createDirectories(sessionDir); - metadata = null; - } - - if (metadata == null) { - metadata = new UploadMetadata(); - metadata.setUploadId(uploadId); - metadata.setTargetType(targetType.name()); - metadata.setOwnerId(ownerId); - metadata.setFileName(requestDTO.getFileName()); - metadata.setContentType(requestDTO.getContentType()); - metadata.setFileSize(requestDTO.getFileSize()); - metadata.setFileFingerprint(requestDTO.getFileFingerprint()); - metadata.setScene(requestDTO.getScene()); - metadata.setChunkSize(CHUNK_SIZE); - metadata.setTotalChunks(totalChunks); - metadata.setCreatedAt(Instant.now().toEpochMilli()); - } - metadata.setUpdatedAt(Instant.now().toEpochMilli()); - /** - * Run business method `writeMetadata`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param metadata parameter `metadata` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - writeMetadata(sessionDir, metadata); - - ChunkUploadSessionVO sessionVO = new ChunkUploadSessionVO(); - sessionVO.setUploadId(uploadId); - sessionVO.setChunkSize(metadata.getChunkSize()); - sessionVO.setTotalChunks(metadata.getTotalChunks()); - sessionVO.setUploadedChunks(getUploadedChunks(sessionDir, metadata.getTotalChunks())); - return sessionVO; - } catch (IOException e) { - log.error("初始化分片上传失败, uploadId={}", uploadId, e); - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("初始化上传失败"); - } - } - - /** - * Run business method `uploadChunk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @param chunkFile parameter `chunkFile` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void uploadChunk(UploadTargetType targetType, Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { - if (ownerId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("未获取到上传用户信息"); - } - if (!StringUtils.hasText(uploadId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传标识不能为空"); - } - if (chunkIndex == null || chunkIndex < 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("分片序号不合法"); - } - if (totalChunks == null || totalChunks <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("分片总数不合法"); - } - if (chunkFile == null || chunkFile.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传分片不能为空"); - } - - Path sessionDir = getSessionDir(uploadId); - UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); - if (!Objects.equals(metadata.getTotalChunks(), totalChunks)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("分片总数不匹配,请重新上传"); - } - if (chunkIndex >= metadata.getTotalChunks()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("分片序号超出范围"); - } - - try { - Path chunkPath = getChunkPath(sessionDir, chunkIndex); - Path tempChunkPath = sessionDir.resolve(chunkPath.getFileName().toString() + ".tmp"); - try (InputStream inputStream = chunkFile.getInputStream()) { - Files.copy(inputStream, tempChunkPath, StandardCopyOption.REPLACE_EXISTING); - } - Files.move(tempChunkPath, chunkPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - metadata.setUpdatedAt(Instant.now().toEpochMilli()); - /** - * Run business method `writeMetadata`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param metadata parameter `metadata` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - writeMetadata(sessionDir, metadata); - } catch (IOException e) { - log.error("保存分片失败, uploadId={}, chunkIndex={}", uploadId, chunkIndex, e); - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传分片失败"); - } - } - - /** - * Run business method `prepareMergedFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return private PreparedUploadFile result consumed by the caller or returned to the frontend - */ - private PreparedUploadFile prepareMergedFile(UploadTargetType targetType, Long ownerId, String uploadId) { - Path sessionDir = getSessionDir(uploadId); - UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); - List uploadedChunks = getUploadedChunks(sessionDir, metadata.getTotalChunks()); - if (uploadedChunks.size() != metadata.getTotalChunks()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("文件尚未上传完成,请稍后再试"); - } - - try { - Path mergedFilePath = Files.createTempFile("fingertipdesigner-upload-", ".tmp"); - try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergedFilePath))) { - for (int chunkIndex = 0; chunkIndex < metadata.getTotalChunks(); chunkIndex++) { - Path chunkPath = getChunkPath(sessionDir, chunkIndex); - if (!Files.exists(chunkPath)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("缺少上传分片,请重新上传"); - } - Files.copy(chunkPath, outputStream); - } - } - return new LocalPreparedUploadFile(mergedFilePath.toFile(), metadata.getFileName(), metadata.getContentType(), metadata.getFileSize()); - } catch (IOException e) { - log.error("合并上传文件失败, uploadId={}", uploadId, e); - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("合并上传文件失败"); - } - } - - /** - * Run business method `clearUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void clearUpload(UploadTargetType targetType, Long ownerId, String uploadId) { - Path sessionDir = getSessionDir(uploadId); - /** - * Run business method `readAndValidateMetadata`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - deleteDirectory(sessionDir); - } - - /** - * Run business method `readAndValidateMetadata`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return private UploadMetadata result consumed by the caller or returned to the frontend - */ - private UploadMetadata readAndValidateMetadata(Path sessionDir, UploadTargetType targetType, Long ownerId, String uploadId) { - UploadMetadata metadata = readMetadataIfExists(sessionDir); - if (metadata == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传会话不存在,请重新上传"); - } - if (!targetType.name().equals(metadata.getTargetType()) || !Objects.equals(ownerId, metadata.getOwnerId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权操作该上传会话"); - } - if (!uploadId.equals(metadata.getUploadId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传会话不匹配"); - } - return metadata; - } - - /** - * Run business method `validateInitRequest`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateInitRequest(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - if (ownerId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("未获取到上传用户信息"); - } - if (requestDTO == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传参数不能为空"); - } - if (!StringUtils.hasText(requestDTO.getFileName())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("文件名不能为空"); - } - if (!StringUtils.hasText(requestDTO.getContentType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("文件类型不能为空"); - } - if (!StringUtils.hasText(requestDTO.getFileFingerprint())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("文件指纹不能为空"); - } - if (!StringUtils.hasText(requestDTO.getScene())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("上传场景不能为空"); - } - if (requestDTO.getFileSize() == null || requestDTO.getFileSize() <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("文件大小不合法"); - } - } - - /** - * Run business method `isCompatible`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param metadata parameter `metadata` supplied by the caller - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isCompatible(UploadMetadata metadata, UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO, int totalChunks) { - return targetType.name().equals(metadata.getTargetType()) - && Objects.equals(ownerId, metadata.getOwnerId()) - && Objects.equals(metadata.getFileSize(), requestDTO.getFileSize()) - && Objects.equals(metadata.getTotalChunks(), totalChunks) - && Objects.equals(metadata.getFileFingerprint(), requestDTO.getFileFingerprint()) - && Objects.equals(metadata.getScene(), requestDTO.getScene()); - } - - /** - * Run business method `buildUploadId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param ownerId parameter `ownerId` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildUploadId(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { - String raw = targetType.name() + "|" + ownerId + "|" + requestDTO.getScene() + "|" + requestDTO.getFileFingerprint(); - return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param uploadId parameter `uploadId` supplied by the caller - * @return private Path result consumed by the caller or returned to the frontend - */ - private Path getSessionDir(String uploadId) { - return getUploadRoot().resolve(uploadId); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private Path result consumed by the caller or returned to the frontend - */ - private Path getUploadRoot() { - return Path.of(System.getProperty("java.io.tmpdir"), "fingertipdesigner", "chunk-upload"); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param chunkIndex parameter `chunkIndex` supplied by the caller - * @return private Path result consumed by the caller or returned to the frontend - */ - private Path getChunkPath(Path sessionDir, int chunkIndex) { - return sessionDir.resolve(CHUNK_FILE_PREFIX + String.format("%05d", chunkIndex) + CHUNK_FILE_SUFFIX); - } - - /** - * Run business method `readMetadataIfExists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @return private UploadMetadata result consumed by the caller or returned to the frontend - */ - private UploadMetadata readMetadataIfExists(Path sessionDir) { - Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); - if (!Files.exists(metadataPath)) { - return null; - } - try { - return objectMapper.readValue(metadataPath.toFile(), UploadMetadata.class); - } catch (IOException e) { - log.warn("读取上传元数据失败: {}", metadataPath, e); - return null; - } - } - - /** - * Run business method `writeMetadata`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param metadata parameter `metadata` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void writeMetadata(Path sessionDir, UploadMetadata metadata) throws IOException { - Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); - objectMapper.writeValue(metadataPath.toFile(), metadata); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param totalChunks parameter `totalChunks` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List getUploadedChunks(Path sessionDir, int totalChunks) { - List uploadedChunks = new ArrayList<>(); - for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { - if (Files.exists(getChunkPath(sessionDir, chunkIndex))) { - uploadedChunks.add(chunkIndex); - } - } - return uploadedChunks; - } - - /** - * Run business method `cleanupExpiredSessionsQuietly`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private void result consumed by the caller or returned to the frontend - */ - private void cleanupExpiredSessionsQuietly() { - try { - Path uploadRoot = getUploadRoot(); - if (!Files.exists(uploadRoot)) { - return; - } - Instant expireAt = Instant.now().minus(SESSION_EXPIRE_HOURS, ChronoUnit.HOURS); - try (var stream = Files.list(uploadRoot)) { - stream.filter(Files::isDirectory) - .sorted(Comparator.comparing(Path::toString)) - .forEach(sessionDir -> cleanupExpiredSession(sessionDir, expireAt)); - } - } catch (IOException e) { - log.warn("清理过期上传会话失败", e); - } - } - - /** - * Run business method `cleanupExpiredSession`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @param expireAt parameter `expireAt` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void cleanupExpiredSession(Path sessionDir, Instant expireAt) { - UploadMetadata metadata = readMetadataIfExists(sessionDir); - if (metadata == null) { - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - deleteDirectory(sessionDir); - return; - } - Instant updatedAt = Instant.ofEpochMilli(metadata.getUpdatedAt() == null ? 0L : metadata.getUpdatedAt()); - if (updatedAt.isBefore(expireAt)) { - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionDir parameter `sessionDir` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - deleteDirectory(sessionDir); - } - } - - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param directory parameter `directory` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void deleteDirectory(Path directory) { - if (directory == null || !Files.exists(directory)) { - return; - } - try (var walk = Files.walk(directory)) { - walk.sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - log.warn("删除上传临时文件失败: {}", path, e); - } - }); - } catch (IOException e) { - log.warn("删除上传目录失败: {}", directory, e); - } - } - - /** - * Purpose: UploadTargetType supports ChunkUploadServiceImpl.java by holding or executing the upload target type business role. - * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. - */ - private enum UploadTargetType { - ADMIN_OBJECT_STORAGE, - USER_AVATAR, - USER_PROFILE_IMAGE, - COMMENT_IMAGE - } - - @Data - /** - * Purpose: UploadMetadata supports ChunkUploadServiceImpl.java by holding or executing the upload metadata business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static class UploadMetadata { - /** - * Purpose: uploadId supports ChunkUploadServiceImpl.java by holding or executing the upload id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String uploadId; - /** - * Purpose: targetType supports ChunkUploadServiceImpl.java by holding or executing the target type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String targetType; - /** - * Purpose: ownerId supports ChunkUploadServiceImpl.java by holding or executing the owner id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long ownerId; - /** - * Purpose: fileName supports ChunkUploadServiceImpl.java by holding or executing the file name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String fileName; - /** - * Purpose: contentType supports ChunkUploadServiceImpl.java by holding or executing the content type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String contentType; - /** - * Purpose: fileSize supports ChunkUploadServiceImpl.java by holding or executing the file size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long fileSize; - /** - * Purpose: fileFingerprint supports ChunkUploadServiceImpl.java by holding or executing the file fingerprint business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String fileFingerprint; - /** - * Purpose: scene supports ChunkUploadServiceImpl.java by holding or executing the scene business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String scene; - /** - * Purpose: chunkSize supports ChunkUploadServiceImpl.java by holding or executing the chunk size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer chunkSize; - /** - * Purpose: totalChunks supports ChunkUploadServiceImpl.java by holding or executing the total chunks business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer totalChunks; - /** - * Purpose: createdAt supports ChunkUploadServiceImpl.java by holding or executing the created at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long createdAt; - /** - * Purpose: updatedAt supports ChunkUploadServiceImpl.java by holding or executing the updated at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long updatedAt; - } - - /** - * Purpose: LocalPreparedUploadFile supports ChunkUploadServiceImpl.java by holding or executing the local prepared upload file business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static class LocalPreparedUploadFile implements PreparedUploadFile { - /** - * Variable `file`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final File file; - /** - * Variable `fileName`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String fileName; - /** - * Variable `contentType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String contentType; - /** - * Variable `fileSize`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final long fileSize; - - /** - * Run business method `LocalPreparedUploadFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param file parameter `file` supplied by the caller - * @param fileName parameter `fileName` supplied by the caller - * @param contentType parameter `contentType` supplied by the caller - * @param fileSize parameter `fileSize` supplied by the caller - * @return private result consumed by the caller or returned to the frontend - */ - private LocalPreparedUploadFile(File file, String fileName, String contentType, long fileSize) { - this.file = file; - this.fileName = fileName; - this.contentType = contentType; - this.fileSize = fileSize; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return File result consumed by the caller or returned to the frontend - */ - public File getFile() { - return file; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - public String getFileName() { - return fileName; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - public String getContentType() { - return contentType; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return long result consumed by the caller or returned to the frontend - */ - public long getFileSize() { - return fileSize; - } - - @Override - /** - * Run business method `close`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - */ - public void close() { - if (file != null && file.exists() && !file.delete()) { - log.warn("删除合并后的临时文件失败: {}", file.getAbsolutePath()); - } - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/MinioObjectStorageProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/MinioObjectStorageProvider.java deleted file mode 100644 index a1956fba..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/MinioObjectStorageProvider.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.file.config.MinioStorageConfig; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageProvider; -import io.minio.GetObjectArgs; -import io.minio.GetPresignedObjectUrlArgs; -import io.minio.MinioClient; -import io.minio.PutObjectArgs; -import io.minio.RemoveObjectArgs; -import io.minio.http.Method; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.io.InputStream; -import java.util.concurrent.TimeUnit; - -@Slf4j -@Service -@RequiredArgsConstructor -public class MinioObjectStorageProvider implements ObjectStorageProvider { - - private static final long UNKNOWN_SIZE_PART_SIZE = 10 * 1024 * 1024L; - - private final ObjectProvider minioClientProvider; - private final MinioStorageConfig minioStorageConfig; - - @Override - public String providerCode() { - return "MINIO"; - } - - @Override - public boolean isEnabled() { - return Boolean.TRUE.equals(minioStorageConfig.getEnabled()) - && minioClientProvider.getIfAvailable() != null - && StringUtils.hasText(minioStorageConfig.getBucketName()); - } - - @Override - public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { - MinioClient minioClient = requireClient(); - PutObjectArgs.Builder builder = PutObjectArgs.builder() - .bucket(minioStorageConfig.getBucketName()) - .object(objectName) - .stream(inputStream, fileSize, fileSize < 0 ? UNKNOWN_SIZE_PART_SIZE : -1L); - if (StringUtils.hasText(contentType)) { - builder.contentType(contentType); - } - minioClient.putObject(builder.build()); - log.info("MinIO object uploaded, objectName={}", objectName); - return getFileUrl(objectName); - } - - @Override - public InputStream downloadFile(String objectName) throws Exception { - return requireClient().getObject( - GetObjectArgs.builder() - .bucket(minioStorageConfig.getBucketName()) - .object(objectName) - .build() - ); - } - - @Override - public void deleteFile(String objectName) throws Exception { - requireClient().removeObject( - RemoveObjectArgs.builder() - .bucket(minioStorageConfig.getBucketName()) - .object(objectName) - .build() - ); - } - - @Override - public String getFileUrl(String objectName) { - return normalizeEndpoint(minioStorageConfig.getEndpoint()) + "/" + minioStorageConfig.getBucketName() + "/" + objectName; - } - - @Override - public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception { - if (!Boolean.TRUE.equals(minioStorageConfig.getPrivateBucket())) { - return getFileUrl(objectName); - } - return requireClient().getPresignedObjectUrl( - GetPresignedObjectUrlArgs.builder() - .method(Method.GET) - .bucket(minioStorageConfig.getBucketName()) - .object(objectName) - .expiry(resolveExpireMinutes(expiryTimeInMinutes), TimeUnit.MINUTES) - .build() - ); - } - - private MinioClient requireClient() { - MinioClient minioClient = minioClientProvider.getIfAvailable(); - if (minioClient == null) { - throw new IllegalStateException("MinIO is not enabled or not configured"); - } - return minioClient; - } - - private int resolveExpireMinutes(Integer expiryTimeInMinutes) { - if (expiryTimeInMinutes != null && expiryTimeInMinutes > 0) { - return expiryTimeInMinutes; - } - return minioStorageConfig.getSignedUrlExpireMinutes(); - } - - private String normalizeEndpoint(String endpoint) { - String normalized = endpoint.trim(); - while (normalized.endsWith("/")) { - normalized = normalized.substring(0, normalized.length() - 1); - } - return normalized; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java deleted file mode 100644 index eef2952e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageFileDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.mapper.ObjectStorageFileMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageBackupService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageOrchestrationService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.time.LocalDateTime; - -@Slf4j -@Service -@RequiredArgsConstructor -public class ObjectStorageBackupServiceImpl implements ObjectStorageBackupService { - - public static final int UPLOAD_STATUS_PENDING = 0; - public static final int UPLOAD_STATUS_SUCCEEDED = 1; - public static final int UPLOAD_STATUS_FAILED = 2; - - private static final int ACTIVE_STATUS = 1; - private static final int MAX_ERROR_LENGTH = 500; - - private final ObjectStorageFileMapper objectStorageFileMapper; - private final ObjectStorageOrchestrationService objectStorageOrchestrationService; - private final ObjectStorageFileService objectStorageFileService; - - @Override - public void backupFile(Long fileId) { - if (fileId == null || fileId <= 0) { - return; - } - ObjectStorageFileDO file = objectStorageFileMapper.selectById(fileId); - if (!shouldBackup(file)) { - return; - } - - try { - objectStorageOrchestrationService.completeReplicas(file); - markSucceeded(file); - } catch (Exception e) { - log.warn("Complete object storage replicas failed, fileId={}", fileId, e); - markFailed(file, e); - } - } - - private boolean shouldBackup(ObjectStorageFileDO file) { - return file != null - && Integer.valueOf(ACTIVE_STATUS).equals(file.getStatus()) - && Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getPrimaryUploadStatus()) - && StringUtils.hasText(file.getObjectName()); - } - - private void markSucceeded(ObjectStorageFileDO file) { - file.setBackupUploadStatus(UPLOAD_STATUS_SUCCEEDED); - file.setBackupUploadedAt(LocalDateTime.now()); - file.setBackupLastError(null); - objectStorageFileMapper.updateById(file); - objectStorageFileService.evictObjectStorageFileCache(file.getId()); - } - - private void markFailed(ObjectStorageFileDO file, Exception e) { - file.setBackupUploadStatus(UPLOAD_STATUS_FAILED); - file.setBackupRetryCount((file.getBackupRetryCount() == null ? 0 : file.getBackupRetryCount()) + 1); - file.setBackupLastError(truncateError(e)); - file.setBackupLastRetryTime(LocalDateTime.now()); - objectStorageFileMapper.updateById(file); - objectStorageFileService.evictObjectStorageFileCache(file.getId()); - } - - private String truncateError(Exception e) { - String message = e.getClass().getSimpleName() + ": " + (e.getMessage() == null ? "" : e.getMessage()); - return message.length() <= MAX_ERROR_LENGTH ? message : message.substring(0, MAX_ERROR_LENGTH); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java deleted file mode 100644 index bca9c0be..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.fasterxml.jackson.core.type.TypeReference; -import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties; -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageFileDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageFileDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.mapper.ObjectStorageFileMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.mq.ObjectStorageBackupMessagePublisher; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageReplicaService; -import com.xiaowang.jacyucloudsalon.core.support.cache.MultiLevelCacheService; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import java.time.Duration; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * 对象存储文件信息表 Service 实现 - * 对应数据库表 t_object_storage_file - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class ObjectStorageFileServiceImpl extends ServiceImpl implements ObjectStorageFileService { - - /** - * Purpose: FILE_DETAIL_CACHE_PREFIX supports ObjectStorageFileServiceImpl.java by holding or executing the file detail cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String FILE_DETAIL_CACHE_PREFIX = "cache:file:detail:"; - /** - * Variable `objectStorageFileMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageFileMapper objectStorageFileMapper; - /** - * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MultiLevelCacheService multiLevelCacheService; - /** - * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AppCacheProperties appCacheProperties; - private final ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher; - private final ObjectStorageProperties objectStorageProperties; - private final ObjectStorageReplicaService objectStorageReplicaService; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO) { - ObjectStorageFileDO objectStorageFileDO = new ObjectStorageFileDO(); - applyDTO(objectStorageFileDO, objectStorageFileDTO); - objectStorageFileMapper.insert(objectStorageFileDO); - objectStorageReplicaService.saveInitialReplicas(objectStorageFileDO.getId(), objectStorageFileDTO.getUploadAttempts()); - evictFileCache(objectStorageFileDO.getId()); - publishBackupIfNeeded(objectStorageFileDO); - return objectStorageFileDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateObjectStorageFile(Long id, ObjectStorageFileDTO objectStorageFileDTO) { - ObjectStorageFileDO objectStorageFileDO = objectStorageFileMapper.selectById(id); - if (objectStorageFileDO == null) { - return false; - } - applyDTO(objectStorageFileDO, objectStorageFileDTO); - boolean updated = objectStorageFileMapper.updateById(objectStorageFileDO) > 0; - if (updated) { - /** - * Run business method `evictFileCache`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictFileCache(id); - } - return updated; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteObjectStorageFile(Long id) { - boolean deleted = objectStorageFileMapper.deleteById(id) > 0; - if (deleted) { - /** - * Run business method `evictFileCache`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictFileCache(id); - } - return deleted; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return ObjectStorageFileVO result consumed by the caller or returned to the frontend - */ - public ObjectStorageFileVO getObjectStorageFileById(Long id) { - return getObjectStorageFileMapByIds(Collections.singleton(id)).get(id); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return Map result consumed by the caller or returned to the frontend - */ - public Map getObjectStorageFileMapByIds(Collection ids) { - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyMap(); - } - - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getObjectStorageFile(); - Duration localTtl = Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()); - Duration redisTtl = Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()); - Map result = new LinkedHashMap<>(); - Set missingIds = new LinkedHashSet<>(); - - for (Long id : ids) { - if (id == null || id <= 0) { - continue; - } - MultiLevelCacheService.CacheLookup lookup = multiLevelCacheService.get( - buildDetailCacheKey(id), - localTtl, - new TypeReference() { - } - ); - if (lookup.isHit()) { - if (lookup.getValue() != null) { - result.put(id, lookup.getValue()); - } - continue; - } - missingIds.add(id); - } - - if (!missingIds.isEmpty()) { - Map loadedMap = objectStorageFileMapper.selectBatchIds(missingIds).stream() - .collect(Collectors.toMap(ObjectStorageFileDO::getId, this::convertToVO, (left, right) -> left, LinkedHashMap::new)); - for (Long missingId : missingIds) { - ObjectStorageFileVO fileVO = loadedMap.get(missingId); - multiLevelCacheService.put(buildDetailCacheKey(missingId), fileVO, localTtl, redisTtl); - if (fileVO != null) { - result.put(missingId, fileVO); - } - } - } - - return result; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllObjectStorageFiles() { - List objectStorageFileDOs = objectStorageFileMapper.selectList(null); - return objectStorageFileDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param status parameter `status` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listObjectStorageFilesByStatus(Integer status) { - List objectStorageFileDOs = objectStorageFileMapper.selectList( - Wrappers.lambdaQuery(ObjectStorageFileDO.class) - .eq(ObjectStorageFileDO::getStatus, status) - ); - return objectStorageFileDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param objectStorageFileDO 文件DO - * @return 文件VO - */ - private ObjectStorageFileVO convertToVO(ObjectStorageFileDO objectStorageFileDO) { - ObjectStorageFileVO objectStorageFileVO = new ObjectStorageFileVO(); - objectStorageFileVO.setId(objectStorageFileDO.getId()); - objectStorageFileVO.setFileName(objectStorageFileDO.getFileName()); - objectStorageFileVO.setFileUrl(objectStorageFileDO.getFileUrl()); - objectStorageFileVO.setObjectName(objectStorageFileDO.getObjectName()); - objectStorageFileVO.setPrimaryProvider(objectStorageFileDO.getPrimaryProvider()); - objectStorageFileVO.setPrimaryUrl(objectStorageFileDO.getPrimaryUrl()); - objectStorageFileVO.setBackupProvider(objectStorageFileDO.getBackupProvider()); - objectStorageFileVO.setBackupUrl(objectStorageFileDO.getBackupUrl()); - objectStorageFileVO.setContentType(objectStorageFileDO.getContentType()); - objectStorageFileVO.setFileSize(objectStorageFileDO.getFileSize()); - objectStorageFileVO.setPrimaryUploadStatus(objectStorageFileDO.getPrimaryUploadStatus()); - objectStorageFileVO.setBackupUploadStatus(objectStorageFileDO.getBackupUploadStatus()); - objectStorageFileVO.setBackupRetryCount(objectStorageFileDO.getBackupRetryCount()); - objectStorageFileVO.setBackupLastError(objectStorageFileDO.getBackupLastError()); - objectStorageFileVO.setBackupUploadedAt(objectStorageFileDO.getBackupUploadedAt()); - objectStorageFileVO.setBackupLastRetryTime(objectStorageFileDO.getBackupLastRetryTime()); - objectStorageFileVO.setCreateTime(objectStorageFileDO.getCreateTime()); - objectStorageFileVO.setStatus(objectStorageFileDO.getStatus()); - objectStorageFileVO.setDeleteTime(objectStorageFileDO.getDeleteTime()); - objectStorageFileVO.setRecycleTime(objectStorageFileDO.getRecycleTime()); - return objectStorageFileVO; - } - - private void applyDTO(ObjectStorageFileDO objectStorageFileDO, ObjectStorageFileDTO objectStorageFileDTO) { - objectStorageFileDO.setFileName(objectStorageFileDTO.getFileName()); - objectStorageFileDO.setFileUrl(objectStorageFileDTO.getFileUrl()); - objectStorageFileDO.setObjectName(objectStorageFileDTO.getObjectName()); - objectStorageFileDO.setPrimaryProvider(objectStorageFileDTO.getPrimaryProvider()); - objectStorageFileDO.setPrimaryUrl(objectStorageFileDTO.getPrimaryUrl()); - objectStorageFileDO.setBackupProvider(objectStorageFileDTO.getBackupProvider()); - objectStorageFileDO.setBackupUrl(objectStorageFileDTO.getBackupUrl()); - objectStorageFileDO.setContentType(objectStorageFileDTO.getContentType()); - objectStorageFileDO.setFileSize(objectStorageFileDTO.getFileSize()); - objectStorageFileDO.setPrimaryUploadStatus(objectStorageFileDTO.getPrimaryUploadStatus()); - objectStorageFileDO.setBackupUploadStatus(objectStorageFileDTO.getBackupUploadStatus()); - objectStorageFileDO.setBackupRetryCount(objectStorageFileDTO.getBackupRetryCount()); - objectStorageFileDO.setBackupLastError(objectStorageFileDTO.getBackupLastError()); - objectStorageFileDO.setBackupUploadedAt(objectStorageFileDTO.getBackupUploadedAt()); - objectStorageFileDO.setBackupLastRetryTime(objectStorageFileDTO.getBackupLastRetryTime()); - objectStorageFileDO.setStatus(objectStorageFileDTO.getStatus()); - objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime()); - objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime()); - } - - private void publishBackupIfNeeded(ObjectStorageFileDO objectStorageFileDO) { - if (StringUtils.hasText(objectStorageFileDO.getObjectName()) - && objectStorageProperties.getProviderOrder().contains(objectStorageFileDO.getPrimaryProvider()) - && Integer.valueOf(1).equals(objectStorageFileDO.getPrimaryUploadStatus()) - && Integer.valueOf(0).equals(objectStorageFileDO.getBackupUploadStatus())) { - objectStorageBackupMessagePublisher.publish(objectStorageFileDO.getId()); - } - } - - @Override - public void evictObjectStorageFileCache(Long id) { - evictFileCache(id); - } - - /** - * Run business method `evictFileCache`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void evictFileCache(Long id) { - if (id != null && id > 0) { - multiLevelCacheService.evict(buildDetailCacheKey(id)); - } - } - - /** - * Run business method `buildDetailCacheKey`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildDetailCacheKey(Long id) { - return FILE_DETAIL_CACHE_PREFIX + id; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java deleted file mode 100644 index 9a6cff01..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageReplicaDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageUploadAttempt; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageUploadOutcome; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageFileDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageReplicaDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageOrchestrationService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageProvider; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageReplicaService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Slf4j -@Service -@RequiredArgsConstructor -public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrchestrationService { - - private static final int MAX_ERROR_LENGTH = 500; - - private final List providers; - private final ObjectStorageProperties objectStorageProperties; - private final ObjectStorageReplicaService objectStorageReplicaService; - - @Override - public ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { - byte[] bytes = toBytes(inputStream); - List attempts = new ArrayList<>(); - Exception lastFailure = null; - for (String providerCode : objectStorageProperties.getProviderOrder()) { - ObjectStorageProvider provider = requireProvider(providerCode); - try { - ensureEnabled(provider); - String objectUrl = provider.uploadStream( - new ByteArrayInputStream(bytes), - fileSize, - contentType, - objectName - ); - attempts.add(new ObjectStorageUploadAttempt( - provider.providerCode(), - objectName, - objectUrl, - ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED, - 0, - null - )); - return new ObjectStorageUploadOutcome(provider.providerCode(), objectUrl, attempts); - } catch (Exception e) { - lastFailure = e; - attempts.add(new ObjectStorageUploadAttempt( - provider.providerCode(), - objectName, - null, - ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED, - 1, - truncateError(e) - )); - log.warn("Upload object to provider failed, provider={}, objectName={}", provider.providerCode(), objectName, e); - } - } - throw new IllegalStateException("No available object storage provider for objectName=" + objectName, lastFailure); - } - - @Override - public void completeReplicas(ObjectStorageFileDO file) { - if (file == null || file.getId() == null || !StringUtils.hasText(file.getObjectName())) { - return; - } - List replicas = objectStorageReplicaService.listByFileId(file.getId()); - Map replicaMap = replicas.stream() - .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); - boolean completed = true; - for (String providerCode : objectStorageProperties.getReplicaRequiredProviders()) { - ObjectStorageReplicaDO existing = replicaMap.get(providerCode); - if (existing != null - && Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(existing.getUploadStatus())) { - continue; - } - completed = uploadReplica(file, providerCode, replicaMap) && completed; - } - if (!completed) { - throw new IllegalStateException("Object storage replicas are not fully completed for fileId=" + file.getId()); - } - } - - @Override - public String getPresignedUrl(Long fileId, String objectName, Integer expiryTimeInMinutes) { - if (fileId == null || fileId <= 0) { - return getPresignedUrl(objectName, expiryTimeInMinutes); - } - List replicas = objectStorageReplicaService.listByFileId(fileId); - if (CollectionUtils.isEmpty(replicas)) { - return getPresignedUrl(objectName, expiryTimeInMinutes); - } - Map replicaMap = replicas.stream() - .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); - Exception lastFailure = null; - for (String providerCode : objectStorageProperties.getProviderOrder()) { - ObjectStorageReplicaDO replica = replicaMap.get(providerCode); - if (replica == null - || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { - continue; - } - try { - return requireProvider(providerCode).getPresignedUrl(replica.getObjectName(), expiryTimeInMinutes); - } catch (Exception e) { - lastFailure = e; - log.warn("Generate object storage signed URL failed, fileId={}, provider={}", fileId, providerCode, e); - } - } - throw new IllegalStateException("No available object storage signed URL for fileId=" + fileId, lastFailure); - } - - @Override - public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { - Exception lastFailure = null; - for (String providerCode : objectStorageProperties.getProviderOrder()) { - try { - ObjectStorageProvider provider = requireProvider(providerCode); - ensureEnabled(provider); - return provider.getPresignedUrl(objectName, expiryTimeInMinutes); - } catch (Exception e) { - lastFailure = e; - log.warn("Generate object storage signed URL by objectName failed, provider={}, objectName={}", providerCode, objectName, e); - } - } - throw new IllegalStateException("No available object storage signed URL for objectName=" + objectName, lastFailure); - } - - private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map replicaMap) { - ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); - replicaDTO.setProvider(providerCode); - replicaDTO.setObjectName(file.getObjectName()); - boolean success = false; - try (InputStream inputStream = openReadableReplica(replicaMap, file.getObjectName())) { - ObjectStorageProvider targetProvider = requireProvider(providerCode); - ensureEnabled(targetProvider); - String objectUrl = targetProvider.uploadStream( - inputStream, - file.getFileSize() == null ? -1L : file.getFileSize(), - file.getContentType(), - file.getObjectName() - ); - replicaDTO.setObjectUrl(objectUrl); - replicaDTO.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED); - replicaDTO.setRetryCount(0); - replicaDTO.setUploadedAt(LocalDateTime.now()); - replicaDTO.setLastError(null); - success = true; - } catch (Exception e) { - ObjectStorageReplicaDO existing = replicaMap.get(providerCode); - replicaDTO.setObjectUrl(existing == null ? null : existing.getObjectUrl()); - replicaDTO.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED); - replicaDTO.setRetryCount((existing == null || existing.getRetryCount() == null ? 0 : existing.getRetryCount()) + 1); - replicaDTO.setLastRetryTime(LocalDateTime.now()); - replicaDTO.setLastError(truncateError(e)); - log.warn("Complete object storage replica failed, fileId={}, provider={}", file.getId(), providerCode, e); - } - objectStorageReplicaService.saveOrUpdateReplica(file.getId(), replicaDTO); - return success; - } - - private InputStream openReadableReplica(Map replicaMap, String objectName) throws Exception { - Exception lastFailure = null; - for (String providerCode : objectStorageProperties.getProviderOrder()) { - ObjectStorageReplicaDO replica = replicaMap.get(providerCode); - if (replica == null - || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { - continue; - } - try { - return requireProvider(providerCode).downloadFile(replica.getObjectName()); - } catch (Exception e) { - lastFailure = e; - log.warn("Download object storage readable replica failed, provider={}, objectName={}", providerCode, replica.getObjectName(), e); - } - } - throw new IllegalStateException("No readable object storage replica for objectName=" + objectName, lastFailure); - } - - private ObjectStorageProvider requireProvider(String providerCode) { - for (ObjectStorageProvider provider : providers) { - if (provider.providerCode().equals(providerCode)) { - return provider; - } - } - throw new IllegalStateException("Object storage provider is not registered: " + providerCode); - } - - private void ensureEnabled(ObjectStorageProvider provider) { - if (!provider.isEnabled()) { - throw new IllegalStateException("Object storage provider is disabled or incomplete: " + provider.providerCode()); - } - } - - private byte[] toBytes(InputStream inputStream) throws Exception { - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - byte[] buffer = new byte[8192]; - int read; - while ((read = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, read); - } - return outputStream.toByteArray(); - } - } - - private String truncateError(Exception e) { - String message = e.getClass().getSimpleName() + ": " + (e.getMessage() == null ? "" : e.getMessage()); - return message.length() <= MAX_ERROR_LENGTH ? message : message.substring(0, MAX_ERROR_LENGTH); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java deleted file mode 100644 index 44891afa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageReplicaDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ObjectStorageUploadAttempt; -import com.xiaowang.jacyucloudsalon.core.modules.file.entity.ObjectStorageReplicaDO; -import com.xiaowang.jacyucloudsalon.core.modules.file.mapper.ObjectStorageReplicaMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageReplicaService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.time.LocalDateTime; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -public class ObjectStorageReplicaServiceImpl implements ObjectStorageReplicaService { - - private final ObjectStorageReplicaMapper objectStorageReplicaMapper; - - @Override - public List listByFileId(Long fileId) { - if (fileId == null || fileId <= 0) { - return Collections.emptyList(); - } - return objectStorageReplicaMapper.selectList( - Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) - .eq(ObjectStorageReplicaDO::getFileId, fileId) - ); - } - - @Override - public Map> listMapByFileIds(Collection fileIds) { - if (CollectionUtils.isEmpty(fileIds)) { - return Collections.emptyMap(); - } - List replicas = objectStorageReplicaMapper.selectList( - Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) - .in(ObjectStorageReplicaDO::getFileId, fileIds) - ); - return replicas.stream() - .collect(Collectors.groupingBy( - ObjectStorageReplicaDO::getFileId, - LinkedHashMap::new, - Collectors.toList() - )); - } - - @Override - public void saveInitialReplicas(Long fileId, List attempts) { - if (fileId == null || fileId <= 0 || CollectionUtils.isEmpty(attempts)) { - return; - } - for (ObjectStorageUploadAttempt attempt : attempts) { - ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); - replicaDTO.setProvider(attempt.getProvider()); - replicaDTO.setObjectName(attempt.getObjectName()); - replicaDTO.setObjectUrl(attempt.getObjectUrl()); - replicaDTO.setUploadStatus(attempt.getUploadStatus()); - replicaDTO.setRetryCount(attempt.getRetryCount()); - replicaDTO.setLastError(attempt.getLastError()); - if (Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(attempt.getUploadStatus())) { - replicaDTO.setUploadedAt(LocalDateTime.now()); - } - saveOrUpdateReplica(fileId, replicaDTO); - } - } - - @Override - public void saveOrUpdateReplica(Long fileId, ObjectStorageReplicaDTO replicaDTO) { - if (fileId == null || fileId <= 0 || replicaDTO == null) { - return; - } - ObjectStorageReplicaDO replica = objectStorageReplicaMapper.selectOne( - Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) - .eq(ObjectStorageReplicaDO::getFileId, fileId) - .eq(ObjectStorageReplicaDO::getProvider, replicaDTO.getProvider()) - .last("LIMIT 1") - ); - if (replica == null) { - replica = new ObjectStorageReplicaDO(); - replica.setFileId(fileId); - replica.setProvider(replicaDTO.getProvider()); - } - replica.setObjectName(replicaDTO.getObjectName()); - replica.setObjectUrl(replicaDTO.getObjectUrl()); - replica.setUploadStatus(replicaDTO.getUploadStatus()); - replica.setRetryCount(replicaDTO.getRetryCount()); - replica.setLastError(replicaDTO.getLastError()); - replica.setUploadedAt(replicaDTO.getUploadedAt()); - replica.setLastRetryTime(replicaDTO.getLastRetryTime()); - if (replica.getId() == null) { - objectStorageReplicaMapper.insert(replica); - } else { - objectStorageReplicaMapper.updateById(replica); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java deleted file mode 100644 index 8a7f0338..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.service.impl; - -import com.qiniu.http.Response; -import com.qiniu.storage.BucketManager; -import com.qiniu.storage.UploadManager; -import com.qiniu.storage.model.DefaultPutRet; -import com.qiniu.util.Auth; -import com.qiniu.util.StringMap; -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.modules.file.config.QiniuKodoConfig; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageProvider; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.PrimaryObjectStorageService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import java.io.InputStream; -import java.io.ByteArrayOutputStream; -import java.net.URL; -import java.util.concurrent.TimeUnit; - -@Slf4j -@Service -@RequiredArgsConstructor -public class QiniuObjectStorageServiceImpl implements PrimaryObjectStorageService, ObjectStorageProvider { - - private final QiniuKodoConfig qiniuKodoConfig; - private final ObjectStorageProperties objectStorageProperties; - private final Auth qiniuAuth; - private final UploadManager qiniuUploadManager; - private final BucketManager qiniuBucketManager; - - @Override - public String providerCode() { - return "QINIU_KODO"; - } - - @Override - public boolean isEnabled() { - return StringUtils.hasText(qiniuKodoConfig.getAccessKey()) - && StringUtils.hasText(qiniuKodoConfig.getSecretKey()) - && StringUtils.hasText(qiniuKodoConfig.getBucketName()) - && StringUtils.hasText(qiniuKodoConfig.getDomain()); - } - - @Override - public String uploadFile(MultipartFile file, String objectName) throws Exception { - try (InputStream inputStream = file.getInputStream()) { - return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName); - } - } - - @Override - public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { - byte[] bytes = toBytes(inputStream); - String uploadToken = qiniuAuth.uploadToken( - qiniuKodoConfig.getBucketName(), - objectName, - buildUploadPolicyExpirySeconds(), - new StringMap() - ); - Response response = qiniuUploadManager.put( - bytes, - objectName, - uploadToken, - null, - contentType, - false - ); - DefaultPutRet putRet = response.jsonToObject(DefaultPutRet.class); - log.info("七牛云文件上传成功, key={}", putRet.key); - return getFileUrl(objectName); - } - - @Override - public InputStream downloadFile(String objectName) throws Exception { - URL url = new URL(getPresignedUrl(objectName, objectStorageProperties.getSignedUrlExpireMinutes())); - return url.openStream(); - } - - @Override - public void deleteFile(String objectName) throws Exception { - qiniuBucketManager.delete(qiniuKodoConfig.getBucketName(), objectName); - log.info("七牛云文件删除成功, key={}", objectName); - } - - @Override - public String getFileUrl(String objectName) { - return normalizeDomain(qiniuKodoConfig.getDomain()) + "/" + objectName; - } - - @Override - public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception { - if (!Boolean.TRUE.equals(qiniuKodoConfig.getPrivateBucket())) { - return getFileUrl(objectName); - } - int expireMinutes = expiryTimeInMinutes == null || expiryTimeInMinutes <= 0 - ? qiniuKodoConfig.getSignedUrlExpireMinutes() - : expiryTimeInMinutes; - return qiniuAuth.privateDownloadUrl( - getFileUrl(objectName), - TimeUnit.MINUTES.toSeconds(expireMinutes) - ); - } - - private long buildUploadPolicyExpirySeconds() { - return TimeUnit.MINUTES.toSeconds(qiniuKodoConfig.getSignedUrlExpireMinutes()); - } - - private byte[] toBytes(InputStream inputStream) throws Exception { - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - byte[] buffer = new byte[8192]; - int read; - while ((read = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, read); - } - return outputStream.toByteArray(); - } - } - - private String normalizeDomain(String domain) { - String normalized = domain.trim(); - while (normalized.endsWith("/")) { - normalized = normalized.substring(0, normalized.length() - 1); - } - if (!StringUtils.hasText(normalized)) { - throw new IllegalStateException("Qiniu domain is blank"); - } - if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { - return "http://" + normalized; - } - return normalized; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/support/ObjectStorageUrlSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/support/ObjectStorageUrlSupport.java deleted file mode 100644 index c0756fb7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/support/ObjectStorageUrlSupport.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.support; - -import com.xiaowang.jacyucloudsalon.core.config.ObjectStorageProperties; -import com.xiaowang.jacyucloudsalon.core.modules.file.config.QiniuKodoConfig; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.AliyunOssService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageOrchestrationService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.PrimaryObjectStorageService; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import java.net.URI; - -@Slf4j -@Component -@RequiredArgsConstructor -public class ObjectStorageUrlSupport { - - private static final int UPLOAD_STATUS_SUCCEEDED = 1; - - private final PrimaryObjectStorageService primaryObjectStorageService; - private final QiniuKodoConfig qiniuKodoConfig; - private final AliyunOssService aliyunOssService; - private final ObjectStorageProperties objectStorageProperties; - private final ObjectStorageOrchestrationService objectStorageOrchestrationService; - - public String toAccessibleUrl(String fileUrl) { - if (!StringUtils.hasText(fileUrl)) { - return fileUrl; - } - String objectName = extractObjectName(fileUrl); - if (!StringUtils.hasText(objectName)) { - return fileUrl; - } - try { - return objectStorageOrchestrationService.getPresignedUrl( - objectName, - objectStorageProperties.getSignedUrlExpireMinutes() - ); - } catch (Exception e) { - log.warn("生成主对象存储访问链接失败, fileUrl={}", fileUrl, e); - return null; - } - } - - public String toAccessibleUrl(ObjectStorageFileVO file) { - return toAccessibleUrl(file, objectStorageProperties.getSignedUrlExpireMinutes()); - } - - public String toAccessibleUrl(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { - if (file == null) { - return null; - } - try { - return getSignedUrlOrThrow(file, expiryTimeInMinutes); - } catch (Exception e) { - String fallback = hasObjectStorageReference(file) ? null : firstText(file.getFileUrl(), file.getPrimaryUrl()); - log.warn("生成对象存储访问链接失败, fileId={}", file.getId(), e); - return fallback; - } - } - - public String getSignedUrlOrThrow(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { - if (file == null) { - throw new IllegalStateException("No available object storage signed URL: file is null"); - } - String objectName = resolveObjectName(file); - if (!StringUtils.hasText(objectName)) { - throw new IllegalStateException("No available object storage signed URL: objectName is empty"); - } - - Exception primaryFailure = null; - try { - return objectStorageOrchestrationService.getPresignedUrl(file.getId(), objectName, expiryTimeInMinutes); - } catch (Exception e) { - primaryFailure = e; - log.warn("生成主对象存储访问链接失败, fileId={}, objectName={}", file.getId(), objectName, e); - } - - if (Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getBackupUploadStatus())) { - try { - return aliyunOssService.getPresignedUrl(objectName); - } catch (Exception e) { - IllegalStateException failure = new IllegalStateException( - "No available object storage signed URL for fileId=" + file.getId(), - e - ); - failure.addSuppressed(primaryFailure); - throw failure; - } - } - - IllegalStateException failure = new IllegalStateException( - "No available object storage signed URL for fileId=" + file.getId() - ); - failure.addSuppressed(primaryFailure); - throw failure; - } - - public String toStoredUrl(String fileUrl) { - if (!StringUtils.hasText(fileUrl)) { - return fileUrl; - } - String objectName = extractObjectName(fileUrl); - if (!StringUtils.hasText(objectName)) { - return fileUrl; - } - return primaryObjectStorageService.getFileUrl(objectName); - } - - public String extractObjectName(String fileUrl) { - if (!StringUtils.hasText(fileUrl)) { - return ""; - } - - String normalizedUrl = fileUrl.trim(); - if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) { - return stripQuery(stripLeadingSlash(normalizedUrl)); - } - - try { - URI fileUri = URI.create(normalizedUrl); - URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain())); - if (!sameAuthority(fileUri, domainUri)) { - return ""; - } - return stripQuery(stripLeadingSlash(fileUri.getPath())); - } catch (Exception e) { - log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e); - return ""; - } - } - - private String resolveObjectName(ObjectStorageFileVO file) { - if (StringUtils.hasText(file.getObjectName())) { - return file.getObjectName(); - } - String objectName = extractObjectName(file.getPrimaryUrl()); - if (StringUtils.hasText(objectName)) { - return objectName; - } - return extractObjectName(file.getFileUrl()); - } - - private boolean hasObjectStorageReference(ObjectStorageFileVO file) { - return StringUtils.hasText(file.getObjectName()) - || StringUtils.hasText(extractObjectName(file.getPrimaryUrl())) - || StringUtils.hasText(extractObjectName(file.getFileUrl())); - } - - private String firstText(String... values) { - if (values == null) { - return null; - } - for (String value : values) { - if (StringUtils.hasText(value)) { - return value; - } - } - return null; - } - - private String normalizeDomain(String domain) { - String normalized = domain.trim(); - while (normalized.endsWith("/")) { - normalized = normalized.substring(0, normalized.length() - 1); - } - if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { - return "http://" + normalized; - } - return normalized; - } - - private boolean sameAuthority(URI left, URI right) { - return left.getScheme() != null - && left.getScheme().equalsIgnoreCase(right.getScheme()) - && left.getHost() != null - && left.getHost().equalsIgnoreCase(right.getHost()) - && normalizedPort(left) == normalizedPort(right); - } - - private int normalizedPort(URI uri) { - if (uri.getPort() >= 0) { - return uri.getPort(); - } - return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; - } - - private String stripLeadingSlash(String rawValue) { - String normalized = rawValue; - while (normalized.startsWith("/")) { - normalized = normalized.substring(1); - } - return normalized; - } - - private String stripQuery(String rawValue) { - int queryIndex = rawValue.indexOf('?'); - return queryIndex >= 0 ? rawValue.substring(0, queryIndex) : rawValue; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/vo/ChunkUploadSessionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/vo/ChunkUploadSessionVO.java deleted file mode 100644 index 4763b2ce..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/vo/ChunkUploadSessionVO.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.vo; - -import lombok.Data; - -import java.util.List; - -/** - * 分片上传会话信息 - */ -@Data -public class ChunkUploadSessionVO { - - /** - * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String uploadId; - - /** - * Field `chunkSize` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer chunkSize; - - /** - * Field `totalChunks` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer totalChunks; - - /** - * Field `uploadedChunks` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List uploadedChunks; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/vo/ObjectStorageFileVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/vo/ObjectStorageFileVO.java deleted file mode 100644 index 095da50e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/file/vo/ObjectStorageFileVO.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.file.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 对象存储文件信息表 VO - * 用于前端展示文件信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class ObjectStorageFileVO { - - /** - * 文件记录唯一主键ID(雪花ID) - */ - private Long id; - - /** - * 文件名称 - */ - private String fileName; - - /** - * 文件访问链接 - */ - private String fileUrl; - - private String objectName; - - private String primaryProvider; - - private String primaryUrl; - - private String backupProvider; - - private String backupUrl; - - private String contentType; - - private Long fileSize; - - private Integer primaryUploadStatus; - - private Integer backupUploadStatus; - - private Integer backupRetryCount; - - private String backupLastError; - - private LocalDateTime backupUploadedAt; - - private LocalDateTime backupLastRetryTime; - - /** - * 文件上传时间 - */ - private LocalDateTime createTime; - - /** - * 文件状态:1-可用,0-不可用,2-回收站 - */ - private Integer status; - - /** - * 文件状态名称 - */ - private String statusName; - - /** - * 文件删除时间(NULL表示未删除) - */ - private LocalDateTime deleteTime; - - /** - * 文件移入回收站时间(NULL表示未移入) - */ - private LocalDateTime recycleTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/controller/front/MessageHubPushConfigController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/controller/front/MessageHubPushConfigController.java deleted file mode 100644 index d85e327a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/controller/front/MessageHubPushConfigController.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.MessageHubPushConfigDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.MessageHubPushTestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubPushConfigService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.MessageHubPushConfigVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/messagehub-push-config", "/api/messagehub-push-config", "/admin/messagehub-push-config"}) -/** - * MessageHubPushConfigController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class MessageHubPushConfigController { - /** - * Variable `configService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MessageHubPushConfigService configService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @GetMapping("/admin/list") - @RequirePermission("messagehub:config:manage") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> list(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.listConfigs(currentUser)); - } - - @PostMapping("/admin/create") - @RequirePermission("messagehub:config:manage") - @OperationGuard(action = "messagehub-push-config-create", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result create(HttpServletRequest request, @Valid @RequestBody MessageHubPushConfigDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.createConfig(currentUser, dto)); - } - - @PutMapping("/admin/{id}") - @RequirePermission("messagehub:config:manage") - @OperationGuard(action = "messagehub-push-config-update", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushConfigDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.updateConfig(currentUser, id, dto)); - } - - @PutMapping("/admin/{id}/status") - @RequirePermission("messagehub:config:manage") - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param enabled parameter `enabled` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer enabled) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.updateStatus(currentUser, id, enabled)); - } - - @PostMapping("/admin/{id}/test") - @RequirePermission("messagehub:config:manage") - @OperationGuard(action = "messagehub-push-config-test", ttlSeconds = 8, message = "测试投递处理中,请勿重复提交") - /** - * Run a test call without changing normal business data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result test(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushTestDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.testConfig(currentUser, id, dto)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/MessageHubPushConfigDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/MessageHubPushConfigDTO.java deleted file mode 100644 index 7ca83847..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/MessageHubPushConfigDTO.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - -@Data -/** - * MessageHubPushConfigDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class MessageHubPushConfigDTO { - - @NotBlank(message = "场景编码不能为空") - @Size(max = 80, message = "场景编码不能超过80个字符") - /** - * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sceneCode; - - @NotBlank(message = "场景名称不能为空") - @Size(max = 100, message = "场景名称不能超过100个字符") - /** - * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sceneName; - - @NotBlank(message = "消息平台不能为空") - @Size(max = 20, message = "消息平台不能超过20个字符") - /** - * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String platform = "SMS"; - - @NotBlank(message = "消息类型不能为空") - @Size(max = 30, message = "消息类型不能超过30个字符") - /** - * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String msgType = "VERIFICATION"; - - @NotBlank(message = "队列名称不能为空") - @Size(max = 100, message = "队列名称不能超过100个字符") - /** - * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String queueName; - - @NotBlank(message = "来源系统不能为空") - @Size(max = 80, message = "来源系统不能超过80个字符") - /** - * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceSystem; - - @NotBlank(message = "模板编码不能为空") - @Size(max = 100, message = "模板编码不能超过100个字符") - /** - * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String templateCode; - - /** - * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long channelId; - - @Size(max = 30, message = "发送方式不能超过30个字符") - /** - * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sendMethod; - - /** - * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer enabled = 1; - - @Size(max = 255, message = "备注不能超过255个字符") - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/MessageHubPushTestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/MessageHubPushTestDTO.java deleted file mode 100644 index 58c3ec90..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/MessageHubPushTestDTO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; - -@Data -/** - * MessageHubPushTestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class MessageHubPushTestDTO { - - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") - /** - * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String phone; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java deleted file mode 100644 index 75ed5435..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; - -/** - * 微信小程序自动登录请求。 - */ -@Data -public class WechatMiniAutoLoginRequestDTO { - - @NotBlank(message = "微信登录凭证不能为空") - /** - * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String wxCode; - - /** - * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long preferredShopId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java deleted file mode 100644 index bd6bd91a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import java.util.Map; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -/** - * 微信小程序补选店铺后确认登录请求。 - */ -@Data -public class WechatMiniConfirmLoginRequestDTO implements AgreementAwareRequest { - - @NotBlank(message = "登录票据不能为空") - /** - * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String ticket; - - @NotNull(message = "店铺不能为空") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - /** - * Purpose: agreementAccepted supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the agreement accepted business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean agreementAccepted; - - /** - * Purpose: agreementVersions supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the agreement versions business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map agreementVersions; - - /** - * Purpose: clientType supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the client type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String clientType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java deleted file mode 100644 index 07a4ff07..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import java.util.Map; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -/** - * 微信小程序手机号一键登录请求。 - */ -@Data -public class WechatMiniPhoneLoginRequestDTO implements AgreementAwareRequest { - - @NotBlank(message = "微信登录凭证不能为空") - /** - * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String wxCode; - - @NotBlank(message = "手机号授权凭证不能为空") - /** - * Field `phoneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String phoneCode; - - /** - * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long preferredShopId; - - /** - * Purpose: agreementAccepted supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the agreement accepted business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean agreementAccepted; - - /** - * Purpose: agreementVersions supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the agreement versions business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map agreementVersions; - - /** - * Purpose: clientType supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the client type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String clientType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/BusinessEventOutboxDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/BusinessEventOutboxDO.java deleted file mode 100644 index e7abf05e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/BusinessEventOutboxDO.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_business_event_outbox") -/** - * Purpose: BusinessEventOutboxDO supports BusinessEventOutboxDO.java by holding or executing the business event outbox do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class BusinessEventOutboxDO extends BaseEntity { - - @TableField("event_key") - /** - * Purpose: eventKey supports BusinessEventOutboxDO.java by holding or executing the event key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String eventKey; - - @TableField("event_type") - /** - * Purpose: eventType supports BusinessEventOutboxDO.java by holding or executing the event type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String eventType; - - @TableField("business_type") - /** - * Purpose: businessType supports BusinessEventOutboxDO.java by holding or executing the business type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String businessType; - - @TableField("business_id") - /** - * Purpose: businessId supports BusinessEventOutboxDO.java by holding or executing the business id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long businessId; - - @TableField("payload_json") - /** - * Purpose: payloadJson supports BusinessEventOutboxDO.java by holding or executing the payload json business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String payloadJson; - - @TableField("status") - /** - * Purpose: status supports BusinessEventOutboxDO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String status; - - @TableField("retry_count") - /** - * Purpose: retryCount supports BusinessEventOutboxDO.java by holding or executing the retry count business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer retryCount; - - @TableField("next_retry_time") - /** - * Purpose: nextRetryTime supports BusinessEventOutboxDO.java by holding or executing the next retry time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime nextRetryTime; - - @TableField("last_error") - /** - * Purpose: lastError supports BusinessEventOutboxDO.java by holding or executing the last error business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String lastError; - - @TableField("claimed_at") - /** - * Purpose: claimedAt supports BusinessEventOutboxDO.java by holding or executing the claimed at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime claimedAt; - - @TableField("processed_at") - /** - * Purpose: processedAt supports BusinessEventOutboxDO.java by holding or executing the processed at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime processedAt; - - @TableField("is_delete") - /** - * Purpose: isDelete supports BusinessEventOutboxDO.java by holding or executing the is delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/MessageHubPushConfigDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/MessageHubPushConfigDO.java deleted file mode 100644 index 813a79f7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/MessageHubPushConfigDO.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * FingertipDesigner 调用 MessageHub 的场景级配置。 - * - *

这里不保存 Spug、阿里云等供应商密钥;这些真实通道仍由 MessageHub 自己管理。 - * 本表只描述 FingertipDesigner 在某个业务功能里投递 MessageHub 时要携带的参数。

- */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_messagehub_push_config") -public class MessageHubPushConfigDO extends BaseEntity { - - @TableField("scene_code") - /** - * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sceneCode; - - @TableField("scene_name") - /** - * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sceneName; - - @TableField("platform") - /** - * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String platform; - - @TableField("msg_type") - /** - * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String msgType; - - @TableField("queue_name") - /** - * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String queueName; - - @TableField("source_system") - /** - * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceSystem; - - @TableField("template_code") - /** - * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String templateCode; - - @TableField("channel_id") - /** - * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long channelId; - - @TableField("send_method") - /** - * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sendMethod; - - @TableField("enabled") - /** - * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer enabled; - - @TableField("remark") - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/WechatMiniBindingDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/WechatMiniBindingDO.java deleted file mode 100644 index 7f9d4a15..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/entity/WechatMiniBindingDO.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 微信小程序用户绑定关系。 - */ -@Getter -@Setter -@TableName("t_wechat_mini_binding") -public class WechatMiniBindingDO extends BaseEntity { - - @TableId(type = IdType.ASSIGN_ID) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - - @TableField("user_id") - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - @TableField("app_id") - /** - * Field `appId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String appId; - - @TableField("openid") - /** - * Field `openId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String openId; - - @TableField("unionid") - /** - * Field `unionId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String unionId; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/BusinessEventOutboxMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/BusinessEventOutboxMapper.java deleted file mode 100644 index df1bf1bb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/BusinessEventOutboxMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.BusinessEventOutboxDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -import java.time.LocalDateTime; -import java.util.List; - -@Mapper -/** - * Purpose: BusinessEventOutboxMapper supports BusinessEventOutboxMapper.java by holding or executing the business event outbox mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface BusinessEventOutboxMapper extends BaseMapper { - - @Select("SELECT * FROM t_business_event_outbox WHERE status IN ('PENDING', 'FAILED') AND is_delete = 0 AND (next_retry_time IS NULL OR next_retry_time <= #{now}) ORDER BY create_time ASC, id ASC LIMIT #{limit}") - List selectDueEvents(@Param("now") LocalDateTime now, @Param("limit") int limit); - - @Update("UPDATE t_business_event_outbox SET status = 'PROCESSING', claimed_at = #{now} WHERE id = #{id} AND status IN ('PENDING', 'FAILED') AND is_delete = 0") - int claimDueEvent(@Param("id") Long id, @Param("now") LocalDateTime now); - - @Update("UPDATE t_business_event_outbox SET status = 'SUCCEEDED', processed_at = #{now}, last_error = NULL WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0") - int markSucceeded(@Param("id") Long id, @Param("now") LocalDateTime now); - - @Update("UPDATE t_business_event_outbox SET status = 'FAILED', retry_count = COALESCE(retry_count, 0) + 1, next_retry_time = #{nextRetryTime}, last_error = #{lastError} WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0") - int markFailed(@Param("id") Long id, @Param("nextRetryTime") LocalDateTime nextRetryTime, @Param("lastError") String lastError); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/MessageHubPushConfigMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/MessageHubPushConfigMapper.java deleted file mode 100644 index 4f1fdffb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/MessageHubPushConfigMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.MessageHubPushConfigDO; - -/** - * MessageHubPushConfigMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface MessageHubPushConfigMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/WechatMiniBindingMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/WechatMiniBindingMapper.java deleted file mode 100644 index 11949835..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/mapper/WechatMiniBindingMapper.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.WechatMiniBindingDO; - -/** - * 微信小程序绑定关系 Mapper。 - */ -public interface WechatMiniBindingMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/BusinessEventOutboxService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/BusinessEventOutboxService.java deleted file mode 100644 index 3bc54606..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/BusinessEventOutboxService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service; - -/** - * Purpose: BusinessEventOutboxService supports BusinessEventOutboxService.java by holding or executing the business event outbox service business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface BusinessEventOutboxService { - - void enqueueOrderCompleted(Long orderId); - - void processDueEvents(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MapService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MapService.java deleted file mode 100644 index 769ac3f3..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MapService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service; - -import java.math.BigDecimal; -import java.util.Map; - -/** - * Purpose: MapService supports MapService.java by holding or executing the map service business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface MapService { - - String normalizeProvider(String provider); - - Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubClientService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubClientService.java deleted file mode 100644 index a840fa2e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubClientService.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service; - - -/** - * MessageHub客户端服务接口 - * 用于调用MessageHub服务发送消息 - * - * @author xiaowang - * @date 2026-03-03 - */ -public interface MessageHubClientService { - - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - */ - void sendSmsVerificationCode(String phone, String code); - - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sceneCode parameter `sceneCode` supplied by the caller - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - */ - void sendSmsVerificationCode(String sceneCode, String phone, String code); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java deleted file mode 100644 index 65994c02..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service; - -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.MessageHubPushConfigDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.MessageHubPushTestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.MessageHubPushConfigDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.MessageHubPushConfigVO; - -import java.util.List; - -/** - * MessageHubPushConfigService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface MessageHubPushConfigService { - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listConfigs(UserDO currentUser); - - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto); - - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param enabled parameter `enabled` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updateStatus(UserDO currentUser, Long id, Integer enabled); - - /** - * Run a test call without changing normal business data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sceneCode parameter `sceneCode` supplied by the caller - * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend - */ - MessageHubPushConfigDO getEnabledConfig(String sceneCode); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java deleted file mode 100644 index 125288da..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service; - -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.WechatMiniLoginResultVO; - -/** - * 微信小程序登录编排服务。 - */ -public interface WechatMiniAuthService { - - /** - * Run business method `autoLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend - */ - WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO); - - /** - * Run business method `phoneLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend - */ - WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO); - - /** - * Run business method `confirmLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend - */ - WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO); - - /** - * Run business method `invalidateBindingsByUserId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - */ - void invalidateBindingsByUserId(Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniClientService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniClientService.java deleted file mode 100644 index 1d9c53a4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniClientService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service; - - -/** - * 微信小程序开放接口客户端。 - */ -public interface WechatMiniClientService { - - /** - * Run business method `code2Session`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wxCode parameter `wxCode` supplied by the caller - * @return SessionInfo result consumed by the caller or returned to the frontend - */ - SessionInfo code2Session(String wxCode); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phoneCode parameter `phoneCode` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - String getPhoneNumber(String phoneCode); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - String getConfiguredAppId(); - - /** - * Run business method `SessionInfo`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param openId parameter `openId` supplied by the caller - * @param unionId parameter `unionId` supplied by the caller - * @param sessionKey parameter `sessionKey` supplied by the caller - * @return record result consumed by the caller or returned to the frontend - */ - record SessionInfo(String openId, String unionId, String sessionKey) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java deleted file mode 100644 index ddace3c7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.BusinessEventOutboxDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.mapper.BusinessEventOutboxMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import lombok.RequiredArgsConstructor; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDateTime; -import java.util.List; - -import com.xiaowang.jacyucloudsalon.core.modules.order.service.impl.OrderServiceImpl; - -@Component -@RequiredArgsConstructor -/** - * Purpose: BusinessEventOutboxProcessor supports BusinessEventOutboxProcessor.java by holding or executing the business event outbox processor business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class BusinessEventOutboxProcessor { - - /** - * Purpose: EVENT_ORDER_COMPLETED supports BusinessEventOutboxProcessor.java by holding or executing the event order completed business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED"; - /** - * Purpose: PROCESS_BATCH_SIZE supports BusinessEventOutboxProcessor.java by holding or executing the process batch size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int PROCESS_BATCH_SIZE = 20; - - /** - * Purpose: outboxMapper supports BusinessEventOutboxProcessor.java by holding or executing the outbox mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final BusinessEventOutboxMapper outboxMapper; - /** - * Purpose: orderMapper supports BusinessEventOutboxProcessor.java by holding or executing the order mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final OrderMapper orderMapper; - /** - * Purpose: orderService supports BusinessEventOutboxProcessor.java by holding or executing the order service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final OrderServiceImpl orderService; - - @Scheduled(fixedDelay = 2000L) - @Transactional - /** - * Purpose: processDueEvents supports BusinessEventOutboxProcessor.java by holding or executing the process due events business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void processDueEvents() { - LocalDateTime now = LocalDateTime.now(); - List events = outboxMapper.selectDueEvents(now, PROCESS_BATCH_SIZE); - for (BusinessEventOutboxDO event : events) { - processOne(event); - } - } - - @Transactional - /** - * Purpose: processOne supports BusinessEventOutboxProcessor.java by holding or executing the process one business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void processOne(BusinessEventOutboxDO event) { - if (event == null || event.getId() == null) { - return; - } - LocalDateTime now = LocalDateTime.now(); - if (outboxMapper.claimDueEvent(event.getId(), now) == 0) { - return; - } - try { - if (EVENT_ORDER_COMPLETED.equals(event.getEventType())) { - OrderDO order = orderMapper.selectById(event.getBusinessId()); - orderService.createPendingArtistReviewTasksAndNotifyFromOutbox(order); - } - outboxMapper.markSucceeded(event.getId(), LocalDateTime.now()); - } catch (Exception exception) { - int retryCount = event.getRetryCount() == null ? 0 : event.getRetryCount(); - LocalDateTime nextRetryTime = LocalDateTime.now().plusSeconds(Math.min(300L, (long) Math.pow(2, retryCount) * 10L)); - outboxMapper.markFailed(event.getId(), nextRetryTime, - BusinessEventOutboxServiceImpl.limit(exception.getMessage(), 500)); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java deleted file mode 100644 index 4f4db482..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.BusinessEventOutboxDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.mapper.BusinessEventOutboxMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.BusinessEventOutboxService; -import lombok.RequiredArgsConstructor; -import org.springframework.dao.DuplicateKeyException; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.time.LocalDateTime; - -@Service -@RequiredArgsConstructor -/** - * Purpose: BusinessEventOutboxServiceImpl supports BusinessEventOutboxServiceImpl.java by holding or executing the business event outbox service impl business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class BusinessEventOutboxServiceImpl implements BusinessEventOutboxService { - - /** - * Purpose: EVENT_ORDER_COMPLETED supports BusinessEventOutboxServiceImpl.java by holding or executing the event order completed business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED"; - /** - * Purpose: BUSINESS_ORDER supports BusinessEventOutboxServiceImpl.java by holding or executing the business order business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String BUSINESS_ORDER = "ORDER"; - /** - * Purpose: STATUS_PENDING supports BusinessEventOutboxServiceImpl.java by holding or executing the status pending business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String STATUS_PENDING = "PENDING"; - - /** - * Purpose: outboxMapper supports BusinessEventOutboxServiceImpl.java by holding or executing the outbox mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final BusinessEventOutboxMapper outboxMapper; - - @Override - /** - * Purpose: enqueueOrderCompleted supports BusinessEventOutboxServiceImpl.java by holding or executing the enqueue order completed business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void enqueueOrderCompleted(Long orderId) { - if (orderId == null) { - return; - } - BusinessEventOutboxDO event = new BusinessEventOutboxDO(); - event.setEventKey("ORDER:" + orderId + ":COMPLETED"); - event.setEventType(EVENT_ORDER_COMPLETED); - event.setBusinessType(BUSINESS_ORDER); - event.setBusinessId(orderId); - event.setPayloadJson("{\"orderId\":" + orderId + "}"); - event.setStatus(STATUS_PENDING); - event.setRetryCount(0); - event.setNextRetryTime(LocalDateTime.now()); - event.setIsDelete(0); - try { - outboxMapper.insert(event); - } catch (DuplicateKeyException ignored) { - // The order-completed event is idempotent by event_key. - } - } - - @Override - /** - * Purpose: processDueEvents supports BusinessEventOutboxServiceImpl.java by holding or executing the process due events business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void processDueEvents() { - // Processing is owned by BusinessEventOutboxProcessor. This method remains on - // the public service contract for callers that only need enqueue capability. - } - - static String limit(String value, int max) { - if (!StringUtils.hasText(value) || value.length() <= max) { - return value; - } - return value.substring(0, max); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MapServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MapServiceImpl.java deleted file mode 100644 index ac42f235..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MapServiceImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MapService; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriUtils; - -import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; -import java.util.LinkedHashMap; -import java.util.Map; - -@Service -/** - * Purpose: MapServiceImpl supports MapServiceImpl.java by holding or executing the map service impl business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class MapServiceImpl implements MapService { - - @Override - /** - * Purpose: normalizeProvider supports MapServiceImpl.java by holding or executing the normalize provider business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String normalizeProvider(String provider) { - if (!StringUtils.hasText(provider)) { - return "TENCENT"; - } - String value = provider.trim().toUpperCase(); - return "AMAP".equals(value) || "TENCENT".equals(value) ? value : "TENCENT"; - } - - @Override - /** - * Purpose: buildNavigationUrls supports MapServiceImpl.java by holding or executing the build navigation urls business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude) { - Map urls = new LinkedHashMap<>(); - if (longitude == null || latitude == null) { - return urls; - } - String name = encode(StringUtils.hasText(shopName) ? shopName : "店铺位置"); - String addr = encode(StringUtils.hasText(address) ? address : ""); - String lon = longitude.stripTrailingZeros().toPlainString(); - String lat = latitude.stripTrailingZeros().toPlainString(); - - urls.put("AMAP", "https://uri.amap.com/navigation?to=" + lon + "," + lat + "," + name + "&mode=car&policy=1&src=fingertipdesigner&coordinate=gaode&callnative=1"); - urls.put("TENCENT", "https://apis.map.qq.com/uri/v1/routeplan?type=drive&tocoord=" + lat + "," + lon + "&to=" + name + "&referer=fingertipdesigner"); - urls.put("BROWSER", "https://apis.map.qq.com/uri/v1/marker?marker=coord:" + lat + "," + lon + ";title:" + name + ";addr:" + addr + "&referer=fingertipdesigner"); - return urls; - } - - /** - * Purpose: encode supports MapServiceImpl.java by holding or executing the encode business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String encode(String value) { - return UriUtils.encode(value, StandardCharsets.UTF_8); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java deleted file mode 100644 index 01b2f593..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jacyucloudsalon.core.config.BrandProperties; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.MessageHubPushConfigDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubClientService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubPushConfigService; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.amqp.core.Message; -import org.springframework.amqp.core.MessageBuilder; -import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -/** - * FingertipDesigner 到 MessageHub 的投递客户端。 - * - *

FingertipDesigner 只决定某个业务场景使用哪组 MessageHub 对接参数,不直接连接 Spug、 - * 阿里云等短信供应商。真实通道选择和供应商密钥仍归 MessageHub 管理。

- */ -@Slf4j -@Service -@RefreshScope -@RequiredArgsConstructor -public class MessageHubClientServiceImpl implements MessageHubClientService { - /** - * Variable `rabbitTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final RabbitTemplate rabbitTemplate; - /** - * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectMapper objectMapper; - /** - * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - /** - * Variable `messageHubPushConfigService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MessageHubPushConfigService messageHubPushConfigService; - /** - * 平台品牌文案配置。 - */ - private final BrandProperties brandProperties; - - @Value("${messagehub.client.sms-queue:smsQueue}") - /** - * Purpose: smsQueue supports MessageHubClientServiceImpl.java by holding or executing the sms queue business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String smsQueue; - - @Value("${messagehub.client.source-system:fingertipdesigner}") - /** - * Purpose: sourceSystem supports MessageHubClientServiceImpl.java by holding or executing the source system business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sourceSystem; - - @Value("${messagehub.client.verify-template-code:SPUG0001}") - /** - * Purpose: verifyTemplateCode supports MessageHubClientServiceImpl.java by holding or executing the verify template code business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String verifyTemplateCode; - - @Value("${messagehub.client.send-method:SPUG}") - /** - * Purpose: sendMethod supports MessageHubClientServiceImpl.java by holding or executing the send method business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sendMethod; - - @Override - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - */ - public void sendSmsVerificationCode(String phone, String code) { - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, code); - } - - @Override - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sceneCode parameter `sceneCode` supplied by the caller - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - */ - public void sendSmsVerificationCode(String sceneCode, String phone, String code) { - try { - MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode); - String messageId = snowflakeIdGenerator.nextIdString(); - Map messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId); - String jsonBody = objectMapper.writeValueAsString(messageBody); - Message message = MessageBuilder - .withBody(jsonBody.getBytes(StandardCharsets.UTF_8)) - .setContentType("application/json") - .setContentEncoding(StandardCharsets.UTF_8.name()) - .setMessageId(messageId) - .build(); - - String queueName = config == null ? smsQueue : config.getQueueName(); - rabbitTemplate.convertAndSend(queueName, message); - log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}", - sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); - } catch (Exception exception) { - log.error("发送短信验证码失败", exception); - throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); - } - } - - /** - * Run business method `buildSmsMessageBody`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param config parameter `config` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map buildSmsMessageBody(MessageHubPushConfigDO config, String sceneCode, String phone, String code, String messageId) { - String platform = config == null ? "SMS" : config.getPlatform(); - String resolvedSendMethod = config == null ? sendMethod : config.getSendMethod(); - - Map messageBody = new HashMap<>(); - messageBody.put("receiver", phone); - messageBody.put("channelType", platform); - messageBody.put("platform", platform); - messageBody.put("msgType", config == null ? "VERIFICATION" : config.getMsgType()); - messageBody.put("templateCode", config == null ? verifyTemplateCode : config.getTemplateCode()); - messageBody.put("sourceSystem", config == null ? sourceSystem : config.getSourceSystem()); - messageBody.put("uniqueId", messageId); - messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"); - if (config != null && config.getChannelId() != null) { - messageBody.put("channelId", config.getChannelId()); - } - - Map templateParams = new HashMap<>(); - templateParams.put("name", brandProperties.getMessageTemplateName()); - templateParams.put("code", code); - templateParams.put("min", "5"); - templateParams.put("minutes", "5"); - templateParams.put("number", "5"); - templateParams.put("sceneCode", sceneCode); - messageBody.put("templateParams", templateParams); - return messageBody; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java deleted file mode 100644 index 05ae64d9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java +++ /dev/null @@ -1,328 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.MessageHubPushConfigDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.MessageHubPushTestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.MessageHubPushConfigDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.mapper.MessageHubPushConfigMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubClientService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubPushConfigService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.MessageHubPushConfigVO; -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * MessageHubPushConfigServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class MessageHubPushConfigServiceImpl implements MessageHubPushConfigService { - /** - * Variable `configMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MessageHubPushConfigMapper configMapper; - @Lazy - /** - * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MessageHubClientService messageHubClientService; - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listConfigs(UserDO currentUser) { - /** - * Run business method `ensurePlatformAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlatformAdmin(currentUser); - return configMapper.selectList(new LambdaQueryWrapper() - .eq(MessageHubPushConfigDO::getIsDelete, 0) - .orderByAsc(MessageHubPushConfigDO::getSceneCode)) - .stream() - .map(this::toVO) - .collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto) { - /** - * Run business method `ensurePlatformAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlatformAdmin(currentUser); - String sceneCode = normalizeSceneCode(dto.getSceneCode()); - MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() - .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) - .eq(MessageHubPushConfigDO::getIsDelete, 0) - .last("LIMIT 1")); - if (existing != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该场景编码已存在"); - } - MessageHubPushConfigDO config = new MessageHubPushConfigDO(); - /** - * Run business method `apply`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param config parameter `config` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - apply(config, dto, sceneCode); - config.setIsDelete(0); - configMapper.insert(config); - return config.getId(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto) { - /** - * Run business method `ensurePlatformAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlatformAdmin(currentUser); - MessageHubPushConfigDO config = requireConfig(id); - String sceneCode = normalizeSceneCode(dto.getSceneCode()); - MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() - .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) - .eq(MessageHubPushConfigDO::getIsDelete, 0) - .ne(MessageHubPushConfigDO::getId, id) - .last("LIMIT 1")); - if (existing != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该场景编码已存在"); - } - /** - * Run business method `apply`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param config parameter `config` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - apply(config, dto, sceneCode); - configMapper.updateById(config); - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param enabled parameter `enabled` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updateStatus(UserDO currentUser, Long id, Integer enabled) { - /** - * Run business method `ensurePlatformAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlatformAdmin(currentUser); - MessageHubPushConfigDO config = requireConfig(id); - config.setEnabled(Integer.valueOf(1).equals(enabled) ? 1 : 0); - configMapper.updateById(config); - return true; - } - - @Override - /** - * Run a test call without changing normal business data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto) { - /** - * Run business method `ensurePlatformAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlatformAdmin(currentUser); - MessageHubPushConfigDO config = requireConfig(id); - messageHubClientService.sendSmsVerificationCode(config.getSceneCode(), dto.getPhone(), "123456"); - return true; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sceneCode parameter `sceneCode` supplied by the caller - * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend - */ - public MessageHubPushConfigDO getEnabledConfig(String sceneCode) { - if (!StringUtils.hasText(sceneCode)) { - return null; - } - return configMapper.selectOne(new LambdaQueryWrapper() - .eq(MessageHubPushConfigDO::getSceneCode, normalizeSceneCode(sceneCode)) - .eq(MessageHubPushConfigDO::getEnabled, 1) - .eq(MessageHubPushConfigDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - /** - * Run business method `apply`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param config parameter `config` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void apply(MessageHubPushConfigDO config, MessageHubPushConfigDTO dto, String sceneCode) { - config.setSceneCode(sceneCode); - config.setSceneName(dto.getSceneName().trim()); - config.setPlatform(normalizeUpper(dto.getPlatform(), "SMS")); - config.setMsgType(normalizeUpper(dto.getMsgType(), "VERIFICATION")); - config.setQueueName(dto.getQueueName().trim()); - config.setSourceSystem(dto.getSourceSystem().trim()); - config.setTemplateCode(dto.getTemplateCode().trim()); - config.setChannelId(dto.getChannelId()); - config.setSendMethod(StringUtils.hasText(dto.getSendMethod()) ? dto.getSendMethod().trim().toUpperCase(Locale.ROOT) : null); - config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); - config.setRemark(dto.getRemark()); - } - - /** - * Run business method `requireConfig`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private MessageHubPushConfigDO result consumed by the caller or returned to the frontend - */ - private MessageHubPushConfigDO requireConfig(Long id) { - MessageHubPushConfigDO config = configMapper.selectById(id); - if (config == null || Integer.valueOf(1).equals(config.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("MessageHub 推送配置不存在"); - } - return config; - } - - /** - * Run business method `ensurePlatformAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensurePlatformAdmin(UserDO currentUser) { - if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("仅平台管理员可以管理消息推送配置"); - } - } - - /** - * Run business method `normalizeSceneCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sceneCode parameter `sceneCode` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeSceneCode(String sceneCode) { - if (!StringUtils.hasText(sceneCode)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("场景编码不能为空"); - } - return sceneCode.trim().toUpperCase(Locale.ROOT); - } - - /** - * Run business method `normalizeUpper`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param value parameter `value` supplied by the caller - * @param fallback parameter `fallback` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeUpper(String value, String fallback) { - return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : fallback; - } - - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param config parameter `config` supplied by the caller - * @return private MessageHubPushConfigVO result consumed by the caller or returned to the frontend - */ - private MessageHubPushConfigVO toVO(MessageHubPushConfigDO config) { - MessageHubPushConfigVO vo = new MessageHubPushConfigVO(); - vo.setId(config.getId()); - vo.setSceneCode(config.getSceneCode()); - vo.setSceneName(config.getSceneName()); - vo.setPlatform(config.getPlatform()); - vo.setMsgType(config.getMsgType()); - vo.setQueueName(config.getQueueName()); - vo.setSourceSystem(config.getSourceSystem()); - vo.setTemplateCode(config.getTemplateCode()); - vo.setChannelId(config.getChannelId()); - vo.setSendMethod(config.getSendMethod()); - vo.setEnabled(config.getEnabled()); - vo.setRemark(config.getRemark()); - vo.setCreateTime(config.getCreateTime()); - vo.setUpdateTime(config.getUpdateTime()); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java deleted file mode 100644 index 54b455cd..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java +++ /dev/null @@ -1,762 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jacyucloudsalon.core.common.BusinessException; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.WechatMiniBindingDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.mapper.WechatMiniBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniAuthService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniClientService; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginShopSelectionVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.WechatMiniLoginResultVO; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.time.Duration; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; - -/** - * 微信小程序登录编排服务实现。 - */ -@Service -@Slf4j -@RequiredArgsConstructor -public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { - - /** - * Purpose: PHONE_REGEX supports WechatMiniAuthServiceImpl.java by holding or executing the phone regex business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; - /** - * Purpose: TICKET_KEY_PREFIX supports WechatMiniAuthServiceImpl.java by holding or executing the ticket key prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:"; - private static final Duration TICKET_TTL = Duration.ofMinutes(5); - /** - * Variable `wechatMiniClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final WechatMiniClientService wechatMiniClientService; - /** - * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final WechatMiniBindingMapper wechatMiniBindingMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - /** - * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final StringRedisTemplate redisTemplate; - /** - * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectMapper objectMapper; - /** - * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - - @Override - /** - * Run business method `autoLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend - */ - public WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO) { - WechatMiniClientService.SessionInfo sessionInfo; - try { - sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); - } catch (RuntimeException exception) { - log.warn("微信小程序自动登录识别失败,回退手动登录: {}", exception.getMessage()); - return WechatMiniLoginResultVO.needManualLogin("微信自动识别失败,请手动登录"); - } - - WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId()); - if (bindingDO == null) { - return WechatMiniLoginResultVO.needManualLogin("当前微信尚未绑定账号,请使用微信手机号一键登录。"); - } - - UserDO userDO = getAvailableBoundUser(bindingDO); - if (userDO == null) { - return WechatMiniLoginResultVO.needManualLogin("当前微信绑定已失效,请重新使用微信手机号一键登录。"); - } - - return loginOrSelectShop(userDO, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); - } - - @Override - /** - * Run business method `phoneLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend - */ - public WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO) { - WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); - String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode())); - if (!StringUtils.hasText(phone) || !phone.matches(PHONE_REGEX)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("获取到的微信手机号格式不正确"); - } - - WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId()); - if (bindingDO != null) { - UserDO boundUser = getAvailableBoundUser(bindingDO); - if (boundUser != null) { - UserDO phoneUser = findActiveUserByPhone(phone); - if (phoneUser != null && !Objects.equals(phoneUser.getId(), boundUser.getId())) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("当前微信已绑定其他账号,无法关联该手机号"); - } - return loginOrSelectShop(boundUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); - } - } - - UserDO phoneUser = findActiveUserByPhone(phone); - if (phoneUser != null) { - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phoneUser parameter `phoneUser` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(phoneUser); - return loginOrSelectShop(phoneUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); - } - - List shops = userShopBindingSupport.listAllActiveShopOptions(); - if (shops.isEmpty()) { - return WechatMiniLoginResultVO.needManualLogin("当前暂无可登录门店,请稍后再试。"); - } - return buildSelectShopResult( - "首次使用微信手机号一键登录,请先选择本次登录门店。", - shops, - new TicketPayload(null, phone, sessionInfo.openId(), sessionInfo.unionId(), true) - ); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `confirmLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend - */ - public WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO) { - Long shopId = normalizeShopId(requestDTO.getShopId()); - if (shopId == null) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("请选择登录门店"); - } - - TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket()); - LoginResponseVO loginResponse; - if (ticketPayload.getUserId() != null) { - loginResponse = userService.loginByUserId(ticketPayload.getUserId(), shopId); - } else if (StringUtils.hasText(ticketPayload.getPhone())) { - loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId); - } else { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("登录票据数据不完整,请重新发起微信一键登录"); - } - - ensureBinding(loginResponse.getUserInfo().getId(), ticketPayload.getOpenId(), ticketPayload.getUnionId()); - deleteTicketPayload(requestDTO.getTicket()); - return WechatMiniLoginResultVO.success( - Boolean.TRUE.equals(ticketPayload.getNewUser()) ? "注册并登录成功" : "登录成功", - loginResponse, - Boolean.TRUE.equals(ticketPayload.getNewUser()) - ); - } - - @Override - /** - * Run business method `invalidateBindingsByUserId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - */ - public void invalidateBindingsByUserId(Long userId) { - if (userId == null) { - return; - } - wechatMiniBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(WechatMiniBindingDO::getUserId, userId) - .set(WechatMiniBindingDO::getStatus, 0) - .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) - ); - } - - private WechatMiniLoginResultVO loginOrSelectShop( - UserDO userDO, - Long preferredShopId, - WechatMiniClientService.SessionInfo sessionInfo, - boolean newUser - ) { - if (Integer.valueOf(4).equals(userDO.getType())) { - List platformAdminShops = resolvePlatformAdminLoginShops(userDO); - if (platformAdminShops.isEmpty()) { - LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), null); - ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId()); - return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser); - } - return buildSelectShopResult( - "平台管理员可选择任意门店作为本次登录门店。", - platformAdminShops, - new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser) - ); - } - - List activeShops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); - if (activeShops.isEmpty()) { - return WechatMiniLoginResultVO.needManualLogin("当前账号没有可登录的门店,请联系管理员处理。"); - } - - Long resolvedShopId = resolvePreferredOrOnlyShop(activeShops, preferredShopId); - if (resolvedShopId != null) { - LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), resolvedShopId); - ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId()); - return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser); - } - - return buildSelectShopResult( - "该账号绑定了多家门店,请选择本次登录门店。", - activeShops, - new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser) - ); - } - - /** - * Purpose: resolvePlatformAdminLoginShops supports WechatMiniAuthServiceImpl.java by holding or executing the resolve platform admin login shops business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List resolvePlatformAdminLoginShops(UserDO userDO) { - LoginShopSelectionVO selection = null; - if (StringUtils.hasText(userDO.getPhone())) { - selection = userService.getLoginShopSelectionByPhone(userDO.getPhone()); - } else if (StringUtils.hasText(userDO.getAccount())) { - selection = userService.getLoginShopSelectionByAccount(userDO.getAccount()); - } - return selection == null || selection.getShops() == null ? List.of() : selection.getShops(); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bindingDO parameter `bindingDO` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO getAvailableBoundUser(WechatMiniBindingDO bindingDO) { - UserDO userDO = userMapper.selectById(bindingDO.getUserId()); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - deactivateBinding(bindingDO.getId()); - return null; - } - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - return userDO; - } - - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertUserAvailable(UserDO userDO) { - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("账号不存在"); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("账号已停用"); - } - } - - /** - * Run business method `findActiveUserByPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO findActiveUserByPhone(String phone) { - if (!StringUtils.hasText(phone)) { - return null; - } - return userMapper.selectOne( - new LambdaQueryWrapper() - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - } - - /** - * Run business method `findBindingByOpenId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param openId parameter `openId` supplied by the caller - * @return private WechatMiniBindingDO result consumed by the caller or returned to the frontend - */ - private WechatMiniBindingDO findBindingByOpenId(String openId) { - return wechatMiniBindingMapper.selectOne( - new LambdaQueryWrapper() - .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId()) - .eq(WechatMiniBindingDO::getOpenId, openId) - .eq(WechatMiniBindingDO::getStatus, 1) - .last("limit 1") - ); - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param appId parameter `appId` supplied by the caller - * @param openId parameter `openId` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List listBindingsByOpenId(String appId, String openId) { - if (!StringUtils.hasText(openId)) { - return List.of(); - } - return wechatMiniBindingMapper.selectList( - new LambdaQueryWrapper() - .eq(WechatMiniBindingDO::getAppId, appId) - .eq(WechatMiniBindingDO::getOpenId, openId) - .orderByDesc(WechatMiniBindingDO::getStatus) - .orderByDesc(WechatMiniBindingDO::getUpdateTime) - .orderByDesc(WechatMiniBindingDO::getCreateTime) - .orderByDesc(WechatMiniBindingDO::getId) - ); - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param appId parameter `appId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List listBindingsByUserId(String appId, Long userId) { - if (userId == null) { - return List.of(); - } - return wechatMiniBindingMapper.selectList( - new LambdaQueryWrapper() - .eq(WechatMiniBindingDO::getAppId, appId) - .eq(WechatMiniBindingDO::getUserId, userId) - .orderByDesc(WechatMiniBindingDO::getStatus) - .orderByDesc(WechatMiniBindingDO::getUpdateTime) - .orderByDesc(WechatMiniBindingDO::getCreateTime) - .orderByDesc(WechatMiniBindingDO::getId) - ); - } - - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `ensureBinding`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param openId parameter `openId` supplied by the caller - * @param unionId parameter `unionId` supplied by the caller - */ - protected void ensureBinding(Long userId, String openId, String unionId) { - if (userId == null || !StringUtils.hasText(openId)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("微信绑定信息不完整"); - } - - String appId = wechatMiniClientService.getConfiguredAppId(); - List openIdBindings = listBindingsByOpenId(appId, openId); - List userBindings = listBindingsByUserId(appId, userId); - - /** - * Run business method `validateExclusiveActiveBinding`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param openId parameter `openId` supplied by the caller - * @param openIdBindings parameter `openIdBindings` supplied by the caller - * @param userBindings parameter `userBindings` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateExclusiveActiveBinding(userId, openId, openIdBindings, userBindings); - - WechatMiniBindingDO targetBinding = pickTargetBinding(userId, openId, openIdBindings, userBindings); - if (targetBinding == null) { - WechatMiniBindingDO bindingDO = new WechatMiniBindingDO(); - bindingDO.setUserId(userId); - bindingDO.setAppId(appId); - bindingDO.setOpenId(openId); - bindingDO.setUnionId(unionId); - bindingDO.setStatus(1); - wechatMiniBindingMapper.insert(bindingDO); - return; - } - - targetBinding.setUserId(userId); - targetBinding.setAppId(appId); - targetBinding.setOpenId(openId); - targetBinding.setUnionId(unionId); - targetBinding.setStatus(1); - targetBinding.setUpdateTime(LocalDateTime.now()); - wechatMiniBindingMapper.updateById(targetBinding); - - deactivateDuplicateBindings(targetBinding.getId(), mergeBindings(openIdBindings, userBindings)); - } - - /** - * Run business method `deactivateBinding`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bindingId parameter `bindingId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void deactivateBinding(Long bindingId) { - if (bindingId == null) { - return; - } - wechatMiniBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(WechatMiniBindingDO::getId, bindingId) - .set(WechatMiniBindingDO::getStatus, 0) - .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) - ); - } - - private void validateExclusiveActiveBinding( - Long userId, - String openId, - List openIdBindings, - List userBindings - ) { - boolean openIdBoundToOtherUser = openIdBindings.stream() - .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) - .anyMatch(binding -> !Objects.equals(binding.getUserId(), userId)); - if (openIdBoundToOtherUser) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("当前微信已绑定其他账号,无法完成登录"); - } - - boolean userBoundToOtherWechat = userBindings.stream() - .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) - .anyMatch(binding -> !Objects.equals(binding.getOpenId(), openId)); - if (userBoundToOtherWechat) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("当前账号已绑定其他微信,请联系管理员处理"); - } - } - - private WechatMiniBindingDO pickTargetBinding( - Long userId, - String openId, - List openIdBindings, - List userBindings - ) { - List mergedBindings = mergeBindings(openIdBindings, userBindings); - return mergedBindings.stream() - .filter(binding -> Objects.equals(binding.getUserId(), userId) && Objects.equals(binding.getOpenId(), openId)) - .findFirst() - .orElseGet(() -> mergedBindings.stream() - .filter(binding -> Objects.equals(binding.getOpenId(), openId)) - .findFirst() - .orElseGet(() -> mergedBindings.stream() - .filter(binding -> Objects.equals(binding.getUserId(), userId)) - .findFirst() - .orElse(null))); - } - - private List mergeBindings( - List openIdBindings, - List userBindings - ) { - List merged = new ArrayList<>(); - openIdBindings.forEach(binding -> appendUniqueBinding(merged, binding)); - userBindings.forEach(binding -> appendUniqueBinding(merged, binding)); - merged.sort(Comparator - .comparing((WechatMiniBindingDO binding) -> Integer.valueOf(1).equals(binding.getStatus()) ? 0 : 1) - .thenComparing(WechatMiniBindingDO::getUpdateTime, Comparator.nullsLast(Comparator.reverseOrder())) - .thenComparing(WechatMiniBindingDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())) - .thenComparing(WechatMiniBindingDO::getId, Comparator.nullsLast(Comparator.reverseOrder()))); - return merged; - } - - /** - * Run business method `appendUniqueBinding`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param merged parameter `merged` supplied by the caller - * @param candidate parameter `candidate` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void appendUniqueBinding(List merged, WechatMiniBindingDO candidate) { - if (candidate == null) { - return; - } - boolean exists = merged.stream().anyMatch(item -> Objects.equals(item.getId(), candidate.getId())); - if (!exists) { - merged.add(candidate); - } - } - - /** - * Run business method `deactivateDuplicateBindings`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keepBindingId parameter `keepBindingId` supplied by the caller - * @param bindings parameter `bindings` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void deactivateDuplicateBindings(Long keepBindingId, List bindings) { - bindings.stream() - .filter(binding -> binding.getId() != null && !Objects.equals(binding.getId(), keepBindingId)) - .forEach(binding -> deactivateBinding(binding.getId())); - } - - /** - * Run business method `resolvePreferredOrOnlyShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shops parameter `shops` supplied by the caller - * @param preferredShopId parameter `preferredShopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolvePreferredOrOnlyShop(List shops, Long preferredShopId) { - Long normalizedPreferredShopId = normalizeShopId(preferredShopId); - if (normalizedPreferredShopId != null) { - boolean matched = shops.stream().anyMatch(shop -> Objects.equals(shop.getId(), normalizedPreferredShopId)); - if (matched) { - return normalizedPreferredShopId; - } - } - if (shops.size() == 1) { - return shops.get(0).getId(); - } - return null; - } - - private WechatMiniLoginResultVO buildSelectShopResult( - String message, - List shops, - TicketPayload ticketPayload - ) { - String ticket = storeTicketPayload(ticketPayload); - return WechatMiniLoginResultVO.selectShop(message, ticket, Boolean.TRUE.equals(ticketPayload.getNewUser()), shops); - } - - /** - * Run business method `storeTicketPayload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ticketPayload parameter `ticketPayload` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String storeTicketPayload(TicketPayload ticketPayload) { - String ticket = "wxmini_" + snowflakeIdGenerator.nextIdString(); - try { - redisTemplate.opsForValue().set( - TICKET_KEY_PREFIX + ticket, - objectMapper.writeValueAsString(ticketPayload), - TICKET_TTL - ); - return ticket; - } catch (JsonProcessingException exception) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param exception parameter `exception` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("生成微信登录票据失败", exception); - } - } - - /** - * Run business method `readTicketPayload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ticket parameter `ticket` supplied by the caller - * @return private TicketPayload result consumed by the caller or returned to the frontend - */ - private TicketPayload readTicketPayload(String ticket) { - String payloadJson = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + ticket); - if (!StringUtils.hasText(payloadJson)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("登录票据已失效,请重新发起微信一键登录"); - } - try { - return objectMapper.readValue(payloadJson, TicketPayload.class); - } catch (JsonProcessingException exception) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param exception parameter `exception` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("解析微信登录票据失败", exception); - } - } - - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ticket parameter `ticket` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void deleteTicketPayload(String ticket) { - redisTemplate.delete(TICKET_KEY_PREFIX + ticket); - } - - /** - * Run business method `normalizeShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long normalizeShopId(Long shopId) { - return shopId != null && shopId > 0 ? shopId : null; - } - - /** - * Run business method `normalizePhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizePhone(String phone) { - return phone == null ? "" : phone.trim(); - } - - @Data - /** - * Purpose: TicketPayload supports WechatMiniAuthServiceImpl.java by holding or executing the ticket payload business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static class TicketPayload { - /** - * Purpose: userId supports WechatMiniAuthServiceImpl.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - /** - * Purpose: phone supports WechatMiniAuthServiceImpl.java by holding or executing the phone business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String phone; - /** - * Purpose: openId supports WechatMiniAuthServiceImpl.java by holding or executing the open id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String openId; - /** - * Purpose: unionId supports WechatMiniAuthServiceImpl.java by holding or executing the union id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String unionId; - /** - * Purpose: newUser supports WechatMiniAuthServiceImpl.java by holding or executing the new user business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean newUser; - - /** - * Run business method `TicketPayload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return public result consumed by the caller or returned to the frontend - */ - public TicketPayload() { - } - - /** - * Run business method `TicketPayload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param phone parameter `phone` supplied by the caller - * @param openId parameter `openId` supplied by the caller - * @param unionId parameter `unionId` supplied by the caller - * @param newUser parameter `newUser` supplied by the caller - * @return public result consumed by the caller or returned to the frontend - */ - public TicketPayload(Long userId, String phone, String openId, String unionId, Boolean newUser) { - this.userId = userId; - this.phone = phone; - this.openId = openId; - this.unionId = unionId; - this.newUser = newUser; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java deleted file mode 100644 index 59971ebe..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java +++ /dev/null @@ -1,399 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jacyucloudsalon.core.common.BusinessException; -import com.xiaowang.jacyucloudsalon.core.config.WechatMiniProperties; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniClientService; -import lombok.RequiredArgsConstructor; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import java.time.Duration; -import java.util.Map; -import java.util.Objects; - -/** - * WeChat mini program API client. - */ -@Service -@RequiredArgsConstructor -public class WechatMiniClientServiceImpl implements WechatMiniClientService { - - /** - * Purpose: ACCESS_TOKEN_CACHE_KEY_PREFIX supports WechatMiniClientServiceImpl.java by holding or executing the access token cache key prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String ACCESS_TOKEN_CACHE_KEY_PREFIX = "wechat:mini:access-token:"; - /** - * Purpose: ACCESS_TOKEN_URL supports WechatMiniClientServiceImpl.java by holding or executing the access token url business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; - /** - * Variable `restTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final RestTemplate restTemplate; - /** - * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final StringRedisTemplate redisTemplate; - /** - * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectMapper objectMapper; - /** - * Variable `properties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final WechatMiniProperties properties; - - @Override - /** - * Run business method `code2Session`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wxCode parameter `wxCode` supplied by the caller - * @return SessionInfo result consumed by the caller or returned to the frontend - */ - public SessionInfo code2Session(String wxCode) { - if (!StringUtils.hasText(wxCode)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("微信登录凭证不能为空"); - } - /** - * Run business method `requireConfiguredCredentials`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return result consumed by the caller or returned to the frontend - */ - requireConfiguredCredentials(); - Map response = readJsonResponse( - doGetForString( - UriComponentsBuilder.fromHttpUrl(properties.getCode2sessionUrl()) - .queryParam("appid", properties.getAppId()) - .queryParam("secret", properties.getAppSecret()) - .queryParam("js_code", wxCode) - .queryParam("grant_type", "authorization_code") - .build(true) - .toUriString(), - "获取微信登录身份失败" - ), - "获取微信登录身份失败" - ); - /** - * Run business method `assertWechatResponseOk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param response parameter `response` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertWechatResponseOk(response, "获取微信登录身份失败"); - String openId = asText(response.get("openid")); - if (!StringUtils.hasText(openId)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param openid parameter `openid` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("获取微信登录身份失败:缺少 openid"); - } - return new SessionInfo(openId, asText(response.get("unionid")), asText(response.get("session_key"))); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phoneCode parameter `phoneCode` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - public String getPhoneNumber(String phoneCode) { - if (!StringUtils.hasText(phoneCode)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("微信手机号凭证不能为空"); - } - - String accessToken = getAccessToken(); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - - Map response = readJsonResponse( - doPostForString( - UriComponentsBuilder.fromHttpUrl(properties.getPhoneNumberUrl()) - .queryParam("access_token", accessToken) - .build(true) - .toUriString(), - new HttpEntity<>(Map.of("code", phoneCode), headers), - "获取微信手机号失败" - ), - "获取微信手机号失败" - ); - /** - * Run business method `assertWechatResponseOk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param response parameter `response` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertWechatResponseOk(response, "获取微信手机号失败"); - - Object phoneInfoRaw = response.get("phone_info"); - if (phoneInfoRaw == null) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("获取微信手机号失败:未返回手机号信息"); - } - Map phoneInfo = objectMapper.convertValue(phoneInfoRaw, new TypeReference>() { - }); - if (phoneInfo == null || phoneInfo.isEmpty()) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("获取微信手机号失败:未返回手机号信息"); - } - - String phoneNumber = asText(phoneInfo.get("phoneNumber")); - if (!StringUtils.hasText(phoneNumber)) { - phoneNumber = asText(phoneInfo.get("purePhoneNumber")); - } - if (!StringUtils.hasText(phoneNumber)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("获取微信手机号失败:未返回手机号信息"); - } - return phoneNumber; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ - public String getConfiguredAppId() { - /** - * Run business method `requireConfiguredCredentials`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return result consumed by the caller or returned to the frontend - */ - requireConfiguredCredentials(); - return properties.getAppId(); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private String result consumed by the caller or returned to the frontend - */ - private String getAccessToken() { - /** - * Run business method `requireConfiguredCredentials`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return result consumed by the caller or returned to the frontend - */ - requireConfiguredCredentials(); - String cacheKey = ACCESS_TOKEN_CACHE_KEY_PREFIX + properties.getAppId(); - String cachedToken = redisTemplate.opsForValue().get(cacheKey); - if (StringUtils.hasText(cachedToken)) { - return cachedToken; - } - - Map response = readJsonResponse( - doGetForString( - UriComponentsBuilder.fromHttpUrl(ACCESS_TOKEN_URL) - .queryParam("grant_type", "client_credential") - .queryParam("appid", properties.getAppId()) - .queryParam("secret", properties.getAppSecret()) - .build(true) - .toUriString(), - "获取微信 access_token 失败" - ), - "获取微信 access_token 失败" - ); - /** - * Run business method `assertWechatResponseOk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param response parameter `response` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertWechatResponseOk(response, "获取微信 access_token 失败"); - - String accessToken = asText(response.get("access_token")); - if (!StringUtils.hasText(accessToken)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param access_token parameter `access_token` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("获取微信 access_token 失败:未返回 access_token"); - } - - long expiresIn = parseLong(response.get("expires_in"), 7200L); - long safeBuffer = Math.max(0L, Objects.requireNonNullElse(properties.getAccessTokenBufferSeconds(), 60)); - long ttlSeconds = Math.max(60L, expiresIn - safeBuffer); - redisTemplate.opsForValue().set(cacheKey, accessToken, Duration.ofSeconds(ttlSeconds)); - return accessToken; - } - - /** - * Run business method `requireConfiguredCredentials`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private void result consumed by the caller or returned to the frontend - */ - private void requireConfiguredCredentials() { - if (!StringUtils.hasText(properties.getAppId()) || !StringUtils.hasText(properties.getAppSecret())) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param appIdappSecret parameter `appIdappSecret` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException("微信小程序登录未配置 appId/appSecret"); - } - } - - /** - * Run business method `doGetForString`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param url parameter `url` supplied by the caller - * @param defaultMessage parameter `defaultMessage` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String doGetForString(String url, String defaultMessage) { - try { - return restTemplate.getForObject(url, String.class); - } catch (RestClientException exception) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param exception parameter `exception` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); - } - } - - /** - * Run business method `doPostForString`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param url parameter `url` supplied by the caller - * @param requestEntity parameter `requestEntity` supplied by the caller - * @param defaultMessage parameter `defaultMessage` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String doPostForString(String url, HttpEntity requestEntity, String defaultMessage) { - try { - return restTemplate.postForObject(url, requestEntity, String.class); - } catch (RestClientException exception) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param exception parameter `exception` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); - } - } - - /** - * Run business method `readJsonResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param responseBody parameter `responseBody` supplied by the caller - * @param defaultMessage parameter `defaultMessage` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map readJsonResponse(String responseBody, String defaultMessage) { - if (!StringUtils.hasText(responseBody)) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException(defaultMessage + ":微信服务未返回数据"); - } - try { - return objectMapper.readValue(responseBody, new TypeReference>() { - }); - } catch (JsonProcessingException exception) { - /** - * Run business method `BusinessException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param exception parameter `exception` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new BusinessException(defaultMessage + ":微信服务返回了无法解析的响应", exception); - } - } - - /** - * Run business method `assertWechatResponseOk`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param response parameter `response` supplied by the caller - * @param defaultMessage parameter `defaultMessage` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertWechatResponseOk(Map response, String defaultMessage) { - long errCode = parseLong(response.get("errcode"), 0L); - if (errCode == 0L) { - return; - } - String errMsg = asText(response.get("errmsg")); - throw new BusinessException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode))); - } - - /** - * Run business method `parseLong`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param value parameter `value` supplied by the caller - * @param defaultValue parameter `defaultValue` supplied by the caller - * @return private long result consumed by the caller or returned to the frontend - */ - private long parseLong(Object value, long defaultValue) { - if (value == null) { - return defaultValue; - } - if (value instanceof Number number) { - return number.longValue(); - } - if (value instanceof String text && StringUtils.hasText(text)) { - try { - return Long.parseLong(text); - } catch (NumberFormatException ignored) { - return defaultValue; - } - } - return defaultValue; - } - - /** - * Run business method `asText`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param value parameter `value` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String asText(Object value) { - return value == null ? "" : String.valueOf(value).trim(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/MessageHubPushConfigVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/MessageHubPushConfigVO.java deleted file mode 100644 index 52fb5fa1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/MessageHubPushConfigVO.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -/** - * MessageHubPushConfigVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class MessageHubPushConfigVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sceneCode; - /** - * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sceneName; - /** - * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String platform; - /** - * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String msgType; - /** - * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String queueName; - /** - * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceSystem; - /** - * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String templateCode; - /** - * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long channelId; - /** - * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sendMethod; - /** - * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer enabled; - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java deleted file mode 100644 index f67196f4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.integration.vo; - -import lombok.Data; - -import java.util.List; - -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -/** - * 微信小程序登录结果。 - */ -@Data -public class WechatMiniLoginResultVO { - - /** - * Purpose: STATUS_SUCCESS supports WechatMiniLoginResultVO.java by holding or executing the status success business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String STATUS_SUCCESS = "SUCCESS"; - /** - * Purpose: STATUS_SELECT_SHOP supports WechatMiniLoginResultVO.java by holding or executing the status select shop business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String STATUS_SELECT_SHOP = "SELECT_SHOP"; - /** - * Purpose: STATUS_NEED_MANUAL_LOGIN supports WechatMiniLoginResultVO.java by holding or executing the status need manual login business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String STATUS_NEED_MANUAL_LOGIN = "NEED_MANUAL_LOGIN"; - - /** - * Field `status` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String status; - /** - * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String message; - /** - * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String ticket; - /** - * Field `newUser` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean newUser; - /** - * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shops; - /** - * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String accessToken; - /** - * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String refreshToken; - /** - * Field `userInfo` (LoginResponseVO.UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LoginResponseVO.UserInfo userInfo; - /** - * Field `needSetPassword` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean needSetPassword; - - /** - * Purpose: success supports WechatMiniLoginResultVO.java by holding or executing the success business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static WechatMiniLoginResultVO success(String message, LoginResponseVO loginResponse, boolean newUser) { - WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); - resultVO.setStatus(STATUS_SUCCESS); - resultVO.setMessage(message); - resultVO.setNewUser(newUser); - resultVO.setAccessToken(loginResponse.getAccessToken()); - resultVO.setRefreshToken(loginResponse.getRefreshToken()); - resultVO.setUserInfo(loginResponse.getUserInfo()); - resultVO.setNeedSetPassword(loginResponse.isNeedSetPassword()); - return resultVO; - } - - public static WechatMiniLoginResultVO selectShop( - String message, - String ticket, - boolean newUser, - List shops - ) { - WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); - resultVO.setStatus(STATUS_SELECT_SHOP); - resultVO.setMessage(message); - resultVO.setTicket(ticket); - resultVO.setNewUser(newUser); - resultVO.setShops(shops); - return resultVO; - } - - /** - * Purpose: needManualLogin supports WechatMiniLoginResultVO.java by holding or executing the need manual login business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static WechatMiniLoginResultVO needManualLogin(String message) { - WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); - resultVO.setStatus(STATUS_NEED_MANUAL_LOGIN); - resultVO.setMessage(message); - resultVO.setNewUser(false); - return resultVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/dto/InventoryAdjustDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/dto/InventoryAdjustDTO.java deleted file mode 100644 index 408d6c74..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/dto/InventoryAdjustDTO.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class InventoryAdjustDTO { - private String changeType; - private BigDecimal changeQuantity; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/dto/InventoryItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/dto/InventoryItemDTO.java deleted file mode 100644 index 2a63d636..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/dto/InventoryItemDTO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class InventoryItemDTO { - private Long shopId; - private String category; - private String itemName; - private String unit; - private BigDecimal stockQuantity; - private BigDecimal warningThreshold; - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/entity/InventoryItemDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/entity/InventoryItemDO.java deleted file mode 100644 index 25dc08cf..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/entity/InventoryItemDO.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_inventory_item") -public class InventoryItemDO extends BaseEntity { - @TableField("shop_id") - private Long shopId; - @TableField("category") - private String category; - @TableField("item_name") - private String itemName; - @TableField("unit") - private String unit; - @TableField("stock_quantity") - private BigDecimal stockQuantity; - @TableField("warning_threshold") - private BigDecimal warningThreshold; - @TableField("status") - private Integer status; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/entity/InventoryRecordDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/entity/InventoryRecordDO.java deleted file mode 100644 index e3b2c056..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/entity/InventoryRecordDO.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_inventory_record") -public class InventoryRecordDO extends BaseEntity { - @TableField("inventory_item_id") - private Long inventoryItemId; - @TableField("shop_id") - private Long shopId; - @TableField("change_type") - private String changeType; - @TableField("change_quantity") - private BigDecimal changeQuantity; - @TableField("before_quantity") - private BigDecimal beforeQuantity; - @TableField("after_quantity") - private BigDecimal afterQuantity; - @TableField("operator_id") - private Long operatorId; - @TableField("remark") - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/mapper/InventoryItemMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/mapper/InventoryItemMapper.java deleted file mode 100644 index 2d510c05..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/mapper/InventoryItemMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.entity.InventoryItemDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface InventoryItemMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/mapper/InventoryRecordMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/mapper/InventoryRecordMapper.java deleted file mode 100644 index 5d009f3f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/mapper/InventoryRecordMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.entity.InventoryRecordDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface InventoryRecordMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/service/InventoryService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/service/InventoryService.java deleted file mode 100644 index f1bcd85f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/service/InventoryService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.service; - -import com.xiaowang.jacyucloudsalon.core.modules.inventory.dto.InventoryAdjustDTO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.dto.InventoryItemDTO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.vo.InventoryItemVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; - -public interface InventoryService { - InventoryItemVO saveItem(InventoryItemDTO dto); - - InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto); - - PageResultVO listItems(Long shopId, Integer page, Integer size); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/service/impl/InventoryServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/service/impl/InventoryServiceImpl.java deleted file mode 100644 index a75d4314..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/service/impl/InventoryServiceImpl.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.dto.InventoryAdjustDTO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.dto.InventoryItemDTO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.entity.InventoryItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.entity.InventoryRecordDO; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.mapper.InventoryItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.mapper.InventoryRecordMapper; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.service.InventoryService; -import com.xiaowang.jacyucloudsalon.core.modules.inventory.vo.InventoryItemVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.math.BigDecimal; - -@Service -@RequiredArgsConstructor -public class InventoryServiceImpl implements InventoryService { - - private final InventoryItemMapper inventoryItemMapper; - private final InventoryRecordMapper inventoryRecordMapper; - - @Override - @Transactional - public InventoryItemVO saveItem(InventoryItemDTO dto) { - if (dto == null || dto.getShopId() == null || dto.getItemName() == null || dto.getItemName().isBlank()) { - throw new RuntimeException("库存物料信息不完整"); - } - InventoryItemDO item = new InventoryItemDO(); - BeanUtils.copyProperties(dto, item); - item.setStockQuantity(dto.getStockQuantity() == null ? BigDecimal.ZERO : dto.getStockQuantity()); - item.setWarningThreshold(dto.getWarningThreshold() == null ? BigDecimal.ZERO : dto.getWarningThreshold()); - item.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); - item.setIsDelete(0); - inventoryItemMapper.insert(item); - return toVO(item); - } - - @Override - @Transactional - public InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto) { - InventoryItemDO item = inventoryItemMapper.selectById(itemId); - if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { - throw new RuntimeException("库存物料不存在"); - } - BigDecimal before = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity(); - BigDecimal delta = dto == null || dto.getChangeQuantity() == null ? BigDecimal.ZERO : dto.getChangeQuantity(); - BigDecimal after = before.add(delta); - if (after.compareTo(BigDecimal.ZERO) < 0) { - throw new RuntimeException("库存不能小于 0"); - } - item.setStockQuantity(after); - inventoryItemMapper.updateById(item); - InventoryRecordDO record = new InventoryRecordDO(); - record.setInventoryItemId(item.getId()); - record.setShopId(item.getShopId()); - record.setChangeType(dto == null ? null : dto.getChangeType()); - record.setChangeQuantity(delta); - record.setBeforeQuantity(before); - record.setAfterQuantity(after); - record.setOperatorId(operatorId); - record.setRemark(dto == null ? null : dto.getRemark()); - inventoryRecordMapper.insert(record); - return toVO(item); - } - - @Override - public PageResultVO listItems(Long shopId, Integer page, Integer size) { - int current = page == null || page < 1 ? 1 : page; - int pageSize = size == null || size < 1 ? 10 : size; - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(InventoryItemDO::getIsDelete, 0) - .orderByDesc(InventoryItemDO::getCreateTime); - if (shopId != null) { - wrapper.eq(InventoryItemDO::getShopId, shopId); - } - Page result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper); - PageResultVO vo = new PageResultVO<>(); - vo.setList(result.getRecords().stream().map(this::toVO).toList()); - vo.setTotal(result.getTotal()); - vo.setPage(current); - vo.setSize(pageSize); - return vo; - } - - private InventoryItemVO toVO(InventoryItemDO item) { - InventoryItemVO vo = new InventoryItemVO(); - BeanUtils.copyProperties(item, vo); - BigDecimal stock = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity(); - BigDecimal warning = item.getWarningThreshold() == null ? BigDecimal.ZERO : item.getWarningThreshold(); - vo.setWarning(stock.compareTo(warning) <= 0); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/vo/InventoryItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/vo/InventoryItemVO.java deleted file mode 100644 index eaf50c02..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/inventory/vo/InventoryItemVO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.inventory.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class InventoryItemVO { - private Long id; - private Long shopId; - private String category; - private String itemName; - private String unit; - private BigDecimal stockQuantity; - private BigDecimal warningThreshold; - private Boolean warning; - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/dto/ManagerCustomerCreateDTO.java deleted file mode 100644 index 9d30f604..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/dto/ManagerCustomerCreateDTO.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.manager.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; - -@Data -public class ManagerCustomerCreateDTO { - - @NotBlank(message = "客户姓名不能为空") - private String nickname; - - @NotBlank(message = "手机号不能为空") - @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") - private String phone; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/CouponController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/CouponController.java deleted file mode 100644 index 80ed6861..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/CouponController.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.CouponService; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.UserCouponVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * 优惠券控制器 - */ -@RestController -@RequestMapping("/coupon") -@RequiredArgsConstructor -public class CouponController { - /** - * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponService couponService; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建优惠券 - */ - @PostMapping("/create") - @RequirePermission("coupon:create") - public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 获取用户优惠券列表 - */ - @GetMapping("/user/list") - public Result> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) { - List userCoupons = couponService.listUserCoupons(userId, status); - return Result.success(userCoupons); - } - - /** - * 使用优惠券 - */ - @PostMapping("/use") - public Result useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) { - boolean success = couponService.useCoupon(userCouponId, userId); - return Result.success(success); - } - - /** - * 获取商品可用的优惠券 - */ - @GetMapping("/available") - public Result> getAvailableCoupons( - @RequestParam(required = false, defaultValue = "") String productTags, - @RequestParam Double productPrice, - @RequestParam(required = false) Long shopId, - @RequestAttribute("userId") Long userId - ) { - List availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId); - return Result.success(availableCoupons); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/GrowthController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/GrowthController.java deleted file mode 100644 index 1a549315..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/GrowthController.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.GrowthService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.GrowthSummaryVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/growth") -@RequiredArgsConstructor -public class GrowthController { - - private final GrowthService growthService; - - @GetMapping("/summary") - public Result summary(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(growthService.getSummary(userId)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/ProductLikeController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/ProductLikeController.java deleted file mode 100644 index 63ad65fa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/ProductLikeController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.ProductLikeService; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -/** - * 商品点赞控制器 - * - * @author xiaowang - * @date 2026-03-05 - */ -@RestController -@RequestMapping("/product-like") -@RequiredArgsConstructor -public class ProductLikeController { - /** - * Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductLikeService productLikeService; - - /** - * 点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/like/{productId}") - @OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.addLike(userId, productId); - return Result.success(true); - } - - /** - * 取消点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/unlike/{productId}") - @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.removeLike(userId, productId); - return Result.success(true); - } - - /** - * 检查用户是否已点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否已点赞 - */ - @GetMapping("/check/{productId}") - public Result checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - boolean isLiked = productLikeService.isProductLiked(userId, productId); - return Result.success(isLiked); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipBenefitController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipBenefitController.java deleted file mode 100644 index fbc63c38..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipBenefitController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipBenefitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipBenefitVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.VipBenefitService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * VIP权益信息表 Controller - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/vip-benefit", "/api/vip-benefit"}) -@RequiredArgsConstructor -public class VipBenefitController { - /** - * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipBenefitService vipBenefitService; - - /** - * 创建VIP权益 - * - * @param vipBenefitDTO VIP权益DTO - * @return VIP权益ID - */ - @PostMapping("/create") - public Result createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { - Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); - return Result.success(id); - } - - /** - * 更新VIP权益 - * - * @param id VIP权益ID - * @param vipBenefitDTO VIP权益DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { - boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); - return Result.success(success); - } - - /** - * 删除VIP权益 - * - * @param id VIP权益ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipBenefit(@PathVariable Long id) { - boolean success = vipBenefitService.deleteVipBenefit(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP权益 - * - * @param id VIP权益ID - * @return VIP权益VO - */ - @GetMapping("/get/{id}") - public Result getVipBenefitById(@PathVariable Long id) { - VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); - return Result.success(vipBenefitVO); - } - - /** - * 查询所有VIP权益 - * - * @return VIP权益VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipBenefits() { - List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); - return Result.success(vipBenefitVOs); - } - - /** - * 根据所需VIP等级查询VIP权益 - * - * @param requiredVipLevel 所需VIP等级 - * @return VIP权益VO列表 - */ - @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") - public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { - List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); - return Result.success(vipBenefitVOs); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipInfoController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipInfoController.java deleted file mode 100644 index fbedeae5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipInfoController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipInfoVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.VipInfoService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户VIP信息表 Controller - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/vip-info", "/api/vip-info"}) -@RequiredArgsConstructor -public class VipInfoController { - /** - * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipInfoService vipInfoService; - - /** - * 创建VIP信息 - * - * @param vipInfoDTO VIP信息DTO - * @return VIP信息ID - */ - @PostMapping("/create") - public Result createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { - Long id = vipInfoService.createVipInfo(vipInfoDTO); - return Result.success(id); - } - - /** - * 更新VIP信息 - * - * @param id VIP信息ID - * @param vipInfoDTO VIP信息DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { - boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); - return Result.success(success); - } - - /** - * 删除VIP信息 - * - * @param id VIP信息ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipInfo(@PathVariable Long id) { - boolean success = vipInfoService.deleteVipInfo(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP信息 - * - * @param id VIP信息ID - * @return VIP信息VO - */ - @GetMapping("/get/{id}") - public Result getVipInfoById(@PathVariable Long id) { - VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); - return Result.success(vipInfoVO); - } - - /** - * 查询所有VIP信息 - * - * @return VIP信息VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipInfos() { - List vipInfoVOs = vipInfoService.listAllVipInfos(); - return Result.success(vipInfoVOs); - } - - /** - * 根据VIP等级查询VIP信息 - * - * @param vipLevel VIP等级 - * @return VIP信息VO列表 - */ - @GetMapping("/list/vipLevel/{vipLevel}") - public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { - List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); - return Result.success(vipInfoVOs); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipRechargePlanController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipRechargePlanController.java deleted file mode 100644 index 4e1b43a4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/VipRechargePlanController.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipRechargePlanDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.VipRechargePlanService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipRechargePlanVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"}) -/** - * VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class VipRechargePlanController { - /** - * Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipRechargePlanService vipRechargePlanService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @GetMapping("/admin/list") - @RequirePermission("user:vip:manage") - /** - * Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); - } - - @PostMapping("/admin/create") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); - } - - @PutMapping("/admin/{id}") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); - } - - @PutMapping("/admin/{id}/status") - @RequirePermission("user:vip:manage") - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); - } - - @GetMapping("/my/list") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listMy(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(vipRechargePlanService.listMyPlans(userId)); - } - - @GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"}) - /** - * Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/WishlistController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/WishlistController.java deleted file mode 100644 index 92a63021..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/controller/front/WishlistController.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistAddWithGroupDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistGroupDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistMoveDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.WishlistService; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.WishlistGroupVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.WishlistInspirationVO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestAttribute; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/wishlist") -public class WishlistController { - - @Autowired - private WishlistService wishlistService; - - @PostMapping("/add") - @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @PostMapping("/add-with-group") - @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request); - return Result.success("ok"); - } - - @PostMapping("/remove") - @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.removeFromWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @GetMapping("/check") - public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.isInWishlist(userId, productId)); - } - - @GetMapping("/list") - public Result> getWishlist(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getWishlistByUserId(userId)); - } - - @GetMapping("/groups") - public Result> listGroups(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.listGroups(userId)); - } - - @PostMapping("/groups") - public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.createGroup(userId, request)); - } - - @PutMapping("/groups/{id}") - public Result updateGroup( - @PathVariable Long id, - @RequestBody WishlistGroupDTO request, - @RequestAttribute("userId") Long userId - ) { - return Result.success(wishlistService.updateGroup(userId, id, request)); - } - - @DeleteMapping("/groups/{id}") - public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.deleteGroup(userId, id)); - } - - @PostMapping("/move") - @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.moveWishlist(userId, request)); - } - - @GetMapping("/inspiration") - public Result getInspiration(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getInspiration(userId)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/CampaignDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/CampaignDTO.java deleted file mode 100644 index 93ed0457..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/CampaignDTO.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -public class CampaignDTO { - private Long shopId; - private String title; - private String description; - private String scene; - private String productIds; - private String couponIds; - private Integer status; - private LocalDateTime startTime; - private LocalDateTime endTime; - private Integer sortOrder; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/CouponDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/CouponDTO.java deleted file mode 100644 index 44fe1255..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/CouponDTO.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -/** - * 优惠券DTO - */ -@Data -public class CouponDTO { - - /** - * 优惠券编码 - */ - private String couponCode; - - /** - * 优惠券名称 - */ - private String couponName; - - /** - * 优惠券类型:1-折扣券,2-满减券 - */ - private Integer couponType; - - /** - * 折扣值(如9.5表示95折) - */ - private BigDecimal discountValue; - - /** - * 满减券最低消费金额 - */ - private BigDecimal minAmount; - - /** - * 满减券减免金额 - */ - private BigDecimal reduceAmount; - - /** - * 优惠券总数量 - */ - private Integer totalCount; - - /** - * 开始时间 - */ - private LocalDateTime startTime; - - /** - * 结束时间 - */ - private LocalDateTime endTime; - - /** - * 所属店铺ID - */ - private Long shopId; - /** - * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponScene; - /** - * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String requiredVipLevel; - /** - * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer autoMatch; - - /** - * 可用标签ID列表 - */ - private List availableTagIds; - - /** - * 不可用标签ID列表 - */ - private List unavailableTagIds; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipBenefitDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipBenefitDTO.java deleted file mode 100644 index 1988f547..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipBenefitDTO.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -/** - * VIP权益信息表 DTO - * 用于VIP权益信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class VipBenefitDTO { - - /** - * 权益详情(如折扣、专属服务) - */ - private String benefitInfo; - - /** - * 所需VIP等级 - */ - private String requiredVipLevel; - /** - * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer levelRank; - /** - * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal rechargeThreshold; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipInfoDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipInfoDTO.java deleted file mode 100644 index f997005f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipInfoDTO.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 用户VIP信息表 DTO - * 用于VIP信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class VipInfoDTO { - - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - /** - * VIP等级(如青铜、白银) - */ - private String vipLevel; - - /** - * VIP开通时间 - */ - private LocalDateTime startTime; - - /** - * VIP到期时间 - */ - private LocalDateTime expireTime; - - /** - * VIP开通方式(如购买、赠送) - */ - private String activationMethod; - - /** - * 关联VIP权益信息表主键 - */ - private Long benefitId; - /** - * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer manualOverride; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipRechargePlanDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipRechargePlanDTO.java deleted file mode 100644 index 3b2b7639..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/VipRechargePlanDTO.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -import javax.validation.constraints.DecimalMin; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import java.math.BigDecimal; - -@Data -/** - * VipRechargePlanDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class VipRechargePlanDTO { - - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @NotBlank(message = "充值档位标题不能为空") - @Size(max = 100, message = "充值档位标题不能超过100个字符") - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - - @NotNull(message = "充值金额不能为空") - @DecimalMin(value = "0.01", message = "充值金额必须大于0") - /** - * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal rechargeAmount; - - @NotNull(message = "赠送金额不能为空") - @DecimalMin(value = "0.00", message = "赠送金额不能小于0") - /** - * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal giftAmount; - - @NotBlank(message = "VIP等级不能为空") - @Size(max = 20, message = "VIP等级不能超过20个字符") - /** - * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String vipLevel; - - @Size(max = 255, message = "说明不能超过255个字符") - /** - * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String description; - - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder = 0; - - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status = 1; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistAddWithGroupDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistAddWithGroupDTO.java deleted file mode 100644 index 11583ffe..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistAddWithGroupDTO.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -@Data -public class WishlistAddWithGroupDTO { - private Long productId; - private Long groupId; - private String note; - private Integer sortOrder; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistDTO.java deleted file mode 100644 index 7ee3fe2b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistDTO.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.ProductVO; -import lombok.Data; - -/** - * 收藏夹 DTO - * 用于收藏夹商品信息的传输 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class WishlistDTO { - - /** - * 收藏记录ID - */ - private Long id; - - /** - * 用户ID - */ - private Long userId; - - /** - * 商品ID - */ - private Long productId; - - private Long groupId; - - private String groupName; - - private String note; - - private Integer sortOrder; - - /** - * 商品详细信息 - */ - private ProductVO product; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistGroupDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistGroupDTO.java deleted file mode 100644 index 30d7a505..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistGroupDTO.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -@Data -public class WishlistGroupDTO { - private String name; - private Integer sortOrder; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistMoveDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistMoveDTO.java deleted file mode 100644 index bd36de09..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/dto/WishlistMoveDTO.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.dto; - -import lombok.Data; - -@Data -public class WishlistMoveDTO { - private Long wishlistId; - private Long productId; - private Long groupId; - private String note; - private Integer sortOrder; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CampaignDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CampaignDO.java deleted file mode 100644 index cded94dc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CampaignDO.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_campaign") -public class CampaignDO extends BaseEntity { - @TableField("shop_id") - private Long shopId; - @TableField("title") - private String title; - @TableField("description") - private String description; - @TableField("scene") - private String scene; - @TableField("product_ids") - private String productIds; - @TableField("coupon_ids") - private String couponIds; - @TableField("status") - private Integer status; - @TableField("start_time") - private LocalDateTime startTime; - @TableField("end_time") - private LocalDateTime endTime; - @TableField("sort_order") - private Integer sortOrder; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CouponDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CouponDO.java deleted file mode 100644 index a26ccdb4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CouponDO.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 优惠券信息表 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_coupon") -public class CouponDO extends BaseEntity { - - /** - * 优惠券编码 - */ - private String couponCode; - - /** - * 优惠券名称 - */ - private String couponName; - - /** - * 优惠券类型:1-折扣券,2-满减券 - */ - private Integer couponType; - - /** - * 折扣值(如9.5表示95折) - */ - private BigDecimal discountValue; - - /** - * 满减券最低消费金额 - */ - private BigDecimal minAmount; - - /** - * 满减券减免金额 - */ - private BigDecimal reduceAmount; - - /** - * 优惠券总数量 - */ - private Integer totalCount; - - /** - * 已使用数量 - */ - private Integer usedCount; - - /** - * 开始时间 - */ - private LocalDateTime startTime; - - /** - * 结束时间 - */ - private LocalDateTime endTime; - - /** - * 状态:1-可用,2-已过期,3-已用完 - */ - private Integer status; - - /** - * 所属店铺ID - */ - private Long shopId; - - /** - * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponScene; - - /** - * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String requiredVipLevel; - - /** - * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer autoMatch; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CouponTagDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CouponTagDO.java deleted file mode 100644 index 7646c3ac..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/CouponTagDO.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 优惠券标签关联表 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_coupon_tag") -public class CouponTagDO extends BaseEntity { - - /** - * 关联优惠券表主键 - */ - private Long couponId; - - /** - * 关联标签表主键 - */ - private Long tagId; - - /** - * 是否可用:1-可用,0-不可用 - */ - private Integer isAvailable; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/ProductLikeDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/ProductLikeDO.java deleted file mode 100644 index a746d53f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/ProductLikeDO.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 商品点赞记录表 DO - * 对应数据库表 t_product_like - * - * @author xiaowang - * @date 2026-03-05 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_product_like") -public class ProductLikeDO extends BaseEntity { - - /** - * 关联用户表主键 - */ - @TableField("user_id") - private Long userId; - - /** - * 关联商品表主键 - */ - @TableField("product_id") - private Long productId; - - /** - * 逻辑删除标识:0-未删除,1-已删除 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/UserCouponDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/UserCouponDO.java deleted file mode 100644 index 30bf46d3..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/UserCouponDO.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 用户优惠券关联表 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_user_coupon") -public class UserCouponDO extends BaseEntity { - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 关联优惠券表主键 - */ - private Long couponId; - - /** - * 状态:1-未使用,2-已使用,3-已过期 - */ - private Integer status; - - /** - * 获取时间 - */ - private LocalDateTime obtainTime; - - /** - * 使用时间 - */ - private LocalDateTime useTime; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipBenefitDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipBenefitDO.java deleted file mode 100644 index 1eca6114..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipBenefitDO.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * VIP权益信息表 DO - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_vip_benefit") -public class VipBenefitDO extends BaseEntity { - - /** - * 权益详情(如折扣、专属服务) - */ - @TableField("benefit_info") - private String benefitInfo; - - /** - * 所需VIP等级 - */ - @TableField("required_vip_level") - private String requiredVipLevel; - - @TableField("level_rank") - /** - * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer levelRank; - - @TableField("recharge_threshold") - /** - * Field `rechargeThreshold` (java.math.BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private java.math.BigDecimal rechargeThreshold; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipInfoDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipInfoDO.java deleted file mode 100644 index d0aab30a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipInfoDO.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 用户VIP信息表 DO - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_vip_info") -public class VipInfoDO extends BaseEntity { - - @TableField("user_id") - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - /** - * VIP等级(如青铜、白银) - */ - @TableField("vip_level") - private String vipLevel; - - /** - * VIP开通时间 - */ - @TableField("start_time") - private LocalDateTime startTime; - - /** - * VIP到期时间 - */ - @TableField("expire_time") - private LocalDateTime expireTime; - - /** - * VIP开通方式(如购买、赠送) - */ - @TableField("activation_method") - private String activationMethod; - - /** - * 关联VIP权益信息表主键 - */ - @TableField("benefit_id") - private Long benefitId; - - @TableField("manual_override") - /** - * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer manualOverride; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipRechargePlanDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipRechargePlanDO.java deleted file mode 100644 index 72584b9b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/VipRechargePlanDO.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_vip_recharge_plan") -/** - * VipRechargePlanDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class VipRechargePlanDO extends BaseEntity { - - @TableField("shop_id") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @TableField("title") - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - - @TableField("recharge_amount") - /** - * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal rechargeAmount; - - @TableField("gift_amount") - /** - * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal giftAmount; - - @TableField("vip_level") - /** - * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String vipLevel; - - @TableField("description") - /** - * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String description; - - @TableField("sort_order") - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/WishlistDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/WishlistDO.java deleted file mode 100644 index b1339719..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/WishlistDO.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@TableName("t_wishlist") -/** - * WishlistDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class WishlistDO extends BaseEntity { - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - /** - * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long productId; - - @TableField("group_id") - private Long groupId; - - @TableField("note") - private String note; - - @TableField("sort_order") - private Integer sortOrder; - - @TableField("is_delete") - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/WishlistGroupDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/WishlistGroupDO.java deleted file mode 100644 index dc72e6fe..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/entity/WishlistGroupDO.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_wishlist_group") -public class WishlistGroupDO extends BaseEntity { - - @TableField("user_id") - private Long userId; - - @TableField("name") - private String name; - - @TableField("sort_order") - private Integer sortOrder; - - @TableField("is_delete") - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CampaignMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CampaignMapper.java deleted file mode 100644 index e0b91a94..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CampaignMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CampaignDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface CampaignMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CouponMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CouponMapper.java deleted file mode 100644 index 2ab3e940..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CouponMapper.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponDO; -import org.apache.ibatis.annotations.Mapper; - -/** - * 优惠券Mapper - */ -@Mapper -public interface CouponMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CouponTagMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CouponTagMapper.java deleted file mode 100644 index df9f2f65..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/CouponTagMapper.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponTagDO; -import org.apache.ibatis.annotations.Mapper; - -/** - * 优惠券标签关联Mapper - */ -@Mapper -public interface CouponTagMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/ProductLikeMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/ProductLikeMapper.java deleted file mode 100644 index 87f1d50e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/ProductLikeMapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.ProductLikeDO; -import org.apache.ibatis.annotations.Param; - -/** - * 商品点赞记录表 Mapper - * 对应数据库表 t_product_like - * - * @author xiaowang - * @date 2026-03-05 - */ -public interface ProductLikeMapper extends BaseMapper { - - /** - * 检查用户是否已点赞商品 - * - * @param userId 用户ID - * @param productId 商品ID - * @return 是否已点赞 - */ - boolean isProductLiked(@Param("userId") Long userId, @Param("productId") Long productId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/UserCouponMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/UserCouponMapper.java deleted file mode 100644 index 886c9efc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/UserCouponMapper.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.UserCouponDO; -import org.apache.ibatis.annotations.Mapper; - -/** - * 用户优惠券Mapper - */ -@Mapper -public interface UserCouponMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipBenefitMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipBenefitMapper.java deleted file mode 100644 index b2132c61..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipBenefitMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipBenefitDO; - -/** - * VIP权益信息表 Mapper - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface VipBenefitMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipInfoMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipInfoMapper.java deleted file mode 100644 index f01227da..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipInfoMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipInfoDO; - -/** - * 用户VIP信息表 Mapper - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface VipInfoMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipRechargePlanMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipRechargePlanMapper.java deleted file mode 100644 index 3b2e140d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/VipRechargePlanMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipRechargePlanDO; - -/** - * VipRechargePlanMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface VipRechargePlanMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/WishlistGroupMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/WishlistGroupMapper.java deleted file mode 100644 index 08155415..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/WishlistGroupMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.WishlistGroupDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface WishlistGroupMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/WishlistMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/WishlistMapper.java deleted file mode 100644 index 81554b45..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/mapper/WishlistMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.WishlistDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * WishlistMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface WishlistMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/CampaignService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/CampaignService.java deleted file mode 100644 index c3767139..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/CampaignService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.CampaignDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.CampaignVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; - -public interface CampaignService { - CampaignVO saveCampaign(CampaignDTO dto); - - PageResultVO listCampaigns(Long shopId, Integer status, Integer page, Integer size); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/CouponService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/CouponService.java deleted file mode 100644 index 9d46b72a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/CouponService.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.UserCouponVO; - -import java.util.List; - -/** - * 优惠券服务 - */ -public interface CouponService extends IService { - - /** - * 创建优惠券 - * @param couponDTO 优惠券DTO - * @param shopId 店铺ID - * @return 优惠券ID - */ - Long createCoupon(CouponDTO couponDTO, Long shopId); - - /** - * 更新优惠券 - * @param id 优惠券ID - * @param couponDTO 优惠券DTO - * @param shopId 店铺ID - * @return 是否成功 - */ - boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId); - - /** - * 删除优惠券 - * @param id 优惠券ID - * @param shopId 店铺ID - * @return 是否成功 - */ - boolean deleteCoupon(Long id, Long shopId); - - /** - * 获取优惠券详情 - * @param id 优惠券ID - * @return 优惠券VO - */ - CouponVO getCouponById(Long id); - - /** - * 获取优惠券列表 - * @param page 页码 - * @param size 每页大小 - * @param shopId 店铺ID - * @return 分页结果 - */ - PageResultVO listCoupons(Integer page, Integer size, Long shopId); - - /** - * 获取所有优惠券 - * @return 优惠券列表 - */ - List listAllCoupons(); - - /** - * 为用户分配优惠券 - * @param userId 用户ID - * @param couponId 优惠券ID - * @param shopId 店铺ID - * @return 是否成功 - */ - boolean assignCouponToUser(Long userId, Long couponId, Long shopId); - - /** - * 获取用户优惠券列表 - * @param userId 用户ID - * @param status 状态 - * @return 用户优惠券列表 - */ - List listUserCoupons(Long userId, Integer status); - - /** - * 使用优惠券 - * @param userCouponId 用户优惠券ID - * @param userId 用户ID - * @return 是否成功 - */ - boolean useCoupon(Long userCouponId, Long userId); - - /** - * 获取商品可用的优惠券 - * @param userId 用户ID - * @param productTags 商品标签 - * @param productPrice 商品价格 - * @return 可用优惠券列表 - */ - List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId); - - /** - * 为新店铺初始化默认 VIP 自动券模板 - * - * @param shopId 店铺ID - */ - void initializeDefaultVipAutoCoupons(Long shopId); - - /** - * 发放优惠券 - * @param couponId 优惠券ID - * @param userIds 用户ID列表 - * @param quantity 发放数量 - * @param shopId 店铺ID - * @return 是否成功 - */ - boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/GrowthService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/GrowthService.java deleted file mode 100644 index 5409988d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/GrowthService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.GrowthSummaryVO; - -public interface GrowthService { - GrowthSummaryVO getSummary(Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/ProductLikeService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/ProductLikeService.java deleted file mode 100644 index 50673319..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/ProductLikeService.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.ProductLikeDO; - -/** - * 商品点赞记录表 Service - * 对应数据库表 t_product_like - * - * @author xiaowang - * @date 2026-03-05 - */ -public interface ProductLikeService extends IService { - - /** - * 添加点赞记录 - * - * @param userId 用户ID - * @param productId 商品ID - */ - void addLike(Long userId, Long productId); - - /** - * 取消点赞 - * - * @param userId 用户ID - * @param productId 商品ID - */ - void removeLike(Long userId, Long productId); - - /** - * 检查用户是否已点赞商品 - * - * @param userId 用户ID - * @param productId 商品ID - * @return 是否已点赞 - */ - boolean isProductLiked(Long userId, Long productId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipBenefitService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipBenefitService.java deleted file mode 100644 index 81a370b4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipBenefitService.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipBenefitDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipBenefitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipBenefitVO; - -import java.util.List; - -/** - * VIP权益信息表 Service - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface VipBenefitService extends IService { - - /** - * 创建VIP权益 - * - * @param vipBenefitDTO VIP权益DTO - * @return VIP权益ID - */ - Long createVipBenefit(VipBenefitDTO vipBenefitDTO); - - /** - * 更新VIP权益 - * - * @param id VIP权益ID - * @param vipBenefitDTO VIP权益DTO - * @return 是否更新成功 - */ - boolean updateVipBenefit(Long id, VipBenefitDTO vipBenefitDTO); - - /** - * 删除VIP权益 - * - * @param id VIP权益ID - * @return 是否删除成功 - */ - boolean deleteVipBenefit(Long id); - - /** - * 根据ID查询VIP权益 - * - * @param id VIP权益ID - * @return VIP权益VO - */ - VipBenefitVO getVipBenefitById(Long id); - - /** - * 查询所有VIP权益 - * - * @return VIP权益VO列表 - */ - List listAllVipBenefits(); - - /** - * 根据所需VIP等级查询VIP权益 - * - * @param requiredVipLevel 所需VIP等级 - * @return VIP权益VO列表 - */ - List listVipBenefitsByRequiredVipLevel(String requiredVipLevel); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipInfoService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipInfoService.java deleted file mode 100644 index 28c3f317..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipInfoService.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipInfoVO; - -import java.util.List; - -/** - * 用户VIP信息表 Service - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface VipInfoService extends IService { - - /** - * 创建VIP信息 - * - * @param vipInfoDTO VIP信息DTO - * @return VIP信息ID - */ - Long createVipInfo(VipInfoDTO vipInfoDTO); - - /** - * 更新VIP信息 - * - * @param id VIP信息ID - * @param vipInfoDTO VIP信息DTO - * @return 是否更新成功 - */ - boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO); - - /** - * 删除VIP信息 - * - * @param id VIP信息ID - * @return 是否删除成功 - */ - boolean deleteVipInfo(Long id); - - /** - * 根据ID查询VIP信息 - * - * @param id VIP信息ID - * @return VIP信息VO - */ - VipInfoVO getVipInfoById(Long id); - - /** - * 查询所有VIP信息 - * - * @return VIP信息VO列表 - */ - List listAllVipInfos(); - - /** - * 根据VIP等级查询VIP信息 - * - * @param vipLevel VIP等级 - * @return VIP信息VO列表 - */ - List listVipInfosByVipLevel(String vipLevel); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipRechargePlanService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipRechargePlanService.java deleted file mode 100644 index 4fc2567c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/VipRechargePlanService.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipRechargePlanDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipRechargePlanDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipRechargePlanVO; - -import java.util.List; - -/** - * VipRechargePlanService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface VipRechargePlanService extends IService { - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long createPlan(UserDO currentUser, VipRechargePlanDTO dto); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto); - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updateStatus(UserDO currentUser, Long id, Integer status); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listAdminPlans(UserDO currentUser, Long shopId); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listMyPlans(Long userId); - - List listVipLevelOptions(UserDO currentUser, Long shopId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/WishlistService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/WishlistService.java deleted file mode 100644 index 380312ef..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/WishlistService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistAddWithGroupDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistGroupDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistMoveDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.WishlistDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.WishlistGroupVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.WishlistInspirationVO; - -import java.util.List; - -/** - * WishlistService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface WishlistService extends IService { - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ - void addToWishlist(Long userId, Long productId); - void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO); - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ - void removeFromWishlist(Long userId, Long productId); - /** - * Run business method `isInWishlist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean isInWishlist(Long userId, Long productId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getWishlistByUserId(Long userId); - - List listGroups(Long userId); - - Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO); - - boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO); - - boolean deleteGroup(Long userId, Long groupId); - - boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO); - - WishlistInspirationVO getInspiration(Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/CampaignServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/CampaignServiceImpl.java deleted file mode 100644 index fb647ee7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/CampaignServiceImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.CampaignDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CampaignDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.CampaignMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.CampaignService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.CampaignVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@RequiredArgsConstructor -public class CampaignServiceImpl implements CampaignService { - - private final CampaignMapper campaignMapper; - - @Override - @Transactional - public CampaignVO saveCampaign(CampaignDTO dto) { - if (dto == null || dto.getTitle() == null || dto.getTitle().isBlank()) { - throw new RuntimeException("活动标题不能为空"); - } - CampaignDO campaign = new CampaignDO(); - BeanUtils.copyProperties(dto, campaign); - campaign.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); - campaign.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); - campaign.setIsDelete(0); - campaignMapper.insert(campaign); - return toVO(campaign); - } - - @Override - public PageResultVO listCampaigns(Long shopId, Integer status, Integer page, Integer size) { - int current = page == null || page < 1 ? 1 : page; - int pageSize = size == null || size < 1 ? 10 : size; - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(CampaignDO::getIsDelete, 0) - .orderByAsc(CampaignDO::getSortOrder) - .orderByDesc(CampaignDO::getCreateTime); - if (shopId != null) { - wrapper.eq(CampaignDO::getShopId, shopId); - } - if (status != null) { - wrapper.eq(CampaignDO::getStatus, status); - } - Page result = campaignMapper.selectPage(new Page<>(current, pageSize), wrapper); - PageResultVO vo = new PageResultVO<>(); - vo.setList(result.getRecords().stream().map(this::toVO).toList()); - vo.setTotal(result.getTotal()); - vo.setPage(current); - vo.setSize(pageSize); - return vo; - } - - private CampaignVO toVO(CampaignDO campaign) { - CampaignVO vo = new CampaignVO(); - BeanUtils.copyProperties(campaign, vo); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/CouponServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/CouponServiceImpl.java deleted file mode 100644 index c691d7eb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/CouponServiceImpl.java +++ /dev/null @@ -1,1233 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.CouponDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponTagDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.TagDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.UserCouponDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.CouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.CouponTagMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.TagMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.UserCouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.CouponService; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.CouponVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.UserCouponVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -/** - * 优惠券服务实现 - */ -@Service -@RequiredArgsConstructor -public class CouponServiceImpl extends ServiceImpl implements CouponService { - - /** - * Purpose: COUPON_SOURCE_USER supports CouponServiceImpl.java by holding or executing the coupon source user business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String COUPON_SOURCE_USER = "USER_COUPON"; - /** - * Purpose: COUPON_SOURCE_SYSTEM_VIP supports CouponServiceImpl.java by holding or executing the coupon source system vip business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; - /** - * Purpose: COUPON_SCENE_VIP_AUTO supports CouponServiceImpl.java by holding or executing the coupon scene vip auto business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String COUPON_SCENE_VIP_AUTO = "VIP_AUTO"; - /** - * Purpose: DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT supports CouponServiceImpl.java by holding or executing the default vip auto coupon total count business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT = 999999; - private static final LocalDateTime DEFAULT_VIP_AUTO_COUPON_END_TIME = LocalDateTime.of(2099, 12, 31, 23, 59, 59); - private static final List DEFAULT_SHOP_VIP_AUTO_COUPONS = List.of( - new VipAutoCouponTemplate("BRONZE_95", "青铜VIP自动95折券", "青铜", BigDecimal.valueOf(9.5)), - new VipAutoCouponTemplate("SILVER_92", "白银VIP自动92折券", "白银", BigDecimal.valueOf(9.2)), - new VipAutoCouponTemplate("GOLD_90", "黄金VIP自动90折券", "黄金", BigDecimal.valueOf(9.0)) - ); - /** - * Purpose: VIP_LEVEL_NORMAL supports CouponServiceImpl.java by holding or executing the vip level normal business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String VIP_LEVEL_NORMAL = "普通"; - /** - * Variable `couponTagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponTagMapper couponTagMapper; - /** - * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserCouponMapper userCouponMapper; - /** - * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TagMapper tagMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - /** - * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - - @Override - @Transactional - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDTO parameter `couponDTO` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createCoupon(CouponDTO couponDTO, Long shopId) { - // 创建优惠券 - CouponDO couponDO = new CouponDO(); - couponDO.setCouponCode(resolveCouponCodeForCreate(couponDTO.getCouponCode())); - couponDO.setCouponName(couponDTO.getCouponName()); - couponDO.setCouponType(couponDTO.getCouponType()); - couponDO.setDiscountValue(couponDTO.getDiscountValue()); - couponDO.setMinAmount(couponDTO.getMinAmount()); - couponDO.setReduceAmount(couponDTO.getReduceAmount()); - couponDO.setTotalCount(couponDTO.getTotalCount()); - couponDO.setUsedCount(0); - couponDO.setStartTime(couponDTO.getStartTime()); - couponDO.setEndTime(couponDTO.getEndTime()); - couponDO.setStatus(1); - couponDO.setShopId(shopId); - couponDO.setCouponScene(couponDTO.getCouponScene()); - couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); - couponDO.setAutoMatch(couponDTO.getAutoMatch()); - /** - * Save submitted data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - save(couponDO); - - // 处理标签关联 - handleCouponTags(couponDO.getId(), couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds()); - - return couponDO.getId(); - } - - @Override - @Transactional - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param couponDTO parameter `couponDTO` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId) { - // 更新优惠券 - CouponDO couponDO = getById(id); - if (couponDO == null) { - return false; - } - - couponDO.setCouponCode(resolveCouponCodeForUpdate(couponDO.getCouponCode(), couponDTO.getCouponCode())); - couponDO.setCouponName(couponDTO.getCouponName()); - couponDO.setCouponType(couponDTO.getCouponType()); - couponDO.setDiscountValue(couponDTO.getDiscountValue()); - couponDO.setMinAmount(couponDTO.getMinAmount()); - couponDO.setReduceAmount(couponDTO.getReduceAmount()); - couponDO.setTotalCount(couponDTO.getTotalCount()); - couponDO.setStartTime(couponDTO.getStartTime()); - couponDO.setEndTime(couponDTO.getEndTime()); - couponDO.setShopId(shopId); - couponDO.setCouponScene(couponDTO.getCouponScene()); - couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); - couponDO.setAutoMatch(couponDTO.getAutoMatch()); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateById(couponDO); - /** - * Run business method `refreshCouponDistributionStatus`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - refreshCouponDistributionStatus(id); - - // 处理标签关联 - handleCouponTags(id, couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds()); - - return true; - } - - @Override - @Transactional - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteCoupon(Long id, Long shopId) { - // 删除优惠券 - CouponDO couponDO = getById(id); - if (couponDO == null) { - return false; - } - couponDO.setIsDelete(1); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return updateById(couponDO); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return CouponVO result consumed by the caller or returned to the frontend - */ - public CouponVO getCouponById(Long id) { - CouponDO couponDO = getById(id); - if (couponDO == null || couponDO.getIsDelete() == 1) { - return null; - } - /** - * Run business method `convertToCouponVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToCouponVO(couponDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - public PageResultVO listCoupons(Integer page, Integer size, Long shopId) { - Page pageInfo = new Page<>(page, size); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(CouponDO::getIsDelete, 0) - .orderByDesc(CouponDO::getCreateTime); - if (shopId != null) { - wrapper.eq(CouponDO::getShopId, shopId); - } - IPage couponPage = page(pageInfo, wrapper); - - List couponVOs = couponPage.getRecords().stream() - .map(this::convertToCouponVO) - .collect(Collectors.toList()); - - PageResultVO pageResult = new PageResultVO<>(); - pageResult.setList(couponVOs); - pageResult.setTotal(couponPage.getTotal()); - pageResult.setPage(page); - pageResult.setSize(size); - - return pageResult; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllCoupons() { - List couponDOs = list(new LambdaQueryWrapper() - .eq(CouponDO::getIsDelete, 0) - .orderByDesc(CouponDO::getCreateTime) - ); - return couponDOs.stream() - .map(this::convertToCouponVO) - .collect(Collectors.toList()); - } - - @Override - @Transactional - /** - * Run business method `assignCouponToUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param couponId parameter `couponId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean assignCouponToUser(Long userId, Long couponId, Long shopId) { - // 检查优惠券是否存在 - CouponDO couponDO = getById(couponId); - if (couponDO == null || couponDO.getIsDelete() == 1) { - return false; - } - - // 检查优惠券是否可用 - if (couponDO.getStatus() != 1) { - return false; - } - if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) { - return false; - } - if (isVipAutoCoupon(couponDO)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); - } - if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { - return false; - } - - // 检查是否已经分配 - UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper() - .eq(UserCouponDO::getUserId, userId) - .eq(UserCouponDO::getCouponId, couponId) - .eq(UserCouponDO::getIsDelete, 0) - ); - if (existing != null) { - return false; - } - if (!hasRemainingDistributionStock(couponDO, 1)) { - return false; - } - - // 分配优惠券 - UserCouponDO userCouponDO = new UserCouponDO(); - userCouponDO.setUserId(userId); - userCouponDO.setCouponId(couponId); - userCouponDO.setStatus(1); - userCouponDO.setObtainTime(LocalDateTime.now()); - userCouponMapper.insert(userCouponDO); - /** - * Run business method `refreshCouponDistributionStatus`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - refreshCouponDistributionStatus(couponId); - - return true; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listUserCoupons(Long userId, Integer status) { - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() - .eq(UserCouponDO::getUserId, userId) - .eq(UserCouponDO::getIsDelete, 0); - - if (status != null) { - queryWrapper.eq(UserCouponDO::getStatus, status); - } - - List userCouponDOs = userCouponMapper.selectList(queryWrapper); - return userCouponDOs.stream() - .map(userCouponDO -> { - CouponDO couponDO = getById(userCouponDO.getCouponId()); - return couponDO == null ? null : convertToUserCouponVO(userCouponDO, couponDO); - }) - .filter(java.util.Objects::nonNull) - .collect(Collectors.toList()); - } - - @Override - @Transactional - /** - * Run business method `useCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userCouponId parameter `userCouponId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean useCoupon(Long userCouponId, Long userId) { - // 检查用户优惠券是否存在 - UserCouponDO userCouponDO = userCouponMapper.selectById(userCouponId); - if (userCouponDO == null || userCouponDO.getIsDelete() == 1) { - return false; - } - - // 检查是否属于当前用户 - if (!userCouponDO.getUserId().equals(userId)) { - return false; - } - - // 检查是否未使用 - if (userCouponDO.getStatus() != 1) { - return false; - } - - // 检查优惠券是否过期 - CouponDO couponDO = getById(userCouponDO.getCouponId()); - if (couponDO == null || couponDO.getEndTime().isBefore(LocalDateTime.now())) { - return false; - } - - // 使用优惠券 - userCouponDO.setStatus(2); - userCouponDO.setUseTime(LocalDateTime.now()); - userCouponMapper.updateById(userCouponDO); - - // 更新优惠券使用数量 - incrementCouponUsedCount(couponDO.getId()); - - return true; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productTags parameter `productTags` supplied by the caller - * @param productPrice parameter `productPrice` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId) { - BigDecimal orderAmount = productPrice == null ? BigDecimal.ZERO : BigDecimal.valueOf(productPrice); - LocalDateTime now = LocalDateTime.now(); - List availableCoupons = new ArrayList<>(); - - List userCouponDOs = userCouponMapper.selectList(new LambdaQueryWrapper() - .eq(UserCouponDO::getUserId, userId) - .eq(UserCouponDO::getStatus, 1) - .eq(UserCouponDO::getIsDelete, 0) - ); - - for (UserCouponDO userCouponDO : userCouponDOs) { - CouponDO couponDO = getById(userCouponDO.getCouponId()); - if (!isCouponApplicable(couponDO, now, orderAmount, productTags, shopId)) { - continue; - } - availableCoupons.add(convertToUserCouponVO(userCouponDO, couponDO)); - } - - UserDO userDO = userMapper.selectById(userId); - String currentVipLevel = userDO != null ? userDO.getLevel() : null; - if (currentVipLevel != null && !currentVipLevel.isBlank() && !VIP_LEVEL_NORMAL.equals(currentVipLevel)) { - List vipCoupons = listVipAutoCouponsByShop(currentVipLevel, shopId); - - for (CouponDO couponDO : vipCoupons) { - if (!isCouponApplicable(couponDO, now, orderAmount, productTags, shopId)) { - continue; - } - availableCoupons.add(convertToSystemVipCouponVO(couponDO)); - } - } - - availableCoupons.sort(Comparator - .comparing((UserCouponVO item) -> calculateDiscountAmount(item, orderAmount)).reversed() - .thenComparing(UserCouponVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))); - return availableCoupons; - } - - @Override - @Transactional - /** - * Run business method `initializeDefaultVipAutoCoupons`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - */ - public void initializeDefaultVipAutoCoupons(Long shopId) { - if (shopId == null || shopId <= 0) { - return; - } - - LocalDateTime startTime = LocalDateTime.now(); - for (VipAutoCouponTemplate template : DEFAULT_SHOP_VIP_AUTO_COUPONS) { - String couponCode = buildShopVipAutoCouponCode(shopId, template.codeSuffix()); - CouponDO existingCoupon = lambdaQuery() - .eq(CouponDO::getCouponCode, couponCode) - .one(); - if (existingCoupon != null) { - continue; - } - - CouponDO couponDO = new CouponDO(); - couponDO.setCouponCode(couponCode); - couponDO.setCouponName(template.couponName()); - couponDO.setCouponType(1); - couponDO.setDiscountValue(template.discountValue()); - couponDO.setMinAmount(BigDecimal.ZERO); - couponDO.setReduceAmount(BigDecimal.ZERO); - couponDO.setTotalCount(DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT); - couponDO.setUsedCount(0); - couponDO.setStartTime(startTime); - couponDO.setEndTime(DEFAULT_VIP_AUTO_COUPON_END_TIME); - couponDO.setStatus(1); - couponDO.setShopId(shopId); - couponDO.setCouponScene(COUPON_SCENE_VIP_AUTO); - couponDO.setRequiredVipLevel(template.requiredVipLevel()); - couponDO.setAutoMatch(1); - couponDO.setIsDelete(0); - /** - * Save submitted data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - save(couponDO); - } - } - - @Override - @Transactional - /** - * Run business method `distributeCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @param userIds parameter `userIds` supplied by the caller - * @param quantity parameter `quantity` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId) { - // 检查优惠券是否存在 - CouponDO couponDO = getById(couponId); - if (couponDO == null || couponDO.getIsDelete() == 1) { - return false; - } - - // 检查优惠券是否可用 - if (couponDO.getStatus() != 1) { - return false; - } - if (isVipAutoCoupon(couponDO)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); - } - - // 检查优惠券数量是否足够 - if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) { - return false; - } - if (userIds == null || userIds.isEmpty() || quantity == null || quantity < 1) { - return false; - } - if (quantity > 1) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前用户券受唯一索引限制,同一用户同一模板只能发放 1 张"); - } - List targetUserIds = userIds.stream() - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - if (targetUserIds.isEmpty()) { - return false; - } - - for (Long userId : targetUserIds) { - if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { - return false; - } - UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper() - .eq(UserCouponDO::getUserId, userId) - .eq(UserCouponDO::getCouponId, couponId) - .eq(UserCouponDO::getIsDelete, 0)); - if (existing != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户已持有该优惠券,不能重复发放"); - } - } - - int totalNeeded = targetUserIds.size() * quantity; - if (!hasRemainingDistributionStock(couponDO, totalNeeded)) { - return false; - } - - // 发放优惠券 - LocalDateTime obtainTime = LocalDateTime.now(); - for (Long userId : targetUserIds) { - UserCouponDO userCouponDO = new UserCouponDO(); - userCouponDO.setUserId(userId); - userCouponDO.setCouponId(couponId); - userCouponDO.setStatus(1); - userCouponDO.setObtainTime(obtainTime); - userCouponMapper.insert(userCouponDO); - } - /** - * Run business method `refreshCouponDistributionStatus`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - refreshCouponDistributionStatus(couponId); - - return true; - } - - /** - * 处理优惠券标签关联 - */ - private void handleCouponTags(Long couponId, List availableTagIds, List unavailableTagIds) { - // 先查询所有现有的标签关联 - List existingTags = couponTagMapper.selectList(new LambdaQueryWrapper() - .eq(CouponTagDO::getCouponId, couponId) - .eq(CouponTagDO::getIsDelete, 0) - ); - - // 构建现有标签的映射,方便快速查找 - java.util.Map existingTagMap = new java.util.HashMap<>(); - for (CouponTagDO tag : existingTags) { - existingTagMap.put(tag.getTagId(), tag); - } - - // 处理可用标签 - if (availableTagIds != null) { - for (Long tagId : availableTagIds) { - if (existingTagMap.containsKey(tagId)) { - // 如果标签已存在,更新其状态 - CouponTagDO existingTag = existingTagMap.get(tagId); - if (existingTag.getIsAvailable() != 1) { - existingTag.setIsAvailable(1); - couponTagMapper.updateById(existingTag); - } - existingTagMap.remove(tagId); // 标记为已处理 - } else { - // 如果标签不存在,创建新的 - CouponTagDO couponTagDO = new CouponTagDO(); - couponTagDO.setCouponId(couponId); - couponTagDO.setTagId(tagId); - couponTagDO.setIsAvailable(1); - couponTagMapper.insert(couponTagDO); - } - } - } - - // 处理不可用标签 - if (unavailableTagIds != null) { - for (Long tagId : unavailableTagIds) { - if (existingTagMap.containsKey(tagId)) { - // 如果标签已存在,更新其状态 - CouponTagDO existingTag = existingTagMap.get(tagId); - if (existingTag.getIsAvailable() != 0) { - existingTag.setIsAvailable(0); - couponTagMapper.updateById(existingTag); - } - existingTagMap.remove(tagId); // 标记为已处理 - } else { - // 如果标签不存在,创建新的 - CouponTagDO couponTagDO = new CouponTagDO(); - couponTagDO.setCouponId(couponId); - couponTagDO.setTagId(tagId); - couponTagDO.setIsAvailable(0); - couponTagMapper.insert(couponTagDO); - } - } - } - - // 删除剩余的标签关联(这些是不在新列表中的标签) - for (CouponTagDO tagToDelete : existingTagMap.values()) { - couponTagMapper.deleteById(tagToDelete.getId()); - } - } - - /** - * 检查标签是否匹配 - */ - private boolean checkTagMatch(Long couponId, String productTags) { - if (productTags == null || productTags.isEmpty()) { - return true; - } - - // 解析商品标签 - String[] tagNames = productTags.split(","); - - // 查询所有标签 - List allTags = tagMapper.selectList(new LambdaQueryWrapper<>()); - - // 找到匹配的标签ID - List productTagIds = allTags.stream() - .filter(tag -> { - for (String tagName : tagNames) { - if (tag.getTagName() != null && tag.getTagName().equals(tagName.trim())) { - return true; - } - } - return false; - }) - .map(tag -> tag.getId()) - .collect(Collectors.toList()); - - if (productTagIds.isEmpty()) { - return true; - } - - // 查询优惠券的所有标签关联 - List couponTagDOs = couponTagMapper.selectList(new LambdaQueryWrapper() - .eq(CouponTagDO::getCouponId, couponId) - ); - - // 分离可用标签和不可用标签 - List availableTagIds = couponTagDOs.stream() - .filter(tag -> tag.getIsAvailable() == 1) - .map(tag -> tag.getTagId()) - .collect(Collectors.toList()); - - List unavailableTagIds = couponTagDOs.stream() - .filter(tag -> tag.getIsAvailable() == 0) - .map(tag -> tag.getTagId()) - .collect(Collectors.toList()); - - // 检查是否有不可用标签 - for (Long tagId : productTagIds) { - if (unavailableTagIds.contains(tagId)) { - return false; - } - } - - // 检查是否只包含可用标签(如果有可用标签配置) - if (!availableTagIds.isEmpty()) { - for (Long tagId : productTagIds) { - if (!availableTagIds.contains(tagId)) { - return false; - } - } - } - - return true; - } - - /** - * 转换为CouponVO - */ - private List listVipAutoCouponsByShop(String requiredVipLevel, Long shopId) { - if (shopId != null && shopId > 0) { - List shopCoupons = list(buildVipAutoCouponQuery(requiredVipLevel) - .eq(CouponDO::getShopId, shopId)); - if (!shopCoupons.isEmpty()) { - return shopCoupons; - } - return list(buildVipAutoCouponQuery(requiredVipLevel) - .isNull(CouponDO::getShopId)); - } - return list(buildVipAutoCouponQuery(requiredVipLevel)); - } - - /** - * Run business method `buildVipAutoCouponQuery`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller - * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend - */ - private LambdaQueryWrapper buildVipAutoCouponQuery(String requiredVipLevel) { - return new LambdaQueryWrapper() - .eq(CouponDO::getIsDelete, 0) - .eq(CouponDO::getStatus, 1) - .eq(CouponDO::getAutoMatch, 1) - .eq(CouponDO::getCouponScene, COUPON_SCENE_VIP_AUTO) - .eq(CouponDO::getRequiredVipLevel, requiredVipLevel) - .orderByDesc(CouponDO::getDiscountValue) - .orderByAsc(CouponDO::getEndTime); - } - - /** - * Run business method `buildShopVipAutoCouponCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @param codeSuffix parameter `codeSuffix` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildShopVipAutoCouponCode(Long shopId, String codeSuffix) { - return String.format("VIP_AUTO_SHOP_%d_%s", shopId, codeSuffix); - } - - /** - * Run business method `resolveCouponCodeForCreate`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestedCode parameter `requestedCode` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveCouponCodeForCreate(String requestedCode) { - if (StringUtils.hasText(requestedCode)) { - return requestedCode.trim(); - } - /** - * Run business method `generateUniqueManualCouponCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return return result consumed by the caller or returned to the frontend - */ - return generateUniqueManualCouponCode(); - } - - /** - * Run business method `resolveCouponCodeForUpdate`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param existingCode parameter `existingCode` supplied by the caller - * @param requestedCode parameter `requestedCode` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveCouponCodeForUpdate(String existingCode, String requestedCode) { - if (StringUtils.hasText(requestedCode)) { - return requestedCode.trim(); - } - if (StringUtils.hasText(existingCode)) { - return existingCode.trim(); - } - /** - * Run business method `generateUniqueManualCouponCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return return result consumed by the caller or returned to the frontend - */ - return generateUniqueManualCouponCode(); - } - - /** - * Run business method `generateUniqueManualCouponCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private String result consumed by the caller or returned to the frontend - */ - private String generateUniqueManualCouponCode() { - for (int attempt = 0; attempt < 10; attempt++) { - String candidate = "CPN_" + snowflakeIdGenerator.nextBase36String(13); - if (lambdaQuery().eq(CouponDO::getCouponCode, candidate).count() == 0) { - return candidate; - } - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("生成优惠券编码失败,请稍后重试"); - } - - /** - * Run business method `convertToCouponVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return private CouponVO result consumed by the caller or returned to the frontend - */ - private CouponVO convertToCouponVO(CouponDO couponDO) { - CouponVO couponVO = new CouponVO(); - couponVO.setId(couponDO.getId()); - couponVO.setCouponCode(couponDO.getCouponCode()); - couponVO.setCouponName(couponDO.getCouponName()); - couponVO.setCouponType(couponDO.getCouponType()); - couponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券"); - couponVO.setDiscountValue(couponDO.getDiscountValue()); - couponVO.setMinAmount(couponDO.getMinAmount()); - couponVO.setReduceAmount(couponDO.getReduceAmount()); - couponVO.setTotalCount(couponDO.getTotalCount()); - couponVO.setUsedCount(normalizeCount(couponDO.getUsedCount())); - couponVO.setRemainingCount(calculateRemainingDistributionCount(couponDO)); - couponVO.setStartTime(couponDO.getStartTime()); - couponVO.setEndTime(couponDO.getEndTime()); - couponVO.setStatus(couponDO.getStatus()); - couponVO.setShopId(couponDO.getShopId()); - couponVO.setCouponScene(couponDO.getCouponScene()); - couponVO.setRequiredVipLevel(couponDO.getRequiredVipLevel()); - couponVO.setAutoMatch(couponDO.getAutoMatch()); - - // 获取店铺名称 - if (couponDO.getShopId() != null) { - ShopDO shopDO = shopMapper.selectById(couponDO.getShopId()); - if (shopDO != null) { - couponVO.setShopName(shopDO.getShopName()); - } - } - - switch (couponDO.getStatus()) { - case 1: - couponVO.setStatusName("可用"); - break; - case 2: - couponVO.setStatusName("已过期"); - break; - case 3: - couponVO.setStatusName("已用完"); - break; - default: - couponVO.setStatusName("未知"); - } - - // 获取可用标签 - List availableTags = couponTagMapper.selectList(new LambdaQueryWrapper() - .eq(CouponTagDO::getCouponId, couponDO.getId()) - .eq(CouponTagDO::getIsAvailable, 1) - ).stream() - .map(couponTag -> { - TagVO tagVO = new TagVO(); - tagVO.setId(couponTag.getTagId()); - return tagVO; - }) - .collect(Collectors.toList()); - couponVO.setAvailableTags(availableTags); - - // 获取不可用标签 - List unavailableTags = couponTagMapper.selectList(new LambdaQueryWrapper() - .eq(CouponTagDO::getCouponId, couponDO.getId()) - .eq(CouponTagDO::getIsAvailable, 0) - ).stream() - .map(couponTag -> { - TagVO tagVO = new TagVO(); - tagVO.setId(couponTag.getTagId()); - return tagVO; - }) - .collect(Collectors.toList()); - couponVO.setUnavailableTags(unavailableTags); - - return couponVO; - } - - /** - * 转换为UserCouponVO - */ - private UserCouponVO convertToUserCouponVO(UserCouponDO userCouponDO, CouponDO couponDO) { - UserCouponVO userCouponVO = buildCouponOption(userCouponDO.getId(), couponDO, COUPON_SOURCE_USER, false); - userCouponVO.setStatus(userCouponDO.getStatus()); - switch (userCouponDO.getStatus()) { - case 1: - userCouponVO.setStatusName("未使用"); - break; - case 2: - userCouponVO.setStatusName("已使用"); - break; - case 3: - userCouponVO.setStatusName("已过期"); - break; - default: - userCouponVO.setStatusName("未知"); - } - userCouponVO.setObtainTime(userCouponDO.getObtainTime()); - userCouponVO.setUseTime(userCouponDO.getUseTime()); - return userCouponVO; - } - - /** - * Run business method `convertToSystemVipCouponVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return private UserCouponVO result consumed by the caller or returned to the frontend - */ - private UserCouponVO convertToSystemVipCouponVO(CouponDO couponDO) { - UserCouponVO userCouponVO = buildCouponOption(couponDO.getId(), couponDO, COUPON_SOURCE_SYSTEM_VIP, true); - userCouponVO.setStatus(1); - userCouponVO.setStatusName("系统自动匹配"); - return userCouponVO; - } - - /** - * Run business method `buildCouponOption`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param optionId parameter `optionId` supplied by the caller - * @param couponDO parameter `couponDO` supplied by the caller - * @param sourceType parameter `sourceType` supplied by the caller - * @param autoMatched parameter `autoMatched` supplied by the caller - * @return private UserCouponVO result consumed by the caller or returned to the frontend - */ - private UserCouponVO buildCouponOption(Long optionId, CouponDO couponDO, String sourceType, boolean autoMatched) { - UserCouponVO userCouponVO = new UserCouponVO(); - userCouponVO.setId(optionId); - userCouponVO.setCouponId(couponDO.getId()); - userCouponVO.setCouponName(couponDO.getCouponName()); - userCouponVO.setCouponType(couponDO.getCouponType()); - userCouponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券"); - userCouponVO.setDiscountValue(couponDO.getDiscountValue() != null ? couponDO.getDiscountValue().toString() : ""); - userCouponVO.setMinAmount(couponDO.getMinAmount() != null ? couponDO.getMinAmount().toString() : ""); - userCouponVO.setReduceAmount(couponDO.getReduceAmount() != null ? couponDO.getReduceAmount().toString() : ""); - userCouponVO.setStartTime(couponDO.getStartTime()); - userCouponVO.setEndTime(couponDO.getEndTime()); - userCouponVO.setSourceType(sourceType); - userCouponVO.setRequiredVipLevel(couponDO.getRequiredVipLevel()); - userCouponVO.setAutoMatched(autoMatched); - return userCouponVO; - } - - /** - * Run business method `isCouponApplicable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @param now parameter `now` supplied by the caller - * @param orderAmount parameter `orderAmount` supplied by the caller - * @param productTags parameter `productTags` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isCouponApplicable(CouponDO couponDO, LocalDateTime now, BigDecimal orderAmount, String productTags, Long shopId) { - if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { - return false; - } - if (couponDO.getStatus() == null || couponDO.getStatus() != 1) { - return false; - } - if (couponDO.getStartTime() != null && now.isBefore(couponDO.getStartTime())) { - return false; - } - if (couponDO.getEndTime() != null && now.isAfter(couponDO.getEndTime())) { - return false; - } - if (!matchesShop(couponDO, shopId)) { - return false; - } - if (couponDO.getCouponType() == 2 - && couponDO.getMinAmount() != null - && couponDO.getMinAmount().compareTo(orderAmount) > 0) { - return false; - } - return checkTagMatch(couponDO.getId(), productTags); - } - - /** - * Run business method `matchesShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean matchesShop(CouponDO couponDO, Long shopId) { - if (shopId == null || couponDO.getShopId() == null) { - return true; - } - return shopId.equals(couponDO.getShopId()); - } - - /** - * Run business method `isVipAutoCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isVipAutoCoupon(CouponDO couponDO) { - return couponDO != null - && Integer.valueOf(1).equals(couponDO.getAutoMatch()) - && COUPON_SCENE_VIP_AUTO.equals(couponDO.getCouponScene()); - } - - /** - * Run business method `hasRemainingDistributionStock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @param requiredCount parameter `requiredCount` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean hasRemainingDistributionStock(CouponDO couponDO, int requiredCount) { - return calculateRemainingDistributionCount(couponDO) >= requiredCount; - } - - /** - * Run business method `calculateRemainingDistributionCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return private int result consumed by the caller or returned to the frontend - */ - private int calculateRemainingDistributionCount(CouponDO couponDO) { - if (couponDO == null || couponDO.getId() == null) { - return 0; - } - int totalCount = normalizeCount(couponDO.getTotalCount()); - long issuedCount = userCouponMapper.selectCount(new LambdaQueryWrapper() - .eq(UserCouponDO::getCouponId, couponDO.getId()) - .eq(UserCouponDO::getIsDelete, 0)); - return Math.max(0, totalCount - (int) issuedCount); - } - - /** - * Run business method `incrementCouponUsedCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void incrementCouponUsedCount(Long couponId) { - CouponDO couponDO = getById(couponId); - if (couponDO == null) { - return; - } - couponDO.setUsedCount(normalizeCount(couponDO.getUsedCount()) + 1); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateById(couponDO); - } - - /** - * Run business method `decrementCouponUsedCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void decrementCouponUsedCount(Long couponId) { - CouponDO couponDO = getById(couponId); - if (couponDO == null) { - return; - } - couponDO.setUsedCount(Math.max(0, normalizeCount(couponDO.getUsedCount()) - 1)); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateById(couponDO); - } - - /** - * Run business method `isUserEligibleForCouponDistribution`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param couponDO parameter `couponDO` supplied by the caller - * @param requestedShopId parameter `requestedShopId` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isUserEligibleForCouponDistribution(Long userId, CouponDO couponDO, Long requestedShopId) { - if (userId == null) { - return false; - } - - UserDO userDO = userMapper.selectById(userId); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return false; - } - if (requestedShopId != null && !userShopBindingSupport.isUserAccessibleInShop(userId, requestedShopId)) { - return false; - } - if (couponDO != null && couponDO.getShopId() != null - && !userShopBindingSupport.isUserAccessibleInShop(userId, couponDO.getShopId())) { - return false; - } - return true; - } - - /** - * Run business method `refreshCouponDistributionStatus`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void refreshCouponDistributionStatus(Long couponId) { - CouponDO couponDO = getById(couponId); - if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { - return; - } - if (Integer.valueOf(2).equals(couponDO.getStatus())) { - return; - } - - int remainingCount = calculateRemainingDistributionCount(couponDO); - int targetStatus = remainingCount > 0 ? 1 : 3; - if (!Objects.equals(couponDO.getStatus(), targetStatus)) { - couponDO.setStatus(targetStatus); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponDO parameter `couponDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateById(couponDO); - } - } - - /** - * Run business method `normalizeCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param count parameter `count` supplied by the caller - * @return private int result consumed by the caller or returned to the frontend - */ - private int normalizeCount(Integer count) { - return count == null ? 0 : count; - } - - /** - * Run business method `calculateDiscountAmount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponVO parameter `couponVO` supplied by the caller - * @param orderAmount parameter `orderAmount` supplied by the caller - * @return private BigDecimal result consumed by the caller or returned to the frontend - */ - private BigDecimal calculateDiscountAmount(UserCouponVO couponVO, BigDecimal orderAmount) { - if (couponVO == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) { - return BigDecimal.ZERO; - } - if (couponVO.getCouponType() == 1 && couponVO.getDiscountValue() != null && !couponVO.getDiscountValue().isBlank()) { - BigDecimal discountValue = new BigDecimal(couponVO.getDiscountValue()); - BigDecimal actualAmount = orderAmount.multiply(discountValue) - .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); - return orderAmount.subtract(actualAmount); - } - if (couponVO.getCouponType() == 2 && couponVO.getReduceAmount() != null && !couponVO.getReduceAmount().isBlank()) { - return new BigDecimal(couponVO.getReduceAmount()); - } - return BigDecimal.ZERO; - } - - /** - * Purpose: VipAutoCouponTemplate supports CouponServiceImpl.java by holding or executing the vip auto coupon template business role. - * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. - */ - private record VipAutoCouponTemplate( - String codeSuffix, - String couponName, - String requiredVipLevel, - BigDecimal discountValue - ) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/GrowthServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/GrowthServiceImpl.java deleted file mode 100644 index 0af76234..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/GrowthServiceImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserGrowthRecordDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserGrowthRecordMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.GrowthService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.GrowthSummaryVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -@Service -@RequiredArgsConstructor -public class GrowthServiceImpl implements GrowthService { - - private final UserGrowthRecordMapper userGrowthRecordMapper; - - @Override - public GrowthSummaryVO getSummary(Long userId) { - Integer growthValue = userGrowthRecordMapper.selectList(new LambdaQueryWrapper() - .eq(UserGrowthRecordDO::getUserId, userId)) - .stream() - .map(UserGrowthRecordDO::getGrowthValue) - .filter(value -> value != null) - .reduce(0, Integer::sum); - GrowthSummaryVO vo = new GrowthSummaryVO(); - vo.setUserId(userId); - vo.setGrowthValue(growthValue); - vo.setLevelName(growthValue >= 1000 ? "黄金会员" : growthValue >= 300 ? "白银会员" : "成长新客"); - vo.setAppointmentCount(0); - vo.setReviewCount(0); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/ProductLikeServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/ProductLikeServiceImpl.java deleted file mode 100644 index a9c7acfe..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/ProductLikeServiceImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.ProductLikeDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.ProductLikeMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.ProductLikeService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * 商品点赞记录表 Service 实现 - * 对应数据库表 t_product_like - * - * @author xiaowang - * @date 2026-03-05 - */ -@Service -public class ProductLikeServiceImpl extends ServiceImpl implements ProductLikeService { - - @Autowired - /** - * Purpose: productMapper supports ProductLikeServiceImpl.java by holding or executing the product mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ProductMapper productMapper; - - @Override - @Transactional - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ - public void addLike(Long userId, Long productId) { - // 检查是否已点赞 - if (isProductLiked(userId, productId)) { - return; - } - - // 添加点赞记录 - ProductLikeDO productLikeDO = new ProductLikeDO(); - productLikeDO.setUserId(userId); - productLikeDO.setProductId(productId); - /** - * Save submitted data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productLikeDO parameter `productLikeDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - save(productLikeDO); - - // 增加商品点赞数 - productMapper.incrementLikeCount(productId); - } - - @Override - @Transactional - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ - public void removeLike(Long userId, Long productId) { - // 检查是否已点赞 - if (!isProductLiked(userId, productId)) { - return; - } - - // 删除点赞记录 - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductLikeDO::getUserId, userId); - wrapper.eq(ProductLikeDO::getProductId, productId); - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - remove(wrapper); - - // 减少商品点赞数 - productMapper.decrementLikeCount(productId); - } - - @Override - /** - * Run business method `isProductLiked`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean isProductLiked(Long userId, Long productId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductLikeDO::getUserId, userId); - wrapper.eq(ProductLikeDO::getProductId, productId); - return count(wrapper) > 0; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipBenefitServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipBenefitServiceImpl.java deleted file mode 100644 index 628c7497..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipBenefitServiceImpl.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipBenefitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipBenefitDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.VipBenefitMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.VipBenefitService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipBenefitVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * VIP权益信息表 Service 实现 - * 对应数据库表 t_vip_benefit - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class VipBenefitServiceImpl extends ServiceImpl implements VipBenefitService { - /** - * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipBenefitMapper vipBenefitMapper; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createVipBenefit(VipBenefitDTO vipBenefitDTO) { - VipBenefitDO vipBenefitDO = new VipBenefitDO(); - vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); - vipBenefitDO.setRequiredVipLevel(vipBenefitDTO.getRequiredVipLevel()); - vipBenefitMapper.insert(vipBenefitDO); - return vipBenefitDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateVipBenefit(Long id, VipBenefitDTO vipBenefitDTO) { - VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); - if (vipBenefitDO == null) { - return false; - } - vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); - vipBenefitDO.setRequiredVipLevel(vipBenefitDTO.getRequiredVipLevel()); - return vipBenefitMapper.updateById(vipBenefitDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteVipBenefit(Long id) { - return vipBenefitMapper.deleteById(id) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return VipBenefitVO result consumed by the caller or returned to the frontend - */ - public VipBenefitVO getVipBenefitById(Long id) { - VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); - if (vipBenefitDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param vipBenefitDO parameter `vipBenefitDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(vipBenefitDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllVipBenefits() { - List vipBenefitDOs = vipBenefitMapper.selectList(null); - return vipBenefitDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listVipBenefitsByRequiredVipLevel(String requiredVipLevel) { - List vipBenefitDOs = vipBenefitMapper.selectList( - Wrappers.lambdaQuery(VipBenefitDO.class) - .eq(VipBenefitDO::getRequiredVipLevel, requiredVipLevel) - ); - return vipBenefitDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param vipBenefitDO VIP权益DO - * @return VIP权益VO - */ - private VipBenefitVO convertToVO(VipBenefitDO vipBenefitDO) { - VipBenefitVO vipBenefitVO = new VipBenefitVO(); - vipBenefitVO.setId(vipBenefitDO.getId()); - vipBenefitVO.setBenefitInfo(vipBenefitDO.getBenefitInfo()); - vipBenefitVO.setRequiredVipLevel(vipBenefitDO.getRequiredVipLevel()); - vipBenefitVO.setCreateTime(vipBenefitDO.getCreateTime()); - vipBenefitVO.setUpdateTime(vipBenefitDO.getUpdateTime()); - return vipBenefitVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipInfoServiceImpl.java deleted file mode 100644 index 08780594..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipInfoServiceImpl.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.VipInfoMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.VipInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipInfoVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * 用户VIP信息表 Service 实现 - * 对应数据库表 t_vip_info - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class VipInfoServiceImpl extends ServiceImpl implements VipInfoService { - /** - * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipInfoMapper vipInfoMapper; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createVipInfo(VipInfoDTO vipInfoDTO) { - VipInfoDO vipInfoDO = new VipInfoDO(); - vipInfoDO.setUserId(vipInfoDTO.getUserId()); - vipInfoDO.setVipLevel(vipInfoDTO.getVipLevel()); - vipInfoDO.setStartTime(vipInfoDTO.getStartTime()); - vipInfoDO.setExpireTime(vipInfoDTO.getExpireTime()); - vipInfoDO.setActivationMethod(vipInfoDTO.getActivationMethod()); - vipInfoDO.setBenefitId(vipInfoDTO.getBenefitId()); - vipInfoDO.setManualOverride(vipInfoDTO.getManualOverride()); - vipInfoMapper.insert(vipInfoDO); - return vipInfoDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO) { - VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); - if (vipInfoDO == null) { - return false; - } - vipInfoDO.setUserId(vipInfoDTO.getUserId()); - vipInfoDO.setVipLevel(vipInfoDTO.getVipLevel()); - vipInfoDO.setStartTime(vipInfoDTO.getStartTime()); - vipInfoDO.setExpireTime(vipInfoDTO.getExpireTime()); - vipInfoDO.setActivationMethod(vipInfoDTO.getActivationMethod()); - vipInfoDO.setBenefitId(vipInfoDTO.getBenefitId()); - vipInfoDO.setManualOverride(vipInfoDTO.getManualOverride()); - return vipInfoMapper.updateById(vipInfoDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteVipInfo(Long id) { - return vipInfoMapper.deleteById(id) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return VipInfoVO result consumed by the caller or returned to the frontend - */ - public VipInfoVO getVipInfoById(Long id) { - VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); - if (vipInfoDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param vipInfoDO parameter `vipInfoDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(vipInfoDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllVipInfos() { - List vipInfoDOs = vipInfoMapper.selectList(null); - return vipInfoDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param vipLevel parameter `vipLevel` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listVipInfosByVipLevel(String vipLevel) { - List vipInfoDOs = vipInfoMapper.selectList( - Wrappers.lambdaQuery(VipInfoDO.class) - .eq(VipInfoDO::getVipLevel, vipLevel) - ); - return vipInfoDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param vipInfoDO VIP信息DO - * @return VIP信息VO - */ - private VipInfoVO convertToVO(VipInfoDO vipInfoDO) { - VipInfoVO vipInfoVO = new VipInfoVO(); - vipInfoVO.setId(vipInfoDO.getId()); - vipInfoVO.setUserId(vipInfoDO.getUserId()); - vipInfoVO.setVipLevel(vipInfoDO.getVipLevel()); - vipInfoVO.setStartTime(vipInfoDO.getStartTime()); - vipInfoVO.setExpireTime(vipInfoDO.getExpireTime()); - vipInfoVO.setActivationMethod(vipInfoDO.getActivationMethod()); - vipInfoVO.setBenefitId(vipInfoDO.getBenefitId()); - vipInfoVO.setManualOverride(vipInfoDO.getManualOverride()); - vipInfoVO.setCreateTime(vipInfoDO.getCreateTime()); - vipInfoVO.setUpdateTime(vipInfoDO.getUpdateTime()); - return vipInfoVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java deleted file mode 100644 index 0ef55762..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java +++ /dev/null @@ -1,397 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.VipRechargePlanDTO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipRechargePlanDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.VipRechargePlanMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.VipRechargePlanService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.VipRechargePlanVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.math.BigDecimal; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * VipRechargePlanServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class VipRechargePlanServiceImpl extends ServiceImpl implements VipRechargePlanService { - public static final List DEFAULT_VIP_LEVELS = List.of("普通", "青铜", "白银", "黄金"); - /** - * Variable `planMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipRechargePlanMapper planMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingMapper userShopBindingMapper; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createPlan(UserDO currentUser, VipRechargePlanDTO dto) { - Long shopId = resolveManagedShopId(currentUser, dto.getShopId()); - VipRechargePlanDO plan = new VipRechargePlanDO(); - /** - * Run business method `apply`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param plan parameter `plan` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - apply(plan, dto, shopId); - plan.setIsDelete(0); - planMapper.insert(plan); - return plan.getId(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto) { - VipRechargePlanDO plan = requirePlan(id); - /** - * Run business method `ensurePlanAccessible`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param plan parameter `plan` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlanAccessible(currentUser, plan); - Long shopId = resolveManagedShopId(currentUser, dto.getShopId() == null ? plan.getShopId() : dto.getShopId()); - /** - * Run business method `apply`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param plan parameter `plan` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - apply(plan, dto, shopId); - planMapper.updateById(plan); - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updateStatus(UserDO currentUser, Long id, Integer status) { - VipRechargePlanDO plan = requirePlan(id); - /** - * Run business method `ensurePlanAccessible`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param plan parameter `plan` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePlanAccessible(currentUser, plan); - plan.setStatus(Integer.valueOf(1).equals(status) ? 1 : 0); - planMapper.updateById(plan); - return true; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listAdminPlans(UserDO currentUser, Long shopId) { - Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - if (scopedShopId != null && scopedShopId > 0) { - ensureDefaultPlans(scopedShopId); - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(VipRechargePlanDO::getIsDelete, 0) - .orderByAsc(VipRechargePlanDO::getSortOrder) - .orderByDesc(VipRechargePlanDO::getCreateTime); - if (scopedShopId != null && scopedShopId > 0) { - wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); - } - return toVOList(planMapper.selectList(wrapper)); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listMyPlans(Long userId) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户不存在"); - } - Set shopIds = new LinkedHashSet<>(); - if (user.getShopId() != null && user.getShopId() > 0) { - shopIds.add(user.getShopId()); - } - userShopBindingMapper.selectList(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getIsDelete, 0) - .eq(UserShopBindingDO::getStatus, 1)) - .forEach(binding -> { - if (binding.getShopId() != null && binding.getShopId() > 0) shopIds.add(binding.getShopId()); - }); - if (shopIds.isEmpty()) { - return List.of(); - } - shopIds.forEach(this::ensureDefaultPlans); - return toVOList(planMapper.selectList(new LambdaQueryWrapper() - .eq(VipRechargePlanDO::getIsDelete, 0) - .eq(VipRechargePlanDO::getStatus, 1) - .in(VipRechargePlanDO::getShopId, shopIds) - .orderByAsc(VipRechargePlanDO::getSortOrder) - .orderByAsc(VipRechargePlanDO::getRechargeAmount))); - } - - @Override - /** - * Purpose: listVipLevelOptions supports VipRechargePlanServiceImpl.java by holding or executing the list vip level options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listVipLevelOptions(UserDO currentUser, Long shopId) { - Long scopedShopId = currentUser == null ? shopId : adminScopeHelper.resolveShopScope(currentUser, shopId); - if (scopedShopId != null && scopedShopId > 0) { - ensureDefaultPlans(scopedShopId); - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(VipRechargePlanDO::getIsDelete, 0) - .eq(VipRechargePlanDO::getStatus, 1) - .isNotNull(VipRechargePlanDO::getVipLevel) - .orderByAsc(VipRechargePlanDO::getSortOrder) - .orderByAsc(VipRechargePlanDO::getRechargeAmount); - if (scopedShopId != null && scopedShopId > 0) { - wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); - } - LinkedHashSet levels = new LinkedHashSet<>(DEFAULT_VIP_LEVELS); - planMapper.selectList(wrapper).stream() - .map(VipRechargePlanDO::getVipLevel) - .filter(level -> level != null && !level.trim().isEmpty()) - .map(String::trim) - .forEach(levels::add); - return List.copyOf(levels); - } - - /** - * Run business method `apply`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param plan parameter `plan` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void apply(VipRechargePlanDO plan, VipRechargePlanDTO dto, Long shopId) { - /** - * Run business method `ensureShopExists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureShopExists(shopId); - plan.setShopId(shopId); - plan.setTitle(dto.getTitle().trim()); - plan.setRechargeAmount(dto.getRechargeAmount()); - plan.setGiftAmount(dto.getGiftAmount()); - plan.setVipLevel(dto.getVipLevel().trim()); - plan.setDescription(dto.getDescription()); - plan.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); - plan.setStatus(Integer.valueOf(0).equals(dto.getStatus()) ? 0 : 1); - } - - /** - * Run business method `resolveManagedShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param requestedShopId parameter `requestedShopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolveManagedShopId(UserDO currentUser, Long requestedShopId) { - Long shopId = adminScopeHelper.resolveShopScope(currentUser, requestedShopId); - if (shopId == null || shopId <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择店铺"); - } - adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权维护其他店铺充值档位"); - return shopId; - } - - /** - * Run business method `ensurePlanAccessible`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param plan parameter `plan` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensurePlanAccessible(UserDO currentUser, VipRechargePlanDO plan) { - adminScopeHelper.ensureShopAccessible(currentUser, plan.getShopId(), "无权维护其他店铺充值档位"); - } - - /** - * Run business method `requirePlan`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private VipRechargePlanDO result consumed by the caller or returned to the frontend - */ - private VipRechargePlanDO requirePlan(Long id) { - VipRechargePlanDO plan = planMapper.selectById(id); - if (plan == null || Integer.valueOf(1).equals(plan.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("充值档位不存在"); - } - return plan; - } - - /** - * Run business method `ensureShopExists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensureShopExists(Long shopId) { - ShopDO shop = shopMapper.selectById(shopId); - if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("店铺不存在"); - } - } - - /** - * Purpose: ensureDefaultPlans supports VipRechargePlanServiceImpl.java by holding or executing the ensure default plans business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void ensureDefaultPlans(Long shopId) { - if (shopId == null || shopId <= 0) { - return; - } - createDefaultPlanIfMissing(shopId, "青铜", new BigDecimal("99.00"), 10); - createDefaultPlanIfMissing(shopId, "白银", new BigDecimal("299.00"), 20); - createDefaultPlanIfMissing(shopId, "黄金", new BigDecimal("599.00"), 30); - } - - /** - * Purpose: createDefaultPlanIfMissing supports VipRechargePlanServiceImpl.java by holding or executing the create default plan if missing business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void createDefaultPlanIfMissing(Long shopId, String vipLevel, BigDecimal rechargeAmount, int sortOrder) { - Long count = planMapper.selectCount(new LambdaQueryWrapper() - .eq(VipRechargePlanDO::getShopId, shopId) - .eq(VipRechargePlanDO::getVipLevel, vipLevel) - .eq(VipRechargePlanDO::getIsDelete, 0)); - if (count != null && count > 0) { - return; - } - VipRechargePlanDO plan = new VipRechargePlanDO(); - plan.setShopId(shopId); - plan.setTitle(vipLevel + "会员充值"); - plan.setRechargeAmount(rechargeAmount); - plan.setGiftAmount(BigDecimal.ZERO); - plan.setVipLevel(vipLevel); - plan.setDescription("系统默认配置,可按门店实际规则修改"); - plan.setSortOrder(sortOrder); - plan.setStatus(1); - plan.setIsDelete(0); - planMapper.insert(plan); - } - - /** - * Run business method `toVOList`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param plans parameter `plans` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List toVOList(List plans) { - Set shopIds = plans.stream().map(VipRechargePlanDO::getShopId).filter(Objects::nonNull).collect(Collectors.toSet()); - Map shopNameMap = shopIds.isEmpty() - ? Map.of() - : shopMapper.selectList(new LambdaQueryWrapper().in(ShopDO::getId, shopIds)) - .stream() - .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); - return plans.stream().map(plan -> { - VipRechargePlanVO vo = new VipRechargePlanVO(); - vo.setId(plan.getId()); - vo.setShopId(plan.getShopId()); - vo.setShopName(shopNameMap.get(plan.getShopId())); - vo.setTitle(plan.getTitle()); - vo.setRechargeAmount(plan.getRechargeAmount()); - vo.setGiftAmount(plan.getGiftAmount()); - vo.setVipLevel(plan.getVipLevel()); - vo.setDescription(plan.getDescription()); - vo.setSortOrder(plan.getSortOrder()); - vo.setStatus(plan.getStatus()); - vo.setCreateTime(plan.getCreateTime()); - vo.setUpdateTime(plan.getUpdateTime()); - return vo; - }).collect(Collectors.toList()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/WishlistServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/WishlistServiceImpl.java deleted file mode 100644 index 63067265..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/service/impl/WishlistServiceImpl.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistAddWithGroupDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistGroupDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistMoveDTO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.WishlistDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.WishlistGroupDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.WishlistGroupMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.WishlistMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.ProductService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.WishlistService; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.ProductVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.WishlistGroupVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.WishlistInspirationVO; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -public class WishlistServiceImpl extends ServiceImpl implements WishlistService { - - private static final List PRESET_GROUP_NAMES = List.of( - "\u6700\u8fd1\u60f3\u505a", - "\u5a5a\u793c\u6b3e", - "\u590f\u5929\u6b3e" - ); - private static final int DEFAULT_SORT_ORDER = 100; - private static final int NOTE_MAX_LENGTH = 500; - - private final WishlistMapper wishlistMapper; - private final WishlistGroupMapper wishlistGroupMapper; - private final ProductService productService; - private final ProductMapper productMapper; - - @Override - @Transactional - public void addToWishlist(Long userId, Long productId) { - WishlistAddWithGroupDTO dto = new WishlistAddWithGroupDTO(); - dto.setProductId(productId); - addToWishlist(userId, dto); - } - - @Override - @Transactional - public void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO) { - Long productId = wishlistDTO == null ? null : wishlistDTO.getProductId(); - ProductDO product = getValidProduct(productId); - if (product == null) { - throw new RuntimeException("\u5546\u54c1\u4e0d\u5b58\u5728\u6216\u5df2\u4e0b\u67b6"); - } - - WishlistGroupDO group = resolveTargetGroup(userId, wishlistDTO == null ? null : wishlistDTO.getGroupId()); - WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); - if (existing == null) { - WishlistDO wishlistDO = new WishlistDO(); - wishlistDO.setUserId(userId); - wishlistDO.setProductId(productId); - wishlistDO.setGroupId(group.getId()); - wishlistDO.setNote(normalizeNote(wishlistDTO == null ? null : wishlistDTO.getNote())); - wishlistDO.setSortOrder(normalizeSortOrder(wishlistDTO == null ? null : wishlistDTO.getSortOrder())); - wishlistDO.setIsDelete(0); - wishlistMapper.insert(wishlistDO); - productMapper.incrementCollectCount(productId); - return; - } - - existing.setGroupId(group.getId()); - existing.setNote(normalizeNote(wishlistDTO.getNote())); - if (wishlistDTO.getSortOrder() != null) { - existing.setSortOrder(normalizeSortOrder(wishlistDTO.getSortOrder())); - } else if (existing.getSortOrder() == null) { - existing.setSortOrder(DEFAULT_SORT_ORDER); - } - wishlistMapper.updateById(existing); - } - - @Override - @Transactional - public void removeFromWishlist(Long userId, Long productId) { - WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); - if (existing == null) { - return; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getProductId, productId); - wrapper.eq(WishlistDO::getIsDelete, 0); - wishlistMapper.delete(wrapper); - if (getValidProduct(productId) != null) { - productMapper.decrementCollectCount(productId); - } - } - - @Override - public boolean isInWishlist(Long userId, Long productId) { - if (getValidProduct(productId) == null) { - return false; - } - return findActiveWishlistByUserAndProduct(userId, productId) != null; - } - - @Override - public List getWishlistByUserId(Long userId) { - List groups = listGroups(userId); - Map groupNames = groups.stream() - .filter(group -> group.getId() != null) - .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); - return loadActiveWishlist(userId).stream() - .map(wishlistDO -> toWishlistDTO(wishlistDO, groupNames)) - .filter(wishlistDTO -> wishlistDTO.getProduct() != null) - .collect(Collectors.toList()); - } - - @Override - @Transactional - public List listGroups(Long userId) { - return ensurePresetGroups(userId).stream() - .map(this::toGroupVO) - .collect(Collectors.toList()); - } - - @Override - @Transactional - public Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO) { - WishlistGroupDO group = new WishlistGroupDO(); - group.setUserId(userId); - group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); - group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); - group.setIsDelete(0); - wishlistGroupMapper.insert(group); - return group.getId(); - } - - @Override - @Transactional - public boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO) { - WishlistGroupDO group = findOwnedGroup(userId, groupId); - if (group == null) { - return false; - } - group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); - group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); - return wishlistGroupMapper.updateById(group) > 0; - } - - @Override - @Transactional - public boolean deleteGroup(Long userId, Long groupId) { - WishlistGroupDO group = findOwnedGroup(userId, groupId); - if (group == null) { - return false; - } - WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getGroupId, groupId); - wrapper.eq(WishlistDO::getIsDelete, 0); - wishlistMapper.selectList(wrapper).forEach(wishlistDO -> { - wishlistDO.setGroupId(defaultGroup.getId()); - wishlistMapper.updateById(wishlistDO); - }); - group.setIsDelete(1); - return wishlistGroupMapper.updateById(group) > 0; - } - - @Override - @Transactional - public boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { - WishlistDO wishlistDO = findTargetWishlist(userId, wishlistMoveDTO); - if (wishlistDO == null) { - return false; - } - WishlistGroupDO group = resolveTargetGroup(userId, wishlistMoveDTO == null ? null : wishlistMoveDTO.getGroupId()); - wishlistDO.setGroupId(group.getId()); - wishlistDO.setNote(normalizeNote(wishlistMoveDTO == null ? null : wishlistMoveDTO.getNote())); - wishlistDO.setSortOrder(normalizeSortOrder(wishlistMoveDTO == null ? null : wishlistMoveDTO.getSortOrder())); - return wishlistMapper.updateById(wishlistDO) > 0; - } - - @Override - @Transactional - public WishlistInspirationVO getInspiration(Long userId) { - List groups = listGroups(userId); - Map groupMap = new LinkedHashMap<>(); - groups.forEach(group -> groupMap.put(group.getId(), group)); - - WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); - Map groupNames = groups.stream() - .filter(group -> group.getId() != null) - .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); - - List items = loadActiveWishlist(userId).stream() - .map(wishlistDO -> { - if (wishlistDO.getGroupId() == null || !groupMap.containsKey(wishlistDO.getGroupId())) { - wishlistDO.setGroupId(defaultGroup.getId()); - } - return toWishlistDTO(wishlistDO, groupNames); - }) - .filter(wishlistDTO -> wishlistDTO.getProduct() != null) - .collect(Collectors.toList()); - - items.forEach(item -> { - WishlistGroupVO group = groupMap.get(item.getGroupId()); - if (group != null) { - group.getItems().add(item); - } - }); - groups.forEach(group -> group.setItemCount(group.getItems().size())); - - WishlistInspirationVO inspirationVO = new WishlistInspirationVO(); - inspirationVO.setTotal(items.size()); - inspirationVO.setGroups(groups); - return inspirationVO; - } - - private WishlistDTO toWishlistDTO(WishlistDO wishlistDO, Map groupNames) { - WishlistDTO wishlistDTO = new WishlistDTO(); - BeanUtils.copyProperties(wishlistDO, wishlistDTO); - wishlistDTO.setGroupName(groupNames.get(wishlistDO.getGroupId())); - ProductVO productVO = productService.getProductById(wishlistDO.getProductId()); - wishlistDTO.setProduct(productVO); - return wishlistDTO; - } - - private WishlistGroupVO toGroupVO(WishlistGroupDO groupDO) { - WishlistGroupVO groupVO = new WishlistGroupVO(); - groupVO.setId(groupDO.getId()); - groupVO.setName(groupDO.getName()); - groupVO.setSortOrder(normalizeSortOrder(groupDO.getSortOrder())); - groupVO.setItemCount(0); - groupVO.setItems(new ArrayList<>()); - return groupVO; - } - - private WishlistDO findTargetWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { - if (wishlistMoveDTO == null) { - return null; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getIsDelete, 0); - if (wishlistMoveDTO.getWishlistId() != null) { - wrapper.eq(WishlistDO::getId, wishlistMoveDTO.getWishlistId()); - } else if (wishlistMoveDTO.getProductId() != null) { - wrapper.eq(WishlistDO::getProductId, wishlistMoveDTO.getProductId()); - } else { - return null; - } - wrapper.last("LIMIT 1"); - return wishlistMapper.selectOne(wrapper); - } - - private WishlistDO findActiveWishlistByUserAndProduct(Long userId, Long productId) { - if (userId == null || productId == null) { - return null; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getProductId, productId); - wrapper.eq(WishlistDO::getIsDelete, 0); - wrapper.last("LIMIT 1"); - return wishlistMapper.selectOne(wrapper); - } - - private List loadActiveWishlist(Long userId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getIsDelete, 0); - wrapper.orderByAsc(WishlistDO::getSortOrder); - wrapper.orderByDesc(WishlistDO::getCreateTime); - return wishlistMapper.selectList(wrapper); - } - - private List ensurePresetGroups(Long userId) { - List groups = loadActiveGroups(userId); - Map groupByName = groups.stream() - .collect(Collectors.toMap(WishlistGroupDO::getName, group -> group, (left, right) -> left)); - for (int index = 0; index < PRESET_GROUP_NAMES.size(); index++) { - String name = PRESET_GROUP_NAMES.get(index); - if (!groupByName.containsKey(name)) { - WishlistGroupDO group = new WishlistGroupDO(); - group.setUserId(userId); - group.setName(name); - group.setSortOrder((index + 1) * 10); - group.setIsDelete(0); - wishlistGroupMapper.insert(group); - groups.add(group); - groupByName.put(name, group); - } - } - return groups.stream() - .sorted(Comparator - .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) - .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) - .collect(Collectors.toList()); - } - - private WishlistGroupDO resolveDefaultGroup(Long userId) { - return ensurePresetGroups(userId).stream() - .filter(group -> PRESET_GROUP_NAMES.get(0).equals(group.getName())) - .findFirst() - .orElseThrow(() -> new RuntimeException("\u9ed8\u8ba4\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728")); - } - - private WishlistGroupDO resolveTargetGroup(Long userId, Long groupId) { - if (groupId == null) { - return resolveDefaultGroup(userId); - } - WishlistGroupDO group = findOwnedGroup(userId, groupId); - if (group == null) { - throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728"); - } - return group; - } - - private WishlistGroupDO findOwnedGroup(Long userId, Long groupId) { - if (userId == null || groupId == null) { - return null; - } - WishlistGroupDO group = wishlistGroupMapper.selectById(groupId); - if (group == null || Integer.valueOf(1).equals(group.getIsDelete()) || !userId.equals(group.getUserId())) { - return null; - } - return group; - } - - private List loadActiveGroups(Long userId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistGroupDO::getUserId, userId); - wrapper.eq(WishlistGroupDO::getIsDelete, 0); - return wishlistGroupMapper.selectList(wrapper).stream() - .sorted(Comparator - .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) - .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) - .collect(Collectors.toList()); - } - - private ProductDO getValidProduct(Long productId) { - if (productId == null) { - return null; - } - - ProductDO product = productMapper.selectById(productId); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - return null; - } - - return product; - } - - private String normalizeGroupName(String name) { - if (!StringUtils.hasText(name)) { - throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a"); - } - return name.trim(); - } - - private String normalizeNote(String note) { - if (!StringUtils.hasText(note)) { - return null; - } - String trimmedNote = note.trim(); - return trimmedNote.length() > NOTE_MAX_LENGTH ? trimmedNote.substring(0, NOTE_MAX_LENGTH) : trimmedNote; - } - - private Integer normalizeSortOrder(Integer sortOrder) { - return sortOrder == null ? DEFAULT_SORT_ORDER : sortOrder; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/CampaignVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/CampaignVO.java deleted file mode 100644 index 0f7a3063..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/CampaignVO.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -public class CampaignVO { - private Long id; - private Long shopId; - private String title; - private String description; - private String scene; - private String productIds; - private String couponIds; - private Integer status; - private LocalDateTime startTime; - private LocalDateTime endTime; - private Integer sortOrder; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/CouponVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/CouponVO.java deleted file mode 100644 index fbdf1341..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/CouponVO.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; -/** - * 优惠券VO - */ -@Data -public class CouponVO { - - /** - * 优惠券ID - */ - private Long id; - - /** - * 优惠券编码 - */ - private String couponCode; - - /** - * 优惠券名称 - */ - private String couponName; - - /** - * 优惠券类型:1-折扣券,2-满减券 - */ - private Integer couponType; - - /** - * 优惠券类型名称 - */ - private String couponTypeName; - - /** - * 折扣值(如9.5表示95折) - */ - private BigDecimal discountValue; - - /** - * 满减券最低消费金额 - */ - private BigDecimal minAmount; - - /** - * 满减券减免金额 - */ - private BigDecimal reduceAmount; - - /** - * 优惠券总数量 - */ - private Integer totalCount; - - /** - * 已使用数量 - */ - private Integer usedCount; - - /** - * 剩余数量 - */ - private Integer remainingCount; - - /** - * 开始时间 - */ - private LocalDateTime startTime; - - /** - * 结束时间 - */ - private LocalDateTime endTime; - - /** - * 状态:1-可用,2-已过期,3-已用完 - */ - private Integer status; - - /** - * 状态名称 - */ - private String statusName; - - /** - * 所属店铺ID - */ - private Long shopId; - - /** - * 所属店铺名称 - */ - private String shopName; - /** - * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponScene; - /** - * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String requiredVipLevel; - /** - * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer autoMatch; - - /** - * 可用标签列表 - */ - private List availableTags; - - /** - * 不可用标签列表 - */ - private List unavailableTags; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/GrowthSummaryVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/GrowthSummaryVO.java deleted file mode 100644 index 058a1226..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/GrowthSummaryVO.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -@Data -public class GrowthSummaryVO { - private Long userId; - private Integer growthValue; - private String levelName; - private Integer appointmentCount; - private Integer reviewCount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/UserCouponVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/UserCouponVO.java deleted file mode 100644 index a53a2046..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/UserCouponVO.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 用户优惠券VO - */ -@Data -public class UserCouponVO { - - /** - * 关联ID - */ - private Long id; - - /** - * 优惠券ID - */ - private Long couponId; - - /** - * 优惠券名称 - */ - private String couponName; - - /** - * 优惠券类型:1-折扣券,2-满减券 - */ - private Integer couponType; - - /** - * 优惠券类型名称 - */ - private String couponTypeName; - - /** - * 折扣值(如9.5表示95折) - */ - private String discountValue; - - /** - * 满减券最低消费金额 - */ - private String minAmount; - - /** - * 满减券减免金额 - */ - private String reduceAmount; - - /** - * 开始时间 - */ - private LocalDateTime startTime; - - /** - * 结束时间 - */ - private LocalDateTime endTime; - - /** - * 状态:1-未使用,2-已使用,3-已过期 - */ - private Integer status; - - /** - * 状态名称 - */ - private String statusName; - - /** - * 获取时间 - */ - private LocalDateTime obtainTime; - - /** - * 使用时间 - */ - private LocalDateTime useTime; - /** - * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceType; - /** - * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String requiredVipLevel; - /** - * Field `autoMatched` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean autoMatched; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipBenefitVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipBenefitVO.java deleted file mode 100644 index b12efbd6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipBenefitVO.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * VIP权益信息表 VO - * 用于前端展示VIP权益信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class VipBenefitVO { - - /** - * VIP权益唯一主键ID(雪花ID) - */ - private Long id; - - /** - * 权益详情(如折扣、专属服务) - */ - private String benefitInfo; - - /** - * 所需VIP等级 - */ - private String requiredVipLevel; - /** - * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer levelRank; - /** - * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal rechargeThreshold; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipInfoVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipInfoVO.java deleted file mode 100644 index 51c7e9c1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipInfoVO.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 用户VIP信息表 VO - * 用于前端展示VIP信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class VipInfoVO { - - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - /** - * VIP信息唯一主键ID(雪花ID) - */ - private Long id; - - /** - * VIP等级(如青铜、白银) - */ - private String vipLevel; - - /** - * VIP开通时间 - */ - private LocalDateTime startTime; - - /** - * VIP到期时间 - */ - private LocalDateTime expireTime; - - /** - * VIP开通方式(如购买、赠送) - */ - private String activationMethod; - - /** - * 关联VIP权益信息表主键 - */ - private Long benefitId; - - /** - * 权益详情 - */ - private String benefitInfo; - /** - * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer manualOverride; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipRechargePlanVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipRechargePlanVO.java deleted file mode 100644 index 831ed80b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/VipRechargePlanVO.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -/** - * VipRechargePlanVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class VipRechargePlanVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - /** - * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal rechargeAmount; - /** - * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal giftAmount; - /** - * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String vipLevel; - /** - * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String description; - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/WishlistGroupVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/WishlistGroupVO.java deleted file mode 100644 index f2b23430..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/WishlistGroupVO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import com.xiaowang.jacyucloudsalon.core.modules.marketing.dto.WishlistDTO; -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -@Data -public class WishlistGroupVO { - private Long id; - private String name; - private Integer sortOrder; - private Integer itemCount; - private List items = new ArrayList<>(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/WishlistInspirationVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/WishlistInspirationVO.java deleted file mode 100644 index 03303ae8..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/marketing/vo/WishlistInspirationVO.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.marketing.vo; - -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -@Data -public class WishlistInspirationVO { - private Integer total; - private List groups = new ArrayList<>(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/controller/front/AnnouncementController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/controller/front/AnnouncementController.java deleted file mode 100644 index 6e42f6dc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/controller/front/AnnouncementController.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.message.dto.AnnouncementCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.service.AnnouncementService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.AnnouncementVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageTargetOptionsVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/announcement", "/api/announcement", "/admin/announcement"}) -/** - * AnnouncementController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class AnnouncementController { - /** - * Variable `announcementService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AnnouncementService announcementService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @PostMapping("/admin/create") - @RequirePermission("announcement:create") - @OperationGuard(action = "announcement-create", ttlSeconds = 8, message = "公告发布处理中,请勿重复提交") - // 后台发布公告时,targetType 决定“全平台 / 指定店铺 / 指定用户”的范围。 - // 前端只需要按 target-options 返回值组装表单即可。 - /** - * Run business method `publish`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result publish(HttpServletRequest request, @Valid @RequestBody AnnouncementCreateDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(announcementService.publishAnnouncement(currentUser, dto)); - } - - @GetMapping("/admin/list") - @RequirePermission("announcement:view") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listAdmin(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(announcementService.listAdminAnnouncements(currentUser)); - } - - @GetMapping("/admin/{id}") - @RequirePermission("announcement:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getAdmin(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(announcementService.getAdminAnnouncement(currentUser, id)); - } - - @PutMapping("/admin/{id}/revoke") - @RequirePermission("announcement:delete") - @OperationGuard(action = "announcement-revoke", ttlSeconds = 8, message = "公告撤回处理中,请勿重复操作") - /** - * Run business method `revoke`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result revoke(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(announcementService.revokeAnnouncement(currentUser, id)); - } - - @GetMapping("/admin/target-options") - @RequirePermission("announcement:create") - /** - * Run business method `targetOptions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result targetOptions(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(announcementService.listTargetOptions(currentUser)); - } - - @GetMapping("/my/list") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listMy(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(announcementService.listMyAnnouncements(userId)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/controller/front/SystemMessageController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/controller/front/SystemMessageController.java deleted file mode 100644 index a56faa26..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/controller/front/SystemMessageController.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.message.dto.SystemMessageCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.service.SystemMessageService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageTargetOptionsVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageUnreadCountVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.SystemMessageVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/system-message", "/api/system-message", "/admin/system-message"}) -/** - * SystemMessageController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class SystemMessageController { - /** - * Variable `systemMessageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final SystemMessageService systemMessageService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @PostMapping("/admin/create") - @RequirePermission("message:create") - @OperationGuard(action = "system-message-create", ttlSeconds = 8, message = "消息发布处理中,请勿重复提交") - /** - * Run business method `publish`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result publish(HttpServletRequest request, @Valid @RequestBody SystemMessageCreateDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(systemMessageService.publishMessage(currentUser, dto)); - } - - @GetMapping("/admin/list") - @RequirePermission("message:view") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listAdminMessages(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(systemMessageService.listAdminMessages(currentUser)); - } - - @GetMapping("/admin/{id}") - @RequirePermission("message:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getAdminMessage(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(systemMessageService.getAdminMessage(currentUser, id)); - } - - @PutMapping("/admin/{id}/revoke") - @RequirePermission("message:delete") - @OperationGuard(action = "system-message-revoke", ttlSeconds = 8, message = "消息撤回处理中,请勿重复操作") - /** - * Run business method `revoke`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result revoke(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(systemMessageService.revokeMessage(currentUser, id)); - } - - @GetMapping("/admin/target-options") - @RequirePermission("message:create") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result listTargetOptions(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(systemMessageService.listTargetOptions(currentUser)); - } - - @GetMapping("/my/list") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listMyMessages(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(systemMessageService.listMyMessages(userId)); - } - - @GetMapping("/my/popup") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listMyPopupMessages(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(systemMessageService.listMyPopupMessages(userId)); - } - - @GetMapping("/my/unread-count") - /** - * Run business method `countMyUnreadMessages`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result countMyUnreadMessages(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(new MessageUnreadCountVO(systemMessageService.countMyUnreadMessages(userId))); - } - - @GetMapping("/my/{id}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getMyMessage(HttpServletRequest request, @PathVariable Long id) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(systemMessageService.getMyMessage(userId, id)); - } - - @PutMapping("/my/{id}/popup-shown") - /** - * Mark user state such as read or popup shown. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result markPopupShown(HttpServletRequest request, @PathVariable Long id) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(systemMessageService.markPopupShown(userId, id)); - } - - @PutMapping("/my/{id}/read") - /** - * Mark user state such as read or popup shown. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result markRead(HttpServletRequest request, @PathVariable Long id) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(systemMessageService.markRead(userId, id)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/dto/AnnouncementCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/dto/AnnouncementCreateDTO.java deleted file mode 100644 index 75339fda..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/dto/AnnouncementCreateDTO.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; -import java.util.List; - -@Data -/** - * AnnouncementCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class AnnouncementCreateDTO { - - @NotBlank(message = "公告标题不能为空") - @Size(max = 100, message = "公告标题不能超过100个字符") - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - - @NotBlank(message = "公告内容不能为空") - @Size(max = 1000, message = "公告内容不能超过1000个字符") - /** - * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String content; - - @NotBlank(message = "公告范围不能为空") - /** - * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetType; - - /** - * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shopIds; - - /** - * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List userIds; - - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder = 0; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/dto/SystemMessageCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/dto/SystemMessageCreateDTO.java deleted file mode 100644 index 1857907c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/dto/SystemMessageCreateDTO.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.dto; - -import lombok.Data; - -import javax.validation.constraints.Size; -import java.util.List; - -@Data -/** - * SystemMessageCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class SystemMessageCreateDTO { - - @Size(max = 100, message = "消息标题不能超过100个字符") - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - - @Size(max = 2000, message = "消息内容不能超过2000个字符") - /** - * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String content; - - /** - * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetType; - - /** - * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long imageFileId; - - /** - * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shopIds; - - /** - * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List userIds; - - /** - * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer popupEnabled = 1; - - /** - * Purpose: businessType supports SystemMessageCreateDTO.java by holding or executing the business type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String businessType; - - /** - * Purpose: businessId supports SystemMessageCreateDTO.java by holding or executing the business id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long businessId; - - /** - * Purpose: actionPath supports SystemMessageCreateDTO.java by holding or executing the action path business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String actionPath; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/AnnouncementDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/AnnouncementDO.java deleted file mode 100644 index 51ce334c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/AnnouncementDO.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_announcement") -/** - * AnnouncementDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class AnnouncementDO extends BaseEntity { - - @TableField("title") - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - - @TableField("content") - /** - * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String content; - - @TableField("publisher_id") - /** - * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long publisherId; - - @TableField("publisher_name") - /** - * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String publisherName; - - @TableField("publisher_type") - /** - * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer publisherType; - - @TableField("target_type") - /** - * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetType; - - @TableField("target_ids") - /** - * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetIds; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - @TableField("sort_order") - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - - @TableField("publish_time") - /** - * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime publishTime; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/SystemMessageDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/SystemMessageDO.java deleted file mode 100644 index bac56eaf..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/SystemMessageDO.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Getter -@Setter -@TableName("t_system_message") -/** - * SystemMessageDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class SystemMessageDO extends BaseEntity { - - @TableField("title") - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - - @TableField("content") - /** - * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String content; - - @TableField("image_file_id") - /** - * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long imageFileId; - - @TableField("publisher_id") - /** - * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long publisherId; - - @TableField("publisher_name") - /** - * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String publisherName; - - @TableField("publisher_type") - /** - * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer publisherType; - - @TableField("target_type") - /** - * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetType; - - @TableField("target_ids") - /** - * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetIds; - - @TableField("business_type") - /** - * Purpose: businessType supports SystemMessageDO.java by holding or executing the business type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String businessType; - - @TableField("business_id") - /** - * Purpose: businessId supports SystemMessageDO.java by holding or executing the business id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long businessId; - - @TableField("action_path") - /** - * Purpose: actionPath supports SystemMessageDO.java by holding or executing the action path business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String actionPath; - - @TableField("idempotency_key") - /** - * Purpose: idempotencyKey supports SystemMessageDO.java by holding or executing the idempotency key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String idempotencyKey; - - @TableField("popup_enabled") - /** - * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer popupEnabled; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - @TableField("publish_time") - /** - * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime publishTime; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/SystemMessageUserStateDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/SystemMessageUserStateDO.java deleted file mode 100644 index af8b9193..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/entity/SystemMessageUserStateDO.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Getter -@Setter -@TableName("t_system_message_user_state") -/** - * SystemMessageUserStateDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class SystemMessageUserStateDO extends BaseEntity { - - @TableField("message_id") - /** - * Field `messageId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long messageId; - - @TableField("user_id") - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - @TableField("popup_shown") - /** - * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer popupShown; - - @TableField("read_status") - /** - * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer readStatus; - - @TableField("popup_time") - /** - * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime popupTime; - - @TableField("read_time") - /** - * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime readTime; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/AnnouncementMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/AnnouncementMapper.java deleted file mode 100644 index 336d4149..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/AnnouncementMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.AnnouncementDO; - -/** - * AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface AnnouncementMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/SystemMessageMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/SystemMessageMapper.java deleted file mode 100644 index 8b5b8bba..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/SystemMessageMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * SystemMessageMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface SystemMessageMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/SystemMessageUserStateMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/SystemMessageUserStateMapper.java deleted file mode 100644 index 8665e934..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/mapper/SystemMessageUserStateMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageUserStateDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * SystemMessageUserStateMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface SystemMessageUserStateMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/AnnouncementService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/AnnouncementService.java deleted file mode 100644 index 0194800d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/AnnouncementService.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.message.dto.AnnouncementCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.AnnouncementDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.AnnouncementVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageTargetOptionsVO; - -import java.util.List; - -/** - * AnnouncementService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface AnnouncementService extends IService { - /** - * Run business method `publishAnnouncement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listAdminAnnouncements(UserDO currentUser); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return AnnouncementVO result consumed by the caller or returned to the frontend - */ - AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id); - /** - * Run business method `revokeAnnouncement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean revokeAnnouncement(UserDO currentUser, Long id); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend - */ - MessageTargetOptionsVO listTargetOptions(UserDO currentUser); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listMyAnnouncements(Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/SystemMessageService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/SystemMessageService.java deleted file mode 100644 index 91598b21..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/SystemMessageService.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.message.dto.SystemMessageCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageTargetOptionsVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.SystemMessageVO; - -import java.util.List; - -/** - * SystemMessageService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface SystemMessageService extends IService { - - /** - * Run business method `publishMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listAdminMessages(UserDO currentUser); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return SystemMessageVO result consumed by the caller or returned to the frontend - */ - SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId); - - /** - * Run business method `revokeMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean revokeMessage(UserDO currentUser, Long messageId); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend - */ - MessageTargetOptionsVO listTargetOptions(UserDO currentUser); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listMyMessages(Long userId); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listMyPopupMessages(Long userId); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return SystemMessageVO result consumed by the caller or returned to the frontend - */ - SystemMessageVO getMyMessage(Long userId, Long messageId); - - /** - * Run business method `countMyUnreadMessages`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long countMyUnreadMessages(Long userId); - - /** - * Mark user state such as read or popup shown. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean markPopupShown(Long userId, Long messageId); - - /** - * Mark user state such as read or popup shown. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean markRead(Long userId, Long messageId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/impl/AnnouncementServiceImpl.java deleted file mode 100644 index 67851285..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/impl/AnnouncementServiceImpl.java +++ /dev/null @@ -1,503 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.message.dto.AnnouncementCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.AnnouncementDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.mapper.AnnouncementMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.service.AnnouncementService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.AnnouncementVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageTargetOptionsVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * AnnouncementServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class AnnouncementServiceImpl extends ServiceImpl implements AnnouncementService { - - /** - * Purpose: TARGET_PLATFORM_ALL supports AnnouncementServiceImpl.java by holding or executing the target platform all business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; - /** - * Purpose: TARGET_CURRENT_SHOP_ALL supports AnnouncementServiceImpl.java by holding or executing the target current shop all business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; - /** - * Purpose: TARGET_SHOP_ALL supports AnnouncementServiceImpl.java by holding or executing the target shop all business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TARGET_SHOP_ALL = "SHOP_ALL"; - /** - * Purpose: TARGET_SELECTED_SHOPS supports AnnouncementServiceImpl.java by holding or executing the target selected shops business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; - /** - * Purpose: TARGET_SELECTED_USERS supports AnnouncementServiceImpl.java by holding or executing the target selected users business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; - /** - * Variable `announcementMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AnnouncementMapper announcementMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingMapper userShopBindingMapper; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `publishAnnouncement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto) { - String targetType = normalizeTargetType(dto.getTargetType()); - List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); - AnnouncementDO announcement = new AnnouncementDO(); - announcement.setTitle(dto.getTitle().trim()); - announcement.setContent(dto.getContent().trim()); - announcement.setPublisherId(currentUser.getId()); - announcement.setPublisherName(resolvePublisherName(currentUser)); - announcement.setPublisherType(currentUser.getType()); - announcement.setTargetType(targetType); - announcement.setTargetIds(joinIds(targetIds)); - announcement.setStatus(1); - announcement.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); - announcement.setPublishTime(LocalDateTime.now()); - announcement.setIsDelete(0); - announcementMapper.insert(announcement); - return announcement.getId(); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listAdminAnnouncements(UserDO currentUser) { - return announcementMapper.selectList(new LambdaQueryWrapper() - .eq(AnnouncementDO::getIsDelete, 0) - .orderByDesc(AnnouncementDO::getPublishTime)) - .stream() - .filter(item -> canAdminSee(currentUser, item)) - .map(this::toVO) - .collect(Collectors.toList()); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return AnnouncementVO result consumed by the caller or returned to the frontend - */ - public AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id) { - AnnouncementDO announcement = requireAnnouncement(id); - if (!canAdminSee(currentUser, announcement)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权查看该公告"); - } - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param announcement parameter `announcement` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toVO(announcement); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `revokeAnnouncement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean revokeAnnouncement(UserDO currentUser, Long id) { - AnnouncementDO announcement = requireAnnouncement(id); - if (!canAdminSee(currentUser, announcement)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权撤回该公告"); - } - announcement.setStatus(0); - announcementMapper.updateById(announcement); - return true; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend - */ - public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { - MessageTargetOptionsVO options = new MessageTargetOptionsVO(); - List shops = adminScopeHelper.isPlatformAdmin(currentUser) - ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) - : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); - Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); - List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); - List users = shopIds.isEmpty() - ? List.of() - : userMapper.selectList(new LambdaQueryWrapper() - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getStatus, 1) - .in(UserDO::getShopId, shopIds) - .orderByAsc(UserDO::getType) - .orderByAsc(UserDO::getNickname)); - options.setShops(shops.stream().map(shop -> { - MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); - vo.setId(shop.getId()); - vo.setShopName(shop.getShopName()); - return vo; - }).collect(Collectors.toList())); - options.setUsers(users.stream().map(user -> { - MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); - vo.setId(user.getId()); - vo.setNickname(user.getNickname()); - vo.setAccount(user.getAccount()); - vo.setShopId(user.getShopId()); - vo.setShopName(shopNameMap.get(user.getShopId())); - vo.setType(user.getType()); - return vo; - }).collect(Collectors.toList())); - return options; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listMyAnnouncements(Long userId) { - UserDO user = requireUser(userId); - return announcementMapper.selectList(new LambdaQueryWrapper() - .eq(AnnouncementDO::getIsDelete, 0) - .eq(AnnouncementDO::getStatus, 1) - .orderByDesc(AnnouncementDO::getSortOrder) - .orderByDesc(AnnouncementDO::getPublishTime)) - .stream() - .filter(item -> isVisibleToUser(item, user)) - .map(this::toVO) - .collect(Collectors.toList()); - } - - /** - * Run business method `resolveAndValidateTargets`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param targetType parameter `targetType` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List resolveAndValidateTargets(UserDO currentUser, String targetType, AnnouncementCreateDTO dto) { - if (adminScopeHelper.isPlatformAdmin(currentUser)) { - if (TARGET_PLATFORM_ALL.equals(targetType)) return List.of(); - if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { - List shopIds = normalizeIds(dto.getShopIds()); - if (shopIds.isEmpty()) throw new RuntimeException("请选择公告店铺"); - /** - * Run business method `assertShopsExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertShopsExist(shopIds); - return shopIds; - } - if (TARGET_SELECTED_USERS.equals(targetType)) { - List userIds = normalizeIds(dto.getUserIds()); - if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); - /** - * Run business method `assertUsersExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userIds parameter `userIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUsersExist(userIds); - return userIds; - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("公告范围不正确"); - } - if (!Integer.valueOf(2).equals(currentUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只有管理员或店长可以发布公告"); - } - Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); - if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { - return List.of(managedShopId); - } - if (TARGET_SELECTED_USERS.equals(targetType)) { - List userIds = normalizeIds(dto.getUserIds()); - if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); - userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); - return userIds; - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("店长只能发布本店公告或本店指定用户公告"); - } - - /** - * Run business method `isVisibleToUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param item parameter `item` supplied by the caller - * @param user parameter `user` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isVisibleToUser(AnnouncementDO item, UserDO user) { - String targetType = item.getTargetType(); - Set targetIds = parseIds(item.getTargetIds()); - if (TARGET_PLATFORM_ALL.equals(targetType)) return true; - if (TARGET_SELECTED_USERS.equals(targetType)) return targetIds.contains(user.getId()); - if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { - return getUserShopIds(user).stream().anyMatch(targetIds::contains); - } - return false; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set getUserShopIds(UserDO user) { - LinkedHashSet ids = new LinkedHashSet<>(); - if (user.getShopId() != null && user.getShopId() > 0) ids.add(user.getShopId()); - userShopBindingMapper.selectList(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, user.getId()) - .eq(UserShopBindingDO::getIsDelete, 0) - .eq(UserShopBindingDO::getStatus, 1)) - .forEach(binding -> { - if (binding.getShopId() != null && binding.getShopId() > 0) ids.add(binding.getShopId()); - }); - return ids; - } - - /** - * Run business method `canAdminSee`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param item parameter `item` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean canAdminSee(UserDO currentUser, AnnouncementDO item) { - if (adminScopeHelper.isPlatformAdmin(currentUser)) return true; - Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); - if (TARGET_CURRENT_SHOP_ALL.equals(item.getTargetType()) || TARGET_SHOP_ALL.equals(item.getTargetType()) || TARGET_SELECTED_SHOPS.equals(item.getTargetType())) { - return parseIds(item.getTargetIds()).contains(managedShopId); - } - return Objects.equals(item.getPublisherId(), currentUser.getId()); - } - - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param item parameter `item` supplied by the caller - * @return private AnnouncementVO result consumed by the caller or returned to the frontend - */ - private AnnouncementVO toVO(AnnouncementDO item) { - AnnouncementVO vo = new AnnouncementVO(); - vo.setId(item.getId()); - vo.setTitle(item.getTitle()); - vo.setContent(item.getContent()); - vo.setPublisherId(item.getPublisherId()); - vo.setPublisherName(item.getPublisherName()); - vo.setPublisherType(item.getPublisherType()); - vo.setTargetType(item.getTargetType()); - vo.setTargetTypeName(targetTypeName(item.getTargetType())); - vo.setTargetIds(new ArrayList<>(parseIds(item.getTargetIds()))); - vo.setStatus(item.getStatus()); - vo.setSortOrder(item.getSortOrder()); - vo.setPublishTime(item.getPublishTime()); - vo.setCreateTime(item.getCreateTime()); - return vo; - } - - /** - * Run business method `requireAnnouncement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private AnnouncementDO result consumed by the caller or returned to the frontend - */ - private AnnouncementDO requireAnnouncement(Long id) { - AnnouncementDO item = announcementMapper.selectById(id); - if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) throw new RuntimeException("公告不存在"); - return item; - } - - /** - * Run business method `requireUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO requireUser(Long userId) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new RuntimeException("用户不存在"); - return user; - } - - /** - * Run business method `assertShopsExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertShopsExist(List shopIds) { - Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); - if (count == null || count < shopIds.size()) throw new RuntimeException("存在无效店铺"); - } - - /** - * Run business method `assertUsersExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userIds parameter `userIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertUsersExist(List userIds) { - Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); - if (count == null || count < userIds.size()) throw new RuntimeException("存在无效用户"); - } - - /** - * Run business method `normalizeTargetType`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeTargetType(String targetType) { - if (!StringUtils.hasText(targetType)) throw new RuntimeException("公告范围不能为空"); - return targetType.trim().toUpperCase(); - } - - /** - * Run business method `normalizeIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List normalizeIds(List ids) { - if (CollectionUtils.isEmpty(ids)) return List.of(); - return ids.stream().filter(Objects::nonNull).filter(id -> id > 0).distinct().collect(Collectors.toList()); - } - - /** - * Run business method `parseIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set parseIds(String ids) { - if (!StringUtils.hasText(ids)) return Set.of(); - return java.util.Arrays.stream(ids.split(",")).map(String::trim).filter(StringUtils::hasText).map(Long::valueOf).collect(Collectors.toCollection(LinkedHashSet::new)); - } - - /** - * Run business method `joinIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String joinIds(List ids) { - return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); - } - - /** - * Run business method `targetTypeName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String targetTypeName(String targetType) { - return switch (targetType) { - case TARGET_PLATFORM_ALL -> "全平台"; - case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; - case TARGET_SELECTED_SHOPS -> "多个店铺"; - case TARGET_SELECTED_USERS -> "指定用户"; - default -> targetType; - }; - } - - /** - * Run business method `resolvePublisherName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolvePublisherName(UserDO currentUser) { - return StringUtils.hasText(currentUser.getNickname()) ? currentUser.getNickname() : currentUser.getAccount(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/impl/SystemMessageServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/impl/SystemMessageServiceImpl.java deleted file mode 100644 index 7bb257d0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/service/impl/SystemMessageServiceImpl.java +++ /dev/null @@ -1,886 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.message.dto.SystemMessageCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageUserStateDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.mapper.SystemMessageMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.mapper.SystemMessageUserStateMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.message.service.SystemMessageService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.MessageTargetOptionsVO; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import com.xiaowang.jacyucloudsalon.core.modules.message.vo.SystemMessageVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * SystemMessageServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class SystemMessageServiceImpl extends ServiceImpl implements SystemMessageService { - - /** - * Purpose: TARGET_PLATFORM_ALL supports SystemMessageServiceImpl.java by holding or executing the target platform all business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; - /** - * Purpose: TARGET_CURRENT_SHOP_ALL supports SystemMessageServiceImpl.java by holding or executing the target current shop all business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; - /** - * Purpose: TARGET_SHOP_ALL supports SystemMessageServiceImpl.java by holding or executing the target shop all business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String TARGET_SHOP_ALL = "SHOP_ALL"; - /** - * Purpose: TARGET_SELECTED_SHOPS supports SystemMessageServiceImpl.java by holding or executing the target selected shops business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; - /** - * Purpose: TARGET_SELECTED_USERS supports SystemMessageServiceImpl.java by holding or executing the target selected users business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; - /** - * Variable `systemMessageMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final SystemMessageMapper systemMessageMapper; - /** - * Variable `stateMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final SystemMessageUserStateMapper stateMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingMapper userShopBindingMapper; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - /** - * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageFileService objectStorageFileService; - /** - * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageUrlSupport objectStorageUrlSupport; - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `publishMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto) { - String targetType = normalizeTargetType(dto.getTargetType()); - List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); - String title = dto.getTitle() == null ? "" : dto.getTitle().trim(); - String content = dto.getContent() == null ? "" : dto.getContent().trim(); - if (!StringUtils.hasText(title)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("消息标题不能为空"); - } - if (!StringUtils.hasText(content) && dto.getImageFileId() == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请填写消息内容或上传消息图片"); - } - if (dto.getImageFileId() != null) { - ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(dto.getImageFileId()); - if (imageFile == null || !Integer.valueOf(1).equals(imageFile.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("消息图片不存在或不可用"); - } - } - - SystemMessageDO message = new SystemMessageDO(); - message.setTitle(title); - message.setContent(content); - message.setImageFileId(dto.getImageFileId()); - message.setPublisherId(currentUser.getId()); - message.setPublisherName(resolvePublisherName(currentUser)); - message.setPublisherType(currentUser.getType()); - message.setTargetType(targetType); - message.setTargetIds(joinIds(targetIds)); - message.setBusinessType(trimToNull(dto.getBusinessType())); - message.setBusinessId(dto.getBusinessId()); - message.setActionPath(trimToNull(dto.getActionPath())); - message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1); - message.setStatus(1); - message.setPublishTime(LocalDateTime.now()); - message.setIsDelete(0); - systemMessageMapper.insert(message); - return message.getId(); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listAdminMessages(UserDO currentUser) { - List messages = systemMessageMapper.selectList(new LambdaQueryWrapper() - .eq(SystemMessageDO::getIsDelete, 0) - .orderByDesc(SystemMessageDO::getPublishTime)); - return messages.stream() - .filter(message -> canAdminSeeMessage(currentUser, message)) - .map(message -> toVO(message, null)) - .collect(Collectors.toList()); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return SystemMessageVO result consumed by the caller or returned to the frontend - */ - public SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId) { - SystemMessageDO message = requireMessage(messageId); - if (!canAdminSeeMessage(currentUser, message)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权查看该消息"); - } - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param message parameter `message` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toVO(message, null); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `revokeMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean revokeMessage(UserDO currentUser, Long messageId) { - SystemMessageDO message = requireMessage(messageId); - if (!canAdminSeeMessage(currentUser, message)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权撤回该消息"); - } - message.setStatus(0); - systemMessageMapper.updateById(message); - return true; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend - */ - public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { - MessageTargetOptionsVO options = new MessageTargetOptionsVO(); - List shops = adminScopeHelper.isPlatformAdmin(currentUser) - ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) - : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); - Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); - - List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); - List users = shopIds.isEmpty() - ? List.of() - : userMapper.selectList(new LambdaQueryWrapper() - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getStatus, 1) - .in(UserDO::getShopId, shopIds) - .orderByAsc(UserDO::getType) - .orderByAsc(UserDO::getNickname)); - - options.setShops(shops.stream().map(shop -> { - MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); - vo.setId(shop.getId()); - vo.setShopName(shop.getShopName()); - return vo; - }).collect(Collectors.toList())); - options.setUsers(users.stream().map(user -> { - MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); - vo.setId(user.getId()); - vo.setNickname(user.getNickname()); - vo.setAccount(user.getAccount()); - vo.setShopId(user.getShopId()); - vo.setShopName(shopNameMap.get(user.getShopId())); - vo.setType(user.getType()); - return vo; - }).collect(Collectors.toList())); - return options; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listMyMessages(Long userId) { - UserDO user = requireUser(userId); - Map stateMap = loadStateMap(userId); - return listVisibleMessages(user).stream() - .map(message -> toVO(message, stateMap.get(message.getId()))) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listMyPopupMessages(Long userId) { - UserDO user = requireUser(userId); - Map stateMap = loadStateMap(userId); - return listVisibleMessages(user).stream() - .filter(message -> Integer.valueOf(1).equals(message.getPopupEnabled())) - .filter(message -> { - SystemMessageUserStateDO state = stateMap.get(message.getId()); - return state == null || !Integer.valueOf(1).equals(state.getPopupShown()); - }) - .map(message -> toVO(message, stateMap.get(message.getId()))) - .collect(Collectors.toList()); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return SystemMessageVO result consumed by the caller or returned to the frontend - */ - public SystemMessageVO getMyMessage(Long userId, Long messageId) { - UserDO user = requireUser(userId); - SystemMessageDO message = requireMessage(messageId); - if (!isMessageVisibleToUser(message, user)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("消息不存在或无权查看"); - } - SystemMessageUserStateDO state = findState(userId, messageId); - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param message parameter `message` supplied by the caller - * @param state parameter `state` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toVO(message, state); - } - - @Override - /** - * Run business method `countMyUnreadMessages`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long countMyUnreadMessages(Long userId) { - UserDO user = requireUser(userId); - Map stateMap = loadStateMap(userId); - return listVisibleMessages(user).stream() - .filter(message -> { - SystemMessageUserStateDO state = stateMap.get(message.getId()); - return state == null || !Integer.valueOf(1).equals(state.getReadStatus()); - }) - .count(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Mark user state such as read or popup shown. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean markPopupShown(Long userId, Long messageId) { - UserDO user = requireUser(userId); - SystemMessageDO message = requireMessage(messageId); - if (!isMessageVisibleToUser(message, user)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("消息不存在或无权查看"); - } - SystemMessageUserStateDO state = getOrCreateState(userId, messageId); - if (!Integer.valueOf(1).equals(state.getPopupShown())) { - state.setPopupShown(1); - state.setPopupTime(LocalDateTime.now()); - stateMapper.updateById(state); - } - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Mark user state such as read or popup shown. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean markRead(Long userId, Long messageId) { - UserDO user = requireUser(userId); - SystemMessageDO message = requireMessage(messageId); - if (!isMessageVisibleToUser(message, user)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("消息不存在或无权查看"); - } - SystemMessageUserStateDO state = getOrCreateState(userId, messageId); - if (!Integer.valueOf(1).equals(state.getReadStatus())) { - state.setReadStatus(1); - state.setReadTime(LocalDateTime.now()); - stateMapper.updateById(state); - } - return true; - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List listVisibleMessages(UserDO user) { - return systemMessageMapper.selectList(new LambdaQueryWrapper() - .eq(SystemMessageDO::getIsDelete, 0) - .eq(SystemMessageDO::getStatus, 1) - .orderByDesc(SystemMessageDO::getPublishTime)) - .stream() - .filter(message -> isMessageVisibleToUser(message, user)) - .collect(Collectors.toList()); - } - - /** - * Run business method `isMessageVisibleToUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param message parameter `message` supplied by the caller - * @param user parameter `user` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isMessageVisibleToUser(SystemMessageDO message, UserDO user) { - String targetType = message.getTargetType(); - Set targetIds = parseIds(message.getTargetIds()); - if (TARGET_PLATFORM_ALL.equals(targetType)) { - return true; - } - if (TARGET_SELECTED_USERS.equals(targetType)) { - return targetIds.contains(user.getId()); - } - Set userShopIds = getUserShopIds(user); - if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { - return userShopIds.stream().anyMatch(targetIds::contains); - } - return false; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set getUserShopIds(UserDO user) { - LinkedHashSet ids = new LinkedHashSet<>(); - if (user.getShopId() != null && user.getShopId() > 0) { - ids.add(user.getShopId()); - } - List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, user.getId()) - .eq(UserShopBindingDO::getIsDelete, 0) - .eq(UserShopBindingDO::getStatus, 1)); - bindings.forEach(binding -> { - if (binding.getShopId() != null && binding.getShopId() > 0) { - ids.add(binding.getShopId()); - } - }); - return ids; - } - - /** - * Run business method `resolveAndValidateTargets`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param targetType parameter `targetType` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List resolveAndValidateTargets(UserDO currentUser, String targetType, SystemMessageCreateDTO dto) { - if (adminScopeHelper.isPlatformAdmin(currentUser)) { - /** - * Run business method `resolveAdminTargets`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return resolveAdminTargets(targetType, dto); - } - if (!Integer.valueOf(2).equals(currentUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只有管理员或店长可以发布消息"); - } - Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); - if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { - return List.of(managedShopId); - } - if (TARGET_SELECTED_USERS.equals(targetType)) { - List userIds = normalizeIds(dto.getUserIds()); - if (userIds.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择接收用户"); - } - userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); - return userIds; - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("店长只能发布本店全员或本店部分用户消息"); - } - - /** - * Run business method `resolveAdminTargets`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List resolveAdminTargets(String targetType, SystemMessageCreateDTO dto) { - if (TARGET_PLATFORM_ALL.equals(targetType)) { - return List.of(); - } - if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { - List shopIds = normalizeIds(dto.getShopIds()); - if (shopIds.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择接收店铺"); - } - /** - * Run business method `assertShopsExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertShopsExist(shopIds); - return shopIds; - } - if (TARGET_SELECTED_USERS.equals(targetType)) { - List userIds = normalizeIds(dto.getUserIds()); - if (userIds.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择接收用户"); - } - /** - * Run business method `assertUsersExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userIds parameter `userIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUsersExist(userIds); - return userIds; - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("管理员消息范围不正确"); - } - - /** - * Run business method `assertShopsExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertShopsExist(List shopIds) { - Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); - if (count == null || count < shopIds.size()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("存在无效店铺"); - } - } - - /** - * Run business method `assertUsersExist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userIds parameter `userIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertUsersExist(List userIds) { - Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); - if (count == null || count < userIds.size()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("存在无效用户"); - } - } - - /** - * Run business method `canAdminSeeMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param message parameter `message` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean canAdminSeeMessage(UserDO currentUser, SystemMessageDO message) { - if (adminScopeHelper.isPlatformAdmin(currentUser)) { - return true; - } - Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); - if (TARGET_CURRENT_SHOP_ALL.equals(message.getTargetType()) || TARGET_SHOP_ALL.equals(message.getTargetType()) || TARGET_SELECTED_SHOPS.equals(message.getTargetType())) { - return parseIds(message.getTargetIds()).contains(managedShopId); - } - return Objects.equals(message.getPublisherId(), currentUser.getId()); - } - - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param message parameter `message` supplied by the caller - * @param state parameter `state` supplied by the caller - * @return private SystemMessageVO result consumed by the caller or returned to the frontend - */ - private SystemMessageVO toVO(SystemMessageDO message, SystemMessageUserStateDO state) { - SystemMessageVO vo = new SystemMessageVO(); - vo.setId(message.getId()); - vo.setTitle(message.getTitle()); - vo.setContent(message.getContent()); - vo.setImageFileId(message.getImageFileId()); - vo.setImageUrl(resolveImageUrl(message.getImageFileId())); - vo.setPublisherId(message.getPublisherId()); - vo.setPublisherName(message.getPublisherName()); - vo.setPublisherType(message.getPublisherType()); - vo.setTargetType(message.getTargetType()); - vo.setTargetTypeName(targetTypeName(message.getTargetType())); - vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds()))); - vo.setBusinessType(message.getBusinessType()); - vo.setBusinessId(message.getBusinessId()); - vo.setActionPath(message.getActionPath()); - vo.setPopupEnabled(message.getPopupEnabled()); - vo.setStatus(message.getStatus()); - vo.setPublishTime(message.getPublishTime()); - vo.setCreateTime(message.getCreateTime()); - vo.setPopupShown(state == null ? 0 : state.getPopupShown()); - vo.setReadStatus(state == null ? 0 : state.getReadStatus()); - vo.setPopupTime(state == null ? null : state.getPopupTime()); - vo.setReadTime(state == null ? null : state.getReadTime()); - return vo; - } - - /** - * Run business method `resolveImageUrl`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param imageFileId parameter `imageFileId` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveImageUrl(Long imageFileId) { - if (imageFileId == null || imageFileId <= 0) { - return null; - } - ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(imageFileId); - if (imageFile == null || !StringUtils.hasText(imageFile.getFileUrl())) { - return null; - } - return objectStorageUrlSupport.toAccessibleUrl(imageFile); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend - */ - private SystemMessageUserStateDO getOrCreateState(Long userId, Long messageId) { - SystemMessageUserStateDO state = findState(userId, messageId); - if (state != null) { - return state; - } - state = new SystemMessageUserStateDO(); - state.setMessageId(messageId); - state.setUserId(userId); - state.setPopupShown(0); - state.setReadStatus(0); - state.setIsDelete(0); - stateMapper.insert(state); - return state; - } - - /** - * Run business method `findState`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param messageId parameter `messageId` supplied by the caller - * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend - */ - private SystemMessageUserStateDO findState(Long userId, Long messageId) { - return stateMapper.selectOne(new LambdaQueryWrapper() - .eq(SystemMessageUserStateDO::getUserId, userId) - .eq(SystemMessageUserStateDO::getMessageId, messageId) - .eq(SystemMessageUserStateDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - /** - * Run business method `loadStateMap`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map loadStateMap(Long userId) { - return stateMapper.selectList(new LambdaQueryWrapper() - .eq(SystemMessageUserStateDO::getUserId, userId) - .eq(SystemMessageUserStateDO::getIsDelete, 0)) - .stream() - .collect(Collectors.toMap(SystemMessageUserStateDO::getMessageId, Function.identity(), (a, b) -> a)); - } - - /** - * Run business method `requireMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param messageId parameter `messageId` supplied by the caller - * @return private SystemMessageDO result consumed by the caller or returned to the frontend - */ - private SystemMessageDO requireMessage(Long messageId) { - SystemMessageDO message = systemMessageMapper.selectById(messageId); - if (message == null || Integer.valueOf(1).equals(message.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("消息不存在"); - } - return message; - } - - /** - * Run business method `requireUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO requireUser(Long userId) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户不存在"); - } - return user; - } - - /** - * Run business method `normalizeTargetType`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeTargetType(String targetType) { - if (!StringUtils.hasText(targetType)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("接收范围不能为空"); - } - return targetType.trim().toUpperCase(); - } - - /** - * Purpose: trimToNull supports SystemMessageServiceImpl.java by holding or executing the trim to null business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String trimToNull(String value) { - if (!StringUtils.hasText(value)) { - return null; - } - return value.trim(); - } - - /** - * Run business method `normalizeIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List normalizeIds(List ids) { - if (CollectionUtils.isEmpty(ids)) { - return List.of(); - } - return ids.stream() - .filter(Objects::nonNull) - .filter(id -> id > 0) - .distinct() - .collect(Collectors.toList()); - } - - /** - * Run business method `parseIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set parseIds(String ids) { - if (!StringUtils.hasText(ids)) { - return Set.of(); - } - return java.util.Arrays.stream(ids.split(",")) - .map(String::trim) - .filter(StringUtils::hasText) - .map(Long::valueOf) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - /** - * Run business method `joinIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param ids parameter `ids` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String joinIds(List ids) { - return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); - } - - /** - * Run business method `targetTypeName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetType parameter `targetType` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String targetTypeName(String targetType) { - return switch (targetType) { - case TARGET_PLATFORM_ALL -> "全平台"; - case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; - case TARGET_SELECTED_SHOPS -> "多个店铺"; - case TARGET_SELECTED_USERS -> "指定用户"; - default -> targetType; - }; - } - - /** - * Run business method `resolvePublisherName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolvePublisherName(UserDO currentUser) { - if (StringUtils.hasText(currentUser.getNickname())) { - return currentUser.getNickname(); - } - return currentUser.getAccount(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/AnnouncementVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/AnnouncementVO.java deleted file mode 100644 index e57f85fb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/AnnouncementVO.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.vo; - -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -@Data -/** - * AnnouncementVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class AnnouncementVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - /** - * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String content; - /** - * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long publisherId; - /** - * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String publisherName; - /** - * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer publisherType; - /** - * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetType; - /** - * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetTypeName; - /** - * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List targetIds; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - /** - * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime publishTime; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/MessageTargetOptionsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/MessageTargetOptionsVO.java deleted file mode 100644 index 1667b7d7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/MessageTargetOptionsVO.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.vo; - -import lombok.Data; - -import java.util.List; - -@Data -/** - * MessageTargetOptionsVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class MessageTargetOptionsVO { - /** - * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List shops; - /** - * Field `users` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List users; - - @Data - /** - * Purpose: ShopOptionVO supports MessageTargetOptionsVO.java by holding or executing the shop option vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class ShopOptionVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - } - - @Data - /** - * Purpose: UserOptionVO supports MessageTargetOptionsVO.java by holding or executing the user option vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class UserOptionVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String nickname; - /** - * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String account; - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - /** - * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer type; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/MessageUnreadCountVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/MessageUnreadCountVO.java deleted file mode 100644 index adbffdbb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/MessageUnreadCountVO.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.vo; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -/** - * MessageUnreadCountVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class MessageUnreadCountVO { - /** - * Field `unreadCount` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long unreadCount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/SystemMessageVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/SystemMessageVO.java deleted file mode 100644 index e8bc452a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/message/vo/SystemMessageVO.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.message.vo; - -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -@Data -/** - * SystemMessageVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class SystemMessageVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - /** - * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String content; - /** - * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long imageFileId; - /** - * Field `imageUrl` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String imageUrl; - /** - * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long publisherId; - /** - * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String publisherName; - /** - * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer publisherType; - /** - * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetType; - /** - * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String targetTypeName; - /** - * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List targetIds; - /** - * Purpose: businessType supports SystemMessageVO.java by holding or executing the business type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String businessType; - /** - * Purpose: businessId supports SystemMessageVO.java by holding or executing the business id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long businessId; - /** - * Purpose: actionPath supports SystemMessageVO.java by holding or executing the action path business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String actionPath; - /** - * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer popupEnabled; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime publishTime; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer popupShown; - /** - * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer readStatus; - /** - * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime popupTime; - /** - * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime readTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/AfterSaleController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/AfterSaleController.java deleted file mode 100644 index 6078a0db..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/AfterSaleController.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.AfterSaleApplyDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.AfterSaleService; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.AfterSaleVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/after-sale") -@RequiredArgsConstructor -public class AfterSaleController { - - private final AfterSaleService afterSaleService; - - @PostMapping("/apply") - public Result apply(HttpServletRequest request, @RequestBody AfterSaleApplyDTO dto) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(afterSaleService.apply(userId, dto)); - } - - @GetMapping("/my") - public Result> listMy(HttpServletRequest request, - @RequestParam(defaultValue = "1") Integer page, - @RequestParam(defaultValue = "10") Integer size) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(afterSaleService.listMy(userId, page, size)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/CartController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/CartController.java deleted file mode 100644 index cb889034..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/CartController.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.CartDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.CartService; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CartVO; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@RestController -@RequestMapping("/cart") -/** - * CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class CartController { - - @Resource - /** - * Purpose: cartService supports CartController.java by holding or executing the cart service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CartService cartService; - - @PostMapping("/add") - @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.addToCart(userId, cartDTO); - return Result.success(); - } - - @DeleteMapping("/remove/{productId}") - @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.removeFromCart(userId, productId); - return Result.success(); - } - - @PostMapping("/batch-remove") - @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `batchRemoveFromCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartItemIds parameter `cartItemIds` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.batchRemoveFromCart(userId, cartItemIds); - return Result.success(); - } - - @PutMapping("/update") - @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.updateCartQuantity(userId, cartDTO); - return Result.success(); - } - - @GetMapping("/list") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getCartList(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - List cartList = cartService.getCartList(userId); - return Result.success(cartList); - } - - @DeleteMapping("/clear") - @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `clearCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result clearCart(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.clearCart(userId); - return Result.success(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/OrderController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/OrderController.java deleted file mode 100644 index 842ee9e1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/controller/front/OrderController.java +++ /dev/null @@ -1,459 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.CheckoutPreviewDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistChangeRejectDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistChangeRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistReviewSubmitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteReplyDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteSubmitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.OrderService; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.SecurityAuditActions; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.SecurityAuditSupport; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CheckoutPreviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistChangeOptionsVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistChangeRequestVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistReviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserVO; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.time.LocalDate; -import java.util.Comparator; -import java.util.List; - -@RestController -@RequestMapping("/order") -/** - * OrderController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class OrderController { - - @Resource - /** - * Purpose: orderService supports OrderController.java by holding or executing the order service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderService orderService; - - @Resource - /** - * Purpose: userService supports OrderController.java by holding or executing the user service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserService userService; - - @Resource - /** - * Purpose: securityAuditSupport supports OrderController.java by holding or executing the security audit support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private SecurityAuditSupport securityAuditSupport; - - @PostMapping("/create") - @OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderDTO parameter `orderDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - OrderVO orderVO = orderService.createOrder(userId, orderDTO); - return Result.success(orderVO); - } - - @PostMapping("/checkout-preview") - public Result checkoutPreview(@RequestBody CheckoutPreviewDTO checkoutPreviewDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.checkoutPreview(userId, checkoutPreviewDTO)); - } - - @GetMapping("/list") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getOrderList(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - List orderList = orderService.getOrderList(userId); - return Result.success(orderList); - } - - @GetMapping("/detail/{orderId}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getOrderDetail(@PathVariable Long orderId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - OrderVO orderVO = orderService.getOrderDetail(orderId, userId); - return Result.success(orderVO); - } - - @PutMapping("/cancel/{orderId}") - @OperationGuard(action = "order-cancel", ttlSeconds = 15, message = "操作进行中,请勿重复点击") - /** - * Run business method `cancelOrder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - orderService.cancelOrder(orderId, userId); - return Result.success(); - } - - // 后台管理接口 - @PostMapping("/{orderId}/quote/reply") - @OperationGuard(action = "order-quote-reply", ttlSeconds = 10, message = "回复处理中,请勿重复提交") - public Result replyQuote(@PathVariable Long orderId, - @RequestBody(required = false) OrderQuoteReplyDTO dto, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.replyQuote(orderId, userId, dto)); - } - - @PutMapping("/{orderId}/quote/confirm") - @OperationGuard(action = "order-quote-user-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") - public Result confirmUserQuote(@PathVariable Long orderId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.confirmUserQuote(orderId, userId)); - } - - @RequirePermission("order:process") - @PostMapping("/{orderId}/quote/shop") - @OperationGuard(action = "order-shop-quote-submit", ttlSeconds = 10, message = "报价处理中,请勿重复提交") - public Result submitShopQuote(@PathVariable Long orderId, - @RequestBody OrderQuoteSubmitDTO dto, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.submitShopQuote(orderId, userId, userType, dto)); - } - - @RequirePermission("order:process") - @PutMapping("/{orderId}/quote/shop/confirm") - @OperationGuard(action = "order-shop-quote-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") - public Result confirmShopQuote(@PathVariable Long orderId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.confirmShopQuote(orderId, userId, userType)); - } - - @RequirePermission("order:view") - @GetMapping("/admin/list") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getAllOrders(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - List orderList; - if (Integer.valueOf(3).equals(userType)) { - orderList = orderService.getOrdersByArtistId(userId); - } else { - orderList = orderService.getAllOrders(); - } - if (!Integer.valueOf(4).equals(userType) && !Integer.valueOf(3).equals(userType)) { - UserVO currentUser = userService.getUserById(userId); - if (currentUser == null || currentUser.getShopId() == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号未绑定店铺"); - } - orderList = orderList.stream() - .filter(order -> currentUser.getShopId().equals(order.getShopId())) - .toList(); - } - return Result.success(orderList); - } - - @RequirePermission("order:process") - @PutMapping("/admin/process/{orderId}") - @OperationGuard(action = "admin-order-process", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - /** - * Run business method `processOrder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - if (Integer.valueOf(3).equals(userType)) { - if (!Integer.valueOf(2).equals(status)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("美甲师只能完成属于自己的订单"); - } - try { - orderService.completeArtistOrder(orderId, userId); - securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId); - return Result.success(); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId + ",reason=" + exception.getMessage()); - throw exception; - } - } - if (!Integer.valueOf(4).equals(userType)) { - UserVO currentUser = userService.getUserById(userId); - if (currentUser == null || currentUser.getShopId() == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号未绑定店铺"); - } - OrderVO orderVO = orderService.getAllOrders().stream() - .filter(order -> orderId.equals(order.getId())) - .findFirst() - .orElse(null); - if (orderVO == null || !currentUser.getShopId().equals(orderVO.getShopId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权处理其他店铺订单"); - } - } - try { - orderService.processOrder(orderId, status); - securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status); - return Result.success(); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",reason=" + exception.getMessage()); - throw exception; - } - } - - // 美甲师查看自己的订单 - @RequirePermission("order:view") - @GetMapping("/artist/list") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getArtistOrders(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("仅美甲师可查看自己的订单"); - } - List orderList; - if (Integer.valueOf(2).equals(userType)) { - UserVO currentUser = userService.getUserById(userId); - if (currentUser == null || currentUser.getShopId() == null) { - throw new RuntimeException("当前账号未绑定店铺"); - } - orderList = orderService.getAllOrders().stream() - .filter(order -> currentUser.getShopId().equals(order.getShopId())) - .peek(order -> { - order.setArtistOrderSource("SHOP"); - order.setArtistOrderSourceText("本店美甲师订单"); - }) - .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) - .toList(); - } else { - orderList = orderService.getArtistWorkbenchOrders(userId); - } - return Result.success(orderList); - } - - @RequirePermission("order:view") - @GetMapping("/artist/calendar/recent") - // 调用示例:GET /order/artist/calendar/recent?days=7 - // 只返回当前登录美甲师/参与制作店长自己的预约,前端不用再做二次过滤。 - public Result getArtistCalendarRecent(@RequestParam(value = "days", required = false) Integer days, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.getArtistCalendarRecent(userId, userType, days)); - } - - @RequirePermission("order:view") - @GetMapping("/artist/calendar/day") - // 调用示例:GET /order/artist/calendar/day?date=2026-05-17 - // date 使用 yyyy-MM-dd,适合日历点选某一天后拉取详情。 - public Result getArtistCalendarDay(@RequestParam("date") - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) - LocalDate date, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.getArtistCalendarDay(userId, userType, date)); - } - - @RequirePermission("order:process") - @PutMapping("/artist/complete/{orderId}") - @OperationGuard(action = "artist-order-complete", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - /** - * Complete a business action. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("仅美甲师可完成自己的订单"); - } - try { - orderService.completeArtistOrder(orderId, userId); - securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId); - return Result.success(); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @GetMapping("/review/my-pending") - /** - * Purpose: listMyPendingReviews supports OrderController.java by holding or executing the list my pending reviews business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listMyPendingReviews(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.listMyPendingReviews(userId)); - } - - @GetMapping("/{orderId}/reviews") - /** - * Purpose: listOrderReviews supports OrderController.java by holding or executing the list order reviews business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listOrderReviews(@PathVariable Long orderId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.listOrderReviews(orderId, userId, userType)); - } - - @PostMapping("/review/{reviewId}/submit") - @OperationGuard(action = "order-artist-review-submit", ttlSeconds = 15, message = "评价正在提交中,请勿重复操作") - public Result submitArtistReview(@PathVariable Long reviewId, - @RequestBody OrderArtistReviewSubmitDTO dto, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.submitArtistReview(reviewId, userId, dto)); - } - - @RequirePermission("order:artist-change") - @GetMapping("/{orderId}/artist-change/options") - public Result getArtistChangeOptions(@PathVariable Long orderId, - @RequestParam Long orderItemId, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.getArtistChangeOptions(orderId, orderItemId, userId, userType)); - } - - @RequirePermission("order:artist-change") - @PostMapping("/artist-change/request") - @OperationGuard(action = "order-artist-change-request", ttlSeconds = 15, message = "改派申请正在提交中,请勿重复操作") - public Result requestArtistChange(@RequestBody OrderArtistChangeRequestDTO dto, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(orderService.requestArtistChange(userId, dto)); - } - - @GetMapping("/artist-change/my-pending") - /** - * Purpose: listMyPendingArtistChangeRequests supports OrderController.java by holding or executing the list my pending artist change requests business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listMyPendingArtistChangeRequests(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.listMyPendingArtistChangeRequests(userId, userType)); - } - - @GetMapping("/{orderId}/artist-change/requests") - /** - * Purpose: listOrderArtistChangeRequests returns pending and processed artist-change records for one order. - * Usage: call it from order pages to build a timeline after the caller has an authenticated session. - */ - public Result> listOrderArtistChangeRequests(@PathVariable Long orderId, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - return Result.success(orderService.listOrderArtistChangeRequests(orderId, userId, userType)); - } - - @PutMapping("/artist-change/{requestId}/approve") - @OperationGuard(action = "order-artist-change-approve", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") - public Result approveArtistChange(@PathVariable Long requestId, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - try { - OrderArtistChangeRequestVO result = orderService.approveArtistChange(requestId, userId, userType); - securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PutMapping("/artist-change/{requestId}/reject") - @OperationGuard(action = "order-artist-change-reject", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") - public Result rejectArtistChange(@PathVariable Long requestId, - @RequestBody(required = false) OrderArtistChangeRejectDTO dto, - HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - Integer userType = (Integer) request.getAttribute("userType"); - try { - OrderArtistChangeRequestVO result = orderService.rejectArtistChange(requestId, userId, userType, dto); - securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId + ",reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/AfterSaleApplyDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/AfterSaleApplyDTO.java deleted file mode 100644 index 52b12d8d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/AfterSaleApplyDTO.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class AfterSaleApplyDTO { - private Long orderId; - private Long orderItemId; - private String type; - private String reason; - private BigDecimal refundAmount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/AfterSaleAuditDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/AfterSaleAuditDTO.java deleted file mode 100644 index 04dd502e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/AfterSaleAuditDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -@Data -public class AfterSaleAuditDTO { - private String auditReason; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/CartDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/CartDTO.java deleted file mode 100644 index 39180af4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/CartDTO.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -/** - * 购物车 DTO - * 用于购物车商品信息的传输 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class CartDTO { - - /** - * 商品ID - */ - private Long productId; - - /** - * 商品数量 - */ - private Integer quantity; -} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/CheckoutPreviewDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/CheckoutPreviewDTO.java deleted file mode 100644 index 6d67fd3c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/CheckoutPreviewDTO.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -import java.util.List; - -/** - * 结算预览请求,只做金额和优惠说明,不创建订单。 - */ -@Data -public class CheckoutPreviewDTO { - - /** - * 已选择的优惠选项ID:用户券传用户券ID,VIP自动券传券模板ID。 - */ - private Long couponId; - - /** - * 优惠来源:USER_COUPON、SYSTEM_VIP、NONE。 - */ - private String couponSourceType; - private String remark; - - /** - * 本次预览的商品列表。 - */ - private List items; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistChangeRejectDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistChangeRejectDTO.java deleted file mode 100644 index 6b61ebdb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistChangeRejectDTO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -@Data -/** - * Purpose: OrderArtistChangeRejectDTO supports OrderArtistChangeRejectDTO.java by holding or executing the order artist change reject dto business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistChangeRejectDTO { - /** - * Purpose: rejectReason supports OrderArtistChangeRejectDTO.java by holding or executing the reject reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String rejectReason; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistChangeRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistChangeRequestDTO.java deleted file mode 100644 index 5b37a414..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistChangeRequestDTO.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -@Data -/** - * Purpose: OrderArtistChangeRequestDTO supports OrderArtistChangeRequestDTO.java by holding or executing the order artist change request dto business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistChangeRequestDTO { - /** - * Purpose: orderId supports OrderArtistChangeRequestDTO.java by holding or executing the order id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderId; - /** - * Purpose: orderItemId supports OrderArtistChangeRequestDTO.java by holding or executing the order item id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderItemId; - /** - * Purpose: requestedArtistId supports OrderArtistChangeRequestDTO.java by holding or executing the requested artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long requestedArtistId; - /** - * Purpose: reason supports OrderArtistChangeRequestDTO.java by holding or executing the reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String reason; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistReviewSubmitDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistReviewSubmitDTO.java deleted file mode 100644 index 27896b5b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderArtistReviewSubmitDTO.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -import java.math.BigDecimal; -import java.util.List; - -@Data -/** - * Purpose: OrderArtistReviewSubmitDTO supports OrderArtistReviewSubmitDTO.java by holding or executing the order artist review submit dto business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistReviewSubmitDTO { - /** - * Purpose: rating supports OrderArtistReviewSubmitDTO.java by holding or executing the rating business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal rating; - /** - * Purpose: content supports OrderArtistReviewSubmitDTO.java by holding or executing the content business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String content; - /** - * Purpose: imageFileIds supports OrderArtistReviewSubmitDTO.java by holding or executing the image file ids business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private List imageFileIds; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderDTO.java deleted file mode 100644 index 1e0e8a6d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderDTO.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -import java.util.List; - -/** - * 订单 DTO - * 用于订单创建请求 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class OrderDTO { - - /** - * 优惠券ID - */ - private Long couponId; - /** - * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponSourceType; - private String remark; - private String clientRequestId; - - /** - * 订单商品列表 - */ - private List items; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderItemDTO.java deleted file mode 100644 index 14ebc7ac..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderItemDTO.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -/** - * 订单商品项 DTO - * 用于订单中的单个商品信息 - * - * @author xiaowang - * @date 2026-03-12 - */ -@Data -public class OrderItemDTO { - - /** - * 商品ID - */ - private Long productId; - - /** - * 商品数量 - */ - private Integer quantity; - - /** - * 美甲师ID - */ - private Long artistId; - - /** - * 预约开始时间 - */ - private String appointmentTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteItemDTO.java deleted file mode 100644 index 169ec463..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteItemDTO.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class OrderQuoteItemDTO { - private Long orderItemId; - private BigDecimal quotedPrice; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteReplyDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteReplyDTO.java deleted file mode 100644 index c56c3a47..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteReplyDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -@Data -public class OrderQuoteReplyDTO { - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteSubmitDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteSubmitDTO.java deleted file mode 100644 index d1fec8ea..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/dto/OrderQuoteSubmitDTO.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.dto; - -import lombok.Data; - -import java.util.List; - -@Data -public class OrderQuoteSubmitDTO { - private String remark; - private List items; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/AfterSaleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/AfterSaleDO.java deleted file mode 100644 index 510c9fcf..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/AfterSaleDO.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_after_sale") -public class AfterSaleDO extends BaseEntity { - @TableField("after_sale_no") - private String afterSaleNo; - @TableField("order_id") - private Long orderId; - @TableField("order_item_id") - private Long orderItemId; - @TableField("user_id") - private Long userId; - @TableField("shop_id") - private Long shopId; - @TableField("type") - private String type; - @TableField("reason") - private String reason; - @TableField("refund_amount") - private BigDecimal refundAmount; - @TableField("status") - private String status; - @TableField("audit_user_id") - private Long auditUserId; - @TableField("audit_reason") - private String auditReason; - @TableField("audit_time") - private LocalDateTime auditTime; - @TableField("refund_order_id") - private Long refundOrderId; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/AfterSaleLogDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/AfterSaleLogDO.java deleted file mode 100644 index c453dc84..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/AfterSaleLogDO.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_after_sale_log") -public class AfterSaleLogDO extends BaseEntity { - @TableField("after_sale_id") - private Long afterSaleId; - @TableField("action") - private String action; - @TableField("from_status") - private String fromStatus; - @TableField("to_status") - private String toStatus; - @TableField("operator_id") - private Long operatorId; - @TableField("operator_type") - private String operatorType; - @TableField("remark") - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/CartDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/CartDO.java deleted file mode 100644 index a96d1c85..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/CartDO.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@TableName("t_cart") -/** - * CartDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class CartDO extends BaseEntity { - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - /** - * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long productId; - /** - * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer quantity; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime updateTime; - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderArtistChangeRequestDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderArtistChangeRequestDO.java deleted file mode 100644 index 965d573a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderArtistChangeRequestDO.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_order_artist_change_request") -/** - * Purpose: OrderArtistChangeRequestDO supports OrderArtistChangeRequestDO.java by holding or executing the order artist change request do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistChangeRequestDO extends BaseEntity { - - @TableField("order_id") - /** - * Purpose: orderId supports OrderArtistChangeRequestDO.java by holding or executing the order id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderId; - - @TableField("order_item_id") - /** - * Purpose: orderItemId supports OrderArtistChangeRequestDO.java by holding or executing the order item id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderItemId; - - @TableField("product_id") - /** - * Purpose: productId supports OrderArtistChangeRequestDO.java by holding or executing the product id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long productId; - - @TableField("shop_id") - /** - * Purpose: shopId supports OrderArtistChangeRequestDO.java by holding or executing the shop id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long shopId; - - @TableField("customer_id") - /** - * Purpose: customerId supports OrderArtistChangeRequestDO.java by holding or executing the customer id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long customerId; - - @TableField("from_artist_id") - /** - * Purpose: fromArtistId supports OrderArtistChangeRequestDO.java by holding or executing the from artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long fromArtistId; - - @TableField("to_artist_id") - /** - * Purpose: toArtistId supports OrderArtistChangeRequestDO.java by holding or executing the to artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long toArtistId; - - @TableField("requester_id") - /** - * Purpose: requesterId supports OrderArtistChangeRequestDO.java by holding or executing the requester id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long requesterId; - - @TableField("status") - /** - * Purpose: status supports OrderArtistChangeRequestDO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String status; - - @TableField("reason") - /** - * Purpose: reason supports OrderArtistChangeRequestDO.java by holding or executing the reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String reason; - - @TableField("reject_reason") - /** - * Purpose: rejectReason supports OrderArtistChangeRequestDO.java by holding or executing the reject reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String rejectReason; - - @TableField("message_id") - /** - * Purpose: messageId supports OrderArtistChangeRequestDO.java by holding or executing the message id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long messageId; - - @TableField("pending_key") - /** - * Purpose: pendingKey supports OrderArtistChangeRequestDO.java by holding or executing the pending key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String pendingKey; - - @TableField("approved_time") - /** - * Purpose: approvedTime supports OrderArtistChangeRequestDO.java by holding or executing the approved time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime approvedTime; - - @TableField("rejected_time") - /** - * Purpose: rejectedTime supports OrderArtistChangeRequestDO.java by holding or executing the rejected time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime rejectedTime; - - @TableField("expire_time") - /** - * Purpose: expireTime supports OrderArtistChangeRequestDO.java by holding or executing the expire time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime expireTime; - - @TableField("is_delete") - /** - * Purpose: isDelete supports OrderArtistChangeRequestDO.java by holding or executing the is delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderArtistReviewDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderArtistReviewDO.java deleted file mode 100644 index 3b529586..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderArtistReviewDO.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_order_artist_review") -/** - * Purpose: OrderArtistReviewDO supports OrderArtistReviewDO.java by holding or executing the order artist review do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistReviewDO extends BaseEntity { - - @TableField("order_id") - /** - * Purpose: orderId supports OrderArtistReviewDO.java by holding or executing the order id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderId; - - @TableField("order_item_id") - /** - * Purpose: orderItemId supports OrderArtistReviewDO.java by holding or executing the order item id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderItemId; - - @TableField("product_id") - /** - * Purpose: productId supports OrderArtistReviewDO.java by holding or executing the product id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long productId; - - @TableField("artist_id") - /** - * Purpose: artistId supports OrderArtistReviewDO.java by holding or executing the artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long artistId; - - @TableField("shop_id") - /** - * Purpose: shopId supports OrderArtistReviewDO.java by holding or executing the shop id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long shopId; - - @TableField("customer_id") - /** - * Purpose: customerId supports OrderArtistReviewDO.java by holding or executing the customer id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long customerId; - - @TableField("status") - /** - * Purpose: status supports OrderArtistReviewDO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer status; - - @TableField("rating_score") - /** - * Purpose: ratingScore supports OrderArtistReviewDO.java by holding or executing the rating score business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal ratingScore; - - @TableField("content") - /** - * Purpose: content supports OrderArtistReviewDO.java by holding or executing the content business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String content; - - @TableField("image_file_ids") - /** - * Purpose: imageFileIds supports OrderArtistReviewDO.java by holding or executing the image file ids business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String imageFileIds; - - @TableField("reminder_message_id") - /** - * Purpose: reminderMessageId supports OrderArtistReviewDO.java by holding or executing the reminder message id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long reminderMessageId; - - @TableField("submitted_at") - /** - * Purpose: submittedAt supports OrderArtistReviewDO.java by holding or executing the submitted at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime submittedAt; - - @TableField("is_delete") - /** - * Purpose: isDelete supports OrderArtistReviewDO.java by holding or executing the is delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java deleted file mode 100644 index 5942252a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@TableName("t_order") -/** - * OrderDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class OrderDO extends BaseEntity { - /** - * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String orderNo; - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalAmount; - /** - * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal actualAmount; - /** - * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long couponId; - /** - * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userCouponId; - /** - * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponSourceType; - private String paymentStatus; - private BigDecimal payAmount; - private BigDecimal paidAmount; - private LocalDateTime payTime; - private String paymentMethod; - private String paymentOrderNo; - private String refundStatus; - private String customerRemark; - private String quoteStatus; - private Integer quoteUserConfirmed; - private Integer quoteShopConfirmed; - private LocalDateTime quoteExpireTime; - private LocalDateTime quoteConfirmedTime; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime updateTime; - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java deleted file mode 100644 index 96cd8983..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@TableName("t_order_item") -/** - * OrderItemDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class OrderItemDO extends BaseEntity { - /** - * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long orderId; - /** - * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long productId; - /** - * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer quantity; - /** - * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal price; - private BigDecimal referencePrice; - private BigDecimal quotedPrice; - private BigDecimal confirmedPrice; - /** - * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long artistId; - - @TableField("appointment_time") - /** - * Field `appointmentTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime appointmentTime; - - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime updateTime; - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderQuoteMessageDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderQuoteMessageDO.java deleted file mode 100644 index a602e439..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderQuoteMessageDO.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_order_quote_message") -public class OrderQuoteMessageDO extends BaseEntity { - - @TableField("order_id") - private Long orderId; - - @TableField("actor_id") - private Long actorId; - - @TableField("actor_type") - private String actorType; - - @TableField("action") - private String action; - - @TableField("remark") - private String remark; - - @TableField("items_snapshot") - private String itemsSnapshot; - - @TableField("is_delete") - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/AfterSaleLogMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/AfterSaleLogMapper.java deleted file mode 100644 index 88ae1947..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/AfterSaleLogMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.AfterSaleLogDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface AfterSaleLogMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/AfterSaleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/AfterSaleMapper.java deleted file mode 100644 index b08989d1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/AfterSaleMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.AfterSaleDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface AfterSaleMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/CartMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/CartMapper.java deleted file mode 100644 index 1aafa330..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/CartMapper.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.CartDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -import java.util.List; - -@Mapper -/** - * CartMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface CartMapper extends BaseMapper { - @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND is_delete = 0") - List selectByUserId(@Param("userId") Long userId); - - @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND product_id = #{productId} AND is_delete = 0") - CartDO selectByUserIdAndProductId(@Param("userId") Long userId, @Param("productId") Long productId); - - @Select({ - "" - }) - List selectByUserIdAndProductIdsForUpdate( - @Param("userId") Long userId, - @Param("productIds") List productIds - ); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderArtistChangeRequestMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderArtistChangeRequestMapper.java deleted file mode 100644 index 76305270..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderArtistChangeRequestMapper.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistChangeRequestDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -import java.time.LocalDateTime; - -import java.util.List; - -@Mapper -/** - * Purpose: OrderArtistChangeRequestMapper supports OrderArtistChangeRequestMapper.java by holding or executing the order artist change request mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface OrderArtistChangeRequestMapper extends BaseMapper { - - @Select("SELECT * FROM t_order_artist_change_request WHERE order_item_id = #{orderItemId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) LIMIT 1") - OrderArtistChangeRequestDO selectPendingByOrderItemId(@Param("orderItemId") Long orderItemId); - - @Select("SELECT * FROM t_order_artist_change_request WHERE customer_id = #{userId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") - List selectPendingByUserId(@Param("userId") Long userId); - - @Select("SELECT * FROM t_order_artist_change_request WHERE (from_artist_id = #{artistId} OR to_artist_id = #{artistId} OR requester_id = #{artistId}) AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") - List selectPendingByArtistId(@Param("artistId") Long artistId); - - @Select("SELECT * FROM t_order_artist_change_request WHERE shop_id = #{shopId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") - List selectPendingByShopId(@Param("shopId") Long shopId); - - @Select("SELECT * FROM t_order_artist_change_request WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") - List selectByOrderId(@Param("orderId") Long orderId); - - @Update("UPDATE t_order_artist_change_request SET status = 'APPROVED', approved_time = #{approvedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{approvedTime})") - int approvePending(@Param("id") Long id, @Param("approvedTime") LocalDateTime approvedTime); - - @Update("UPDATE t_order_artist_change_request SET status = 'REJECTED', reject_reason = #{rejectReason}, rejected_time = #{rejectedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{rejectedTime})") - int rejectPending(@Param("id") Long id, @Param("rejectReason") String rejectReason, @Param("rejectedTime") LocalDateTime rejectedTime); - - @Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}") - int expirePendingById(@Param("id") Long id, @Param("now") LocalDateTime now); - - @Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}") - int expirePendingBefore(@Param("now") LocalDateTime now); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderArtistReviewMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderArtistReviewMapper.java deleted file mode 100644 index 26f5c5f5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderArtistReviewMapper.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistReviewDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -import java.math.BigDecimal; -import java.util.List; - -@Mapper -/** - * Purpose: OrderArtistReviewMapper supports OrderArtistReviewMapper.java by holding or executing the order artist review mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface OrderArtistReviewMapper extends BaseMapper { - - @Select("SELECT * FROM t_order_artist_review WHERE customer_id = #{userId} AND status = 0 AND is_delete = 0 ORDER BY create_time DESC, id DESC") - List selectPendingByUserId(@Param("userId") Long userId); - - @Select("SELECT * FROM t_order_artist_review WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") - List selectByOrderId(@Param("orderId") Long orderId); - - @Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1") - OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId); - - @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0") - BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderItemMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderItemMapper.java deleted file mode 100644 index 6bbfe64d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderItemMapper.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -import java.time.LocalDateTime; -import java.util.List; - -@Mapper -/** - * OrderItemMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface OrderItemMapper extends BaseMapper { - @Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}") - List selectByOrderId(@Param("orderId") Long orderId); - - @Select("SELECT * FROM t_order_item WHERE id = #{id} FOR UPDATE") - OrderItemDO selectByIdForUpdate(@Param("id") Long id); - - @Select("SELECT oi.* FROM t_order_item oi " + - "INNER JOIN t_order o ON o.id = oi.order_id " + - "WHERE oi.artist_id = #{artistId} " + - "AND oi.is_delete = 0 " + - "AND o.is_delete = 0 " + - "AND o.status = 1 " + - "AND oi.appointment_time IS NOT NULL") - List selectActiveAppointmentItemsByArtistId(@Param("artistId") Long artistId); - - @Select("SELECT oi.* FROM t_order_item oi " + - "INNER JOIN t_order o ON o.id = oi.order_id " + - "WHERE oi.artist_id = #{artistId} " + - "AND oi.is_delete = 0 " + - "AND o.is_delete = 0 " + - "AND o.status = 1 " + - "AND oi.appointment_time >= #{startTime} " + - "AND oi.appointment_time < #{endTime} " + - "ORDER BY oi.appointment_time ASC, oi.id ASC") - List selectArtistCalendarItems(@Param("artistId") Long artistId, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime); - - @Select("SELECT COUNT(DISTINCT oi.order_id) as count FROM t_order_item oi " + - "JOIN t_product p ON oi.product_id = p.id " + - "JOIN t_order o ON oi.order_id = o.id " + - "WHERE p.shop_id = #{shopId} AND o.create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND o.is_delete = 0") - java.util.Map countTodayOrdersByShopId(@Param("shopId") Long shopId, @Param("todayStart") String todayStart); - - @Select("SELECT COUNT(DISTINCT id) as count FROM t_order WHERE create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND is_delete = 0") - java.util.Map countTodayOrders(@Param("todayStart") String todayStart); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderMapper.java deleted file mode 100644 index 68c8426a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -import java.util.List; - -@Mapper -/** - * OrderMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface OrderMapper extends BaseMapper { - @Select("SELECT * FROM t_order WHERE user_id = #{userId}") - List selectByUserId(@Param("userId") Long userId); - - @Select("SELECT * FROM t_order WHERE order_no = #{orderNo}") - OrderDO selectByOrderNo(@Param("orderNo") String orderNo); - - @Select("SELECT DISTINCT o.* FROM t_order o " + - "INNER JOIN t_order_item oi ON o.id = oi.order_id " + - "WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " + - "ORDER BY o.create_time DESC") - List selectByArtistId(@Param("artistId") Long artistId); - - @Update("UPDATE t_order SET status = #{toStatus} WHERE id = #{orderId} AND status = #{fromStatus} AND is_delete = 0") - int updateStatusIfCurrent(@Param("orderId") Long orderId, - @Param("fromStatus") Integer fromStatus, - @Param("toStatus") Integer toStatus); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderQuoteMessageMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderQuoteMessageMapper.java deleted file mode 100644 index a987f588..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/mapper/OrderQuoteMessageMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderQuoteMessageDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -import java.util.List; - -@Mapper -public interface OrderQuoteMessageMapper extends BaseMapper { - - @Select("SELECT * FROM t_order_quote_message WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") - List selectByOrderId(@Param("orderId") Long orderId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/AfterSaleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/AfterSaleService.java deleted file mode 100644 index a1a1169a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/AfterSaleService.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.service; - -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.AfterSaleApplyDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.AfterSaleAuditDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.AfterSaleVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; - -public interface AfterSaleService { - AfterSaleVO apply(Long userId, AfterSaleApplyDTO dto); - - PageResultVO listMy(Long userId, Integer page, Integer size); - - PageResultVO listAdmin(Long shopId, String status, Integer page, Integer size); - - AfterSaleVO approve(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto); - - AfterSaleVO reject(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/CartService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/CartService.java deleted file mode 100644 index fb5f2108..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/CartService.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.service; - -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.CartDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CartVO; - -import java.util.List; - -/** - * CartService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface CartService { - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param cartDTO parameter `cartDTO` supplied by the caller - */ - void addToCart(Long userId, CartDTO cartDTO); - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ - void removeFromCart(Long userId, Long productId); - /** - * Run business method `batchRemoveFromCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param cartItemIds parameter `cartItemIds` supplied by the caller - */ - void batchRemoveFromCart(Long userId, List cartItemIds); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param cartDTO parameter `cartDTO` supplied by the caller - */ - void updateCartQuantity(Long userId, CartDTO cartDTO); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getCartList(Long userId); - /** - * Run business method `clearCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - */ - void clearCart(Long userId); -} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/OrderService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/OrderService.java deleted file mode 100644 index 838f9daa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/OrderService.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.service; - -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.CheckoutPreviewDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistChangeRejectDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistChangeRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistReviewSubmitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteReplyDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteSubmitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistCalendarAppointmentVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CheckoutPreviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistChangeOptionsVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistChangeRequestVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistReviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderVO; - -import java.time.LocalDate; -import java.util.List; - -/** - * OrderService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface OrderService { - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param orderDTO parameter `orderDTO` supplied by the caller - * @return OrderVO result consumed by the caller or returned to the frontend - */ - OrderVO createOrder(Long userId, OrderDTO orderDTO); - - /** - * Preview checkout pricing and coupon explanations without creating an order. - */ - CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getOrderList(Long userId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return OrderVO result consumed by the caller or returned to the frontend - */ - OrderVO getOrderDetail(Long orderId, Long userId); - /** - * Run business method `cancelOrder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - */ - void cancelOrder(Long orderId, Long userId); - /** - * Run business method `processOrder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param status parameter `status` supplied by the caller - */ - void processOrder(Long orderId, Integer status); - /** - * Complete a business action. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - */ - void completeArtistOrder(Long orderId, Long artistId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - List getAllOrders(); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistId parameter `artistId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getOrdersByArtistId(Long artistId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistId parameter `artistId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getArtistWorkbenchOrders(Long artistId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @param days parameter `days` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getArtistCalendarRecent(Long userId, Integer userType, Integer days); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @param date parameter `date` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List getArtistCalendarDay(Long userId, Integer userType, LocalDate date); - - List listMyPendingReviews(Long userId); - - List listOrderReviews(Long orderId, Long userId, Integer userType); - - OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto); - - OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType); - - OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto); - - List listMyPendingArtistChangeRequests(Long userId, Integer userType); - - List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType); - - OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType); - - OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto); - - OrderVO submitShopQuote(Long orderId, Long operatorId, Integer operatorType, OrderQuoteSubmitDTO dto); - - OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType); - - OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto); - - OrderVO confirmUserQuote(Long orderId, Long userId); - - int expirePendingQuoteOrders(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/AfterSaleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/AfterSaleServiceImpl.java deleted file mode 100644 index 3d45a0d5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/AfterSaleServiceImpl.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.AfterSaleApplyDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.AfterSaleAuditDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.AfterSaleDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.AfterSaleLogDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.AfterSaleLogMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.AfterSaleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.mapper.SystemMessageMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.AfterSaleService; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.AfterSaleVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDateTime; -import java.util.List; - -@Service -@RequiredArgsConstructor -public class AfterSaleServiceImpl implements AfterSaleService { - - private static final String STATUS_PENDING = "PENDING"; - private static final String STATUS_APPROVED = "APPROVED"; - private static final String STATUS_REJECTED = "REJECTED"; - - private final AfterSaleMapper afterSaleMapper; - private final AfterSaleLogMapper afterSaleLogMapper; - private final OrderMapper orderMapper; - private final SystemMessageMapper systemMessageMapper; - - @Override - @Transactional - public AfterSaleVO apply(Long userId, AfterSaleApplyDTO dto) { - if (dto == null || dto.getOrderId() == null) { - throw new RuntimeException("售后订单信息不完整"); - } - OrderDO order = orderMapper.selectById(dto.getOrderId()); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - throw new RuntimeException("订单不存在"); - } - if (!order.getUserId().equals(userId)) { - throw new RuntimeException("无权申请该订单售后"); - } - if (Integer.valueOf(0).equals(order.getStatus())) { - throw new RuntimeException("询价预约确认价格前暂不能申请售后"); - } - AfterSaleDO afterSale = new AfterSaleDO(); - afterSale.setAfterSaleNo("AS" + System.currentTimeMillis() + dto.getOrderId()); - afterSale.setOrderId(order.getId()); - afterSale.setOrderItemId(dto.getOrderItemId()); - afterSale.setUserId(userId); - afterSale.setShopId(order.getShopId()); - afterSale.setType(dto.getType()); - afterSale.setReason(dto.getReason()); - afterSale.setRefundAmount(dto.getRefundAmount()); - afterSale.setStatus(STATUS_PENDING); - afterSale.setIsDelete(0); - afterSaleMapper.insert(afterSale); - writeLog(afterSale.getId(), "CREATE", null, STATUS_PENDING, userId, "USER", dto.getReason()); - return toVO(afterSale); - } - - @Override - public PageResultVO listMy(Long userId, Integer page, Integer size) { - return pageByWrapper(new LambdaQueryWrapper() - .eq(AfterSaleDO::getUserId, userId) - .eq(AfterSaleDO::getIsDelete, 0) - .orderByDesc(AfterSaleDO::getCreateTime), page, size); - } - - @Override - public PageResultVO listAdmin(Long shopId, String status, Integer page, Integer size) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(AfterSaleDO::getIsDelete, 0) - .orderByDesc(AfterSaleDO::getCreateTime); - if (shopId != null) { - wrapper.eq(AfterSaleDO::getShopId, shopId); - } - if (status != null && !status.isBlank()) { - wrapper.eq(AfterSaleDO::getStatus, status); - } - return pageByWrapper(wrapper, page, size); - } - - @Override - @Transactional - public AfterSaleVO approve(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto) { - return audit(operatorId, afterSaleId, dto, STATUS_APPROVED, "APPROVE"); - } - - @Override - @Transactional - public AfterSaleVO reject(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto) { - return audit(operatorId, afterSaleId, dto, STATUS_REJECTED, "REJECT"); - } - - private AfterSaleVO audit(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto, String targetStatus, String action) { - AfterSaleDO afterSale = afterSaleMapper.selectById(afterSaleId); - if (afterSale == null || Integer.valueOf(1).equals(afterSale.getIsDelete())) { - throw new RuntimeException("售后单不存在"); - } - if (!STATUS_PENDING.equals(afterSale.getStatus())) { - throw new RuntimeException("售后单已处理"); - } - String fromStatus = afterSale.getStatus(); - afterSale.setStatus(targetStatus); - afterSale.setAuditUserId(operatorId); - afterSale.setAuditReason(dto == null ? null : dto.getAuditReason()); - afterSale.setAuditTime(LocalDateTime.now()); - afterSaleMapper.updateById(afterSale); - writeLog(afterSale.getId(), action, fromStatus, targetStatus, operatorId, "ADMIN", afterSale.getAuditReason()); - notifyCustomer(afterSale, targetStatus); - return toVO(afterSale); - } - - private void writeLog(Long afterSaleId, String action, String fromStatus, String toStatus, - Long operatorId, String operatorType, String remark) { - AfterSaleLogDO log = new AfterSaleLogDO(); - log.setAfterSaleId(afterSaleId); - log.setAction(action); - log.setFromStatus(fromStatus); - log.setToStatus(toStatus); - log.setOperatorId(operatorId); - log.setOperatorType(operatorType); - log.setRemark(remark); - afterSaleLogMapper.insert(log); - } - - private void notifyCustomer(AfterSaleDO afterSale, String status) { - SystemMessageDO message = new SystemMessageDO(); - message.setTitle("售后处理进度更新"); - message.setContent("您的售后申请已更新为:" + status); - message.setTargetType("SELECTED_USERS"); - message.setTargetIds(String.valueOf(afterSale.getUserId())); - message.setBusinessType("AFTER_SALE_" + status); - message.setBusinessId(afterSale.getId()); - message.setActionPath("/after-sales?afterSaleId=" + afterSale.getId()); - message.setPopupEnabled(1); - message.setStatus(1); - message.setPublishTime(LocalDateTime.now()); - message.setIsDelete(0); - systemMessageMapper.insert(message); - } - - private PageResultVO pageByWrapper(LambdaQueryWrapper wrapper, Integer page, Integer size) { - int current = page == null || page < 1 ? 1 : page; - int pageSize = size == null || size < 1 ? 10 : size; - Page result = afterSaleMapper.selectPage(new Page<>(current, pageSize), wrapper); - PageResultVO vo = new PageResultVO<>(); - List list = result.getRecords().stream().map(this::toVO).toList(); - vo.setList(list); - vo.setTotal(result.getTotal()); - vo.setPage(current); - vo.setSize(pageSize); - return vo; - } - - private AfterSaleVO toVO(AfterSaleDO afterSale) { - AfterSaleVO vo = new AfterSaleVO(); - BeanUtils.copyProperties(afterSale, vo); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/CartServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/CartServiceImpl.java deleted file mode 100644 index 0e2a7ecd..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/CartServiceImpl.java +++ /dev/null @@ -1,361 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.CartDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.CartDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.CartMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.CartService; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.TagService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.support.BookableArtistSupport; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CartArtistVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CartVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import javax.annotation.Resource; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -@Service -/** - * CartServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class CartServiceImpl implements CartService { - - @Resource - /** - * Purpose: cartMapper supports CartServiceImpl.java by holding or executing the cart mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CartMapper cartMapper; - - @Resource - /** - * Purpose: productMapper supports CartServiceImpl.java by holding or executing the product mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ProductMapper productMapper; - - @Resource - /** - * Purpose: tagService supports CartServiceImpl.java by holding or executing the tag service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private TagService tagService; - - @Resource - /** - * Purpose: userMapper supports CartServiceImpl.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserMapper userMapper; - - @Resource - /** - * Purpose: userShopBindingSupport supports CartServiceImpl.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserShopBindingSupport userShopBindingSupport; - - @Resource - /** - * Purpose: bookableArtistSupport supports CartServiceImpl.java by holding or executing the bookable artist support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BookableArtistSupport bookableArtistSupport; - - @Resource - /** - * Purpose: objectStorageUrlSupport supports CartServiceImpl.java by holding or executing the object storage url support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ObjectStorageUrlSupport objectStorageUrlSupport; - - @Override - @Transactional - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param cartDTO parameter `cartDTO` supplied by the caller - */ - public void addToCart(Long userId, CartDTO cartDTO) { - validateQuantity(cartDTO.getQuantity()); - - ProductDO product = productMapper.selectById(cartDTO.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("商品不存在"); - } - - CartDO existingCart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); - if (existingCart != null) { - existingCart.setQuantity(existingCart.getQuantity() + cartDTO.getQuantity()); - cartMapper.updateById(existingCart); - return; - } - - CartDO newCart = new CartDO(); - newCart.setUserId(userId); - newCart.setProductId(cartDTO.getProductId()); - newCart.setQuantity(cartDTO.getQuantity()); - newCart.setIsDelete(0); - cartMapper.insert(newCart); - } - - @Override - @Transactional - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ - public void removeFromCart(Long userId, Long productId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("user_id", userId) - .eq("product_id", productId) - .eq("is_delete", 0); - cartMapper.delete(wrapper); - } - - @Override - @Transactional - /** - * Run business method `batchRemoveFromCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param cartItemIds parameter `cartItemIds` supplied by the caller - */ - public void batchRemoveFromCart(Long userId, List cartItemIds) { - if (cartItemIds == null || cartItemIds.isEmpty()) { - return; - } - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("user_id", userId) - .in("id", cartItemIds) - .eq("is_delete", 0); - cartMapper.delete(wrapper); - } - - @Override - @Transactional - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param cartDTO parameter `cartDTO` supplied by the caller - */ - public void updateCartQuantity(Long userId, CartDTO cartDTO) { - validateQuantity(cartDTO.getQuantity()); - CartDO cart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); - if (cart != null) { - cart.setQuantity(cartDTO.getQuantity()); - cartMapper.updateById(cart); - return; - } - - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("购物车商品不存在"); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getCartList(Long userId) { - List cartList = cartMapper.selectByUserId(userId); - List cartVOList = new ArrayList<>(); - - for (CartDO cart : cartList) { - if (!Integer.valueOf(0).equals(cart.getIsDelete())) { - continue; - } - - ProductDO product = productMapper.selectById(cart.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - continue; - } - - CartVO cartVO = new CartVO(); - cartVO.setId(cart.getId()); - cartVO.setProductId(product.getId()); - cartVO.setShopId(product.getShopId()); - cartVO.setProductTitle(product.getTitle()); - - String imageFileIds = product.getImageFileIds(); - if (StringUtils.hasText(imageFileIds)) { - String firstImageId = imageFileIds.split(",")[0]; - cartVO.setProductImage("/api/file/get/" + firstImageId); - } - - cartVO.setPrice(product.getPrice()); - cartVO.setQuantity(cart.getQuantity()); - cartVO.setTotalPrice(product.getPrice().multiply(new BigDecimal(cart.getQuantity()))); - cartVO.setTags(product.getTags()); - cartVO.setTagNames(resolveTagNames(product.getTags())); - cartVO.setApproximateDuration(product.getApproximateDuration()); - - String validBookableArtists = bookableArtistSupport.filterValidBookableArtists(product.getShopId(), product.getBookableArtists()); - List availableArtists = resolveAvailableArtists(product.getShopId(), product.getBookableArtists(), validBookableArtists); - cartVO.setBookableArtists(validBookableArtists); - cartVO.setAvailableBookableArtistCount(availableArtists.size()); - cartVO.setBookableArtistRestricted(StringUtils.hasText(product.getBookableArtists())); - cartVO.setAvailableArtists(availableArtists); - - cartVOList.add(cartVO); - } - - return cartVOList; - } - - @Override - @Transactional - /** - * Run business method `clearCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - */ - public void clearCart(Long userId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("user_id", userId) - .eq("is_delete", 0); - cartMapper.delete(wrapper); - } - - /** - * Run business method `validateQuantity`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param quantity parameter `quantity` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateQuantity(Integer quantity) { - if (quantity == null || quantity < 1 || quantity > 99) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("购物车数量必须在 1 到 99 之间"); - } - } - - /** - * Run business method `resolveTagNames`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagIds parameter `tagIds` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveTagNames(String tagIds) { - if (!StringUtils.hasText(tagIds)) { - return ""; - } - - return List.of(tagIds.split(";")).stream() - .map(String::trim) - .filter(tagId -> !tagId.isEmpty()) - .map(tagId -> { - try { - TagVO tagVO = tagService.getTagById(Long.parseLong(tagId)); - return tagVO != null ? tagVO.getTagName() : null; - } catch (NumberFormatException ex) { - return null; - } - }) - .filter(tagName -> tagName != null && !tagName.isBlank()) - .collect(Collectors.joining(",")); - } - - /** - * Run business method `resolveAvailableArtists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller - * @param validBookableArtists parameter `validBookableArtists` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List resolveAvailableArtists(Long shopId, String rawBookableArtists, String validBookableArtists) { - LinkedHashSet candidateArtistIds = new LinkedHashSet<>(); - if (StringUtils.hasText(validBookableArtists)) { - for (String artistIdText : validBookableArtists.split(",")) { - if (!StringUtils.hasText(artistIdText)) { - continue; - } - try { - candidateArtistIds.add(Long.parseLong(artistIdText.trim())); - } catch (NumberFormatException ignored) { - // Ignore invalid ids and keep valid artists only. - } - } - } else if (!StringUtils.hasText(rawBookableArtists) && shopId != null && shopId > 0) { - candidateArtistIds.addAll(userShopBindingSupport.listUserIdsByShopId(shopId, true)); - } - - if (candidateArtistIds.isEmpty()) { - return List.of(); - } - - List artistUsers = userMapper.selectList( - new QueryWrapper() - .in("id", candidateArtistIds) - .in("type", List.of(2, 3)) - .eq("status", 1) - .eq("is_delete", 0) - ); - if (artistUsers.isEmpty()) { - return List.of(); - } - - Map artistMap = artistUsers.stream() - .collect(Collectors.toMap(UserDO::getId, artist -> artist, (left, right) -> left)); - - return candidateArtistIds.stream() - .map(artistMap::get) - .filter(Objects::nonNull) - .filter(bookableArtistSupport::isBookableServiceUser) - .map(this::buildCartArtist) - .collect(Collectors.toList()); - } - - /** - * Run business method `buildCartArtist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artist parameter `artist` supplied by the caller - * @return private CartArtistVO result consumed by the caller or returned to the frontend - */ - private CartArtistVO buildCartArtist(UserDO artist) { - CartArtistVO cartArtistVO = new CartArtistVO(); - cartArtistVO.setId(artist.getId()); - cartArtistVO.setName(artist.getNickname()); - cartArtistVO.setAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); - cartArtistVO.setUserType(artist.getType()); - cartArtistVO.setRoleLabel(Integer.valueOf(2).equals(artist.getType()) ? "店长 · 参与制作" : "美甲师"); - cartArtistVO.setParticipateProduction(Integer.valueOf(2).equals(artist.getType())); - return cartArtistVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java deleted file mode 100644 index d0f69fd2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java +++ /dev/null @@ -1,4639 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.common.BusinessException; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.CheckoutPreviewDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistChangeRejectDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistChangeRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderArtistReviewSubmitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderItemDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteItemDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteReplyDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.dto.OrderQuoteSubmitDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.CartDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistChangeRequestDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistReviewDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderQuoteMessageDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.message.entity.SystemMessageDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.UserCouponDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.CartMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.CouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistChangeRequestMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistReviewMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderQuoteMessageMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.message.mapper.SystemMessageMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.UserCouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.service.AppointmentCapacityService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.BusinessEventOutboxService; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.CouponService; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.OrderService; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.TagService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.support.BookableArtistSupport; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStateMachine; -import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistCalendarAppointmentVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CheckoutCouponPreviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CheckoutPreviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.CheckoutPreviewVO.CheckoutIssueVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistChangeOptionsVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistChangeRequestVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderArtistReviewVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderItemVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderQuoteItemVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderQuoteMessageVO; -import com.xiaowang.jacyucloudsalon.core.modules.order.vo.OrderVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.vo.UserCouponVO; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.script.DefaultRedisScript; -import org.springframework.dao.DuplicateKeyException; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionTemplate; -import org.springframework.util.StringUtils; - -import javax.annotation.Resource; -import javax.annotation.PreDestroy; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -@Service -/** - * OrderServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class OrderServiceImpl implements OrderService { - - private static final DateTimeFormatter ORDER_NO_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); - private static final DateTimeFormatter APPOINTMENT_OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - /** - * Purpose: COUPON_SOURCE_NONE supports OrderServiceImpl.java by holding or executing the coupon source none business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String COUPON_SOURCE_NONE = "NONE"; - /** - * Purpose: COUPON_SOURCE_USER supports OrderServiceImpl.java by holding or executing the coupon source user business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String COUPON_SOURCE_USER = "USER_COUPON"; - /** - * Purpose: COUPON_SOURCE_SYSTEM_VIP supports OrderServiceImpl.java by holding or executing the coupon source system vip business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; - private static final int BOOKING_UNAVAILABLE_CODE = 409; - private static final String ISSUE_ORDER_ITEM = "ORDER_ITEM"; - private static final String ISSUE_PRODUCT_UNAVAILABLE = "PRODUCT_UNAVAILABLE"; - private static final String ISSUE_SHOP_MISMATCH = "SHOP_MISMATCH"; - private static final String ISSUE_ARTIST_UNAVAILABLE = "ARTIST_UNAVAILABLE"; - private static final String ISSUE_ARTIST_MISMATCH = "ARTIST_MISMATCH"; - private static final String ISSUE_APPOINTMENT_TIME = "APPOINTMENT_TIME"; - private static final String ISSUE_BUSINESS_HOURS = "BUSINESS_HOURS"; - private static final String ISSUE_ORDER_CONFLICT = "ORDER_CONFLICT"; - private static final String ISSUE_EXISTING_CONFLICT = "EXISTING_CONFLICT"; - private static final String QUOTE_STATUS_CONFIRMING = "CONFIRMING"; - private static final String QUOTE_STATUS_CONFIRMED = "CONFIRMED"; - private static final String QUOTE_STATUS_EXPIRED = "EXPIRED"; - private static final String QUOTE_ACTOR_USER = "USER"; - private static final String QUOTE_ACTOR_SHOP = "SHOP"; - private static final String QUOTE_ACTOR_SYSTEM = "SYSTEM"; - private static final String QUOTE_ACTION_CREATE = "CREATE"; - private static final String QUOTE_ACTION_SHOP_QUOTE = "SHOP_QUOTE"; - private static final String QUOTE_ACTION_USER_REPLY = "USER_REPLY"; - private static final String QUOTE_ACTION_USER_CONFIRM = "USER_CONFIRM"; - private static final String QUOTE_ACTION_SHOP_CONFIRM = "SHOP_CONFIRM"; - private static final String QUOTE_ACTION_SYSTEM_CONFIRM = "SYSTEM_CONFIRM"; - private static final String QUOTE_ACTION_SYSTEM_EXPIRE = "SYSTEM_EXPIRE"; - private static final String QUOTE_BUSINESS_TYPE = "ORDER_QUOTE"; - private static final int USER_TYPE_SHOP_OWNER = 2; - private static final int QUOTE_EXPIRE_HOURS = 24; - /** - * Purpose: REVIEW_STATUS_PENDING supports OrderServiceImpl.java by holding or executing the review status pending business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int REVIEW_STATUS_PENDING = 0; - /** - * Purpose: REVIEW_STATUS_SUBMITTED supports OrderServiceImpl.java by holding or executing the review status submitted business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int REVIEW_STATUS_SUBMITTED = 1; - /** - * Purpose: CHANGE_STATUS_PENDING supports OrderServiceImpl.java by holding or executing the change status pending business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHANGE_STATUS_PENDING = "PENDING"; - /** - * Purpose: CHANGE_STATUS_APPROVED supports OrderServiceImpl.java by holding or executing the change status approved business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHANGE_STATUS_APPROVED = "APPROVED"; - /** - * Purpose: CHANGE_STATUS_REJECTED supports OrderServiceImpl.java by holding or executing the change status rejected business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHANGE_STATUS_REJECTED = "REJECTED"; - /** - * Purpose: CHANGE_STATUS_EXPIRED supports OrderServiceImpl.java by holding or executing the change status expired business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHANGE_STATUS_EXPIRED = "EXPIRED"; - /** - * Purpose: ARTIST_CHANGE_PENDING_KEY_PREFIX supports OrderServiceImpl.java by holding or executing the artist change pending key prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String ARTIST_CHANGE_PENDING_KEY_PREFIX = "ORDER_ITEM:"; - /** - * Purpose: MESSAGE_TARGET_SELECTED_USERS supports OrderServiceImpl.java by holding or executing the message target selected users business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String MESSAGE_TARGET_SELECTED_USERS = "SELECTED_USERS"; - /** - * Purpose: REVIEW_BUSINESS_TYPE supports OrderServiceImpl.java by holding or executing the review business type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String REVIEW_BUSINESS_TYPE = "ORDER_ARTIST_REVIEW"; - /** - * Purpose: CHANGE_BUSINESS_TYPE supports OrderServiceImpl.java by holding or executing the change business type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String CHANGE_BUSINESS_TYPE = "ORDER_ARTIST_CHANGE"; - /** - * Purpose: ORDER_CREATE_USER_LOCK_PREFIX supports OrderServiceImpl.java by holding or executing the order create user lock prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:"; - /** - * Purpose: ORDER_CREATE_ARTIST_LOCK_PREFIX supports OrderServiceImpl.java by holding or executing the order create artist lock prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:"; - private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15); - private static final long ORDER_CREATE_LOCK_TTL_MILLIS = ORDER_CREATE_LOCK_TTL.toMillis(); - /** - * Purpose: ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS supports OrderServiceImpl.java by holding or executing the order create lock renew interval millis business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS = 5000L; - /** - * Purpose: ARTIST_LOCK_RETRY_INTERVAL_MILLIS supports OrderServiceImpl.java by holding or executing the artist lock retry interval millis business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long ARTIST_LOCK_RETRY_INTERVAL_MILLIS = 150L; - /** - * Purpose: ARTIST_LOCK_WAIT_TIMEOUT_MILLIS supports OrderServiceImpl.java by holding or executing the artist lock wait timeout millis business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long ARTIST_LOCK_WAIT_TIMEOUT_MILLIS = 1500L; - private static final List APPOINTMENT_INPUT_FORMATTERS = Arrays.asList( - DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), - DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"), - DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"), - DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm") - ); - private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)"); - private static final Pattern BUSINESS_HOURS_PATTERN = Pattern.compile("^(\\d{1,2}:\\d{2})\\s*[-~至]\\s*(\\d{1,2}:\\d{2})$"); - /** - * Purpose: DEFAULT_SERVICE_DURATION_MINUTES supports OrderServiceImpl.java by holding or executing the default service duration minutes business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L; - private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); - private static final DefaultRedisScript RENEW_LOCK_SCRIPT = new DefaultRedisScript<>(); - private static final ScheduledExecutorService LOCK_RENEW_EXECUTOR = Executors.newSingleThreadScheduledExecutor(new LockRenewThreadFactory()); - - static { - RELEASE_LOCK_SCRIPT.setScriptText( - "if redis.call('get', KEYS[1]) == ARGV[1] then " + - "return redis.call('del', KEYS[1]) " + - "else return 0 end" - ); - RELEASE_LOCK_SCRIPT.setResultType(Long.class); - - RENEW_LOCK_SCRIPT.setScriptText( - "if redis.call('get', KEYS[1]) == ARGV[1] then " + - "return redis.call('pexpire', KEYS[1], ARGV[2]) " + - "else return 0 end" - ); - RENEW_LOCK_SCRIPT.setResultType(Long.class); - } - - @Resource - /** - * Purpose: orderMapper supports OrderServiceImpl.java by holding or executing the order mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderMapper orderMapper; - - @Resource - /** - * Purpose: orderItemMapper supports OrderServiceImpl.java by holding or executing the order item mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderItemMapper orderItemMapper; - - @Resource - /** - * Purpose: orderArtistReviewMapper supports OrderServiceImpl.java by holding or executing the order artist review mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistReviewMapper orderArtistReviewMapper; - - @Resource - /** - * Purpose: orderArtistChangeRequestMapper supports OrderServiceImpl.java by holding or executing the order artist change request mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; - - @Resource - private OrderQuoteMessageMapper orderQuoteMessageMapper; - - @Resource - /** - * Purpose: cartMapper supports OrderServiceImpl.java by holding or executing the cart mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CartMapper cartMapper; - - @Resource - /** - * Purpose: productMapper supports OrderServiceImpl.java by holding or executing the product mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ProductMapper productMapper; - - @Resource - /** - * Purpose: couponMapper supports OrderServiceImpl.java by holding or executing the coupon mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CouponMapper couponMapper; - - @Resource - /** - * Purpose: nailArtistInfoMapper supports OrderServiceImpl.java by holding or executing the nail artist info mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private NailArtistInfoMapper nailArtistInfoMapper; - - @Resource - /** - * Purpose: userCouponMapper supports OrderServiceImpl.java by holding or executing the user coupon mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserCouponMapper userCouponMapper; - - @Resource - /** - * Purpose: userMapper supports OrderServiceImpl.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserMapper userMapper; - - @Resource - /** - * Purpose: shopMapper supports OrderServiceImpl.java by holding or executing the shop mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ShopMapper shopMapper; - - @Resource - /** - * Purpose: systemMessageMapper supports OrderServiceImpl.java by holding or executing the system message mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private SystemMessageMapper systemMessageMapper; - - @Resource - /** - * Purpose: couponService supports OrderServiceImpl.java by holding or executing the coupon service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private CouponService couponService; - - @Resource - /** - * Purpose: tagService supports OrderServiceImpl.java by holding or executing the tag service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private TagService tagService; - - @Resource - /** - * Purpose: userShopBindingSupport supports OrderServiceImpl.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private UserShopBindingSupport userShopBindingSupport; - - @Resource - /** - * Purpose: bookableArtistSupport supports OrderServiceImpl.java by holding or executing the bookable artist support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BookableArtistSupport bookableArtistSupport; - - @Resource - /** - * Purpose: businessEventOutboxService supports OrderServiceImpl.java by holding or executing the business event outbox service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BusinessEventOutboxService businessEventOutboxService; - - @Resource - /** - * Purpose: snowflakeIdGenerator supports OrderServiceImpl.java by holding or executing the snowflake id generator business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - - @Resource - /** - * Purpose: stringRedisTemplate supports OrderServiceImpl.java by holding or executing the string redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private StringRedisTemplate stringRedisTemplate; - - @Resource - /** - * Purpose: objectStorageUrlSupport supports OrderServiceImpl.java by holding or executing the object storage url support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ObjectStorageUrlSupport objectStorageUrlSupport; - - @Resource - /** - * Purpose: transactionTemplate supports OrderServiceImpl.java by holding or executing the transaction template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private TransactionTemplate transactionTemplate; - - @Resource - private AppointmentCapacityService appointmentCapacityService; - - @Resource - private AppointmentReservationMapper appointmentReservationMapper; - - @PreDestroy - /** - * Run business method `shutdownOrderLockRenewExecutor`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - */ - public void shutdownOrderLockRenewExecutor() { - LOCK_RENEW_EXECUTOR.shutdownNow(); - } - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param orderDTO parameter `orderDTO` supplied by the caller - * @return OrderVO result consumed by the caller or returned to the frontend - */ - public OrderVO createOrder(Long userId, OrderDTO orderDTO) { - if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw bookingUnavailable("订单项不能为空"); - } - - String userLockKey = ORDER_CREATE_USER_LOCK_PREFIX + userId; - String userLockToken = UUID.randomUUID().toString(); - if (!tryAcquireOrderLock(userLockKey, userLockToken)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单正在提交中,请勿重复点击"); - } - - LockLease userLockLease = startOrderLockRenewal(userLockKey, userLockToken); - - String artistLockKey = null; - String artistLockToken = null; - LockLease artistLockLease = null; - try { - Long artistId; - try { - artistId = resolveRequestedArtistId(orderDTO.getItems()); - } catch (RuntimeException exception) { - if (isBookingValidationMessage(exception.getMessage())) { - throw bookingUnavailable(exception.getMessage()); - } - throw exception; - } - artistLockKey = ORDER_CREATE_ARTIST_LOCK_PREFIX + artistId; - artistLockToken = UUID.randomUUID().toString(); - if (!tryAcquireArtistOrderLock(artistLockKey, artistLockToken)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw bookingUnavailable("当前美甲师预约繁忙,请稍后再试"); - } - - artistLockLease = startOrderLockRenewal(artistLockKey, artistLockToken); - - OrderVO orderVO = transactionTemplate.execute(status -> createOrderInTransaction(userId, orderDTO)); - if (orderVO == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单创建失败,请稍后重试"); - } - notifyQuoteCreated(orderVO); - return orderVO; - } finally { - /** - * Run business method `stopOrderLockRenewal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistLockLease parameter `artistLockLease` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - stopOrderLockRenewal(artistLockLease); - /** - * Run business method `releaseOrderLock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistLockKey parameter `artistLockKey` supplied by the caller - * @param artistLockToken parameter `artistLockToken` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - releaseOrderLock(artistLockKey, artistLockToken); - /** - * Run business method `stopOrderLockRenewal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userLockLease parameter `userLockLease` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - stopOrderLockRenewal(userLockLease); - /** - * Run business method `releaseOrderLock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userLockKey parameter `userLockKey` supplied by the caller - * @param userLockToken parameter `userLockToken` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - releaseOrderLock(userLockKey, userLockToken); - } - } - - @Override - public CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO) { - OrderDTO orderDTO = toOrderDTO(checkoutPreviewDTO); - CheckoutPricingContext pricingContext = buildCheckoutPricingContext(userId, orderDTO); - List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); - List availableCouponOptions = couponService.getAvailableCoupons( - userId, - pricingContext.getProductTagNames(), - pricingContext.getTotalAmount().doubleValue(), - pricingContext.getShopId() - ); - if (availableCouponOptions == null) { - availableCouponOptions = List.of(); - } - - List availableCoupons = availableCouponOptions.stream() - .map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount())) - .sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed() - .thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))) - .toList(); - - CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons); - if (bestCoupon != null) { - bestCoupon.setBest(true); - } - - CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon); - BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount()); - BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount); - if (payableAmount.compareTo(BigDecimal.ZERO) < 0) { - payableAmount = BigDecimal.ZERO; - } - - CheckoutPreviewVO preview = new CheckoutPreviewVO(); - preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount())); - preview.setSavedAmount(scaleMoney(savedAmount)); - preview.setPayableAmount(scaleMoney(payableAmount)); - preview.setBestCoupon(bestCoupon); - preview.setAvailableCoupons(availableCoupons); - preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext)); - preview.setBookingAvailable(bookingIssues.isEmpty()); - preview.setBookingIssues(bookingIssues); - preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons)); - preview.setSummaryText(buildCheckoutSummaryText(preview)); - return preview; - } - - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param orderDTO parameter `orderDTO` supplied by the caller - * @return private OrderVO result consumed by the caller or returned to the frontend - */ - private OrderVO createOrderInTransaction(Long userId, OrderDTO orderDTO) { - if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw bookingUnavailable("订单项不能为空"); - } - - List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); - if (!bookingIssues.isEmpty()) { - throw bookingUnavailable(bookingIssues.get(0).getMessage()); - } - - List orderItemDTOs = orderDTO.getItems(); - BigDecimal totalAmount = BigDecimal.ZERO; - List orderItems = new ArrayList<>(); - List requestedSlots = new ArrayList<>(); - Map productCache = new HashMap<>(); - Map shopCache = new HashMap<>(); - Set selectedTagNames = new LinkedHashSet<>(); - Long shopId = null; - Long selectedArtistId = null; - Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); - List requestedProductIds = new ArrayList<>(requestedQuantityByProductId.keySet()); - Map lockedCartItemMap = loadLockedCartItems(userId, requestedProductIds); - - try { - for (OrderItemDTO orderItemDTO : orderItemDTOs) { - validateOrderQuantity(orderItemDTO.getQuantity()); - - ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw bookingUnavailable("商品不存在或已下架"); - } - productCache.put(product.getId(), product); - - CartDO cartItem = lockedCartItemMap.get(orderItemDTO.getProductId()); - if (cartItem == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请先将商品加入购物车后再结算"); - } - Integer requestedQuantity = requestedQuantityByProductId.get(orderItemDTO.getProductId()); - if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); - } - - UserDO artist = validateArtistForProduct(product, orderItemDTO.getArtistId()); - - if (shopId == null) { - shopId = product.getShopId(); - /** - * Run business method `validateUserCanCreateOrderInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateUserCanCreateOrderInShop(userId, shopId); - } else if (!shopId.equals(product.getShopId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw bookingUnavailable("跨店铺商品请分开下单"); - } - - if (selectedArtistId == null) { - selectedArtistId = artist.getId(); - } else if (!selectedArtistId.equals(artist.getId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw bookingUnavailable("不同美甲师的项目请分开下单"); - } - - LocalDateTime appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime()); - validateAppointmentTime(appointmentTime, product.getTitle()); - - long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity(); - LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes); - validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle()); - requestedSlots.add(new AppointmentSlot(product.getTitle(), appointmentTime, appointmentEndTime)); - - collectTagNames(selectedTagNames, product.getTags()); - - BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(orderItemDTO.getQuantity())); - totalAmount = totalAmount.add(itemTotal); - - OrderItemDO orderItem = new OrderItemDO(); - orderItem.setProductId(product.getId()); - orderItem.setQuantity(orderItemDTO.getQuantity()); - orderItem.setPrice(product.getPrice()); - orderItem.setReferencePrice(product.getPrice()); - orderItem.setArtistId(orderItemDTO.getArtistId()); - orderItem.setAppointmentTime(appointmentTime); - orderItems.add(orderItem); - } - - /** - * Run business method `validateRequestedSlotConflicts`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestedSlots parameter `requestedSlots` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateRequestedSlotConflicts(requestedSlots); - /** - * Run business method `validateArtistScheduleConflicts`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param selectedArtistId parameter `selectedArtistId` supplied by the caller - * @param requestedSlots parameter `requestedSlots` supplied by the caller - * @param productCache parameter `productCache` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateArtistScheduleConflicts(selectedArtistId, requestedSlots, productCache); - } catch (BusinessException exception) { - throw exception; - } catch (RuntimeException exception) { - if (isBookingValidationMessage(exception.getMessage())) { - throw bookingUnavailable(exception.getMessage()); - } - throw exception; - } - - if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单金额无效"); - } - - String productTagNames = String.join(",", selectedTagNames); - List availableCouponOptions = couponService.getAvailableCoupons( - userId, - productTagNames, - totalAmount.doubleValue(), - shopId - ); - - BigDecimal actualAmount = totalAmount; - Long couponId = null; - Long userCouponId = null; - String couponSourceType = null; - - CouponSelection couponSelection = resolveRequestedCoupon(orderDTO, availableCouponOptions); - if (couponSelection == null && !isExplicitNoCoupon(orderDTO)) { - couponSelection = selectBestAvailableCoupon(availableCouponOptions, totalAmount); - } - - if (couponSelection != null) { - CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); - if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete()) || coupon.getStatus() != 1) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("优惠券不存在或已失效"); - } - if (shopId != null && coupon.getShopId() != null && !shopId.equals(coupon.getShopId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该优惠券不适用于当前店铺"); - } - - actualAmount = applyCouponDiscount(totalAmount, coupon); - couponId = coupon.getId(); - userCouponId = couponSelection.getUserCouponId(); - couponSourceType = couponSelection.getSourceType(); - - } - - String orderNo = "ORD" + snowflakeIdGenerator.nextIdString(); - - OrderDO order = new OrderDO(); - order.setOrderNo(orderNo); - order.setUserId(userId); - order.setShopId(shopId); - order.setTotalAmount(totalAmount); - order.setActualAmount(actualAmount); - order.setCouponId(couponId); - order.setUserCouponId(userCouponId); - order.setCouponSourceType(couponSourceType); - order.setCustomerRemark(trimToNull(orderDTO.getRemark())); - order.setQuoteStatus(QUOTE_STATUS_CONFIRMING); - order.setQuoteUserConfirmed(0); - order.setQuoteShopConfirmed(0); - order.setQuoteExpireTime(LocalDateTime.now().plusHours(QUOTE_EXPIRE_HOURS)); - order.setPaymentStatus("UNPAID"); - order.setPayAmount(actualAmount); - order.setPaidAmount(BigDecimal.ZERO); - order.setStatus(OrderStatus.PRICE_CONFIRMING.getCode()); - order.setIsDelete(0); - orderMapper.insert(order); - - for (OrderItemDO item : orderItems) { - item.setOrderId(order.getId()); - item.setIsDelete(0); - orderItemMapper.insert(item); - ProductDO product = productCache.get(item.getProductId()); - long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - appointmentCapacityService.reservePendingQuoteOrThrow( - order.getId(), - item.getId(), - order.getShopId(), - item.getArtistId(), - product == null ? null : product.getTitle(), - item.getAppointmentTime(), - item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes), - trimToNull(orderDTO.getClientRequestId()) - ); - } - writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_CREATE, order.getCustomerRemark()); - - QueryWrapper cartWrapper = new QueryWrapper<>(); - cartWrapper.eq("user_id", userId) - .eq("is_delete", 0) - .in("product_id", requestedProductIds); - cartMapper.delete(cartWrapper); - - /** - * Run business method `buildOrderVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildOrderVO(order); - } - - private OrderDTO toOrderDTO(CheckoutPreviewDTO checkoutPreviewDTO) { - OrderDTO orderDTO = new OrderDTO(); - if (checkoutPreviewDTO == null) { - return orderDTO; - } - orderDTO.setCouponId(checkoutPreviewDTO.getCouponId()); - orderDTO.setCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); - orderDTO.setRemark(checkoutPreviewDTO.getRemark()); - orderDTO.setItems(checkoutPreviewDTO.getItems()); - return orderDTO; - } - - private CheckoutPricingContext buildCheckoutPricingContext(Long userId, OrderDTO orderDTO) { - if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { - throw new RuntimeException("订单项不能为空"); - } - - List orderItemDTOs = orderDTO.getItems(); - Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); - BigDecimal totalAmount = BigDecimal.ZERO; - Set selectedTagNames = new LinkedHashSet<>(); - Long shopId = null; - - for (OrderItemDTO orderItemDTO : orderItemDTOs) { - validateOrderQuantity(orderItemDTO.getQuantity()); - ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - throw new RuntimeException("商品不存在或已下架"); - } - - CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId()); - Integer requestedQuantity = requestedQuantityByProductId.get(product.getId()); - if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) { - throw new RuntimeException("请先将商品加入购物车后再结算"); - } - if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { - throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); - } - - if (shopId == null) { - shopId = product.getShopId(); - validateUserCanCreateOrderInShop(userId, shopId); - } else if (!shopId.equals(product.getShopId())) { - throw new RuntimeException("跨店铺商品请分开下单"); - } - - collectPreviewTagNames(selectedTagNames, product.getTags()); - BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()))); - } - - if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { - throw new RuntimeException("订单金额无效"); - } - return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames)); - } - - private List collectCheckoutBookingIssues(Long userId, OrderDTO orderDTO) { - List issues = new ArrayList<>(); - if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { - issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单项不能为空", (OrderItemDTO) null, (ProductDO) null)); - return issues; - } - - Map productCache = new HashMap<>(); - Map shopCache = new HashMap<>(); - List requestedSlots = new ArrayList<>(); - Long shopId = null; - Long selectedArtistId = null; - - for (OrderItemDTO orderItemDTO : orderDTO.getItems()) { - if (orderItemDTO == null || orderItemDTO.getProductId() == null) { - issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单项信息不完整", orderItemDTO, null)); - continue; - } - - ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - issues.add(checkoutIssue(ISSUE_PRODUCT_UNAVAILABLE, "商品不存在或已下架", orderItemDTO, null)); - continue; - } - productCache.put(product.getId(), product); - - if (orderItemDTO.getQuantity() == null || orderItemDTO.getQuantity() < 1) { - issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单商品数量必须大于 0", orderItemDTO, product)); - continue; - } - - if (shopId == null) { - shopId = product.getShopId(); - } else if (!Objects.equals(shopId, product.getShopId())) { - issues.add(checkoutIssue(ISSUE_SHOP_MISMATCH, "跨店铺商品请分开下单", orderItemDTO, product)); - } - - UserDO artist = null; - try { - artist = validateArtistForProduct(product, orderItemDTO.getArtistId()); - } catch (RuntimeException exception) { - issues.add(checkoutIssue(ISSUE_ARTIST_UNAVAILABLE, bookingMessage(exception, "美甲师当前不可预约"), orderItemDTO, product)); - } - - if (artist != null) { - if (selectedArtistId == null) { - selectedArtistId = artist.getId(); - } else if (!selectedArtistId.equals(artist.getId())) { - issues.add(checkoutIssue(ISSUE_ARTIST_MISMATCH, "不同美甲师的项目请分开下单", orderItemDTO, product)); - } - } - - LocalDateTime appointmentTime; - try { - appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime()); - validateAppointmentTime(appointmentTime, product.getTitle()); - } catch (RuntimeException exception) { - issues.add(checkoutIssue(ISSUE_APPOINTMENT_TIME, bookingMessage(exception, "预约时间不正确"), orderItemDTO, product)); - continue; - } - - long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity(); - LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes); - try { - validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle()); - } catch (RuntimeException exception) { - issues.add(checkoutIssue(ISSUE_BUSINESS_HOURS, bookingMessage(exception, "预约时间超出门店营业时间"), orderItemDTO, product)); - continue; - } - - requestedSlots.add(new BookingValidationSlot( - orderItemDTO.getProductId(), - product.getTitle(), - appointmentTime, - appointmentEndTime - )); - } - - collectRequestedSlotIssues(requestedSlots, issues); - collectExistingAppointmentIssues(selectedArtistId, requestedSlots, productCache, issues); - return issues; - } - - private void collectRequestedSlotIssues(List requestedSlots, List issues) { - if (requestedSlots.size() <= 1) { - return; - } - - List sortedSlots = new ArrayList<>(requestedSlots); - sortedSlots.sort(Comparator.comparing(BookingValidationSlot::getStartTime)); - for (int i = 1; i < sortedSlots.size(); i++) { - BookingValidationSlot previous = sortedSlots.get(i - 1); - BookingValidationSlot current = sortedSlots.get(i); - if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) { - issues.add(checkoutIssue( - ISSUE_ORDER_CONFLICT, - "所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间", - current.getProductId(), - current.getProductTitle() - )); - } - } - } - - private void collectExistingAppointmentIssues(Long artistId, - List requestedSlots, - Map productCache, - List issues) { - if (artistId == null || requestedSlots.isEmpty()) { - return; - } - - Set occupiedSlotKeys = new LinkedHashSet<>(); - for (BookingValidationSlot requestedSlot : requestedSlots) { - int activeOccupancyCount = appointmentReservationMapper.countOverlappingActive( - artistId, - requestedSlot.getStartTime(), - requestedSlot.getEndTime() - ); - if (activeOccupancyCount > 0) { - occupiedSlotKeys.add(bookingSlotKey(requestedSlot)); - issues.add(checkoutIssue( - ISSUE_EXISTING_CONFLICT, - "商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约占用冲突,请重新选择", - requestedSlot.getProductId(), - requestedSlot.getProductTitle() - )); - } - } - - List existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId); - if (existingAppointments == null || existingAppointments.isEmpty()) { - return; - } - - for (OrderItemDO existingItem : existingAppointments) { - if (existingItem == null || existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) { - continue; - } - - ProductDO existingProduct = getProductForBookingCheck(existingItem.getProductId(), productCache); - if (existingProduct == null) { - continue; - } - - int existingQuantity = existingItem.getQuantity() == null ? 1 : Math.max(1, existingItem.getQuantity()); - long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * existingQuantity; - LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes); - - for (BookingValidationSlot requestedSlot : requestedSlots) { - if (occupiedSlotKeys.contains(bookingSlotKey(requestedSlot))) { - continue; - } - if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) { - issues.add(checkoutIssue( - ISSUE_EXISTING_CONFLICT, - "商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择", - requestedSlot.getProductId(), - requestedSlot.getProductTitle() - )); - } - } - } - } - - private String bookingSlotKey(BookingValidationSlot requestedSlot) { - return requestedSlot.getProductId() + "|" + requestedSlot.getStartTime() + "|" + requestedSlot.getEndTime(); - } - - private ProductDO getProductForBookingCheck(Long productId, Map productCache) { - if (productId == null) { - return null; - } - if (productCache.containsKey(productId)) { - return productCache.get(productId); - } - - ProductDO product = productMapper.selectById(productId); - if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) { - product = null; - } - productCache.put(productId, product); - return product; - } - - private CheckoutIssueVO checkoutIssue(String code, String message, OrderItemDTO orderItemDTO, ProductDO product) { - Long productId = product == null ? orderItemDTO == null ? null : orderItemDTO.getProductId() : product.getId(); - String productTitle = product == null ? "订单项" : resolveProductTitle(product); - return checkoutIssue(code, message, productId, productTitle); - } - - private CheckoutIssueVO checkoutIssue(String code, String message, Long productId, String productTitle) { - CheckoutIssueVO issue = new CheckoutIssueVO(); - issue.setCode(code); - issue.setMessage(normalizeBookingMessage(message)); - issue.setProductId(productId); - issue.setProductTitle(StringUtils.hasText(productTitle) ? productTitle : "订单项"); - return issue; - } - - private String resolveProductTitle(ProductDO product) { - return product != null && StringUtils.hasText(product.getTitle()) ? product.getTitle() : "订单项"; - } - - private String bookingMessage(RuntimeException exception, String fallbackMessage) { - if (exception != null && StringUtils.hasText(exception.getMessage())) { - return exception.getMessage(); - } - return fallbackMessage; - } - - private BusinessException bookingUnavailable(String message) { - return new BusinessException(BOOKING_UNAVAILABLE_CODE, normalizeBookingMessage(message)); - } - - private boolean isBookingValidationMessage(String message) { - if (!StringUtils.hasText(message)) { - return false; - } - return message.contains("订单项") - || message.contains("订单商品数量") - || message.contains("商品不存在") - || message.contains("跨店铺") - || message.contains("美甲师") - || message.contains("预约时间") - || message.contains("不可预约") - || message.contains("冲突") - || message.contains("營業時間") - || message.contains("营业时间") - || message.contains("涓嶅彲棰勭害") - || message.contains("宸茬害婊") - || message.contains("褰撳墠缇庣敳甯堣"); - } - - private String normalizeBookingMessage(String message) { - if (!StringUtils.hasText(message)) { - return "当前预约不可用,请重新选择预约时间"; - } - - String normalized = message.trim(); - if (normalized.contains("涓嶅彲棰勭害")) { - return "当前美甲师该时段不可预约,请重新选择预约时间"; - } - if (normalized.contains("宸茬害婊") || normalized.contains("褰撳墠缇庣敳甯堣")) { - return "当前美甲师该时间段已约满,请重新选择预约时间"; - } - return normalized; - } - - private void collectPreviewTagNames(Set tagNames, String tags) { - if (tagNames == null || tags == null || tags.isBlank()) { - return; - } - for (String rawTag : tags.split("[,;]")) { - if (rawTag == null || rawTag.isBlank()) { - continue; - } - String tagText = rawTag.trim(); - try { - Long tagId = Long.parseLong(tagText); - if (tagService != null) { - TagVO tagVO = tagService.getTagById(tagId); - if (tagVO != null && StringUtils.hasText(tagVO.getTagName())) { - tagNames.add(tagVO.getTagName()); - } - } - } catch (NumberFormatException ignored) { - tagNames.add(tagText); - } - } - } - - private CheckoutCouponPreviewVO buildAvailableCouponPreview(UserCouponVO coupon, BigDecimal totalAmount) { - CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); - preview.setId(coupon.getId()); - preview.setCouponId(coupon.getCouponId()); - preview.setUserCouponId(COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null); - preview.setSourceType(coupon.getSourceType()); - preview.setCouponName(coupon.getCouponName()); - preview.setCouponType(coupon.getCouponType()); - preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); - preview.setDiscountValue(parseMoney(coupon.getDiscountValue())); - preview.setMinAmount(parseMoney(coupon.getMinAmount())); - preview.setReduceAmount(parseMoney(coupon.getReduceAmount())); - preview.setDiscountAmount(capDiscount(calculateCouponDiscountAmount(coupon, totalAmount), totalAmount)); - preview.setAvailable(true); - preview.setBest(false); - preview.setVipAuto(COUPON_SOURCE_SYSTEM_VIP.equals(coupon.getSourceType())); - preview.setDisplayText(buildCouponDisplayText(preview)); - preview.setSavingText(buildSavingText(preview.getDiscountAmount())); - preview.setStartTime(coupon.getStartTime()); - preview.setEndTime(coupon.getEndTime()); - return preview; - } - - private CheckoutCouponPreviewVO findBestCouponPreview(List availableCoupons) { - if (availableCoupons == null || availableCoupons.isEmpty()) { - return null; - } - return availableCoupons.stream() - .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) - .orElse(null); - } - - private CheckoutCouponPreviewVO resolvePreviewSelectedCoupon(CheckoutPreviewDTO checkoutPreviewDTO, - List availableCoupons, - CheckoutCouponPreviewVO bestCoupon) { - if (checkoutPreviewDTO != null - && checkoutPreviewDTO.getCouponId() == null - && COUPON_SOURCE_NONE.equalsIgnoreCase(checkoutPreviewDTO.getCouponSourceType())) { - return null; - } - if (checkoutPreviewDTO == null || checkoutPreviewDTO.getCouponId() == null || checkoutPreviewDTO.getCouponId() <= 0) { - return bestCoupon; - } - - String requestedSourceType = normalizeCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); - return availableCoupons.stream() - .filter(coupon -> checkoutPreviewDTO.getCouponId().equals(coupon.getId())) - .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) - .findFirst() - .orElseThrow(() -> new RuntimeException("当前订单不可使用所选优惠券")); - } - - private List buildUnavailableCouponPreviews(List availableCoupons, - CheckoutPricingContext pricingContext) { - Set availableCouponIds = availableCoupons == null ? Collections.emptySet() : availableCoupons.stream() - .map(CheckoutCouponPreviewVO::getCouponId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - List coupons = couponMapper.selectList(new LambdaQueryWrapper() - .eq(CouponDO::getIsDelete, 0)); - if (coupons == null || coupons.isEmpty()) { - return List.of(); - } - - LocalDateTime now = LocalDateTime.now(); - return coupons.stream() - .filter(coupon -> coupon != null && coupon.getId() != null) - .filter(coupon -> !availableCouponIds.contains(coupon.getId())) - .map(coupon -> buildUnavailableCouponPreview(coupon, pricingContext, now)) - .filter(Objects::nonNull) - .toList(); - } - - private CheckoutCouponPreviewVO buildUnavailableCouponPreview(CouponDO coupon, - CheckoutPricingContext pricingContext, - LocalDateTime now) { - String reason = resolveUnavailableCouponReason(coupon, pricingContext, now); - if (!StringUtils.hasText(reason)) { - reason = "本单暂不可用"; - } - - CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); - preview.setId(coupon.getId()); - preview.setCouponId(coupon.getId()); - preview.setSourceType(isVipAutoCoupon(coupon) ? COUPON_SOURCE_SYSTEM_VIP : COUPON_SOURCE_USER); - preview.setCouponName(coupon.getCouponName()); - preview.setCouponType(coupon.getCouponType()); - preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); - preview.setDiscountValue(coupon.getDiscountValue()); - preview.setMinAmount(coupon.getMinAmount()); - preview.setReduceAmount(coupon.getReduceAmount()); - preview.setDiscountAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); - preview.setAvailable(false); - preview.setBest(false); - preview.setVipAuto(isVipAutoCoupon(coupon)); - preview.setDisplayText(buildCouponDisplayText(preview)); - preview.setUnavailableReason(reason); - preview.setStartTime(coupon.getStartTime()); - preview.setEndTime(coupon.getEndTime()); - return preview; - } - - private String resolveUnavailableCouponReason(CouponDO coupon, CheckoutPricingContext pricingContext, LocalDateTime now) { - if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete())) { - return "优惠券已失效"; - } - if (coupon.getStatus() == null || coupon.getStatus() != 1) { - return "优惠券已失效"; - } - if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) { - return "还未到可用时间"; - } - if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) { - return "优惠券已过期"; - } - if (coupon.getShopId() != null - && pricingContext.getShopId() != null - && !coupon.getShopId().equals(pricingContext.getShopId())) { - return "仅限其他门店使用"; - } - if (Integer.valueOf(2).equals(coupon.getCouponType()) - && coupon.getMinAmount() != null - && coupon.getMinAmount().compareTo(pricingContext.getTotalAmount()) > 0) { - return "还差 " + formatMoney(coupon.getMinAmount().subtract(pricingContext.getTotalAmount())) + " 可用"; - } - return "本单商品暂不适用"; - } - - private String buildVipTip(Long userId, BigDecimal totalAmount, List availableCoupons) { - CheckoutCouponPreviewVO vipCoupon = availableCoupons == null ? null : availableCoupons.stream() - .filter(coupon -> Boolean.TRUE.equals(coupon.getVipAuto())) - .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) - .orElse(null); - UserDO userDO = userMapper.selectById(userId); - String vipLevel = userDO == null ? null : userDO.getLevel(); - if (vipCoupon != null && safeAmount(vipCoupon.getDiscountAmount()).compareTo(BigDecimal.ZERO) > 0) { - String levelText = StringUtils.hasText(vipLevel) ? vipLevel + "VIP" : "VIP"; - return levelText + "本单可省 " + formatMoney(vipCoupon.getDiscountAmount()) + ",已为你计算。"; - } - if (StringUtils.hasText(vipLevel) && !"普通".equals(vipLevel)) { - return vipLevel + "VIP暂无本单可用自动优惠,已为你保留其他可用优惠。"; - } - if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) { - return "开通VIP后,可在结算页自动匹配VIP优惠。"; - } - return null; - } - - private String buildCheckoutSummaryText(CheckoutPreviewVO preview) { - return "参考价小计 " + formatMoney(preview.getSubtotalAmount()) - + ",预估优惠 " + formatMoney(preview.getSavedAmount()) - + ",预估应付 " + formatMoney(preview.getPayableAmount()) + "。"; - } - - private String buildCouponDisplayText(CheckoutCouponPreviewVO coupon) { - String prefix = Boolean.TRUE.equals(coupon.getVipAuto()) ? "VIP自动优惠" : "优惠券"; - String benefit; - if (Integer.valueOf(1).equals(coupon.getCouponType()) && coupon.getDiscountValue() != null) { - benefit = coupon.getDiscountValue().stripTrailingZeros().toPlainString() + "折"; - } else if (Integer.valueOf(2).equals(coupon.getCouponType())) { - benefit = "满" + formatMoneyValue(coupon.getMinAmount()) + "减" + formatMoneyValue(coupon.getReduceAmount()); - } else { - benefit = "优惠"; - } - return prefix + ":" + coupon.getCouponName() + "," + benefit; - } - - private String buildSavingText(BigDecimal discountAmount) { - BigDecimal amount = safeAmount(discountAmount); - if (amount.compareTo(BigDecimal.ZERO) <= 0) { - return "本单暂不省钱"; - } - return "本单可省 " + formatMoney(amount); - } - - private boolean isVipAutoCoupon(CouponDO coupon) { - return coupon != null - && Integer.valueOf(1).equals(coupon.getAutoMatch()) - && "VIP_AUTO".equals(coupon.getCouponScene()); - } - - private String resolveCouponTypeName(Integer couponType) { - if (Integer.valueOf(1).equals(couponType)) { - return "折扣券"; - } - if (Integer.valueOf(2).equals(couponType)) { - return "满减券"; - } - return "优惠券"; - } - - private BigDecimal parseMoney(String value) { - if (!StringUtils.hasText(value)) { - return null; - } - try { - return new BigDecimal(value.trim()); - } catch (NumberFormatException exception) { - return null; - } - } - - private BigDecimal capDiscount(BigDecimal discountAmount, BigDecimal totalAmount) { - BigDecimal discount = safeAmount(discountAmount); - BigDecimal total = safeAmount(totalAmount); - if (discount.compareTo(total) > 0) { - return scaleMoney(total); - } - return scaleMoney(discount); - } - - private BigDecimal safeAmount(BigDecimal amount) { - return amount == null ? BigDecimal.ZERO : amount; - } - - private BigDecimal scaleMoney(BigDecimal amount) { - return safeAmount(amount).setScale(2, RoundingMode.HALF_UP); - } - - private String formatMoney(BigDecimal amount) { - return "¥" + scaleMoney(amount).toPlainString(); - } - - private String formatMoneyValue(BigDecimal amount) { - return scaleMoney(amount).stripTrailingZeros().toPlainString(); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getOrderList(Long userId) { - List orderList = orderMapper.selectByUserId(userId); - List orderVOList = new ArrayList<>(); - for (OrderDO order : orderList) { - if (!Integer.valueOf(1).equals(order.getIsDelete())) { - orderVOList.add(buildOrderVO(order)); - } - } - return orderVOList; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return OrderVO result consumed by the caller or returned to the frontend - */ - public OrderVO getOrderDetail(Long orderId, Long userId) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单不存在"); - } - if (!order.getUserId().equals(userId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权查看此订单"); - } - /** - * Run business method `buildOrderVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildOrderVO(order); - } - - @Override - @Transactional - /** - * Run business method `cancelOrder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - */ - public void cancelOrder(Long orderId, Long userId) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单不存在"); - } - if (!order.getUserId().equals(userId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无权操作此订单"); - } - if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) - && !Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单状态不允许取消"); - } - - OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.CANCELLED.getCode()); - order.setStatus(3); - if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { - order.setQuoteStatus(QUOTE_STATUS_EXPIRED); - order.setQuoteUserConfirmed(0); - order.setQuoteShopConfirmed(0); - writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_SYSTEM_EXPIRE, "用户取消询价预约"); - } - orderMapper.updateById(order); - appointmentCapacityService.releaseByOrder(orderId); - /** - * Run business method `restoreUserCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - restoreUserCoupon(order, userId); - } - - @Override - @Transactional - /** - * Run business method `processOrder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param status parameter `status` supplied by the caller - */ - public void processOrder(Long orderId, Integer status) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单不存在"); - } - if (status != 2 && status != 3) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("无效的订单状态"); - } - OrderStatus targetStatus = OrderStatus.requireKnown(status); - if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) - && !(Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) - && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status))) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单状态不允许处理"); - } - - OrderStateMachine.requireAllowedTransition(order.getStatus(), status); - if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), status) == 0) { - throw new RuntimeException("订单状态已变化,请刷新后重试"); - } - order.setStatus(status); - if (targetStatus == OrderStatus.COMPLETED) { - businessEventOutboxService.enqueueOrderCompleted(order.getId()); - } - if (targetStatus == OrderStatus.CANCELLED) { - appointmentCapacityService.releaseByOrder(order.getId()); - restoreUserCoupon(order, order.getUserId()); - if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { - order.setQuoteStatus(QUOTE_STATUS_EXPIRED); - order.setQuoteUserConfirmed(0); - order.setQuoteShopConfirmed(0); - orderMapper.updateById(order); - writeQuoteMessage(order.getId(), 0L, QUOTE_ACTOR_SYSTEM, QUOTE_ACTION_SYSTEM_EXPIRE, "询价预约已取消"); - } - } - } - - @Override - @Transactional - /** - * Complete a business action. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderId parameter `orderId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - */ - public void completeArtistOrder(Long orderId, Long artistId) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单不存在"); - } - if (order.getStatus() != 1) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前订单状态不允许完成"); - } - - List activeItems = orderItemMapper.selectByOrderId(orderId).stream() - .filter(item -> !Integer.valueOf(1).equals(item.getIsDelete())) - .toList(); - if (activeItems.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单商品不存在"); - } - - boolean allBelongToArtist = activeItems.stream().allMatch(item -> artistId.equals(item.getArtistId())); - if (!allBelongToArtist) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只能完成全部由自己承接的订单"); - } - - OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.COMPLETED.getCode()); - if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.COMPLETED.getCode()) == 0) { - throw new RuntimeException("订单状态已变化,请刷新后重试"); - } - order.setStatus(OrderStatus.COMPLETED.getCode()); - businessEventOutboxService.enqueueOrderCompleted(order.getId()); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List getAllOrders() { - List orderList = orderMapper.selectList(new QueryWrapper().eq("is_delete", 0)); - List orderVOList = new ArrayList<>(); - for (OrderDO order : orderList) { - orderVOList.add(buildOrderVO(order)); - } - return orderVOList; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistId parameter `artistId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getOrdersByArtistId(Long artistId) { - List orderList = orderMapper.selectByArtistId(artistId); - List orderVOList = new ArrayList<>(); - for (OrderDO order : orderList) { - OrderVO orderVO = buildOrderVO(order, artistId); - if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { - orderVOList.add(orderVO); - } - } - return orderVOList; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistId parameter `artistId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getArtistWorkbenchOrders(Long artistId) { - Map orderMap = new LinkedHashMap<>(); - List serviceOrders = orderMapper.selectByArtistId(artistId); - for (OrderDO order : serviceOrders) { - OrderVO orderVO = buildOrderVO(order, artistId); - if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { - orderVO.setArtistOrderSource("SERVICE"); - orderVO.setArtistOrderSourceText("客户预约我的订单"); - orderMap.put(orderVO.getId(), orderVO); - } - } - - List selfOrders = orderMapper.selectByUserId(artistId); - for (OrderDO order : selfOrders) { - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - continue; - } - OrderVO existing = orderMap.get(order.getId()); - if (existing != null) { - existing.setArtistOrderSource("BOTH"); - existing.setArtistOrderSourceText("我下的订单 / 客户预约我的订单"); - continue; - } - OrderVO orderVO = buildOrderVO(order); - orderVO.setArtistOrderSource("SELF"); - orderVO.setArtistOrderSourceText("我下的订单"); - orderMap.put(orderVO.getId(), orderVO); - } - - return orderMap.values().stream() - .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) - .toList(); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @param days parameter `days` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getArtistCalendarRecent(Long userId, Integer userType, Integer days) { - /** - * Run business method `ensureCalendarAccess`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureCalendarAccess(userId, userType); - int normalizedDays = days == null ? 7 : Math.max(1, Math.min(days, 31)); - LocalDate startDate = LocalDate.now(); - return listArtistCalendarAppointments(userId, startDate.atStartOfDay(), startDate.plusDays(normalizedDays).atStartOfDay()); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @param date parameter `date` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List getArtistCalendarDay(Long userId, Integer userType, LocalDate date) { - /** - * Run business method `ensureCalendarAccess`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureCalendarAccess(userId, userType); - LocalDate targetDate = date == null ? LocalDate.now() : date; - return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay()); - } - - @Override - /** - * Purpose: listMyPendingReviews supports OrderServiceImpl.java by holding or executing the list my pending reviews business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listMyPendingReviews(Long userId) { - return orderArtistReviewMapper.selectPendingByUserId(userId).stream() - .map(this::buildArtistReviewVO) - .toList(); - } - - @Override - /** - * Purpose: listOrderReviews supports OrderServiceImpl.java by holding or executing the list order reviews business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listOrderReviews(Long orderId, Long userId, Integer userType) { - OrderDO order = requireActiveOrder(orderId); - if (!canAccessOrder(order, userId, userType)) { - throw new RuntimeException("无权查看该订单评价"); - } - return orderArtistReviewMapper.selectByOrderId(orderId).stream() - .map(this::buildArtistReviewVO) - .toList(); - } - - @Override - @Transactional - /** - * Purpose: submitArtistReview supports OrderServiceImpl.java by holding or executing the submit artist review business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto) { - OrderArtistReviewDO review = orderArtistReviewMapper.selectById(reviewId); - if (review == null || Integer.valueOf(1).equals(review.getIsDelete())) { - throw new RuntimeException("评价任务不存在"); - } - if (!Objects.equals(userId, review.getCustomerId())) { - throw new RuntimeException("只能提交自己的评价"); - } - if (!Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) { - throw new RuntimeException("评价已提交,不能重复提交"); - } - - BigDecimal rating = normalizeReviewRating(dto == null ? null : dto.getRating()); - review.setRatingScore(rating); - review.setContent(trimToNull(dto == null ? null : dto.getContent())); - review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds())); - review.setStatus(REVIEW_STATUS_SUBMITTED); - review.setSubmittedAt(LocalDateTime.now()); - orderArtistReviewMapper.updateById(review); - refreshArtistRating(review.getArtistId()); - return buildArtistReviewVO(review); - } - - @Override - @Transactional - public OrderVO submitShopQuote(Long orderId, Long operatorId, Integer operatorType, OrderQuoteSubmitDTO dto) { - OrderDO order = requireQuoteOrder(orderId); - ensureShopQuoteOperator(order, operatorId, operatorType); - if (dto == null || dto.getItems() == null || dto.getItems().isEmpty()) { - throw new RuntimeException("请至少填写一个作品报价"); - } - - Map itemMap = loadActiveOrderItemMap(order.getId()); - for (OrderQuoteItemDTO quoteItem : dto.getItems()) { - if (quoteItem == null || quoteItem.getOrderItemId() == null) { - continue; - } - OrderItemDO item = itemMap.get(quoteItem.getOrderItemId()); - if (item == null) { - throw new RuntimeException("报价作品不属于当前订单"); - } - BigDecimal quotedPrice = normalizeQuotePrice(quoteItem.getQuotedPrice()); - item.setQuotedPrice(quotedPrice); - if (item.getReferencePrice() == null) { - item.setReferencePrice(item.getPrice()); - } - orderItemMapper.updateById(item); - } - ensureAllItemsQuoted(order.getId()); - - order.setQuoteStatus(QUOTE_STATUS_CONFIRMING); - order.setQuoteShopConfirmed(1); - order.setQuoteUserConfirmed(0); - orderMapper.updateById(order); - writeQuoteMessage(order.getId(), operatorId, QUOTE_ACTOR_SHOP, QUOTE_ACTION_SHOP_QUOTE, trimToNull(dto.getRemark())); - notifyQuoteUser(order, "门店已回复询价预约", "门店已回复您的询价预约,请查看并确认价格。"); - return buildOrderVO(orderMapper.selectById(order.getId())); - } - - @Override - @Transactional - public OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType) { - OrderDO order = requireQuoteOrder(orderId); - ensureShopQuoteOperator(order, operatorId, operatorType); - ensureAllItemsQuoted(order.getId()); - order.setQuoteShopConfirmed(1); - orderMapper.updateById(order); - writeQuoteMessage(order.getId(), operatorId, QUOTE_ACTOR_SHOP, QUOTE_ACTION_SHOP_CONFIRM, "店长确认当前报价"); - if (Integer.valueOf(1).equals(order.getQuoteUserConfirmed())) { - return finalizeConfirmedQuote(order, operatorId, QUOTE_ACTOR_SHOP); - } - notifyQuoteUser(order, "门店已确认询价价格", "门店已确认当前询价价格,请查看并确认。"); - return buildOrderVO(orderMapper.selectById(order.getId())); - } - - @Override - @Transactional - public OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto) { - OrderDO order = requireQuoteOrder(orderId); - ensureQuoteOwner(order, userId); - order.setQuoteUserConfirmed(0); - order.setQuoteShopConfirmed(0); - orderMapper.updateById(order); - String remark = trimToNull(dto == null ? null : dto.getRemark()); - writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_USER_REPLY, remark); - notifyQuoteShopAndArtist(order, "用户已回复询价预约", "用户已回复询价预约,请查看备注并继续确认价格。"); - return buildOrderVO(orderMapper.selectById(order.getId())); - } - - @Override - @Transactional - public OrderVO confirmUserQuote(Long orderId, Long userId) { - OrderDO order = requireQuoteOrder(orderId); - ensureQuoteOwner(order, userId); - ensureAllItemsQuoted(order.getId()); - order.setQuoteUserConfirmed(1); - orderMapper.updateById(order); - writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_USER_CONFIRM, "用户确认当前报价"); - if (Integer.valueOf(1).equals(order.getQuoteShopConfirmed())) { - return finalizeConfirmedQuote(order, userId, QUOTE_ACTOR_USER); - } - notifyQuoteShopAndArtist(order, "用户已确认询价价格", "用户已确认当前价格,请店长完成确认。"); - return buildOrderVO(orderMapper.selectById(order.getId())); - } - - @Override - @Transactional - public int expirePendingQuoteOrders() { - LocalDateTime now = LocalDateTime.now(); - List expiredOrders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(OrderDO::getStatus, OrderStatus.PRICE_CONFIRMING.getCode()) - .eq(OrderDO::getQuoteStatus, QUOTE_STATUS_CONFIRMING) - .le(OrderDO::getQuoteExpireTime, now) - .eq(OrderDO::getIsDelete, 0)); - int expiredCount = 0; - for (OrderDO order : expiredOrders) { - order.setStatus(OrderStatus.CANCELLED.getCode()); - order.setQuoteStatus(QUOTE_STATUS_EXPIRED); - order.setQuoteUserConfirmed(0); - order.setQuoteShopConfirmed(0); - orderMapper.updateById(order); - appointmentCapacityService.releaseByOrder(order.getId()); - writeQuoteMessage(order.getId(), 0L, QUOTE_ACTOR_SYSTEM, QUOTE_ACTION_SYSTEM_EXPIRE, "询价预约超过24小时未确认,已自动取消"); - expiredCount++; - } - return expiredCount; - } - - @Scheduled(fixedDelay = 60000) - public void expirePendingQuoteOrdersScheduled() { - expirePendingQuoteOrders(); - } - - @Override - /** - * Purpose: getArtistChangeOptions supports OrderServiceImpl.java by holding or executing the get artist change options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType) { - OrderDO order = requireActiveOrder(orderId); - if (!canAccessOrder(order, userId, userType)) { - throw new RuntimeException("无权查看该订单改派选项"); - } - OrderItemDO item = requireOrderItem(orderItemId, orderId); - ProductDO product = requireActiveProduct(item.getProductId()); - - OrderArtistChangeOptionsVO vo = new OrderArtistChangeOptionsVO(); - vo.setOrderId(orderId); - vo.setOrderItemId(orderItemId); - vo.setCurrentArtistId(item.getArtistId()); - UserDO currentArtist = item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId()); - vo.setCurrentArtistName(currentArtist == null ? null : currentArtist.getNickname()); - vo.setArtists(parseIdSet(product.getBookableArtists()).stream() - .filter(artistId -> !Objects.equals(artistId, item.getArtistId())) - .filter(artistId -> isArtistAvailableForItem(order.getShopId(), artistId, item, product)) - .map(this::buildArtistOptionVO) - .filter(Objects::nonNull) - .toList()); - return vo; - } - - @Override - @Transactional - /** - * Purpose: requestArtistChange supports OrderServiceImpl.java by holding or executing the request artist change business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto) { - if (dto == null || dto.getOrderId() == null || dto.getOrderItemId() == null || dto.getRequestedArtistId() == null) { - throw new RuntimeException("改派申请信息不完整"); - } - ensureArtistChangeRequester(userId); - OrderDO order = requireActiveOrder(dto.getOrderId()); - if (!canAccessOrder(order, userId, null)) { - throw new RuntimeException("只能为自己的订单申请改派"); - } - if (!Integer.valueOf(1).equals(order.getStatus())) { - throw new RuntimeException("仅待服务订单允许申请改派"); - } - OrderItemDO item = requireOrderItemForUpdate(dto.getOrderItemId(), order.getId()); - if (!canRequestArtistChangeForItem(order, item, userId)) { - throw new RuntimeException("只能为自己承接的待服务订单项申请改派"); - } - if (item.getArtistId() == null) { - throw new RuntimeException("订单项未分配美甲师"); - } - if (Objects.equals(item.getArtistId(), dto.getRequestedArtistId())) { - throw new RuntimeException("新美甲师不能与原美甲师相同"); - } - if (orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()) != null) { - throw new RuntimeException("该订单项已有待处理改派申请"); - } - ProductDO product = requireActiveProduct(item.getProductId()); - validateRequestedArtistForItem(order.getShopId(), dto.getRequestedArtistId(), item, product); - - OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO(); - request.setOrderId(order.getId()); - request.setOrderItemId(item.getId()); - request.setProductId(item.getProductId()); - request.setShopId(order.getShopId()); - request.setCustomerId(order.getUserId()); - request.setFromArtistId(item.getArtistId()); - request.setToArtistId(dto.getRequestedArtistId()); - request.setRequesterId(userId); - request.setStatus(CHANGE_STATUS_PENDING); - request.setReason(trimToNull(dto.getReason())); - request.setPendingKey(buildArtistChangePendingKey(item.getId())); - request.setExpireTime(LocalDateTime.now().plusDays(2)); - request.setIsDelete(0); - try { - orderArtistChangeRequestMapper.insert(request); - } catch (DuplicateKeyException exception) { - throw new RuntimeException("该订单项已有待处理改派申请"); - } - createArtistChangeMessage(order, request); - return buildArtistChangeRequestVO(request, item); - } - - @Override - /** - * Purpose: listMyPendingArtistChangeRequests supports OrderServiceImpl.java by holding or executing the list my pending artist change requests business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listMyPendingArtistChangeRequests(Long userId, Integer userType) { - expireDueArtistChangeRequests(); - List requests; - if (Integer.valueOf(2).equals(userType)) { - UserDO user = userMapper.selectById(userId); - requests = user != null && user.getShopId() != null - ? orderArtistChangeRequestMapper.selectPendingByShopId(user.getShopId()) - : orderArtistChangeRequestMapper.selectPendingByArtistId(userId); - } else if (Integer.valueOf(3).equals(userType)) { - requests = orderArtistChangeRequestMapper.selectPendingByArtistId(userId); - } else { - requests = orderArtistChangeRequestMapper.selectPendingByUserId(userId); - } - return requests.stream() - .map(this::buildArtistChangeRequestVO) - .toList(); - } - - @Override - /** - * Purpose: listOrderArtistChangeRequests returns every artist-change request for one accessible order. - * Usage: call it from order detail/list pages to build a customer-facing order timeline with pending and historical changes. - */ - public List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType) { - expireDueArtistChangeRequests(); - OrderDO order = requireActiveOrder(orderId); - if (!canAccessOrder(order, userId, userType)) { - throw new RuntimeException("[ORDER_ARTIST_CHANGE_FORBIDDEN] 无权查看该订单改派记录"); - } - return orderArtistChangeRequestMapper.selectByOrderId(orderId).stream() - .map(this::buildArtistChangeRequestVO) - .toList(); - } - - @Override - @Transactional - /** - * Purpose: approveArtistChange supports OrderServiceImpl.java by holding or executing the approve artist change business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType) { - OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId); - assertCanProcessArtistChange(request, userId, userType); - - OrderDO order = requireActiveOrder(request.getOrderId()); - if (!Integer.valueOf(1).equals(order.getStatus())) { - throw new RuntimeException("仅待服务订单允许改派"); - } - if (!Objects.equals(order.getUserId(), request.getCustomerId())) { - throw new RuntimeException("改派申请客户与订单不匹配"); - } - - OrderItemDO item = orderItemMapper.selectByIdForUpdate(request.getOrderItemId()); - if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), order.getId())) { - throw new RuntimeException("订单项不存在"); - } - if (!Objects.equals(item.getArtistId(), request.getFromArtistId())) { - throw new RuntimeException("原美甲师已变更,无法继续改派"); - } - - ProductDO product = requireActiveProduct(item.getProductId()); - validateRequestedArtistForItem(order.getShopId(), request.getToArtistId(), item, product); - long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - appointmentCapacityService.moveReservationForArtistChange( - order.getId(), - item.getId(), - order.getShopId(), - request.getFromArtistId(), - request.getToArtistId(), - product.getTitle(), - item.getAppointmentTime(), - item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes) - ); - - LocalDateTime approvedTime = LocalDateTime.now(); - if (orderArtistChangeRequestMapper.approvePending(request.getId(), approvedTime) == 0) { - throw new RuntimeException("改派申请已处理"); - } - item.setArtistId(request.getToArtistId()); - orderItemMapper.updateById(item); - request.setStatus(CHANGE_STATUS_APPROVED); - request.setApprovedTime(approvedTime); - request.setPendingKey(null); - return buildArtistChangeRequestVO(request, item); - } - - @Override - @Transactional - /** - * Purpose: rejectArtistChange supports OrderServiceImpl.java by holding or executing the reject artist change business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto) { - OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId); - assertCanProcessArtistChange(request, userId, userType); - LocalDateTime rejectedTime = LocalDateTime.now(); - String rejectReason = trimToNull(dto == null ? null : dto.getRejectReason()); - if (orderArtistChangeRequestMapper.rejectPending(request.getId(), rejectReason, rejectedTime) == 0) { - throw new RuntimeException("改派申请已处理"); - } - request.setStatus(CHANGE_STATUS_REJECTED); - request.setRejectReason(rejectReason); - request.setRejectedTime(rejectedTime); - request.setPendingKey(null); - return buildArtistChangeRequestVO(request); - } - - /** - * Purpose: createPendingArtistReviewTasksAndNotifyFromOutbox supports OrderServiceImpl.java by holding or executing the create pending artist review tasks and notify from outbox business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void createPendingArtistReviewTasksAndNotifyFromOutbox(OrderDO order) { - createPendingArtistReviewTasksAndNotify(order); - } - - /** - * Purpose: createPendingArtistReviewTasksAndNotify supports OrderServiceImpl.java by holding or executing the create pending artist review tasks and notify business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void createPendingArtistReviewTasksAndNotify(OrderDO order) { - if (order == null || order.getId() == null || !Integer.valueOf(2).equals(order.getStatus())) { - return; - } - List items = orderItemMapper.selectByOrderId(order.getId()); - if (items == null || items.isEmpty()) { - return; - } - for (OrderItemDO item : items) { - if (item == null - || item.getId() == null - || Integer.valueOf(1).equals(item.getIsDelete()) - || item.getArtistId() == null) { - continue; - } - if (orderArtistReviewMapper.selectByOrderItemId(item.getId()) != null) { - continue; - } - ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>()); - OrderArtistReviewDO review = new OrderArtistReviewDO(); - review.setOrderId(order.getId()); - review.setOrderItemId(item.getId()); - review.setProductId(item.getProductId()); - review.setShopId(order.getShopId()); - review.setArtistId(item.getArtistId()); - review.setCustomerId(order.getUserId()); - review.setStatus(REVIEW_STATUS_PENDING); - review.setIsDelete(0); - review = insertPendingArtistReview(review); - if (review == null || review.getId() == null) { - continue; - } - Long messageId = createReviewReminderMessage(order, item, product, review); - if (messageId != null) { - review.setReminderMessageId(messageId); - orderArtistReviewMapper.updateById(review); - } - } - } - - /** - * Purpose: insertPendingArtistReview supports OrderServiceImpl.java by holding or executing the insert pending artist review business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistReviewDO insertPendingArtistReview(OrderArtistReviewDO review) { - try { - orderArtistReviewMapper.insert(review); - return review; - } catch (DuplicateKeyException exception) { - OrderArtistReviewDO existingReview = review == null || review.getOrderItemId() == null - ? null - : orderArtistReviewMapper.selectByOrderItemId(review.getOrderItemId()); - if (existingReview != null) { - return existingReview; - } - throw exception; - } - } - - /** - * Purpose: createReviewReminderMessage supports OrderServiceImpl.java by holding or executing the create review reminder message business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long createReviewReminderMessage(OrderDO order, OrderItemDO item, ProductDO product, OrderArtistReviewDO review) { - String productTitle = product == null ? "订单项目" : product.getTitle(); - UserDO artist = item == null || item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId()); - String artistName = artist == null || !StringUtils.hasText(artist.getNickname()) ? "美甲师" : artist.getNickname(); - return createSystemBusinessMessage( - order == null ? null : order.getUserId(), - "订单已完成,记得评价美甲师", - "您预约的「" + productTitle + "」已完成,请为" + artistName + "提交本次服务评价。", - REVIEW_BUSINESS_TYPE, - review == null ? null : review.getId(), - order == null ? null : "/orders?orderId=" + order.getId(), - 0L, - "系统通知", - 4 - ); - } - - /** - * Purpose: buildArtistReviewVO supports OrderServiceImpl.java by holding or executing the build artist review vo business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistReviewVO buildArtistReviewVO(OrderArtistReviewDO review) { - if (review == null) { - return null; - } - OrderArtistReviewVO vo = new OrderArtistReviewVO(); - vo.setId(review.getId()); - vo.setOrderId(review.getOrderId()); - vo.setOrderItemId(review.getOrderItemId()); - vo.setProductId(review.getProductId()); - ProductDO product = getProductFromCache(review.getProductId(), new HashMap<>()); - vo.setProductTitle(product == null ? null : product.getTitle()); - vo.setArtistId(review.getArtistId()); - UserDO artist = review.getArtistId() == null ? null : userMapper.selectById(review.getArtistId()); - vo.setArtistName(artist == null ? null : artist.getNickname()); - vo.setArtistAvatar(artist == null ? null : objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); - vo.setUserId(review.getCustomerId()); - vo.setCustomerId(review.getCustomerId()); - vo.setRating(review.getRatingScore()); - vo.setRatingScore(review.getRatingScore()); - vo.setContent(review.getContent()); - vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds()))); - vo.setStatus(review.getStatus()); - vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价"); - vo.setReminderMessageId(review.getReminderMessageId()); - vo.setSubmitTime(review.getSubmittedAt()); - vo.setSubmittedAt(review.getSubmittedAt()); - vo.setCreateTime(review.getCreateTime()); - return vo; - } - - /** - * Purpose: requireActiveOrder supports OrderServiceImpl.java by holding or executing the require active order business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderDO requireActiveOrder(Long orderId) { - if (orderId == null) { - throw new RuntimeException("订单信息不完整"); - } - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - throw new RuntimeException("订单不存在"); - } - return order; - } - - /** - * Purpose: canAccessOrder supports OrderServiceImpl.java by holding or executing the can access order business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean canAccessOrder(OrderDO order, Long userId, Integer userType) { - if (order == null || userId == null) { - return false; - } - if (Objects.equals(order.getUserId(), userId)) { - return true; - } - UserDO user = userMapper.selectById(userId); - Integer effectiveType = userType == null && user != null ? user.getType() : userType; - if (Integer.valueOf(4).equals(effectiveType)) { - return true; - } - if (order.getShopId() != null && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId())) { - return true; - } - List items = orderItemMapper.selectByOrderId(order.getId()); - return items != null && items.stream() - .filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete())) - .anyMatch(item -> Objects.equals(item.getArtistId(), userId)); - } - - /** - * Purpose: normalizeReviewRating supports OrderServiceImpl.java by holding or executing the normalize review rating business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal normalizeReviewRating(BigDecimal rating) { - if (rating == null) { - throw new RuntimeException("评分不能为空"); - } - BigDecimal normalized; - try { - normalized = rating.setScale(1, RoundingMode.UNNECESSARY); - } catch (ArithmeticException exception) { - throw new RuntimeException("评分必须按0.5分递增"); - } - if (normalized.compareTo(new BigDecimal("0.5")) < 0 || normalized.compareTo(new BigDecimal("5.0")) > 0) { - throw new RuntimeException("评分必须在0.5到5分之间"); - } - BigDecimal doubled = normalized.multiply(new BigDecimal("2")); - if (doubled.stripTrailingZeros().scale() > 0) { - throw new RuntimeException("评分必须按0.5分递增"); - } - return normalized; - } - - /** - * Purpose: trimToNull supports OrderServiceImpl.java by holding or executing the trim to null business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String trimToNull(String value) { - if (!StringUtils.hasText(value)) { - return null; - } - return value.trim(); - } - - /** - * Purpose: joinLongIds supports OrderServiceImpl.java by holding or executing the join long ids business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String joinLongIds(List ids) { - if (ids == null || ids.isEmpty()) { - return null; - } - String joined = ids.stream() - .filter(Objects::nonNull) - .distinct() - .map(String::valueOf) - .collect(Collectors.joining(",")); - return joined.isBlank() ? null : joined; - } - - /** - * Purpose: parseIdSet supports OrderServiceImpl.java by holding or executing the parse id set business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Set parseIdSet(String rawIds) { - if (!StringUtils.hasText(rawIds)) { - return Collections.emptySet(); - } - LinkedHashSet result = new LinkedHashSet<>(); - for (String part : rawIds.split("[,;]")) { - if (!StringUtils.hasText(part)) { - continue; - } - try { - result.add(Long.parseLong(part.trim())); - } catch (NumberFormatException ignored) { - } - } - return result; - } - - /** - * Purpose: refreshArtistRating supports OrderServiceImpl.java by holding or executing the refresh artist rating business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void refreshArtistRating(Long artistId) { - if (artistId == null) { - return; - } - BigDecimal average = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); - if (average == null) { - return; - } - NailArtistInfoDO artistInfo = getArtistInfoByUserId(artistId); - if (artistInfo == null) { - return; - } - artistInfo.setRating(average.setScale(1, RoundingMode.HALF_UP)); - nailArtistInfoMapper.updateById(artistInfo); - } - - /** - * Purpose: requireOrderItem supports OrderServiceImpl.java by holding or executing the require order item business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderItemDO requireOrderItem(Long orderItemId, Long orderId) { - return requireOrderItem(orderItemId, orderId, false); - } - - /** - * Purpose: requireOrderItemForUpdate supports OrderServiceImpl.java by holding or executing the require order item for update business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderItemDO requireOrderItemForUpdate(Long orderItemId, Long orderId) { - return requireOrderItem(orderItemId, orderId, true); - } - - /** - * Purpose: buildArtistChangePendingKey supports OrderServiceImpl.java by holding or executing the build artist change pending key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildArtistChangePendingKey(Long orderItemId) { - return orderItemId == null ? null : ARTIST_CHANGE_PENDING_KEY_PREFIX + orderItemId; - } - - /** - * Purpose: requireOrderItem supports OrderServiceImpl.java by holding or executing the require order item business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderItemDO requireOrderItem(Long orderItemId, Long orderId, boolean forUpdate) { - if (orderItemId == null) { - throw new RuntimeException("订单项信息不完整"); - } - OrderItemDO item = forUpdate - ? orderItemMapper.selectByIdForUpdate(orderItemId) - : orderItemMapper.selectById(orderItemId); - if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), orderId)) { - throw new RuntimeException("订单项不存在"); - } - return item; - } - - /** - * Purpose: requireActiveProduct supports OrderServiceImpl.java by holding or executing the require active product business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private ProductDO requireActiveProduct(Long productId) { - ProductDO product = getProductFromCache(productId, new HashMap<>()); - if (product == null) { - throw new RuntimeException("商品不存在或已删除"); - } - return product; - } - - /** - * Purpose: isArtistAvailableForItem supports OrderServiceImpl.java by holding or executing the is artist available for item business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isArtistAvailableForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) { - try { - validateRequestedArtistForItem(shopId, artistId, item, product); - return true; - } catch (RuntimeException exception) { - return false; - } - } - - private OrderArtistChangeOptionsVO.ArtistOptionVO buildArtistOptionVO(Long artistId) { - UserDO artist = userMapper.selectById(artistId); - if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) || !bookableArtistSupport.isBookableServiceUser(artist)) { - return null; - } - NailArtistInfoDO info = getArtistInfoByUserId(artistId); - OrderArtistChangeOptionsVO.ArtistOptionVO vo = new OrderArtistChangeOptionsVO.ArtistOptionVO(); - vo.setArtistId(artist.getId()); - vo.setArtistName(artist.getNickname()); - vo.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); - vo.setUserType(artist.getType()); - vo.setParticipateProduction(info != null && Integer.valueOf(1).equals(info.getParticipateProduction())); - return vo; - } - - /** - * Purpose: validateRequestedArtistForItem supports OrderServiceImpl.java by holding or executing the validate requested artist for item business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void validateRequestedArtistForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) { - validateArtistForProduct(product, artistId); - if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { - throw new RuntimeException("新美甲师不可预约或不属于当前店铺"); - } - if (item == null || item.getAppointmentTime() == null) { - return; - } - int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - long durationMinutes = resolveServiceDurationMinutes(product) * quantity; - LocalDateTime startTime = item.getAppointmentTime(); - LocalDateTime endTime = startTime.plusMinutes(durationMinutes); - validateBusinessHours(getShopFromCache(shopId == null ? product.getShopId() : shopId, new HashMap<>()), startTime, endTime, product.getTitle()); - validateArtistScheduleConflicts(artistId, Collections.singletonList(new AppointmentSlot(product.getTitle(), startTime, endTime)), new HashMap<>()); - } - - /** - * Purpose: createArtistChangeMessage supports OrderServiceImpl.java by holding or executing the create artist change message business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long createArtistChangeMessage(OrderDO order, OrderArtistChangeRequestDO request) { - ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>()); - UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId()); - UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId()); - String fromName = fromArtist == null || !StringUtils.hasText(fromArtist.getNickname()) ? "原美甲师" : fromArtist.getNickname(); - String toName = toArtist == null || !StringUtils.hasText(toArtist.getNickname()) ? "新美甲师" : toArtist.getNickname(); - Long messageId = createSystemBusinessMessage( - request.getCustomerId(), - "美甲师改派申请待确认", - "您的订单项目「" + (product == null ? "订单项目" : product.getTitle()) + "」申请由" + fromName + "改派给" + toName + ",请在订单页确认。", - CHANGE_BUSINESS_TYPE, - request.getId(), - order == null ? null : "/orders?orderId=" + order.getId(), - request.getRequesterId(), - fromName, - 3 - ); - if (messageId != null) { - request.setMessageId(messageId); - orderArtistChangeRequestMapper.updateById(request); - } - return messageId; - } - - /** - * Purpose: buildArtistChangeRequestVO supports OrderServiceImpl.java by holding or executing the build artist change request vo business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request) { - return buildArtistChangeRequestVO(request, null); - } - - /** - * Purpose: buildArtistChangeRequestVO converts a change request plus optional order item into the client timeline payload. - * Usage: pass the locked/current order item when the caller already has it so the conversion does not issue extra reads. - */ - private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request, OrderItemDO requestItem) { - if (request == null) { - return null; - } - OrderArtistChangeRequestVO vo = new OrderArtistChangeRequestVO(); - vo.setId(request.getId()); - vo.setOrderId(request.getOrderId()); - vo.setOrderItemId(request.getOrderItemId()); - vo.setProductId(request.getProductId()); - ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>()); - vo.setProductTitle(product == null ? null : product.getTitle()); - vo.setShopId(request.getShopId()); - vo.setUserId(request.getCustomerId()); - vo.setCustomerId(request.getCustomerId()); - vo.setOriginalArtistId(request.getFromArtistId()); - vo.setFromArtistId(request.getFromArtistId()); - UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId()); - vo.setOriginalArtistName(fromArtist == null ? null : fromArtist.getNickname()); - vo.setFromArtistName(fromArtist == null ? null : fromArtist.getNickname()); - vo.setRequestedArtistId(request.getToArtistId()); - vo.setToArtistId(request.getToArtistId()); - UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId()); - vo.setRequestedArtistName(toArtist == null ? null : toArtist.getNickname()); - vo.setToArtistName(toArtist == null ? null : toArtist.getNickname()); - vo.setRequesterId(request.getRequesterId()); - UserDO requester = request.getRequesterId() == null ? null : userMapper.selectById(request.getRequesterId()); - vo.setRequesterName(requester == null ? null : requester.getNickname()); - vo.setStatus(request.getStatus()); - vo.setStatusText(resolveArtistChangeStatusText(request.getStatus())); - vo.setReason(request.getReason()); - vo.setRejectReason(request.getRejectReason()); - OrderItemDO item = requestItem != null ? requestItem : request.getOrderItemId() == null ? null : orderItemMapper.selectById(request.getOrderItemId()); - if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) { - vo.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); - vo.setOriginalPrice(item.getPrice()); - vo.setNewPrice(item.getPrice()); - vo.setTimeAffected(false); - vo.setTimeImpactText("预约时间不变"); - vo.setPriceAffected(false); - vo.setPriceImpactText("订单价格不变"); - } else { - vo.setTimeImpactText("暂无法确认预约时间,请联系门店"); - vo.setPriceImpactText("暂无法确认订单价格,请联系门店"); - } - vo.setReviewerId(request.getCustomerId()); - vo.setMessageId(request.getMessageId()); - vo.setReviewTime(request.getApprovedTime() != null ? request.getApprovedTime() : request.getRejectedTime()); - vo.setApprovedTime(request.getApprovedTime()); - vo.setRejectedTime(request.getRejectedTime()); - vo.setExpireTime(request.getExpireTime()); - vo.setCreateTime(request.getCreateTime()); - return vo; - } - - /** - * Purpose: requirePendingArtistChangeRequest supports OrderServiceImpl.java by holding or executing the require pending artist change request business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistChangeRequestDO requirePendingArtistChangeRequest(Long requestId) { - if (requestId == null) { - throw new RuntimeException("改派申请信息不完整"); - } - OrderArtistChangeRequestDO request = orderArtistChangeRequestMapper.selectById(requestId); - if (request == null || Integer.valueOf(1).equals(request.getIsDelete())) { - throw new RuntimeException("改派申请不存在"); - } - if (!CHANGE_STATUS_PENDING.equals(request.getStatus())) { - throw new RuntimeException("改派申请已处理"); - } - LocalDateTime now = LocalDateTime.now(); - if (request.getExpireTime() != null && !request.getExpireTime().isAfter(now)) { - orderArtistChangeRequestMapper.expirePendingById(request.getId(), now); - request.setStatus(CHANGE_STATUS_EXPIRED); - request.setPendingKey(null); - throw new RuntimeException("改派申请已过期"); - } - return request; - } - - /** - * Purpose: assertCanProcessArtistChange supports OrderServiceImpl.java by holding or executing the assert can process artist change business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void assertCanProcessArtistChange(OrderArtistChangeRequestDO request, Long userId, Integer userType) { - if (request == null || userId == null || !Objects.equals(request.getCustomerId(), userId)) { - throw new RuntimeException("仅订单客户可以处理改派申请"); - } - } - - @org.springframework.scheduling.annotation.Scheduled(fixedDelay = 300000L) - /** - * Purpose: expireDueArtistChangeRequests supports OrderServiceImpl.java by holding or executing the expire due artist change requests business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void expireDueArtistChangeRequests() { - orderArtistChangeRequestMapper.expirePendingBefore(LocalDateTime.now()); - } - - /** - * Purpose: canRequestArtistChangeForItem supports OrderServiceImpl.java by holding or executing the can request artist change for item business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean canRequestArtistChangeForItem(OrderDO order, OrderItemDO item, Long userId) { - if (order == null || item == null || userId == null) { - return false; - } - if (Objects.equals(item.getArtistId(), userId)) { - return true; - } - UserDO user = userMapper.selectById(userId); - if (user == null || !Integer.valueOf(2).equals(user.getType())) { - return false; - } - NailArtistInfoDO info = getArtistInfoByUserId(userId); - return info != null - && Integer.valueOf(1).equals(info.getParticipateProduction()) - && order.getShopId() != null - && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId()); - } - - /** - * Purpose: ensureArtistChangeRequester supports OrderServiceImpl.java by holding or executing the ensure artist change requester business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void ensureArtistChangeRequester(Long userId) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { - throw new RuntimeException("请先登录有效账号"); - } - if (Integer.valueOf(3).equals(user.getType())) { - return; - } - if (Integer.valueOf(2).equals(user.getType())) { - NailArtistInfoDO info = getArtistInfoByUserId(userId); - if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { - return; - } - } - throw new RuntimeException("仅美甲师或参与制作的店长可以申请改派"); - } - - /** - * Purpose: getArtistInfoByUserId supports OrderServiceImpl.java by holding or executing the get artist info by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private NailArtistInfoDO getArtistInfoByUserId(Long userId) { - if (userId == null) { - return null; - } - return nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getUserId, userId) - .eq(NailArtistInfoDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - /** - * Purpose: resolveArtistChangeStatusText supports OrderServiceImpl.java by holding or executing the resolve artist change status text business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveArtistChangeStatusText(String status) { - if (CHANGE_STATUS_APPROVED.equals(status)) { - return "已同意"; - } - if (CHANGE_STATUS_REJECTED.equals(status)) { - return "已拒绝"; - } - return "待确认"; - } - - private OrderDO requireQuoteOrder(Long orderId) { - OrderDO order = requireActiveOrder(orderId); - if (!Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { - throw new RuntimeException("仅确认价格中的询价预约可以进行报价操作"); - } - if (QUOTE_STATUS_EXPIRED.equals(order.getQuoteStatus())) { - throw new RuntimeException("询价预约已过期"); - } - return order; - } - - private void ensureQuoteOwner(OrderDO order, Long userId) { - if (order == null || userId == null || !userId.equals(order.getUserId())) { - throw new RuntimeException("无权处理该询价预约"); - } - } - - private void ensureShopQuoteOperator(OrderDO order, Long operatorId, Integer operatorType) { - if (!Integer.valueOf(USER_TYPE_SHOP_OWNER).equals(operatorType)) { - throw new RuntimeException("只有店长可以确认或回复价格"); - } - if (order == null || operatorId == null - || !userShopBindingSupport.canUserAccessShop(operatorId, order.getShopId(), true, operatorType)) { - throw new RuntimeException("无权处理其他店铺的询价预约"); - } - } - - private BigDecimal normalizeQuotePrice(BigDecimal price) { - if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) { - throw new RuntimeException("报价金额必须大于0"); - } - return scaleMoney(price); - } - - private Map loadActiveOrderItemMap(Long orderId) { - return orderItemMapper.selectByOrderId(orderId).stream() - .filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete())) - .collect(Collectors.toMap(OrderItemDO::getId, item -> item, (left, right) -> left, LinkedHashMap::new)); - } - - private List loadActiveOrderItems(Long orderId) { - return new ArrayList<>(loadActiveOrderItemMap(orderId).values()); - } - - private List ensureAllItemsQuoted(Long orderId) { - List items = loadActiveOrderItems(orderId); - if (items.isEmpty()) { - throw new RuntimeException("询价预约作品不存在"); - } - for (OrderItemDO item : items) { - if (item.getQuotedPrice() == null || item.getQuotedPrice().compareTo(BigDecimal.ZERO) <= 0) { - throw new RuntimeException("请先为每个作品填写报价"); - } - } - return items; - } - - private OrderVO finalizeConfirmedQuote(OrderDO order, Long actorId, String actorType) { - order = requireQuoteOrder(order.getId()); - if (!Integer.valueOf(1).equals(order.getQuoteUserConfirmed()) - || !Integer.valueOf(1).equals(order.getQuoteShopConfirmed())) { - return buildOrderVO(order); - } - - List items = ensureAllItemsQuoted(order.getId()); - Map productCache = new HashMap<>(); - Map shopCache = new HashMap<>(); - Set selectedTagNames = new LinkedHashSet<>(); - List requestedSlots = new ArrayList<>(); - BigDecimal finalTotal = BigDecimal.ZERO; - Long selectedArtistId = null; - - try { - for (OrderItemDO item : items) { - ProductDO product = requireActiveProduct(item.getProductId()); - productCache.put(product.getId(), product); - validateRequestedArtistForItem(order.getShopId(), item.getArtistId(), item, product); - if (selectedArtistId == null) { - selectedArtistId = item.getArtistId(); - } else if (!Objects.equals(selectedArtistId, item.getArtistId())) { - throw bookingUnavailable("不同美甲师的项目请分开确认"); - } - validateAppointmentTime(item.getAppointmentTime(), product.getTitle()); - long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - LocalDateTime endTime = item.getAppointmentTime().plusMinutes(durationMinutes); - validateBusinessHours(getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache), - item.getAppointmentTime(), endTime, product.getTitle()); - requestedSlots.add(new AppointmentSlot(product.getTitle(), item.getAppointmentTime(), endTime)); - collectTagNames(selectedTagNames, product.getTags()); - BigDecimal confirmedPrice = scaleMoney(item.getQuotedPrice()); - item.setPrice(confirmedPrice); - item.setConfirmedPrice(confirmedPrice); - finalTotal = finalTotal.add(confirmedPrice.multiply(BigDecimal.valueOf(Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity())))); - } - validateRequestedSlotConflicts(requestedSlots); - } catch (BusinessException exception) { - throw exception; - } catch (RuntimeException exception) { - if (isBookingValidationMessage(exception.getMessage())) { - throw bookingUnavailable(exception.getMessage()); - } - throw exception; - } - - CouponSelection couponSelection = resolveFinalCouponSelection(order, selectedTagNames, finalTotal); - BigDecimal actualAmount = finalTotal; - Long couponId = null; - Long userCouponId = null; - String couponSourceType = null; - if (couponSelection != null) { - CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); - if (coupon != null && !Integer.valueOf(1).equals(coupon.getIsDelete()) && coupon.getStatus() != null && coupon.getStatus() == 1) { - actualAmount = applyCouponDiscount(finalTotal, coupon); - couponId = coupon.getId(); - userCouponId = couponSelection.getUserCouponId(); - couponSourceType = couponSelection.getSourceType(); - if (COUPON_SOURCE_USER.equals(couponSourceType)) { - consumeUserCoupon(userCouponId, order.getUserId()); - } - } - } - - OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); - if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()) == 0) { - throw new RuntimeException("询价预约状态已变化,请刷新后重试"); - } - - for (OrderItemDO item : items) { - orderItemMapper.updateById(item); - ProductDO product = productCache.get(item.getProductId()); - long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - appointmentCapacityService.confirmReservationOrThrow( - order.getId(), - item.getId(), - order.getShopId(), - item.getArtistId(), - product == null ? null : product.getTitle(), - item.getAppointmentTime(), - item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes) - ); - } - - order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); - order.setTotalAmount(scaleMoney(finalTotal)); - order.setActualAmount(scaleMoney(actualAmount)); - order.setCouponId(couponId); - order.setUserCouponId(userCouponId); - order.setCouponSourceType(couponSourceType); - order.setQuoteStatus(QUOTE_STATUS_CONFIRMED); - order.setQuoteUserConfirmed(1); - order.setQuoteShopConfirmed(1); - order.setQuoteConfirmedTime(LocalDateTime.now()); - order.setPaymentStatus(actualAmount.compareTo(BigDecimal.ZERO) <= 0 ? "PAID" : "UNPAID"); - order.setPayAmount(scaleMoney(actualAmount)); - order.setPaidAmount(actualAmount.compareTo(BigDecimal.ZERO) <= 0 ? scaleMoney(actualAmount) : BigDecimal.ZERO); - orderMapper.updateById(order); - - writeQuoteMessage(order.getId(), actorId, actorType, QUOTE_ACTION_SYSTEM_CONFIRM, "双方已确认价格,订单进入待完成"); - notifyQuoteUser(order, "询价预约价格已确认", "双方已确认价格,订单已进入待完成状态。"); - notifyQuoteShopAndArtist(order, "询价预约价格已确认", "双方已确认价格,订单已进入待完成状态。"); - return buildOrderVO(orderMapper.selectById(order.getId())); - } - - private CouponSelection resolveFinalCouponSelection(OrderDO order, Set selectedTagNames, BigDecimal finalTotal) { - List availableCouponOptions = couponService.getAvailableCoupons( - order.getUserId(), - String.join(",", selectedTagNames), - finalTotal.doubleValue(), - order.getShopId() - ); - if (availableCouponOptions == null) { - availableCouponOptions = List.of(); - } - OrderDTO couponRequest = new OrderDTO(); - couponRequest.setCouponSourceType(order.getCouponSourceType()); - if (COUPON_SOURCE_USER.equals(order.getCouponSourceType())) { - couponRequest.setCouponId(order.getUserCouponId()); - } else if (COUPON_SOURCE_SYSTEM_VIP.equals(order.getCouponSourceType())) { - couponRequest.setCouponId(order.getCouponId()); - } - try { - CouponSelection selected = resolveRequestedCoupon(couponRequest, availableCouponOptions); - if (selected != null) { - return selected; - } - } catch (RuntimeException ignored) { - } - if (COUPON_SOURCE_NONE.equalsIgnoreCase(order.getCouponSourceType())) { - return null; - } - return selectBestAvailableCoupon(availableCouponOptions, finalTotal); - } - - private void writeQuoteMessage(Long orderId, Long actorId, String actorType, String action, String remark) { - OrderQuoteMessageDO message = new OrderQuoteMessageDO(); - message.setOrderId(orderId); - message.setActorId(actorId); - message.setActorType(actorType); - message.setAction(action); - message.setRemark(remark); - message.setItemsSnapshot(buildQuoteItemsSnapshot(orderId)); - message.setIsDelete(0); - orderQuoteMessageMapper.insert(message); - } - - private String buildQuoteItemsSnapshot(Long orderId) { - List items = buildQuoteItemVOs(orderId); - StringBuilder builder = new StringBuilder("["); - for (int i = 0; i < items.size(); i++) { - OrderQuoteItemVO item = items.get(i); - if (i > 0) { - builder.append(','); - } - builder.append('{'); - appendJsonField(builder, "orderItemId", item.getOrderItemId()); - builder.append(','); - appendJsonField(builder, "productId", item.getProductId()); - builder.append(','); - appendJsonField(builder, "productTitle", item.getProductTitle()); - builder.append(','); - appendJsonField(builder, "quantity", item.getQuantity()); - builder.append(','); - appendJsonField(builder, "referencePrice", item.getReferencePrice()); - builder.append(','); - appendJsonField(builder, "quotedPrice", item.getQuotedPrice()); - builder.append(','); - appendJsonField(builder, "confirmedPrice", item.getConfirmedPrice()); - builder.append('}'); - } - return builder.append(']').toString(); - } - - private void appendJsonField(StringBuilder builder, String name, Object value) { - builder.append('"').append(name).append('"').append(':'); - if (value == null) { - builder.append("null"); - return; - } - if (value instanceof Number) { - builder.append(value); - return; - } - builder.append('"').append(jsonEscape(String.valueOf(value))).append('"'); - } - - private String jsonEscape(String value) { - return value == null ? "" : value.replace("\\", "\\\\").replace("\"", "\\\""); - } - - private List buildQuoteItemVOs(Long orderId) { - return loadActiveOrderItems(orderId).stream() - .map(item -> { - ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>()); - OrderQuoteItemVO vo = new OrderQuoteItemVO(); - vo.setOrderItemId(item.getId()); - vo.setProductId(item.getProductId()); - vo.setProductTitle(product == null ? null : product.getTitle()); - vo.setQuantity(item.getQuantity()); - vo.setReferencePrice(item.getReferencePrice() == null ? item.getPrice() : item.getReferencePrice()); - vo.setQuotedPrice(item.getQuotedPrice()); - vo.setConfirmedPrice(item.getConfirmedPrice()); - return vo; - }) - .toList(); - } - - private OrderQuoteMessageVO buildQuoteMessageVO(OrderQuoteMessageDO message) { - OrderQuoteMessageVO vo = new OrderQuoteMessageVO(); - vo.setId(message.getId()); - vo.setOrderId(message.getOrderId()); - vo.setActorId(message.getActorId()); - vo.setActorType(message.getActorType()); - vo.setActorTypeText(resolveQuoteActorTypeText(message.getActorType())); - vo.setAction(message.getAction()); - vo.setActionText(resolveQuoteActionText(message.getAction())); - vo.setRemark(message.getRemark()); - vo.setItems(buildQuoteItemVOs(message.getOrderId())); - vo.setCreateTime(message.getCreateTime()); - return vo; - } - - private String resolveQuoteActorTypeText(String actorType) { - if (QUOTE_ACTOR_USER.equals(actorType)) { - return "用户"; - } - if (QUOTE_ACTOR_SHOP.equals(actorType)) { - return "门店"; - } - return "系统"; - } - - private String resolveQuoteActionText(String action) { - if (QUOTE_ACTION_CREATE.equals(action)) return "发起询价预约"; - if (QUOTE_ACTION_SHOP_QUOTE.equals(action)) return "门店报价"; - if (QUOTE_ACTION_USER_REPLY.equals(action)) return "用户回复"; - if (QUOTE_ACTION_USER_CONFIRM.equals(action)) return "用户确认"; - if (QUOTE_ACTION_SHOP_CONFIRM.equals(action)) return "店长确认"; - if (QUOTE_ACTION_SYSTEM_CONFIRM.equals(action)) return "价格已确认"; - if (QUOTE_ACTION_SYSTEM_EXPIRE.equals(action)) return "询价已过期"; - return "询价动态"; - } - - private String resolveQuoteStatusText(String quoteStatus, Integer orderStatus) { - if (QUOTE_STATUS_CONFIRMED.equals(quoteStatus)) { - return "价格已确认"; - } - if (QUOTE_STATUS_EXPIRED.equals(quoteStatus)) { - return "询价已过期"; - } - if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(orderStatus)) { - return "确认价格中"; - } - return "价格已确认"; - } - - private void notifyQuoteCreated(OrderVO orderVO) { - if (orderVO == null || orderVO.getId() == null) { - return; - } - OrderDO order = orderMapper.selectById(orderVO.getId()); - notifyQuoteShopAndArtist(order, "新的询价预约", "用户发起了新的询价预约,请查看并确认价格。"); - } - - private void notifyQuoteUser(OrderDO order, String title, String content) { - if (order == null) { - return; - } - createQuoteNotification(order.getUserId(), title, content, "/orders?orderId=" + order.getId(), order.getId(), 0L, "系统通知", 4); - } - - private void notifyQuoteShopAndArtist(OrderDO order, String title, String content) { - if (order == null || order.getId() == null) { - return; - } - Set targetIds = new LinkedHashSet<>(); - if (order.getShopId() != null) { - List owners = userMapper.selectList(new LambdaQueryWrapper() - .eq(UserDO::getShopId, order.getShopId()) - .eq(UserDO::getType, USER_TYPE_SHOP_OWNER) - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getStatus, 1)); - owners.stream().map(UserDO::getId).filter(Objects::nonNull).forEach(targetIds::add); - userShopBindingSupport.listUserIdsByShopId(order.getShopId(), true).forEach(userId -> { - UserDO user = userMapper.selectById(userId); - if (user != null && Integer.valueOf(USER_TYPE_SHOP_OWNER).equals(user.getType())) { - targetIds.add(userId); - } - }); - } - loadActiveOrderItems(order.getId()).stream() - .map(OrderItemDO::getArtistId) - .filter(Objects::nonNull) - .forEach(targetIds::add); - targetIds.remove(order.getUserId()); - targetIds.forEach(targetId -> createQuoteNotification( - targetId, - title, - content, - "/admin/orders?orderId=" + order.getId(), - order.getId(), - order.getUserId(), - "用户询价预约", - 0 - )); - } - - private void createQuoteNotification(Long targetUserId, - String title, - String content, - String actionPath, - Long businessId, - Long publisherId, - String publisherName, - Integer publisherType) { - if (targetUserId == null) { - return; - } - SystemMessageDO message = new SystemMessageDO(); - message.setTitle(title); - message.setContent(content); - message.setPublisherId(publisherId == null ? 0L : publisherId); - message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知"); - message.setPublisherType(publisherType == null ? 4 : publisherType); - message.setTargetType(MESSAGE_TARGET_SELECTED_USERS); - message.setTargetIds(String.valueOf(targetUserId)); - message.setBusinessType(QUOTE_BUSINESS_TYPE); - message.setBusinessId(businessId); - message.setActionPath(actionPath); - message.setPopupEnabled(1); - message.setStatus(1); - message.setPublishTime(LocalDateTime.now()); - message.setIsDelete(0); - systemMessageMapper.insert(message); - } - - private Long createSystemBusinessMessage(Long targetUserId, - String title, - String content, - String businessType, - Long businessId, - String actionPath, - Long publisherId, - String publisherName, - Integer publisherType) { - if (targetUserId == null) { - return null; - } - String targetIds = String.valueOf(targetUserId); - String idempotencyKey = buildSystemMessageIdempotencyKey(businessType, businessId, targetUserId); - if (StringUtils.hasText(idempotencyKey)) { - Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey); - if (existingMessageId != null) { - return existingMessageId; - } - } - SystemMessageDO message = new SystemMessageDO(); - message.setTitle(title); - message.setContent(content); - message.setPublisherId(publisherId == null ? 0L : publisherId); - message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知"); - message.setPublisherType(publisherType == null ? 4 : publisherType); - message.setTargetType(MESSAGE_TARGET_SELECTED_USERS); - message.setTargetIds(targetIds); - message.setBusinessType(businessType); - message.setBusinessId(businessId); - message.setActionPath(actionPath); - message.setIdempotencyKey(idempotencyKey); - message.setPopupEnabled(1); - message.setStatus(1); - message.setPublishTime(LocalDateTime.now()); - message.setIsDelete(0); - try { - systemMessageMapper.insert(message); - } catch (DuplicateKeyException exception) { - Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey); - if (existingMessageId != null) { - return existingMessageId; - } - throw exception; - } - return message.getId(); - } - - /** - * Purpose: buildSystemMessageIdempotencyKey supports OrderServiceImpl.java by holding or executing the build system message idempotency key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildSystemMessageIdempotencyKey(String businessType, Long businessId, Long targetUserId) { - if (!StringUtils.hasText(businessType) || businessId == null || targetUserId == null) { - return null; - } - return businessType + ":" + businessId + ":" + targetUserId; - } - - private Long findSystemBusinessMessageId(String businessType, - Long businessId, - String targetIds, - String idempotencyKey) { - if (!StringUtils.hasText(idempotencyKey)) { - return null; - } - SystemMessageDO existingMessage = systemMessageMapper.selectOne(new LambdaQueryWrapper() - .eq(SystemMessageDO::getBusinessType, businessType) - .eq(SystemMessageDO::getBusinessId, businessId) - .eq(SystemMessageDO::getTargetType, MESSAGE_TARGET_SELECTED_USERS) - .eq(SystemMessageDO::getTargetIds, targetIds) - .eq(SystemMessageDO::getIsDelete, 0) - .and(wrapper -> wrapper - .eq(SystemMessageDO::getIdempotencyKey, idempotencyKey) - .or() - .isNull(SystemMessageDO::getIdempotencyKey)) - .last("LIMIT 1")); - return existingMessage == null ? null : existingMessage.getId(); - } - - /** - * Run business method `buildOrderVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @return private OrderVO result consumed by the caller or returned to the frontend - */ - private OrderVO buildOrderVO(OrderDO order) { - /** - * Run business method `buildOrderVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildOrderVO(order, null); - } - - /** - * Run business method `ensureCalendarAccess`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensureCalendarAccess(Long userId, Integer userType) { - if (userId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请先登录"); - } - if (Integer.valueOf(3).equals(userType)) { - return; - } - if (Integer.valueOf(2).equals(userType)) { - NailArtistInfoDO info = nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() - .eq(NailArtistInfoDO::getUserId, userId) - .eq(NailArtistInfoDO::getIsDelete, 0) - .last("LIMIT 1")); - if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { - return; - } - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("仅美甲师或参与制作的店长可查看预约日历"); - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistId parameter `artistId` supplied by the caller - * @param startTime parameter `startTime` supplied by the caller - * @param endTime parameter `endTime` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List listArtistCalendarAppointments(Long artistId, LocalDateTime startTime, LocalDateTime endTime) { - List items = orderItemMapper.selectArtistCalendarItems(artistId, startTime, endTime); - if (items == null || items.isEmpty()) { - return Collections.emptyList(); - } - - Map userCache = new HashMap<>(); - Map productCache = new HashMap<>(); - Map shopCache = new HashMap<>(); - UserDO artist = getUserFromCache(artistId, userCache); - List result = new ArrayList<>(); - - for (OrderItemDO item : items) { - OrderDO order = orderMapper.selectById(item.getOrderId()); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || Integer.valueOf(3).equals(order.getStatus())) { - continue; - } - ProductDO product = getProductFromCache(item.getProductId(), productCache); - if (product == null || item.getAppointmentTime() == null) { - continue; - } - ShopDO shop = getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache); - UserDO customer = getUserFromCache(order.getUserId(), userCache); - long singleDuration = resolveServiceDurationMinutes(product); - int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - long durationMinutes = singleDuration * quantity; - - ArtistCalendarAppointmentVO vo = new ArtistCalendarAppointmentVO(); - vo.setOrderId(order.getId()); - vo.setOrderNo(order.getOrderNo()); - vo.setTotalAmount(order.getTotalAmount()); - vo.setActualAmount(order.getActualAmount()); - vo.setOrderStatus(order.getStatus()); - vo.setOrderStatusText(resolveOrderStatusText(order.getStatus())); - vo.setOrderItemId(item.getId()); - vo.setProductId(product.getId()); - vo.setProductTitle(product.getTitle()); - vo.setArtistId(artistId); - vo.setArtistName(artist == null ? null : artist.getNickname()); - vo.setCustomerNickname(resolveCustomerNickname(customer)); - vo.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); - vo.setShopId(order.getShopId() == null ? product.getShopId() : order.getShopId()); - vo.setShopName(shop == null ? null : shop.getShopName()); - vo.setAppointmentStartTime(item.getAppointmentTime()); - vo.setAppointmentEndTime(item.getAppointmentTime().plusMinutes(durationMinutes)); - vo.setQuantity(item.getQuantity()); - vo.setDurationMinutes(durationMinutes); - result.add(vo); - } - result.sort(Comparator.comparing(ArtistCalendarAppointmentVO::getAppointmentStartTime)); - return result; - } - - /** - * Run business method `resolveOrderStatusText`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param status parameter `status` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveOrderStatusText(Integer status) { - if (Integer.valueOf(0).equals(status)) { - return "确认价格中"; - } - if (Integer.valueOf(1).equals(status)) { - return "待完成"; - } - if (Integer.valueOf(1).equals(status)) { - return "待服务"; - } - if (Integer.valueOf(2).equals(status)) { - return "已完成"; - } - if (Integer.valueOf(3).equals(status)) { - return "已取消"; - } - return "未知状态"; - } - - /** - * Run business method `buildOrderVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @param artistIdFilter parameter `artistIdFilter` supplied by the caller - * @return private OrderVO result consumed by the caller or returned to the frontend - */ - private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) { - OrderVO orderVO = new OrderVO(); - Map userCache = new HashMap<>(); - orderVO.setId(order.getId()); - orderVO.setOrderNo(order.getOrderNo()); - orderVO.setUserId(order.getUserId()); - orderVO.setShopId(order.getShopId()); - if (order.getShopId() != null) { - ShopDO shop = shopMapper.selectById(order.getShopId()); - orderVO.setShopName(shop == null ? null : shop.getShopName()); - } - orderVO.setTotalAmount(order.getTotalAmount()); - orderVO.setActualAmount(order.getActualAmount()); - orderVO.setCouponId(order.getCouponId()); - orderVO.setUserCouponId(order.getUserCouponId()); - orderVO.setCouponSourceType(order.getCouponSourceType()); - orderVO.setPaymentStatus(order.getPaymentStatus()); - orderVO.setPayAmount(order.getPayAmount()); - orderVO.setPaidAmount(order.getPaidAmount()); - orderVO.setPayTime(order.getPayTime()); - orderVO.setPaymentMethod(order.getPaymentMethod()); - orderVO.setPaymentOrderNo(order.getPaymentOrderNo()); - orderVO.setRefundStatus(order.getRefundStatus()); - orderVO.setCustomerRemark(order.getCustomerRemark()); - orderVO.setQuoteStatus(order.getQuoteStatus()); - orderVO.setQuoteStatusText(resolveQuoteStatusText(order.getQuoteStatus(), order.getStatus())); - orderVO.setQuoteUserConfirmed(Integer.valueOf(1).equals(order.getQuoteUserConfirmed())); - orderVO.setQuoteShopConfirmed(Integer.valueOf(1).equals(order.getQuoteShopConfirmed())); - orderVO.setQuoteExpireTime(order.getQuoteExpireTime()); - orderVO.setQuoteConfirmedTime(order.getQuoteConfirmedTime()); - if (orderQuoteMessageMapper != null) { - orderVO.setQuoteMessages(orderQuoteMessageMapper.selectByOrderId(order.getId()).stream() - .map(this::buildQuoteMessageVO) - .toList()); - } - UserDO customer = getUserFromCache(order.getUserId(), userCache); - orderVO.setCustomerNickname(resolveCustomerNickname(customer)); - orderVO.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); - orderVO.setStatus(order.getStatus()); - - switch (order.getStatus()) { - case 0: - orderVO.setStatusText("确认价格中"); - break; - case 1: - orderVO.setStatusText("待使用"); - break; - case 2: - orderVO.setStatusText("已完成"); - break; - case 3: - orderVO.setStatusText("已取消"); - break; - default: - orderVO.setStatusText("未知状态"); - } - - if (Integer.valueOf(1).equals(order.getStatus())) { - orderVO.setStatusText("待完成"); - } - - if (artistIdFilter == null && order.getCouponId() != null && order.getCouponId() > 0) { - CouponDO coupon = couponMapper.selectById(order.getCouponId()); - if (coupon != null) { - orderVO.setCouponName(coupon.getCouponName()); - } - } - - orderVO.setCreateTime(order.getCreateTime()); - - List orderItemVOs = new ArrayList<>(); - BigDecimal filteredTotal = BigDecimal.ZERO; - List orderItems = orderItemMapper.selectByOrderId(order.getId()); - - for (OrderItemDO item : orderItems) { - if (Integer.valueOf(1).equals(item.getIsDelete())) { - continue; - } - if (artistIdFilter != null && !artistIdFilter.equals(item.getArtistId())) { - continue; - } - - ProductDO product = productMapper.selectById(item.getProductId()); - if (product == null) { - continue; - } - - OrderItemVO itemVO = new OrderItemVO(); - itemVO.setId(item.getId()); - itemVO.setProductId(product.getId()); - itemVO.setProductTitle(product.getTitle()); - - String imageFileIds = product.getImageFileIds(); - if (imageFileIds != null && !imageFileIds.isEmpty()) { - String firstImageId = imageFileIds.split(",")[0]; - itemVO.setProductImage("/api/file/get/" + firstImageId); - } - - itemVO.setQuantity(item.getQuantity()); - itemVO.setPrice(item.getPrice()); - itemVO.setReferencePrice(item.getReferencePrice() == null ? item.getPrice() : item.getReferencePrice()); - itemVO.setQuotedPrice(item.getQuotedPrice()); - itemVO.setConfirmedPrice(item.getConfirmedPrice()); - BigDecimal displayPrice = item.getConfirmedPrice() == null ? item.getPrice() : item.getConfirmedPrice(); - itemVO.setPrice(displayPrice); - itemVO.setTotalPrice(displayPrice.multiply(BigDecimal.valueOf(item.getQuantity()))); - itemVO.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); - String occupancyStatus = resolveOrderItemOccupancyStatus(order); - itemVO.setOccupancyStatus(occupancyStatus); - itemVO.setCanEdit(canEditOrderItem(order)); - itemVO.setCanCancel(canCancelOrderItem(order)); - itemVO.setConflictReason(resolveOrderItemConflictReason(occupancyStatus)); - filteredTotal = filteredTotal.add(itemVO.getTotalPrice()); - - if (item.getArtistId() != null) { - itemVO.setArtistId(item.getArtistId()); - UserDO artist = getUserFromCache(item.getArtistId(), userCache); - if (artist != null) { - itemVO.setArtistName(artist.getNickname()); - itemVO.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); - } - } - - OrderArtistReviewDO review = orderArtistReviewMapper.selectByOrderItemId(item.getId()); - if (review != null) { - OrderArtistReviewVO reviewVO = buildArtistReviewVO(review); - if (Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) { - itemVO.setPendingReview(reviewVO); - } else if (Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus())) { - itemVO.setReviewSummary(reviewVO); - } - } - - OrderArtistChangeRequestDO pendingChangeRequest = orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()); - if (pendingChangeRequest != null) { - itemVO.setPendingArtistChangeRequest(buildArtistChangeRequestVO(pendingChangeRequest)); - } - - orderItemVOs.add(itemVO); - } - - orderVO.setItems(orderItemVOs); - if (artistIdFilter != null) { - orderVO.setTotalAmount(filteredTotal); - orderVO.setActualAmount(filteredTotal); - } - return orderVO; - } - - private String resolveOrderItemOccupancyStatus(OrderDO order) { - if (order == null || order.getStatus() == null) { - return "UNKNOWN"; - } - if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { - return "PENDING_QUOTE"; - } - if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { - return "CONFIRMED"; - } - if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { - return "CANCELLED"; - } - if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { - return "COMPLETED"; - } - return "UNKNOWN"; - } - - private Boolean canEditOrderItem(OrderDO order) { - if (order == null || order.getStatus() == null) { - return false; - } - return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) - || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); - } - - private Boolean canCancelOrderItem(OrderDO order) { - if (order == null || order.getStatus() == null) { - return false; - } - return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) - || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); - } - - private String resolveOrderItemConflictReason(String occupancyStatus) { - if ("PENDING_QUOTE".equals(occupancyStatus)) { - return "该时段已作为待报价预约保留"; - } - if ("CONFIRMED".equals(occupancyStatus)) { - return "该时段已确认占用"; - } - return null; - } - - /** - * Run business method `buildRequestedQuantityMap`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map buildRequestedQuantityMap(List orderItemDTOs) { - Map requestedQuantityByProductId = new HashMap<>(); - for (OrderItemDTO orderItemDTO : orderItemDTOs) { - if (orderItemDTO == null || orderItemDTO.getProductId() == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单商品信息不完整"); - } - requestedQuantityByProductId.merge( - orderItemDTO.getProductId(), - orderItemDTO.getQuantity() == null ? 0 : orderItemDTO.getQuantity(), - Integer::sum - ); - } - return requestedQuantityByProductId; - } - - /** - * Run business method `loadLockedCartItems`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param requestedProductIds parameter `requestedProductIds` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map loadLockedCartItems(Long userId, List requestedProductIds) { - if (requestedProductIds == null || requestedProductIds.isEmpty()) { - return Collections.emptyMap(); - } - - List lockedCartItems = cartMapper.selectByUserIdAndProductIdsForUpdate(userId, requestedProductIds); - Map lockedCartItemMap = new HashMap<>(); - for (CartDO cartDO : lockedCartItems) { - if (cartDO != null && cartDO.getProductId() != null) { - lockedCartItemMap.put(cartDO.getProductId(), cartDO); - } - } - return lockedCartItemMap; - } - - /** - * Run business method `validateUserCanCreateOrderInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateUserCanCreateOrderInShop(Long userId, Long shopId) { - if (!userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号已不可在该店铺下单,请切换门店后重试"); - } - } - - /** - * Run business method `resolveRequestedArtistId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolveRequestedArtistId(List orderItemDTOs) { - Long artistId = null; - for (OrderItemDTO orderItemDTO : orderItemDTOs) { - if (orderItemDTO == null || orderItemDTO.getArtistId() == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请为每个商品选择美甲师"); - } - if (artistId == null) { - artistId = orderItemDTO.getArtistId(); - continue; - } - if (!artistId.equals(orderItemDTO.getArtistId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("不同美甲师的项目请分开下单"); - } - } - if (artistId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请为每个商品选择美甲师"); - } - return artistId; - } - - /** - * Run business method `tryAcquireOrderLock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockKey parameter `lockKey` supplied by the caller - * @param lockToken parameter `lockToken` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean tryAcquireOrderLock(String lockKey, String lockToken) { - return Boolean.TRUE.equals( - stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockToken, ORDER_CREATE_LOCK_TTL) - ); - } - - /** - * Run business method `tryAcquireArtistOrderLock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockKey parameter `lockKey` supplied by the caller - * @param lockToken parameter `lockToken` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean tryAcquireArtistOrderLock(String lockKey, String lockToken) { - long deadline = System.currentTimeMillis() + ARTIST_LOCK_WAIT_TIMEOUT_MILLIS; - while (System.currentTimeMillis() <= deadline) { - if (tryAcquireOrderLock(lockKey, lockToken)) { - return true; - } - try { - Thread.sleep(ARTIST_LOCK_RETRY_INTERVAL_MILLIS); - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - return false; - } - } - return false; - } - - // 慢事务期间持续续租,避免下单锁在事务未完成时提前过期。 - /** - * Run business method `startOrderLockRenewal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockKey parameter `lockKey` supplied by the caller - * @param lockToken parameter `lockToken` supplied by the caller - * @return private LockLease result consumed by the caller or returned to the frontend - */ - private LockLease startOrderLockRenewal(String lockKey, String lockToken) { - if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { - return null; - } - - LockLease lockLease = new LockLease(lockKey, lockToken); - ScheduledFuture future = LOCK_RENEW_EXECUTOR.scheduleWithFixedDelay( - () -> renewOrderLock(lockLease), - ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS, - ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS, - TimeUnit.MILLISECONDS - ); - lockLease.attachFuture(future); - return lockLease; - } - - /** - * Run business method `renewOrderLock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockLease parameter `lockLease` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void renewOrderLock(LockLease lockLease) { - if (lockLease == null || !lockLease.isActive()) { - return; - } - try { - Long renewResult = stringRedisTemplate.execute( - RENEW_LOCK_SCRIPT, - Collections.singletonList(lockLease.getLockKey()), - lockLease.getLockToken(), - String.valueOf(ORDER_CREATE_LOCK_TTL_MILLIS) - ); - if (!Long.valueOf(1L).equals(renewResult)) { - lockLease.cancel(); - } - } catch (Exception ignored) { - } - } - - /** - * Run business method `stopOrderLockRenewal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockLease parameter `lockLease` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void stopOrderLockRenewal(LockLease lockLease) { - if (lockLease == null) { - return; - } - lockLease.cancel(); - } - - /** - * Run business method `releaseOrderLock`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockKey parameter `lockKey` supplied by the caller - * @param lockToken parameter `lockToken` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void releaseOrderLock(String lockKey, String lockToken) { - if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { - return; - } - stringRedisTemplate.execute(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey), lockToken); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userCache parameter `userCache` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO getUserFromCache(Long userId, Map userCache) { - if (userId == null) { - return null; - } - if (userCache.containsKey(userId)) { - return userCache.get(userId); - } - UserDO userDO = userMapper.selectById(userId); - userCache.put(userId, userDO); - return userDO; - } - - /** - * Run business method `resolveCustomerNickname`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param customer parameter `customer` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveCustomerNickname(UserDO customer) { - if (customer == null) { - return "用户"; - } - if (StringUtils.hasText(customer.getNickname())) { - return customer.getNickname(); - } - if (StringUtils.hasText(customer.getAccount())) { - return customer.getAccount(); - } - return "用户"; - } - - /** - * Run business method `maskPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String maskPhone(String phone) { - if (!StringUtils.hasText(phone)) { - return null; - } - String normalizedPhone = phone.trim(); - if (normalizedPhone.length() < 7) { - return normalizedPhone; - } - return normalizedPhone.substring(0, 3) - + "****" - + normalizedPhone.substring(normalizedPhone.length() - 4); - } - - /** - * Run business method `validateOrderQuantity`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param quantity parameter `quantity` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateOrderQuantity(Integer quantity) { - if (quantity == null || quantity < 1) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param 0 parameter `0` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单商品数量必须大于 0"); - } - } - - /** - * Run business method `validateArtistForProduct`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param product parameter `product` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO validateArtistForProduct(ProductDO product, Long artistId) { - if (artistId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请为每个商品选择美甲师"); - } - - UserDO artist = userMapper.selectById(artistId); - if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("美甲师不存在或已删除"); - } - if (!bookableArtistSupport.isBookableServiceUser(artist)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("指定用户不是可预约美甲服务人员"); - } - if (!Integer.valueOf(1).equals(artist.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("美甲师当前不可预约"); - } - if (product.getShopId() != null && !userShopBindingSupport.isUserAccessibleInShop(artistId, product.getShopId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该美甲师不属于当前商品店铺"); - } - - if (product.getBookableArtists() != null && !product.getBookableArtists().isEmpty()) { - String[] artistIds = product.getBookableArtists().split(","); - boolean isBookable = false; - for (String currentArtistId : artistIds) { - if (currentArtistId.trim().equals(artistId.toString())) { - isBookable = true; - break; - } - } - if (!isBookable) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该美甲师无法预约此商品"); - } - } - - return artist; - } - - /** - * Run business method `collectTagNames`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagNames parameter `tagNames` supplied by the caller - * @param tags parameter `tags` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void collectTagNames(Set tagNames, String tags) { - if (tags == null || tags.isBlank()) { - return; - } - - for (String tagId : tags.split(";")) { - if (tagId == null || tagId.isBlank()) { - continue; - } - try { - TagVO tagVO = tagService.getTagById(Long.parseLong(tagId.trim())); - if (tagVO != null && tagVO.getTagName() != null && !tagVO.getTagName().isBlank()) { - tagNames.add(tagVO.getTagName()); - } - } catch (NumberFormatException ignored) { - } - } - } - - /** - * Run business method `parseAppointmentTime`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param appointmentTime parameter `appointmentTime` supplied by the caller - * @return private LocalDateTime result consumed by the caller or returned to the frontend - */ - private LocalDateTime parseAppointmentTime(String appointmentTime) { - if (appointmentTime == null || appointmentTime.isBlank()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请为每个商品选择预约时间"); - } - - String normalized = appointmentTime.trim(); - for (DateTimeFormatter formatter : APPOINTMENT_INPUT_FORMATTERS) { - try { - return LocalDateTime.parse(normalized, formatter); - } catch (DateTimeParseException ignored) { - } - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("预约时间格式不正确"); - } - - /** - * Run business method `validateAppointmentTime`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param appointmentTime parameter `appointmentTime` supplied by the caller - * @param productTitle parameter `productTitle` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateAppointmentTime(LocalDateTime appointmentTime, String productTitle) { - if (!appointmentTime.isAfter(LocalDateTime.now())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("商品「" + productTitle + "」的预约时间必须晚于当前时间"); - } - } - - /** - * Run business method `validateBusinessHours`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shop parameter `shop` supplied by the caller - * @param appointmentTime parameter `appointmentTime` supplied by the caller - * @param appointmentEndTime parameter `appointmentEndTime` supplied by the caller - * @param productTitle parameter `productTitle` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateBusinessHours(ShopDO shop, LocalDateTime appointmentTime, LocalDateTime appointmentEndTime, String productTitle) { - if (shop == null || shop.getBusinessHours() == null || shop.getBusinessHours().isBlank()) { - return; - } - - String normalizedBusinessHours = shop.getBusinessHours() - .replace(':', ':') - .replace('-', '-') - .replace('—', '-') - .trim(); - Matcher matcher = BUSINESS_HOURS_PATTERN.matcher(normalizedBusinessHours); - if (!matcher.matches()) { - return; - } - - LocalTime openTime = LocalTime.parse(matcher.group(1), DateTimeFormatter.ofPattern("H:mm")); - LocalTime closeTime = LocalTime.parse(matcher.group(2), DateTimeFormatter.ofPattern("H:mm")); - if (!closeTime.isAfter(openTime)) { - return; - } - - if (!appointmentTime.toLocalDate().equals(appointmentEndTime.toLocalDate()) - || appointmentTime.toLocalTime().isBefore(openTime) - || appointmentEndTime.toLocalTime().isAfter(closeTime)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("商品「" + productTitle + "」的预约时间超出门店营业时间"); - } - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @param shopCache parameter `shopCache` supplied by the caller - * @return private ShopDO result consumed by the caller or returned to the frontend - */ - private ShopDO getShopFromCache(Long shopId, Map shopCache) { - if (shopId == null) { - return null; - } - if (shopCache.containsKey(shopId)) { - return shopCache.get(shopId); - } - - ShopDO shop = shopMapper.selectById(shopId); - if (shop != null && Integer.valueOf(1).equals(shop.getIsDelete())) { - shop = null; - } - shopCache.put(shopId, shop); - return shop; - } - - /** - * Run business method `validateRequestedSlotConflicts`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestedSlots parameter `requestedSlots` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateRequestedSlotConflicts(List requestedSlots) { - if (requestedSlots.size() <= 1) { - return; - } - - requestedSlots.sort(Comparator.comparing(AppointmentSlot::getStartTime)); - for (int i = 1; i < requestedSlots.size(); i++) { - AppointmentSlot previous = requestedSlots.get(i - 1); - AppointmentSlot current = requestedSlots.get(i); - if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) { - throw new RuntimeException("所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间"); - } - } - } - - /** - * Run business method `validateArtistScheduleConflicts`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param artistId parameter `artistId` supplied by the caller - * @param requestedSlots parameter `requestedSlots` supplied by the caller - * @param productCache parameter `productCache` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateArtistScheduleConflicts(Long artistId, List requestedSlots, Map productCache) { - if (artistId == null || requestedSlots.isEmpty()) { - return; - } - - for (AppointmentSlot requestedSlot : requestedSlots) { - int activeOccupancyCount = appointmentReservationMapper.countOverlappingActive( - artistId, - requestedSlot.getStartTime(), - requestedSlot.getEndTime() - ); - if (activeOccupancyCount > 0) { - throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约占用冲突,请重新选择"); - } - } - - List existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId); - if (existingAppointments == null || existingAppointments.isEmpty()) { - return; - } - - for (OrderItemDO existingItem : existingAppointments) { - if (existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) { - continue; - } - - ProductDO existingProduct = getProductFromCache(existingItem.getProductId(), productCache); - if (existingProduct == null) { - continue; - } - - long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * Math.max(1, existingItem.getQuantity()); - LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes); - - for (AppointmentSlot requestedSlot : requestedSlots) { - if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) { - throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择"); - } - } - } - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param productCache parameter `productCache` supplied by the caller - * @return private ProductDO result consumed by the caller or returned to the frontend - */ - private ProductDO getProductFromCache(Long productId, Map productCache) { - if (productId == null) { - return null; - } - if (productCache.containsKey(productId)) { - return productCache.get(productId); - } - - ProductDO product = productMapper.selectById(productId); - if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) { - product = null; - } - productCache.put(productId, product); - return product; - } - - /** - * Run business method `resolveServiceDurationMinutes`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param product parameter `product` supplied by the caller - * @return private long result consumed by the caller or returned to the frontend - */ - private long resolveServiceDurationMinutes(ProductDO product) { - if (product == null || product.getApproximateDuration() == null || product.getApproximateDuration().isBlank()) { - return DEFAULT_SERVICE_DURATION_MINUTES; - } - - Matcher matcher = DURATION_PATTERN.matcher(product.getApproximateDuration()); - if (matcher.find()) { - try { - return Math.max(1L, Long.parseLong(matcher.group(1))); - } catch (NumberFormatException ignored) { - } - } - return DEFAULT_SERVICE_DURATION_MINUTES; - } - - /** - * Run business method `hasOverlap`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param startA parameter `startA` supplied by the caller - * @param endA parameter `endA` supplied by the caller - * @param startB parameter `startB` supplied by the caller - * @param endB parameter `endB` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean hasOverlap(LocalDateTime startA, LocalDateTime endA, LocalDateTime startB, LocalDateTime endB) { - return startA.isBefore(endB) && startB.isBefore(endA); - } - - /** - * Run business method `formatAppointmentTime`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param appointmentTime parameter `appointmentTime` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String formatAppointmentTime(LocalDateTime appointmentTime) { - if (appointmentTime == null) { - return null; - } - return appointmentTime.format(APPOINTMENT_OUTPUT_FORMATTER); - } - - /** - * Run business method `resolveRequestedCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderDTO parameter `orderDTO` supplied by the caller - * @param availableCoupons parameter `availableCoupons` supplied by the caller - * @return private CouponSelection result consumed by the caller or returned to the frontend - */ - private CouponSelection resolveRequestedCoupon(OrderDTO orderDTO, List availableCoupons) { - if (orderDTO == null || orderDTO.getCouponId() == null || orderDTO.getCouponId() <= 0) { - return null; - } - - String requestedSourceType = normalizeCouponSourceType(orderDTO.getCouponSourceType()); - List matchedCoupons = availableCoupons.stream() - .filter(coupon -> orderDTO.getCouponId().equals(coupon.getId())) - .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) - .toList(); - - if (matchedCoupons.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前订单不可使用所选优惠券"); - } - - UserCouponVO selectedCoupon = matchedCoupons.stream() - .filter(coupon -> COUPON_SOURCE_USER.equals(coupon.getSourceType())) - .findFirst() - .orElse(matchedCoupons.get(0)); - - return new CouponSelection( - selectedCoupon.getSourceType(), - selectedCoupon.getCouponId(), - COUPON_SOURCE_USER.equals(selectedCoupon.getSourceType()) ? selectedCoupon.getId() : null - ); - } - - /** - * Run business method `selectBestAvailableCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param availableCoupons parameter `availableCoupons` supplied by the caller - * @param totalAmount parameter `totalAmount` supplied by the caller - * @return private CouponSelection result consumed by the caller or returned to the frontend - */ - private CouponSelection selectBestAvailableCoupon(List availableCoupons, BigDecimal totalAmount) { - return availableCoupons.stream() - .filter(coupon -> coupon.getCouponId() != null) - .max(Comparator.comparing(coupon -> calculateCouponDiscountAmount(coupon, totalAmount))) - .map(coupon -> new CouponSelection( - coupon.getSourceType(), - coupon.getCouponId(), - COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null - )) - .orElse(null); - } - - /** - * Run business method `normalizeCouponSourceType`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponSourceType parameter `couponSourceType` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeCouponSourceType(String couponSourceType) { - if (couponSourceType == null || couponSourceType.isBlank()) { - return null; - } - return couponSourceType.trim().toUpperCase(); - } - - /** - * Run business method `isExplicitNoCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param orderDTO parameter `orderDTO` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isExplicitNoCoupon(OrderDTO orderDTO) { - return orderDTO != null - && orderDTO.getCouponId() == null - && COUPON_SOURCE_NONE.equalsIgnoreCase(orderDTO.getCouponSourceType()); - } - - /** - * Run business method `calculateCouponDiscountAmount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param coupon parameter `coupon` supplied by the caller - * @param totalAmount parameter `totalAmount` supplied by the caller - * @return private BigDecimal result consumed by the caller or returned to the frontend - */ - private BigDecimal calculateCouponDiscountAmount(UserCouponVO coupon, BigDecimal totalAmount) { - if (coupon == null || totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) { - return BigDecimal.ZERO; - } - - if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null && !coupon.getDiscountValue().isBlank()) { - BigDecimal discountValue = new BigDecimal(coupon.getDiscountValue()); - BigDecimal discountedAmount = totalAmount.multiply(discountValue) - .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); - return totalAmount.subtract(discountedAmount); - } - - if (coupon.getCouponType() == 2 && coupon.getReduceAmount() != null && !coupon.getReduceAmount().isBlank()) { - return new BigDecimal(coupon.getReduceAmount()); - } - - return BigDecimal.ZERO; - } - - /** - * Run business method `applyCouponDiscount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param totalAmount parameter `totalAmount` supplied by the caller - * @param coupon parameter `coupon` supplied by the caller - * @return private BigDecimal result consumed by the caller or returned to the frontend - */ - private BigDecimal applyCouponDiscount(BigDecimal totalAmount, CouponDO coupon) { - if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null) { - return totalAmount.multiply(coupon.getDiscountValue()) - .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); - } - if (coupon.getCouponType() == 2 && coupon.getReduceAmount() != null) { - BigDecimal actualAmount = totalAmount.subtract(coupon.getReduceAmount()); - return actualAmount.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : actualAmount; - } - return totalAmount; - } - - /** - * Run business method `consumeUserCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userCouponId parameter `userCouponId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void consumeUserCoupon(Long userCouponId, Long userId) { - if (userCouponId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户优惠券信息缺失"); - } - - UserCouponDO userCoupon = userCouponMapper.selectById(userCouponId); - if (userCoupon == null || Integer.valueOf(1).equals(userCoupon.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("优惠券不存在或已失效"); - } - if (!userId.equals(userCoupon.getUserId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("优惠券不属于当前用户"); - } - if (userCoupon.getStatus() == null || userCoupon.getStatus() != 1) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("优惠券已被使用或不可用"); - } - - userCoupon.setStatus(2); - userCoupon.setUseTime(LocalDateTime.now()); - userCouponMapper.updateById(userCoupon); - updateCouponUsedCount(userCoupon.getCouponId(), 1); - } - - /** - * Run business method `restoreUserCoupon`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param order parameter `order` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void restoreUserCoupon(OrderDO order, Long userId) { - if (order == null - || !COUPON_SOURCE_USER.equals(order.getCouponSourceType()) - || order.getUserCouponId() == null - || userId == null) { - return; - } - - UserCouponDO userCoupon = userCouponMapper.selectById(order.getUserCouponId()); - if (userCoupon == null || !userId.equals(userCoupon.getUserId()) || userCoupon.getStatus() == null || userCoupon.getStatus() != 2) { - return; - } - - userCoupon.setStatus(1); - userCoupon.setUseTime(null); - userCouponMapper.updateById(userCoupon); - updateCouponUsedCount(userCoupon.getCouponId(), -1); - } - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param couponId parameter `couponId` supplied by the caller - * @param delta parameter `delta` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void updateCouponUsedCount(Long couponId, int delta) { - if (couponId == null || delta == 0) { - return; - } - - CouponDO couponDO = couponMapper.selectById(couponId); - if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { - return; - } - - int currentUsedCount = couponDO.getUsedCount() == null ? 0 : couponDO.getUsedCount(); - couponDO.setUsedCount(Math.max(0, currentUsedCount + delta)); - couponMapper.updateById(couponDO); - } - - /** - * Purpose: LockLease supports OrderServiceImpl.java by holding or executing the lock lease business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final class LockLease { - /** - * Variable `lockKey`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String lockKey; - /** - * Variable `lockToken`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String lockToken; - /** - * Purpose: future supports OrderServiceImpl.java by holding or executing the future business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private volatile ScheduledFuture future; - /** - * Purpose: active supports OrderServiceImpl.java by holding or executing the active business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private volatile boolean active = true; - - /** - * Run business method `LockLease`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param lockKey parameter `lockKey` supplied by the caller - * @param lockToken parameter `lockToken` supplied by the caller - * @return private result consumed by the caller or returned to the frontend - */ - private LockLease(String lockKey, String lockToken) { - this.lockKey = lockKey; - this.lockToken = lockToken; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private String result consumed by the caller or returned to the frontend - */ - private String getLockKey() { - return lockKey; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private String result consumed by the caller or returned to the frontend - */ - private String getLockToken() { - return lockToken; - } - - /** - * Run business method `isActive`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isActive() { - return active; - } - - /** - * Run business method `attachFuture`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param future parameter `future` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void attachFuture(ScheduledFuture future) { - this.future = future; - if (!active && future != null) { - future.cancel(false); - } - } - - /** - * Run business method `cancel`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private void result consumed by the caller or returned to the frontend - */ - private void cancel() { - active = false; - ScheduledFuture currentFuture = future; - if (currentFuture != null) { - currentFuture.cancel(false); - } - } - } - - /** - * Purpose: LockRenewThreadFactory supports OrderServiceImpl.java by holding or executing the lock renew thread factory business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final class LockRenewThreadFactory implements ThreadFactory { - @Override - /** - * Run business method `newThread`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param runnable parameter `runnable` supplied by the caller - * @return Thread result consumed by the caller or returned to the frontend - */ - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable, "order-lock-renew"); - thread.setDaemon(true); - return thread; - } - } - - /** - * Purpose: CouponSelection supports OrderServiceImpl.java by holding or executing the coupon selection business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final class CouponSelection { - /** - * Variable `sourceType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String sourceType; - /** - * Variable `couponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final Long couponId; - /** - * Variable `userCouponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final Long userCouponId; - - /** - * Run business method `CouponSelection`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sourceType parameter `sourceType` supplied by the caller - * @param couponId parameter `couponId` supplied by the caller - * @param userCouponId parameter `userCouponId` supplied by the caller - * @return private result consumed by the caller or returned to the frontend - */ - private CouponSelection(String sourceType, Long couponId, Long userCouponId) { - this.sourceType = sourceType; - this.couponId = couponId; - this.userCouponId = userCouponId; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private String result consumed by the caller or returned to the frontend - */ - private String getSourceType() { - return sourceType; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long getCouponId() { - return couponId; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long getUserCouponId() { - return userCouponId; - } - } - - private static final class CheckoutPricingContext { - private final BigDecimal totalAmount; - private final Long shopId; - private final String productTagNames; - - private CheckoutPricingContext(BigDecimal totalAmount, Long shopId, String productTagNames) { - this.totalAmount = totalAmount; - this.shopId = shopId; - this.productTagNames = productTagNames; - } - - private BigDecimal getTotalAmount() { - return totalAmount; - } - - private Long getShopId() { - return shopId; - } - - private String getProductTagNames() { - return productTagNames; - } - } - - private static final class BookingValidationSlot { - private final Long productId; - private final String productTitle; - private final LocalDateTime startTime; - private final LocalDateTime endTime; - - private BookingValidationSlot(Long productId, String productTitle, LocalDateTime startTime, LocalDateTime endTime) { - this.productId = productId; - this.productTitle = productTitle; - this.startTime = startTime; - this.endTime = endTime; - } - - private Long getProductId() { - return productId; - } - - private String getProductTitle() { - return productTitle; - } - - private LocalDateTime getStartTime() { - return startTime; - } - - private LocalDateTime getEndTime() { - return endTime; - } - } - - /** - * Purpose: AppointmentSlot supports OrderServiceImpl.java by holding or executing the appointment slot business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final class AppointmentSlot { - /** - * Variable `productTitle`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String productTitle; - /** - * Variable `startTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final LocalDateTime startTime; - /** - * Variable `endTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final LocalDateTime endTime; - - /** - * Run business method `AppointmentSlot`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productTitle parameter `productTitle` supplied by the caller - * @param startTime parameter `startTime` supplied by the caller - * @param endTime parameter `endTime` supplied by the caller - * @return private result consumed by the caller or returned to the frontend - */ - private AppointmentSlot(String productTitle, LocalDateTime startTime, LocalDateTime endTime) { - this.productTitle = productTitle; - this.startTime = startTime; - this.endTime = endTime; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private String result consumed by the caller or returned to the frontend - */ - private String getProductTitle() { - return productTitle; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private LocalDateTime result consumed by the caller or returned to the frontend - */ - private LocalDateTime getStartTime() { - return startTime; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private LocalDateTime result consumed by the caller or returned to the frontend - */ - private LocalDateTime getEndTime() { - return endTime; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java deleted file mode 100644 index e754889c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.support; - -/** - * Purpose: OrderStateMachine supports OrderStateMachine.java by holding or executing the order state machine business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public final class OrderStateMachine { - - private OrderStateMachine() { - } - - /** - * Purpose: isAllowedTransition supports OrderStateMachine.java by holding or executing the is allowed transition business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static boolean isAllowedTransition(Integer fromStatus, Integer toStatus) { - OrderStatus from = OrderStatus.requireKnown(fromStatus); - OrderStatus to = OrderStatus.requireKnown(toStatus); - if (from == OrderStatus.PRICE_CONFIRMING) { - return to == OrderStatus.PENDING_SERVICE || to == OrderStatus.CANCELLED; - } - return from == OrderStatus.PENDING_SERVICE - && (to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED); - } - - /** - * Purpose: requireAllowedTransition supports OrderStateMachine.java by holding or executing the require allowed transition business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static void requireAllowedTransition(Integer fromStatus, Integer toStatus) { - if (!isAllowedTransition(fromStatus, toStatus)) { - throw new RuntimeException("订单状态不允许处理"); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java deleted file mode 100644 index 2e1ada17..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.support; - -import java.util.Arrays; - -/** - * Purpose: OrderStatus supports OrderStatus.java by holding or executing the order status business role. - * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. - */ -public enum OrderStatus { - PRICE_CONFIRMING(0), - PENDING_SERVICE(1), - COMPLETED(2), - CANCELLED(3); - - /** - * Purpose: code supports OrderStatus.java by holding or executing the code business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final int code; - - OrderStatus(int code) { - this.code = code; - } - - /** - * Purpose: getCode supports OrderStatus.java by holding or executing the get code business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public int getCode() { - return code; - } - - /** - * Purpose: requireKnown supports OrderStatus.java by holding or executing the require known business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static OrderStatus requireKnown(Integer code) { - return Arrays.stream(values()) - .filter(status -> Integer.valueOf(status.code).equals(code)) - .findFirst() - .orElseThrow(() -> new RuntimeException("无效的订单状态")); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/AfterSaleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/AfterSaleVO.java deleted file mode 100644 index b4bf3b33..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/AfterSaleVO.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -public class AfterSaleVO { - private Long id; - private String afterSaleNo; - private Long orderId; - private Long orderItemId; - private Long userId; - private Long shopId; - private String type; - private String reason; - private BigDecimal refundAmount; - private String status; - private Long auditUserId; - private String auditReason; - private LocalDateTime auditTime; - private Long refundOrderId; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CartArtistVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CartArtistVO.java deleted file mode 100644 index a36ea920..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CartArtistVO.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -@Data -/** - * CartArtistVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class CartArtistVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `name` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String name; - /** - * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String avatar; - /** - * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer userType; - /** - * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String roleLabel; - /** - * Field `participateProduction` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean participateProduction; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CartVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CartVO.java deleted file mode 100644 index 54dbe783..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CartVO.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.util.List; - -@Data -/** - * CartVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class CartVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long productId; - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String productTitle; - /** - * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String productImage; - /** - * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal price; - /** - * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer quantity; - /** - * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalPrice; - /** - * Field `tags` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String tags; - /** - * Field `tagNames` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String tagNames; - /** - * Field `approximateDuration` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String approximateDuration; - /** - * Field `bookableArtists` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String bookableArtists; - /** - * Field `availableBookableArtistCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer availableBookableArtistCount; - /** - * Field `bookableArtistRestricted` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean bookableArtistRestricted; - /** - * Field `availableArtists` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List availableArtists; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CheckoutCouponPreviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CheckoutCouponPreviewVO.java deleted file mode 100644 index bce909c5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CheckoutCouponPreviewVO.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 结算预览里的单张优惠说明。 - */ -@Data -public class CheckoutCouponPreviewVO { - - private Long id; - - private Long couponId; - - private Long userCouponId; - - private String sourceType; - - private String couponName; - - private Integer couponType; - - private String couponTypeName; - - private BigDecimal discountValue; - - private BigDecimal minAmount; - - private BigDecimal reduceAmount; - - private BigDecimal discountAmount; - - private Boolean available; - - private Boolean best; - - private Boolean vipAuto; - - private String displayText; - - private String savingText; - - private String unavailableReason; - - private LocalDateTime startTime; - - private LocalDateTime endTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CheckoutPreviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CheckoutPreviewVO.java deleted file mode 100644 index f21e42fa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/CheckoutPreviewVO.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * 结算页展示用预览结果。 - */ -@Data -public class CheckoutPreviewVO { - - private BigDecimal subtotalAmount = BigDecimal.ZERO; - - private BigDecimal savedAmount = BigDecimal.ZERO; - - private BigDecimal payableAmount = BigDecimal.ZERO; - - private CheckoutCouponPreviewVO bestCoupon; - - private List availableCoupons = new ArrayList<>(); - - private List unavailableCoupons = new ArrayList<>(); - - private Boolean bookingAvailable; - - private List bookingIssues = new ArrayList<>(); - - private String vipTip; - - private String summaryText; - - @Data - public static class CheckoutIssueVO { - private String code; - - private String message; - - private Long itemId; - - private Long productId; - - private String productTitle; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistChangeOptionsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistChangeOptionsVO.java deleted file mode 100644 index 72d0e49d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistChangeOptionsVO.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.util.List; - -@Data -/** - * Purpose: OrderArtistChangeOptionsVO supports OrderArtistChangeOptionsVO.java by holding or executing the order artist change options vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistChangeOptionsVO { - /** - * Purpose: orderId supports OrderArtistChangeOptionsVO.java by holding or executing the order id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderId; - /** - * Purpose: orderItemId supports OrderArtistChangeOptionsVO.java by holding or executing the order item id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderItemId; - /** - * Purpose: currentArtistId supports OrderArtistChangeOptionsVO.java by holding or executing the current artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long currentArtistId; - /** - * Purpose: currentArtistName supports OrderArtistChangeOptionsVO.java by holding or executing the current artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String currentArtistName; - /** - * Purpose: artists supports OrderArtistChangeOptionsVO.java by holding or executing the artists business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private List artists; - - @Data - /** - * Purpose: ArtistOptionVO supports OrderArtistChangeOptionsVO.java by holding or executing the artist option vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class ArtistOptionVO { - /** - * Purpose: artistId supports OrderArtistChangeOptionsVO.java by holding or executing the artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long artistId; - /** - * Purpose: artistName supports OrderArtistChangeOptionsVO.java by holding or executing the artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String artistName; - /** - * Purpose: artistAvatar supports OrderArtistChangeOptionsVO.java by holding or executing the artist avatar business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String artistAvatar; - /** - * Purpose: userType supports OrderArtistChangeOptionsVO.java by holding or executing the user type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer userType; - /** - * Purpose: participateProduction supports OrderArtistChangeOptionsVO.java by holding or executing the participate production business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Boolean participateProduction; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistChangeRequestVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistChangeRequestVO.java deleted file mode 100644 index 7a910d10..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistChangeRequestVO.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -/** - * Purpose: OrderArtistChangeRequestVO supports OrderArtistChangeRequestVO.java by holding or executing the order artist change request vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistChangeRequestVO { - /** - * Purpose: id supports OrderArtistChangeRequestVO.java by holding or executing the id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long id; - /** - * Purpose: orderId supports OrderArtistChangeRequestVO.java by holding or executing the order id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderId; - /** - * Purpose: orderItemId supports OrderArtistChangeRequestVO.java by holding or executing the order item id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderItemId; - /** - * Purpose: productId supports OrderArtistChangeRequestVO.java by holding or executing the product id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long productId; - /** - * Purpose: productTitle supports OrderArtistChangeRequestVO.java by holding or executing the product title business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String productTitle; - /** - * Purpose: shopId supports OrderArtistChangeRequestVO.java by holding or executing the shop id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long shopId; - /** - * Purpose: userId supports OrderArtistChangeRequestVO.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - /** - * Purpose: customerId supports OrderArtistChangeRequestVO.java by holding or executing the customer id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long customerId; - /** - * Purpose: originalArtistId supports OrderArtistChangeRequestVO.java by holding or executing the original artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long originalArtistId; - /** - * Purpose: originalArtistName supports OrderArtistChangeRequestVO.java by holding or executing the original artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String originalArtistName; - /** - * Purpose: requestedArtistId supports OrderArtistChangeRequestVO.java by holding or executing the requested artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long requestedArtistId; - /** - * Purpose: requestedArtistName supports OrderArtistChangeRequestVO.java by holding or executing the requested artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String requestedArtistName; - /** - * Purpose: fromArtistId supports OrderArtistChangeRequestVO.java by holding or executing the from artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long fromArtistId; - /** - * Purpose: fromArtistName supports OrderArtistChangeRequestVO.java by holding or executing the from artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String fromArtistName; - /** - * Purpose: toArtistId supports OrderArtistChangeRequestVO.java by holding or executing the to artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long toArtistId; - /** - * Purpose: toArtistName supports OrderArtistChangeRequestVO.java by holding or executing the to artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String toArtistName; - /** - * Purpose: requesterId supports OrderArtistChangeRequestVO.java by holding or executing the requester id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long requesterId; - /** - * Purpose: requesterName supports OrderArtistChangeRequestVO.java by holding or executing the requester name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String requesterName; - /** - * Purpose: status supports OrderArtistChangeRequestVO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String status; - /** - * Purpose: statusText supports OrderArtistChangeRequestVO.java by holding or executing the status text business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String statusText; - /** - * Purpose: reason supports OrderArtistChangeRequestVO.java by holding or executing the reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String reason; - /** - * Purpose: rejectReason supports OrderArtistChangeRequestVO.java by holding or executing the reject reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String rejectReason; - /** - * Purpose: appointmentTime exposes the affected order-item appointment for customer-facing timelines. - * Usage: render this value beside the change request so users can confirm the change does not move their booking. - */ - private String appointmentTime; - /** - * Purpose: timeAffected tells clients whether the artist change modifies the booking time. - * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. - */ - private Boolean timeAffected; - /** - * Purpose: timeImpactText gives ready-to-display wording for the time impact. - * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. - */ - private String timeImpactText; - /** - * Purpose: originalPrice records the original order-item unit price for impact display. - * Usage: compare it with newPrice when rendering customer-facing price impact copy. - */ - private BigDecimal originalPrice; - /** - * Purpose: newPrice records the post-change order-item unit price for impact display. - * Usage: show it only when priceAffected is true or when detailed impact wording is needed. - */ - private BigDecimal newPrice; - /** - * Purpose: priceAffected tells clients whether the artist change modifies the order amount. - * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. - */ - private Boolean priceAffected; - /** - * Purpose: priceImpactText gives ready-to-display wording for the price impact. - * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. - */ - private String priceImpactText; - /** - * Purpose: reviewerId supports OrderArtistChangeRequestVO.java by holding or executing the reviewer id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long reviewerId; - /** - * Purpose: messageId supports OrderArtistChangeRequestVO.java by holding or executing the message id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long messageId; - /** - * Purpose: reviewTime supports OrderArtistChangeRequestVO.java by holding or executing the review time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime reviewTime; - /** - * Purpose: approvedTime supports OrderArtistChangeRequestVO.java by holding or executing the approved time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime approvedTime; - /** - * Purpose: rejectedTime supports OrderArtistChangeRequestVO.java by holding or executing the rejected time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime rejectedTime; - /** - * Purpose: expireTime supports OrderArtistChangeRequestVO.java by holding or executing the expire time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime expireTime; - /** - * Purpose: createTime supports OrderArtistChangeRequestVO.java by holding or executing the create time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistReviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistReviewVO.java deleted file mode 100644 index b73422e6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderArtistReviewVO.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -@Data -/** - * Purpose: OrderArtistReviewVO supports OrderArtistReviewVO.java by holding or executing the order artist review vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OrderArtistReviewVO { - /** - * Purpose: id supports OrderArtistReviewVO.java by holding or executing the id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long id; - /** - * Purpose: orderId supports OrderArtistReviewVO.java by holding or executing the order id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderId; - /** - * Purpose: orderItemId supports OrderArtistReviewVO.java by holding or executing the order item id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long orderItemId; - /** - * Purpose: productId supports OrderArtistReviewVO.java by holding or executing the product id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long productId; - /** - * Purpose: productTitle supports OrderArtistReviewVO.java by holding or executing the product title business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String productTitle; - /** - * Purpose: artistId supports OrderArtistReviewVO.java by holding or executing the artist id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long artistId; - /** - * Purpose: artistName supports OrderArtistReviewVO.java by holding or executing the artist name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String artistName; - /** - * Purpose: artistAvatar supports OrderArtistReviewVO.java by holding or executing the artist avatar business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String artistAvatar; - /** - * Purpose: userId supports OrderArtistReviewVO.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - /** - * Purpose: customerId supports OrderArtistReviewVO.java by holding or executing the customer id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long customerId; - /** - * Purpose: rating supports OrderArtistReviewVO.java by holding or executing the rating business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal rating; - /** - * Purpose: ratingScore supports OrderArtistReviewVO.java by holding or executing the rating score business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal ratingScore; - /** - * Purpose: content supports OrderArtistReviewVO.java by holding or executing the content business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String content; - /** - * Purpose: imageFileIds supports OrderArtistReviewVO.java by holding or executing the image file ids business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private List imageFileIds; - /** - * Purpose: status supports OrderArtistReviewVO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer status; - /** - * Purpose: statusText supports OrderArtistReviewVO.java by holding or executing the status text business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String statusText; - /** - * Purpose: reminderMessageId supports OrderArtistReviewVO.java by holding or executing the reminder message id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long reminderMessageId; - /** - * Purpose: submitTime supports OrderArtistReviewVO.java by holding or executing the submit time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime submitTime; - /** - * Purpose: submittedAt supports OrderArtistReviewVO.java by holding or executing the submitted at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime submittedAt; - /** - * Purpose: createTime supports OrderArtistReviewVO.java by holding or executing the create time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java deleted file mode 100644 index 398f5cb0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -/** - * OrderItemVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class OrderItemVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long productId; - /** - * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String productTitle; - /** - * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String productImage; - /** - * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer quantity; - /** - * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal price; - private BigDecimal referencePrice; - private BigDecimal quotedPrice; - private BigDecimal confirmedPrice; - /** - * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalPrice; - /** - * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long artistId; - /** - * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String artistName; - /** - * Field `artistAvatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String artistAvatar; - /** - * Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String appointmentTime; - private String occupancyStatus; - private Boolean canEdit; - private Boolean canCancel; - private String conflictReason; - /** - * Purpose: pendingReview supports OrderItemVO.java by holding or executing the pending review business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistReviewVO pendingReview; - /** - * Purpose: reviewSummary supports OrderItemVO.java by holding or executing the review summary business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistReviewVO reviewSummary; - /** - * Purpose: pendingArtistChangeRequest supports OrderItemVO.java by holding or executing the pending artist change request business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private OrderArtistChangeRequestVO pendingArtistChangeRequest; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderQuoteItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderQuoteItemVO.java deleted file mode 100644 index 849ffca0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderQuoteItemVO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class OrderQuoteItemVO { - private Long orderItemId; - private Long productId; - private String productTitle; - private Integer quantity; - private BigDecimal referencePrice; - private BigDecimal quotedPrice; - private BigDecimal confirmedPrice; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderQuoteMessageVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderQuoteMessageVO.java deleted file mode 100644 index 8f7af58b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderQuoteMessageVO.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -@Data -public class OrderQuoteMessageVO { - private Long id; - private Long orderId; - private Long actorId; - private String actorType; - private String actorTypeText; - private String action; - private String actionText; - private String remark; - private List items; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java deleted file mode 100644 index 927772c4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.order.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -@Data -/** - * OrderVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class OrderVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String orderNo; - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Purpose: shopName supports OrderVO.java by holding or executing the shop name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String shopName; - /** - * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalAmount; - /** - * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal actualAmount; - /** - * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long couponId; - /** - * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userCouponId; - /** - * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponSourceType; - /** - * Field `couponName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String couponName; - private String paymentStatus; - private BigDecimal payAmount; - private BigDecimal paidAmount; - private LocalDateTime payTime; - private String paymentMethod; - private String paymentOrderNo; - private String refundStatus; - private String customerRemark; - private String quoteStatus; - private String quoteStatusText; - private Boolean quoteUserConfirmed; - private Boolean quoteShopConfirmed; - private LocalDateTime quoteExpireTime; - private LocalDateTime quoteConfirmedTime; - private List quoteMessages; - /** - * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String customerNickname; - /** - * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String customerPhoneMasked; - /** - * Field `artistOrderSource` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String artistOrderSource; - /** - * Field `artistOrderSourceText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String artistOrderSourceText; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `statusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String statusText; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `items` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List items; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/BalanceChangeDetailController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/BalanceChangeDetailController.java deleted file mode 100644 index 509d4bcc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/BalanceChangeDetailController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.payment.dto.BalanceChangeDetailDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.service.BalanceChangeDetailService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户余额变动明细表 Controller - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"}) -@RequiredArgsConstructor -public class BalanceChangeDetailController { - /** - * Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceChangeDetailService balanceChangeDetailService; - - /** - * 创建余额变动明细 - * - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 余额变动明细ID - */ - @PostMapping("/create") - public Result createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO); - return Result.success(id); - } - - /** - * 更新余额变动明细 - * - * @param id 余额变动明细ID - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO); - return Result.success(success); - } - - /** - * 删除余额变动明细 - * - * @param id 余额变动明细ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalanceChangeDetail(@PathVariable Long id) { - boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id); - return Result.success(success); - } - - /** - * 根据ID查询余额变动明细 - * - * @param id 余额变动明细ID - * @return 余额变动明细VO - */ - @GetMapping("/get/{id}") - public Result getBalanceChangeDetailById(@PathVariable Long id) { - BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id); - return Result.success(balanceChangeDetailVO); - } - - /** - * 查询所有余额变动明细 - * - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalanceChangeDetails() { - List balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails(); - return Result.success(balanceChangeDetailVOs); - } - - /** - * 根据用户ID查询余额变动明细 - * - * @param userId 用户ID - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/user/{userId}") - public Result> listBalanceChangeDetailsByUserId(@PathVariable Long userId) { - List balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId); - return Result.success(balanceChangeDetailVOs); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/BalanceController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/BalanceController.java deleted file mode 100644 index 78e19274..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/BalanceController.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.payment.dto.BalanceDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceVO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.service.BalanceService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 用户余额信息表 Controller - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/balance", "/api/balance"}) -@RequiredArgsConstructor -public class BalanceController { - /** - * Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceService balanceService; - - /** - * 创建余额 - * - * @param balanceDTO 余额DTO - * @return 余额ID - */ - @PostMapping("/create") - public Result createBalance(@RequestBody BalanceDTO balanceDTO) { - Long id = balanceService.createBalance(balanceDTO); - return Result.success(id); - } - - /** - * 更新余额 - * - * @param id 余额ID - * @param balanceDTO 余额DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) { - boolean success = balanceService.updateBalance(id, balanceDTO); - return Result.success(success); - } - - /** - * 删除余额 - * - * @param id 余额ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalance(@PathVariable Long id) { - boolean success = balanceService.deleteBalance(id); - return Result.success(success); - } - - /** - * 根据ID查询余额 - * - * @param id 余额ID - * @return 余额VO - */ - @GetMapping("/get/{id}") - public Result getBalanceById(@PathVariable Long id) { - BalanceVO balanceVO = balanceService.getBalanceById(id); - return Result.success(balanceVO); - } - - /** - * 查询所有余额 - * - * @return 余额VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalances() { - List balanceVOs = balanceService.listAllBalances(); - return Result.success(balanceVOs); - } - - /** - * 根据用户ID查询余额 - * - * @param userId 用户ID - * @return 余额VO - */ - @GetMapping("/get/user/{userId}") - public Result getBalanceByUserId(@PathVariable Long userId) { - BalanceVO balanceVO = balanceService.getBalanceByUserId(userId); - return Result.success(balanceVO); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/PaymentController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/PaymentController.java deleted file mode 100644 index 05335c82..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/controller/front/PaymentController.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.payment.service.PaymentService; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.PaymentOrderVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequestMapping("/payment") -@RequiredArgsConstructor -public class PaymentController { - - private final PaymentService paymentService; - - @PostMapping("/order/{orderId}/prepare") - public Result prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.prepareOrderPayment(userId, orderId)); - } - - @PostMapping("/order/{orderId}/mock-success") - public Result mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/dto/BalanceChangeDetailDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/dto/BalanceChangeDetailDTO.java deleted file mode 100644 index 776b1575..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/dto/BalanceChangeDetailDTO.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.dto; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 用户余额变动明细表 DTO - * 用于余额变动明细信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class BalanceChangeDetailDTO { - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 本次变动金额(正数为增加,负数为减少) - */ - private BigDecimal amount; - - /** - * 变动类型(如充值、消费、退款) - */ - private String type; - - /** - * 变动后的当前余额 - */ - private BigDecimal currentBalance; - /** - * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal beforeBalance; - /** - * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal afterBalance; - /** - * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String changeScene; - /** - * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long relatedOrderId; - /** - * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String relatedOrderNo; - /** - * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String externalOrderNo; - /** - * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long operatorId; - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - - /** - * 变动时间 - */ - private LocalDateTime changeTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/dto/BalanceDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/dto/BalanceDTO.java deleted file mode 100644 index 435a9f42..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/dto/BalanceDTO.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.dto; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 用户余额信息表 DTO - * 用于余额信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class BalanceDTO { - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 当前余额 - */ - private BigDecimal amount; - /** - * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalRechargeAmount; - /** - * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime lastRechargeTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/BalanceChangeDetailDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/BalanceChangeDetailDO.java deleted file mode 100644 index 065ed1eb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/BalanceChangeDetailDO.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 用户余额变动明细表 DO - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@TableName("t_balance_change_detail") -public class BalanceChangeDetailDO { - - @TableId(type = IdType.ASSIGN_ID) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - - /** - * 关联用户表主键 - */ - @TableField("user_id") - private Long userId; - - /** - * 本次变动金额(正数为增加,负数为减少) - */ - @TableField("amount") - private BigDecimal amount; - - /** - * 变动类型(如充值、消费、退款) - */ - @TableField("type") - private String type; - - /** - * 变动后的当前余额 - */ - @TableField("current_balance") - private BigDecimal currentBalance; - - /** - * 变动时间 - */ - @TableField("before_balance") - private BigDecimal beforeBalance; - - @TableField("after_balance") - /** - * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal afterBalance; - - @TableField("change_scene") - /** - * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String changeScene; - - @TableField("related_order_id") - /** - * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long relatedOrderId; - - @TableField("related_order_no") - /** - * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String relatedOrderNo; - - @TableField("external_order_no") - /** - * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String externalOrderNo; - - @TableField("operator_id") - /** - * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long operatorId; - - @TableField("remark") - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - - @TableField("change_time") - /** - * Field `changeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime changeTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/BalanceDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/BalanceDO.java deleted file mode 100644 index cb423cd9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/BalanceDO.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.entity; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 用户余额信息表 DO - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@TableName("t_balance") -public class BalanceDO { - - @TableId(type = IdType.ASSIGN_ID) - /** - * Purpose: id supports BalanceDO.java by holding or executing the id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long id; - - @TableField(fill = FieldFill.INSERT) - /** - * Purpose: createTime supports BalanceDO.java by holding or executing the create time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime createTime; - - /** - * 关联用户表主键 - */ - @TableField("user_id") - private Long userId; - - /** - * 当前余额 - */ - @TableField("amount") - private BigDecimal amount; - - /** - * 最近一次更新时间 - */ - @TableField("total_recharge_amount") - private BigDecimal totalRechargeAmount; - - @TableField("last_recharge_time") - /** - * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime lastRechargeTime; - - @TableField("last_update_time") - /** - * Field `lastUpdateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime lastUpdateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/PaymentOrderDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/PaymentOrderDO.java deleted file mode 100644 index 6fd079c9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/PaymentOrderDO.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_payment_order") -public class PaymentOrderDO extends BaseEntity { - @TableField("pay_no") - private String payNo; - @TableField("order_id") - private Long orderId; - @TableField("order_no") - private String orderNo; - @TableField("user_id") - private Long userId; - @TableField("shop_id") - private Long shopId; - @TableField("channel") - private String channel; - @TableField("status") - private String status; - @TableField("pay_amount") - private BigDecimal payAmount; - @TableField("paid_amount") - private BigDecimal paidAmount; - @TableField("pay_time") - private LocalDateTime payTime; - @TableField("expire_time") - private LocalDateTime expireTime; - @TableField("operator_id") - private Long operatorId; - @TableField("remark") - private String remark; - @TableField("idempotency_key") - private String idempotencyKey; - @TableField("raw_payload") - private String rawPayload; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/RefundOrderDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/RefundOrderDO.java deleted file mode 100644 index ee28d744..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/entity/RefundOrderDO.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_refund_order") -public class RefundOrderDO extends BaseEntity { - @TableField("refund_no") - private String refundNo; - @TableField("after_sale_id") - private Long afterSaleId; - @TableField("payment_order_id") - private Long paymentOrderId; - @TableField("order_id") - private Long orderId; - @TableField("status") - private String status; - @TableField("refund_amount") - private BigDecimal refundAmount; - @TableField("refund_time") - private LocalDateTime refundTime; - @TableField("channel") - private String channel; - @TableField("external_refund_no") - private String externalRefundNo; - @TableField("fail_reason") - private String failReason; - @TableField("idempotency_key") - private String idempotencyKey; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/BalanceChangeDetailMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/BalanceChangeDetailMapper.java deleted file mode 100644 index 41263098..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/BalanceChangeDetailMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceChangeDetailDO; - -/** - * 用户余额变动明细表 Mapper - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface BalanceChangeDetailMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/BalanceMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/BalanceMapper.java deleted file mode 100644 index 944c26e2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/BalanceMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceDO; - -/** - * 用户余额信息表 Mapper - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface BalanceMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/PaymentOrderMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/PaymentOrderMapper.java deleted file mode 100644 index 2f80b05c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/PaymentOrderMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.PaymentOrderDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -@Mapper -public interface PaymentOrderMapper extends BaseMapper { - @Select("SELECT * FROM t_payment_order WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time DESC, id DESC LIMIT 1") - PaymentOrderDO selectLatestByOrderId(@Param("orderId") Long orderId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/RefundOrderMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/RefundOrderMapper.java deleted file mode 100644 index 66256c3b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/mapper/RefundOrderMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.RefundOrderDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface RefundOrderMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/BalanceChangeDetailService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/BalanceChangeDetailService.java deleted file mode 100644 index 58ccc373..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/BalanceChangeDetailService.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceChangeDetailDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.dto.BalanceChangeDetailDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceChangeDetailVO; - -import java.util.List; - -/** - * 用户余额变动明细表 Service - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface BalanceChangeDetailService extends IService { - - /** - * 创建余额变动明细 - * - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 余额变动明细ID - */ - Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO); - - /** - * 更新余额变动明细 - * - * @param id 余额变动明细ID - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 是否更新成功 - */ - boolean updateBalanceChangeDetail(Long id, BalanceChangeDetailDTO balanceChangeDetailDTO); - - /** - * 删除余额变动明细 - * - * @param id 余额变动明细ID - * @return 是否删除成功 - */ - boolean deleteBalanceChangeDetail(Long id); - - /** - * 根据ID查询余额变动明细 - * - * @param id 余额变动明细ID - * @return 余额变动明细VO - */ - BalanceChangeDetailVO getBalanceChangeDetailById(Long id); - - /** - * 查询所有余额变动明细 - * - * @return 余额变动明细VO列表 - */ - List listAllBalanceChangeDetails(); - - /** - * 根据用户ID查询余额变动明细 - * - * @param userId 用户ID - * @return 余额变动明细VO列表 - */ - List listBalanceChangeDetailsByUserId(Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/BalanceService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/BalanceService.java deleted file mode 100644 index 22ca74b5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/BalanceService.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.dto.BalanceDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceVO; - -import java.util.List; - -/** - * 用户余额信息表 Service - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface BalanceService extends IService { - - /** - * 创建余额 - * - * @param balanceDTO 余额DTO - * @return 余额ID - */ - Long createBalance(BalanceDTO balanceDTO); - - /** - * 更新余额 - * - * @param id 余额ID - * @param balanceDTO 余额DTO - * @return 是否更新成功 - */ - boolean updateBalance(Long id, BalanceDTO balanceDTO); - - /** - * 删除余额 - * - * @param id 余额ID - * @return 是否删除成功 - */ - boolean deleteBalance(Long id); - - /** - * 根据ID查询余额 - * - * @param id 余额ID - * @return 余额VO - */ - BalanceVO getBalanceById(Long id); - - /** - * 查询所有余额 - * - * @return 余额VO列表 - */ - List listAllBalances(); - - /** - * 根据用户ID查询余额 - * - * @param userId 用户ID - * @return 余额VO - */ - BalanceVO getBalanceByUserId(Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/PaymentService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/PaymentService.java deleted file mode 100644 index 929f02c6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/PaymentService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.service; - -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.PaymentOrderVO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.RefundOrderVO; - -public interface PaymentService { - PaymentOrderVO prepareOrderPayment(Long userId, Long orderId); - - PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark); - - RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java deleted file mode 100644 index 58d12eaf..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceChangeDetailDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.dto.BalanceChangeDetailDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.mapper.BalanceChangeDetailMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.service.BalanceChangeDetailService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * 用户余额变动明细表 Service 实现 - * 对应数据库表 t_balance_change_detail - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class BalanceChangeDetailServiceImpl extends ServiceImpl implements BalanceChangeDetailService { - /** - * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceChangeDetailMapper balanceChangeDetailMapper; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO) { - BalanceChangeDetailDO balanceChangeDetailDO = new BalanceChangeDetailDO(); - balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); - balanceChangeDetailDO.setAmount(balanceChangeDetailDTO.getAmount()); - balanceChangeDetailDO.setType(balanceChangeDetailDTO.getType()); - balanceChangeDetailDO.setCurrentBalance(balanceChangeDetailDTO.getCurrentBalance()); - balanceChangeDetailDO.setBeforeBalance(balanceChangeDetailDTO.getBeforeBalance()); - balanceChangeDetailDO.setAfterBalance(balanceChangeDetailDTO.getAfterBalance()); - balanceChangeDetailDO.setChangeScene(balanceChangeDetailDTO.getChangeScene()); - balanceChangeDetailDO.setRelatedOrderId(balanceChangeDetailDTO.getRelatedOrderId()); - balanceChangeDetailDO.setRelatedOrderNo(balanceChangeDetailDTO.getRelatedOrderNo()); - balanceChangeDetailDO.setExternalOrderNo(balanceChangeDetailDTO.getExternalOrderNo()); - balanceChangeDetailDO.setOperatorId(balanceChangeDetailDTO.getOperatorId()); - balanceChangeDetailDO.setRemark(balanceChangeDetailDTO.getRemark()); - balanceChangeDetailDO.setChangeTime(balanceChangeDetailDTO.getChangeTime()); - balanceChangeDetailMapper.insert(balanceChangeDetailDO); - return balanceChangeDetailDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateBalanceChangeDetail(Long id, BalanceChangeDetailDTO balanceChangeDetailDTO) { - BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); - if (balanceChangeDetailDO == null) { - return false; - } - balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); - balanceChangeDetailDO.setAmount(balanceChangeDetailDTO.getAmount()); - balanceChangeDetailDO.setType(balanceChangeDetailDTO.getType()); - balanceChangeDetailDO.setCurrentBalance(balanceChangeDetailDTO.getCurrentBalance()); - balanceChangeDetailDO.setBeforeBalance(balanceChangeDetailDTO.getBeforeBalance()); - balanceChangeDetailDO.setAfterBalance(balanceChangeDetailDTO.getAfterBalance()); - balanceChangeDetailDO.setChangeScene(balanceChangeDetailDTO.getChangeScene()); - balanceChangeDetailDO.setRelatedOrderId(balanceChangeDetailDTO.getRelatedOrderId()); - balanceChangeDetailDO.setRelatedOrderNo(balanceChangeDetailDTO.getRelatedOrderNo()); - balanceChangeDetailDO.setExternalOrderNo(balanceChangeDetailDTO.getExternalOrderNo()); - balanceChangeDetailDO.setOperatorId(balanceChangeDetailDTO.getOperatorId()); - balanceChangeDetailDO.setRemark(balanceChangeDetailDTO.getRemark()); - balanceChangeDetailDO.setChangeTime(balanceChangeDetailDTO.getChangeTime()); - return balanceChangeDetailMapper.updateById(balanceChangeDetailDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteBalanceChangeDetail(Long id) { - return balanceChangeDetailMapper.deleteById(id) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return BalanceChangeDetailVO result consumed by the caller or returned to the frontend - */ - public BalanceChangeDetailVO getBalanceChangeDetailById(Long id) { - BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); - if (balanceChangeDetailDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param balanceChangeDetailDO parameter `balanceChangeDetailDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(balanceChangeDetailDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllBalanceChangeDetails() { - List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList(null); - return balanceChangeDetailDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listBalanceChangeDetailsByUserId(Long userId) { - List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList( - Wrappers.lambdaQuery(BalanceChangeDetailDO.class) - .eq(BalanceChangeDetailDO::getUserId, userId) - ); - return balanceChangeDetailDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param balanceChangeDetailDO 余额变动明细DO - * @return 余额变动明细VO - */ - private BalanceChangeDetailVO convertToVO(BalanceChangeDetailDO balanceChangeDetailDO) { - BalanceChangeDetailVO balanceChangeDetailVO = new BalanceChangeDetailVO(); - balanceChangeDetailVO.setId(balanceChangeDetailDO.getId()); - balanceChangeDetailVO.setUserId(balanceChangeDetailDO.getUserId()); - balanceChangeDetailVO.setAmount(balanceChangeDetailDO.getAmount()); - balanceChangeDetailVO.setType(balanceChangeDetailDO.getType()); - balanceChangeDetailVO.setCurrentBalance(balanceChangeDetailDO.getCurrentBalance()); - balanceChangeDetailVO.setBeforeBalance(balanceChangeDetailDO.getBeforeBalance()); - balanceChangeDetailVO.setAfterBalance(balanceChangeDetailDO.getAfterBalance()); - balanceChangeDetailVO.setChangeScene(balanceChangeDetailDO.getChangeScene()); - balanceChangeDetailVO.setRelatedOrderId(balanceChangeDetailDO.getRelatedOrderId()); - balanceChangeDetailVO.setRelatedOrderNo(balanceChangeDetailDO.getRelatedOrderNo()); - balanceChangeDetailVO.setExternalOrderNo(balanceChangeDetailDO.getExternalOrderNo()); - balanceChangeDetailVO.setOperatorId(balanceChangeDetailDO.getOperatorId()); - balanceChangeDetailVO.setRemark(balanceChangeDetailDO.getRemark()); - balanceChangeDetailVO.setChangeTime(balanceChangeDetailDO.getChangeTime()); - return balanceChangeDetailVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/BalanceServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/BalanceServiceImpl.java deleted file mode 100644 index 336485b9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/BalanceServiceImpl.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.payment.dto.BalanceDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.mapper.BalanceMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.service.BalanceService; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Collectors; - -/** - * 用户余额信息表 Service 实现 - * 对应数据库表 t_balance - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class BalanceServiceImpl extends ServiceImpl implements BalanceService { - /** - * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceMapper balanceMapper; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param balanceDTO parameter `balanceDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createBalance(BalanceDTO balanceDTO) { - BalanceDO balanceDO = new BalanceDO(); - balanceDO.setUserId(balanceDTO.getUserId()); - balanceDO.setAmount(balanceDTO.getAmount()); - balanceDO.setTotalRechargeAmount(balanceDTO.getTotalRechargeAmount()); - balanceDO.setLastRechargeTime(balanceDTO.getLastRechargeTime()); - balanceDO.setLastUpdateTime(LocalDateTime.now()); - balanceMapper.insert(balanceDO); - return balanceDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param balanceDTO parameter `balanceDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateBalance(Long id, BalanceDTO balanceDTO) { - BalanceDO balanceDO = balanceMapper.selectById(id); - if (balanceDO == null) { - return false; - } - balanceDO.setUserId(balanceDTO.getUserId()); - balanceDO.setAmount(balanceDTO.getAmount()); - balanceDO.setTotalRechargeAmount(balanceDTO.getTotalRechargeAmount()); - balanceDO.setLastRechargeTime(balanceDTO.getLastRechargeTime()); - balanceDO.setLastUpdateTime(LocalDateTime.now()); - return balanceMapper.updateById(balanceDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteBalance(Long id) { - return balanceMapper.deleteById(id) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return BalanceVO result consumed by the caller or returned to the frontend - */ - public BalanceVO getBalanceById(Long id) { - BalanceDO balanceDO = balanceMapper.selectById(id); - if (balanceDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param balanceDO parameter `balanceDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(balanceDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllBalances() { - List balanceDOs = balanceMapper.selectList(null); - return balanceDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return BalanceVO result consumed by the caller or returned to the frontend - */ - public BalanceVO getBalanceByUserId(Long userId) { - BalanceDO balanceDO = balanceMapper.selectOne( - Wrappers.lambdaQuery(BalanceDO.class) - .eq(BalanceDO::getUserId, userId) - ); - if (balanceDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param balanceDO parameter `balanceDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(balanceDO); - } - - /** - * 将 DO 转换为 VO - * - * @param balanceDO 余额DO - * @return 余额VO - */ - private BalanceVO convertToVO(BalanceDO balanceDO) { - BalanceVO balanceVO = new BalanceVO(); - balanceVO.setId(balanceDO.getId()); - balanceVO.setUserId(balanceDO.getUserId()); - balanceVO.setAmount(balanceDO.getAmount()); - balanceVO.setTotalRechargeAmount(balanceDO.getTotalRechargeAmount()); - balanceVO.setLastRechargeTime(balanceDO.getLastRechargeTime()); - balanceVO.setCreateTime(balanceDO.getCreateTime()); - balanceVO.setLastUpdateTime(balanceDO.getLastUpdateTime()); - return balanceVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/PaymentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/PaymentServiceImpl.java deleted file mode 100644 index 1e1f4141..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/service/impl/PaymentServiceImpl.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.PaymentOrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.RefundOrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.mapper.PaymentOrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.mapper.RefundOrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.service.PaymentService; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.PaymentOrderVO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.RefundOrderVO; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Service -@RequiredArgsConstructor -public class PaymentServiceImpl implements PaymentService { - - private static final String CHANNEL_MANUAL = "MANUAL"; - private static final String STATUS_UNPAID = "UNPAID"; - private static final String STATUS_PAYING = "PAYING"; - private static final String STATUS_PAID = "PAID"; - private static final String STATUS_REFUNDED = "REFUNDED"; - - private final OrderMapper orderMapper; - private final PaymentOrderMapper paymentOrderMapper; - private final RefundOrderMapper refundOrderMapper; - - @Override - @Transactional - public PaymentOrderVO prepareOrderPayment(Long userId, Long orderId) { - OrderDO order = requirePayableOrder(userId, orderId); - PaymentOrderDO latest = paymentOrderMapper.selectLatestByOrderId(orderId); - if (latest != null && (STATUS_PAYING.equals(latest.getStatus()) || STATUS_PAID.equals(latest.getStatus()))) { - return toVO(latest); - } - PaymentOrderDO payment = new PaymentOrderDO(); - payment.setPayNo("PAY" + System.currentTimeMillis() + orderId); - payment.setOrderId(order.getId()); - payment.setOrderNo(order.getOrderNo()); - payment.setUserId(order.getUserId()); - payment.setShopId(order.getShopId()); - payment.setChannel(CHANNEL_MANUAL); - payment.setStatus(STATUS_PAYING); - payment.setPayAmount(order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()); - payment.setPaidAmount(BigDecimal.ZERO); - payment.setExpireTime(LocalDateTime.now().plusMinutes(30)); - payment.setIdempotencyKey("PAY:" + order.getId()); - payment.setIsDelete(0); - paymentOrderMapper.insert(payment); - order.setPaymentStatus(STATUS_PAYING); - order.setPaymentOrderNo(payment.getPayNo()); - order.setPayAmount(payment.getPayAmount()); - orderMapper.updateById(order); - return toVO(payment); - } - - @Override - @Transactional - public PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark) { - OrderDO order = requirePayableOrder(null, orderId); - PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); - if (payment == null) { - prepareOrderPayment(order.getUserId(), orderId); - payment = paymentOrderMapper.selectLatestByOrderId(orderId); - } - if (payment == null) { - throw new RuntimeException("支付单创建失败"); - } - payment.setStatus(STATUS_PAID); - payment.setPaidAmount(payment.getPayAmount()); - payment.setPayTime(LocalDateTime.now()); - payment.setOperatorId(operatorId); - payment.setRemark(remark); - paymentOrderMapper.updateById(payment); - - order.setPaymentStatus(STATUS_PAID); - order.setPaidAmount(payment.getPayAmount()); - order.setPayTime(payment.getPayTime()); - order.setPaymentMethod(payment.getChannel()); - order.setPaymentOrderNo(payment.getPayNo()); - orderMapper.updateById(order); - return toVO(payment); - } - - @Override - @Transactional - public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - throw new RuntimeException("璁㈠崟涓嶅瓨鍦?"); - } - if (!STATUS_PAID.equals(order.getPaymentStatus())) { - throw new RuntimeException("鏈敮浠樿鍗曚笉鍏佽閫€娆?"); - } - PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); - if (payment == null || !STATUS_PAID.equals(payment.getStatus())) { - throw new RuntimeException("鏈壘鍒板凡鏀粯鏀粯鍗?"); - } - RefundOrderDO refund = new RefundOrderDO(); - refund.setRefundNo("RF" + System.currentTimeMillis() + orderId); - refund.setAfterSaleId(afterSaleId); - refund.setPaymentOrderId(payment.getId()); - refund.setOrderId(order.getId()); - refund.setStatus(STATUS_REFUNDED); - refund.setRefundAmount(payment.getPaidAmount() == null ? payment.getPayAmount() : payment.getPaidAmount()); - refund.setRefundTime(LocalDateTime.now()); - refund.setChannel(payment.getChannel()); - refund.setExternalRefundNo(refund.getRefundNo()); - refund.setFailReason(remark); - refund.setIdempotencyKey("REFUND:" + order.getId() + ":" + (afterSaleId == null ? 0 : afterSaleId)); - refund.setIsDelete(0); - refundOrderMapper.insert(refund); - - order.setRefundStatus(STATUS_REFUNDED); - order.setPaymentStatus(STATUS_REFUNDED); - orderMapper.updateById(order); - return toVO(refund); - } - - private OrderDO requirePayableOrder(Long userId, Long orderId) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - throw new RuntimeException("订单不存在"); - } - if (userId != null && !userId.equals(order.getUserId())) { - throw new RuntimeException("无权支付该订单"); - } - if (Integer.valueOf(0).equals(order.getStatus())) { - throw new RuntimeException("询价预约确认价格前暂不能支付"); - } - if (STATUS_PAID.equals(order.getPaymentStatus())) { - throw new RuntimeException("订单已支付"); - } - if (order.getPaymentStatus() == null) { - order.setPaymentStatus(STATUS_UNPAID); - } - return order; - } - - private PaymentOrderVO toVO(PaymentOrderDO payment) { - PaymentOrderVO vo = new PaymentOrderVO(); - BeanUtils.copyProperties(payment, vo); - return vo; - } - - private RefundOrderVO toVO(RefundOrderDO refund) { - RefundOrderVO vo = new RefundOrderVO(); - BeanUtils.copyProperties(refund, vo); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/BalanceChangeDetailVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/BalanceChangeDetailVO.java deleted file mode 100644 index a73e3dd0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/BalanceChangeDetailVO.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 用户余额变动明细表 VO - * 用于前端展示余额变动明细信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class BalanceChangeDetailVO { - - /** - * 变动记录唯一主键ID(雪花ID) - */ - private Long id; - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 用户昵称 - */ - private String userNickname; - - /** - * 本次变动金额(正数为增加,负数为减少) - */ - private BigDecimal amount; - - /** - * 变动类型(如充值、消费、退款) - */ - private String type; - - /** - * 变动后的当前余额 - */ - private BigDecimal currentBalance; - /** - * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal beforeBalance; - /** - * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal afterBalance; - /** - * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String changeScene; - /** - * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long relatedOrderId; - /** - * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String relatedOrderNo; - /** - * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String externalOrderNo; - /** - * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long operatorId; - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - - /** - * 变动时间 - */ - private LocalDateTime changeTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/BalanceVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/BalanceVO.java deleted file mode 100644 index 545509c4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/BalanceVO.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -/** - * 用户余额信息表 VO - * 用于前端展示余额信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class BalanceVO { - - /** - * 余额记录唯一主键ID(雪花ID) - */ - private Long id; - - /** - * 关联用户表主键 - */ - private Long userId; - - /** - * 用户昵称 - */ - private String userNickname; - - /** - * 当前余额 - */ - private BigDecimal amount; - /** - * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalRechargeAmount; - /** - * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime lastRechargeTime; - - /** - * 余额账户创建时间 - */ - private LocalDateTime createTime; - - /** - * 最近一次更新时间 - */ - private LocalDateTime lastUpdateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/PaymentOrderVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/PaymentOrderVO.java deleted file mode 100644 index c8d89a9d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/PaymentOrderVO.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -public class PaymentOrderVO { - private Long id; - private String payNo; - private Long orderId; - private String orderNo; - private Long userId; - private Long shopId; - private String channel; - private String status; - private BigDecimal payAmount; - private BigDecimal paidAmount; - private LocalDateTime payTime; - private LocalDateTime expireTime; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/RefundOrderVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/RefundOrderVO.java deleted file mode 100644 index 0e7d1e03..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/payment/vo/RefundOrderVO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.payment.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -public class RefundOrderVO { - private Long id; - private String refundNo; - private Long afterSaleId; - private Long paymentOrderId; - private Long orderId; - private String status; - private BigDecimal refundAmount; - private LocalDateTime refundTime; - private String channel; - private String externalRefundNo; - private String failReason; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java deleted file mode 100644 index fbd50cad..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class PlanningAppointmentCreateDTO { - private Long customerUserId; - private String customerName; - private String phone; - private Long productId; - private Integer quantity; - private Long artistId; - private String appointmentDate; - private String appointmentTime; - private String appointmentStartTime; - private Integer durationMinutes; - private String manualProductTitle; - private BigDecimal manualProductPrice; - private String manualProductDescription; - private String manualProductTags; - private String manualProductTargetAudience; - private String manualProductPrecautions; - private String manualProductImageFileIds; - private String remark; - private String clientRequestId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentMoveDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentMoveDTO.java deleted file mode 100644 index 1dbdd101..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentMoveDTO.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.dto; - -import lombok.Data; - -@Data -public class PlanningAppointmentMoveDTO { - private Long artistId; - private String appointmentDate; - private String appointmentTime; - private String appointmentStartTime; - private Integer durationMinutes; - private String clientRequestId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java deleted file mode 100644 index 95af9d25..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.dto; - -import lombok.Data; - -@Data -public class PlanningAppointmentStatusDTO { - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningManagerRegisterDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningManagerRegisterDTO.java deleted file mode 100644 index f4010b8d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningManagerRegisterDTO.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.dto; - -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -public class PlanningManagerRegisterDTO { - - private String phone; - - private String code; - - private String password; - - private String confirmPassword; - - private String shopName; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/entity/AppointmentReservationDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/entity/AppointmentReservationDO.java deleted file mode 100644 index 1bca8e37..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/entity/AppointmentReservationDO.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_appointment_reservation") -public class AppointmentReservationDO extends BaseEntity { - @TableField("order_id") - private Long orderId; - @TableField("order_item_id") - private Long orderItemId; - @TableField("shop_id") - private Long shopId; - @TableField("artist_id") - private Long artistId; - @TableField("product_title") - private String productTitle; - @TableField("appointment_start_time") - private LocalDateTime appointmentStartTime; - @TableField("appointment_end_time") - private LocalDateTime appointmentEndTime; - @TableField("status") - private String status; - @TableField("client_request_id") - private String clientRequestId; - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/mapper/AppointmentReservationMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/mapper/AppointmentReservationMapper.java deleted file mode 100644 index 9a7280be..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/mapper/AppointmentReservationMapper.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.entity.AppointmentReservationDO; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Mapper -public interface AppointmentReservationMapper extends BaseMapper { - String ACTIVE_STATUS_SQL = "('LOCKED','PENDING_QUOTE','CONFIRMED')"; - - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + - "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + - "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") - int countOverlappingActiveForUpdate(@Param("artistId") Long artistId, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime); - - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + - "AND order_item_id <> #{orderItemId} AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + - "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") - int countOverlappingActiveForUpdateExcludingOrderItem(@Param("artistId") Long artistId, - @Param("orderItemId") Long orderItemId, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime); - - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + - "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + - "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime}") - int countOverlappingActive(@Param("artistId") Long artistId, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime); - - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + - "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + - "AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) FOR UPDATE") - int countActiveByArtistAndDateForUpdate(@Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("workDate") LocalDate workDate); - - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + - "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + - "AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) " + - "AND (TIME(appointment_start_time) < #{startTime} OR TIME(appointment_end_time) > #{endTime}) FOR UPDATE") - int countActiveOutsideScheduleForUpdate(@Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("workDate") LocalDate workDate, - @Param("startTime") java.time.LocalTime startTime, - @Param("endTime") java.time.LocalTime endTime); - - @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + - "WHERE order_id = #{orderId} AND is_delete = 0") - int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status); - - @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + - "WHERE order_item_id = #{orderItemId} AND is_delete = 0") - int releaseByOrderItem(@Param("orderItemId") Long orderItemId, @Param("status") String status); - - @Update("UPDATE t_appointment_reservation SET order_id = #{orderId}, shop_id = #{shopId}, " + - "artist_id = #{artistId}, product_title = #{productTitle}, " + - "appointment_start_time = #{startTime}, appointment_end_time = #{endTime}, " + - "status = #{status}, is_delete = 0, update_time = NOW() " + - "WHERE order_item_id = #{orderItemId} AND is_delete = 0") - int updateActiveReservationForOrderItem(@Param("orderItemId") Long orderItemId, - @Param("orderId") Long orderId, - @Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("productTitle") String productTitle, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime, - @Param("status") String status); - - @Update("UPDATE t_appointment_reservation SET order_id = #{orderId}, shop_id = #{shopId}, " + - "artist_id = #{artistId}, product_title = #{productTitle}, " + - "appointment_start_time = #{startTime}, appointment_end_time = #{endTime}, " + - "status = #{status}, client_request_id = COALESCE(#{clientRequestId}, client_request_id), is_delete = 0, update_time = NOW() " + - "WHERE order_item_id = #{orderItemId} AND is_delete = 0") - int updateActiveReservationForOrderItemWithClientRequest(@Param("orderItemId") Long orderItemId, - @Param("orderId") Long orderId, - @Param("shopId") Long shopId, - @Param("artistId") Long artistId, - @Param("productTitle") String productTitle, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime, - @Param("status") String status, - @Param("clientRequestId") String clientRequestId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/AppointmentCapacityService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/AppointmentCapacityService.java deleted file mode 100644 index 9a128325..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/AppointmentCapacityService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.service; - -import java.time.LocalDateTime; - -public interface AppointmentCapacityService { - void reserveOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime); - - void reservePendingQuoteOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime, String clientRequestId); - - void reserveConfirmedOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime, String clientRequestId); - - void confirmReservationOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime); - - void releaseByOrder(Long orderId); - - void moveReservationForArtistChange(Long orderId, Long orderItemId, Long shopId, Long fromArtistId, - Long toArtistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java deleted file mode 100644 index 44c28df0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.service; - -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentMoveDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO; - -import java.time.LocalDate; - -public interface PlanningService { - PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId); - - PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto); - - PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId); - - PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto); - - Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java deleted file mode 100644 index 13d2eb60..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.service.impl; - -import com.xiaowang.jacyucloudsalon.core.modules.planning.entity.AppointmentReservationDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.service.AppointmentCapacityService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDateTime; - -@Service -@RequiredArgsConstructor -public class AppointmentCapacityServiceImpl implements AppointmentCapacityService { - - private static final int MIN_CAPACITY = 1; - public static final String STATUS_PENDING_QUOTE = "PENDING_QUOTE"; - private static final String STATUS_CONFIRMED = "CONFIRMED"; - private static final String STATUS_RELEASED = "RELEASED"; - private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害"; - private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿"; - - private final AppointmentReservationMapper reservationMapper; - private final ArtistScheduleMapper scheduleMapper; - - @Override - @Transactional - public void reserveOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime) { - reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, - STATUS_CONFIRMED, null, null); - } - - @Override - @Transactional - public void reservePendingQuoteOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime, String clientRequestId) { - reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, - STATUS_PENDING_QUOTE, clientRequestId, null); - } - - @Override - @Transactional - public void reserveConfirmedOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime, String clientRequestId) { - reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, - STATUS_CONFIRMED, clientRequestId, null); - } - - @Override - @Transactional - public void confirmReservationOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime) { - reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, - STATUS_CONFIRMED, null, orderItemId); - } - - private void reserveWithStatusOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime, String status, - String clientRequestId, Long excludedOrderItemId) { - if (orderId == null || orderItemId == null || shopId == null || artistId == null || startTime == null || endTime == null) { - return; - } - assertCapacityAvailable(shopId, artistId, excludedOrderItemId, startTime, endTime); - int updated = reservationMapper.updateActiveReservationForOrderItemWithClientRequest( - orderItemId, - orderId, - shopId, - artistId, - productTitle, - startTime, - endTime, - status, - clientRequestId - ); - if (updated > 0) { - return; - } - AppointmentReservationDO reservation = new AppointmentReservationDO(); - reservation.setOrderId(orderId); - reservation.setOrderItemId(orderItemId); - reservation.setShopId(shopId); - reservation.setArtistId(artistId); - reservation.setProductTitle(productTitle); - reservation.setAppointmentStartTime(startTime); - reservation.setAppointmentEndTime(endTime); - reservation.setStatus(status); - reservation.setClientRequestId(clientRequestId); - reservation.setIsDelete(0); - reservationMapper.insert(reservation); - } - - @Override - @Transactional - public void releaseByOrder(Long orderId) { - if (orderId != null) { - reservationMapper.releaseByOrderId(orderId, STATUS_RELEASED); - } - } - - @Override - @Transactional - public void moveReservationForArtistChange(Long orderId, Long orderItemId, Long shopId, Long fromArtistId, - Long toArtistId, String productTitle, - LocalDateTime startTime, LocalDateTime endTime) { - if (orderItemId == null || orderId == null || shopId == null || toArtistId == null || startTime == null || endTime == null) { - return; - } - assertCapacityAvailable(shopId, toArtistId, orderItemId, startTime, endTime); - int updated = reservationMapper.updateActiveReservationForOrderItem( - orderItemId, - orderId, - shopId, - toArtistId, - productTitle, - startTime, - endTime, - STATUS_CONFIRMED - ); - if (updated == 0) { - reserveOrThrow(orderId, orderItemId, shopId, toArtistId, productTitle, startTime, endTime); - } - } - - private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId, - LocalDateTime startTime, LocalDateTime endTime) { - int capacity = resolveCapacity(shopId, artistId, startTime, endTime); - int used = excludedOrderItemId == null - ? reservationMapper.countOverlappingActiveForUpdate(artistId, startTime, endTime) - : reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime); - if (used >= capacity) { - throw new RuntimeException(FULL_MESSAGE); - } - } - - private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { - ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule( - shopId, - artistId, - startTime.toLocalDate(), - startTime.toLocalTime(), - endTime.toLocalTime() - ); - if (schedule == null || Integer.valueOf(1).equals(schedule.getIsDelete()) - || !Integer.valueOf(1).equals(schedule.getStatus()) - || schedule.getCapacity() == null || schedule.getCapacity() < MIN_CAPACITY) { - throw new RuntimeException(UNAVAILABLE_MESSAGE); - } - return schedule.getCapacity(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java deleted file mode 100644 index b1ef81e9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ /dev/null @@ -1,901 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentMoveDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.entity.AppointmentReservationDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.planning.service.AppointmentCapacityService; -import com.xiaowang.jacyucloudsalon.core.modules.order.service.OrderService; -import com.xiaowang.jacyucloudsalon.core.modules.planning.service.PlanningService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus; -import com.xiaowang.jacyucloudsalon.core.modules.planning.support.PlanningCalendarSupport; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningArtistCountVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningArtistVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningDaySummaryVO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningScheduleVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.math.BigDecimal; -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -public class PlanningServiceImpl implements PlanningService { - - private static final int DEFAULT_SLOT_MINUTES = 30; - private static final int DEFAULT_DURATION_MINUTES = 60; - private static final int MONTH_AVAILABLE_MINUTES = 90; - private static final String RESERVATION_PENDING_QUOTE = "PENDING_QUOTE"; - private static final String RESERVATION_CONFIRMED = "CONFIRMED"; - private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT"; - private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; - private static final List ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED); - private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - private static final List ARTIST_COLORS = List.of( - "#7BA7C7", "#8FB89A", "#A894C7", "#D7A86E", "#D98DA5", "#79A6A3", "#B9A16B", "#9BA9C8" - ); - - private final AdminScopeHelper adminScopeHelper; - private final UserMapper userMapper; - private final NailArtistInfoMapper nailArtistInfoMapper; - private final ArtistScheduleMapper artistScheduleMapper; - private final AppointmentReservationMapper appointmentReservationMapper; - private final OrderMapper orderMapper; - private final OrderItemMapper orderItemMapper; - private final ProductMapper productMapper; - private final ShopMapper shopMapper; - private final AppointmentCapacityService appointmentCapacityService; - private final OrderService orderService; - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - - @Override - public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) { - LocalDate start = startDate == null ? LocalDate.now() : startDate; - LocalDate end = endDate == null ? start : endDate; - if (end.isBefore(start)) { - end = start; - } - if (start.plusDays(61).isBefore(end)) { - end = start.plusDays(61); - } - - Long shopId = requirePlanningShopId(currentUser); - ShopDO shop = shopMapper.selectById(shopId); - PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours( - shop == null ? null : shop.getBusinessHours() - ); - - List artists = listArtists(shopId, artistId); - List schedules = listSchedules(shopId, start, end, artistId); - List scheduleVos = schedules.stream() - .map(schedule -> toScheduleVO(schedule, artists)) - .sorted(Comparator.comparing(PlanningScheduleVO::getDate) - .thenComparing(PlanningScheduleVO::getStartTime) - .thenComparing(PlanningScheduleVO::getArtistName, Comparator.nullsLast(String::compareTo))) - .toList(); - - LocalDateTime rangeStart = start.atStartOfDay(); - LocalDateTime rangeEnd = end.plusDays(1).atStartOfDay(); - List appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists); - Map countByArtist = appointments.stream() - .filter(appointment -> appointment.getArtistId() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); - artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue())); - - PlanningCalendarVO vo = new PlanningCalendarVO(); - vo.setBusinessStartTime(businessHours.start().toString()); - vo.setBusinessEndTime(businessHours.end().toString()); - vo.setSlotMinutes(DEFAULT_SLOT_MINUTES); - vo.setArtists(artists); - vo.setSchedules(scheduleVos); - vo.setAppointments(appointments); - vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments)); - return vo; - } - - @Override - @Transactional - public PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto) { - if (dto == null) { - throw new RuntimeException("预约信息不能为空"); - } - if (Integer.valueOf(3).equals(currentUser.getType())) { - throw new RuntimeException("美甲师账号只能查看预约,不能新建预约"); - } - Long shopId = requirePlanningShopId(currentUser); - requireAppointmentDuration(dto.getDurationMinutes()); - ProductDO product = resolveAppointmentProduct(dto, shopId); - UserDO artist = requireActiveArtist(dto.getArtistId(), shopId); - UserDO customer = resolveCustomer(shopId, dto); - - int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity(); - int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity; - LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); - LocalDateTime endTime = startTime.plusMinutes(durationMinutes); - ensureWithinBusinessHours(shopId, startTime, endTime); - - BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity)); - - OrderDO order = new OrderDO(); - order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); - order.setUserId(customer.getId()); - order.setShopId(shopId); - order.setTotalAmount(amount); - order.setActualAmount(amount); - order.setCustomerRemark(trimToNull(dto.getRemark())); - order.setQuoteStatus("CONFIRMED"); - order.setQuoteUserConfirmed(1); - order.setQuoteShopConfirmed(1); - order.setQuoteConfirmedTime(LocalDateTime.now()); - order.setPaymentStatus("UNPAID"); - order.setPayAmount(amount); - order.setPaidAmount(BigDecimal.ZERO); - order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); - order.setIsDelete(0); - orderMapper.insert(order); - - OrderItemDO item = new OrderItemDO(); - item.setOrderId(order.getId()); - item.setProductId(product.getId()); - item.setQuantity(quantity); - item.setPrice(unitPrice); - item.setArtistId(artist.getId()); - item.setAppointmentTime(startTime); - item.setIsDelete(0); - orderItemMapper.insert(item); - - appointmentCapacityService.reserveConfirmedOrThrow( - order.getId(), - item.getId(), - shopId, - artist.getId(), - product.getTitle(), - startTime, - endTime, - trimToNull(dto.getClientRequestId()) - ); - - return getAppointment(currentUser, item.getId()); - } - - @Override - public PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId) { - if (orderItemId == null) { - throw new RuntimeException("预约ID不能为空"); - } - OrderItemDO item = orderItemMapper.selectById(orderItemId); - if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { - throw new RuntimeException("预约不存在"); - } - OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); - ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId()); - AppointmentReservationDO reservation = findActiveReservation(orderItemId); - Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - Map customerMap = loadUsers(Set.of(order.getUserId())); - return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); - } - - @Override - @Transactional - public PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto) { - if (orderItemId == null || dto == null) { - throw new RuntimeException("改派信息不能为空"); - } - OrderItemDO item = orderItemMapper.selectByIdForUpdate(orderItemId); - if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { - throw new RuntimeException("预约不存在"); - } - OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); - ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId()); - Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId(); - UserDO artist = requireActiveArtist(targetArtistId, order.getShopId()); - int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * - Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); - LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime()) - ? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()) - : item.getAppointmentTime(); - if (startTime == null) { - throw new RuntimeException("预约时间不能为空"); - } - LocalDateTime endTime = startTime.plusMinutes(durationMinutes); - ensureWithinBusinessHours(order.getShopId(), startTime, endTime); - - appointmentCapacityService.moveReservationForArtistChange( - order.getId(), - item.getId(), - order.getShopId(), - item.getArtistId(), - artist.getId(), - product.getTitle(), - startTime, - endTime - ); - - item.setArtistId(artist.getId()); - item.setAppointmentTime(startTime); - orderItemMapper.updateById(item); - return getAppointment(currentUser, item.getId()); - } - - @Override - @Transactional - public Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto) { - if (orderId == null || dto == null || dto.getStatus() == null) { - throw new RuntimeException("预约状态不能为空"); - } - OrderDO order = requireAccessibleOrder(currentUser, orderId); - int targetStatus = dto.getStatus(); - if (targetStatus == OrderStatus.PENDING_SERVICE.getCode()) { - if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { - orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); - } - return true; - } - orderService.processOrder(orderId, targetStatus); - return true; - } - - private Long requirePlanningShopId(UserDO currentUser) { - Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); - if (shopId == null || shopId <= 0) { - throw new RuntimeException("请先选择店铺后再查看规划"); - } - return shopId; - } - - private List listArtists(Long shopId, Long artistId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("shop_id", shopId) - .eq("type", 3) - .eq("is_delete", 0) - .orderByAsc("id"); - if (artistId != null && artistId > 0) { - wrapper.eq("id", artistId); - } - List artists = userMapper.selectList(wrapper); - if (artists == null || artists.isEmpty()) { - return List.of(); - } - Set artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new)); - Map infoMap = loadArtistInfo(artistIds); - List result = new ArrayList<>(); - for (int i = 0; i < artists.size(); i++) { - UserDO user = artists.get(i); - NailArtistInfoDO info = infoMap.get(user.getId()); - PlanningArtistVO vo = new PlanningArtistVO(); - vo.setId(user.getId()); - vo.setName(firstNonBlank(user.getNickname(), user.getAccount(), "美甲师" + (i + 1))); - vo.setShortName(PlanningCalendarSupport.shortName(vo.getName())); - vo.setPhone(firstNonBlank(user.getContactPhone(), user.getPhone(), "")); - vo.setAvatar(user.getAvatar()); - vo.setColor(colorForArtist(user.getId(), i)); - vo.setStatus(info == null || info.getStatus() == null ? user.getStatus() : info.getStatus()); - vo.setStatusText(Integer.valueOf(0).equals(vo.getStatus()) ? "休息" : "可预约"); - vo.setWorkStartTime(info == null || info.getWorkStartTime() == null ? null : info.getWorkStartTime().toString()); - vo.setWorkEndTime(info == null || info.getWorkEndTime() == null ? null : info.getWorkEndTime().toString()); - vo.setRangeCount(0); - result.add(vo); - } - return result; - } - - private Map loadArtistInfo(Set artistIds) { - if (artistIds == null || artistIds.isEmpty()) { - return Map.of(); - } - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.in("user_id", artistIds).eq("is_delete", 0); - return nailArtistInfoMapper.selectList(wrapper).stream() - .collect(Collectors.toMap(NailArtistInfoDO::getUserId, Function.identity(), (a, b) -> a)); - } - - private List listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("shop_id", shopId) - .between("work_date", start, end) - .eq("is_delete", 0) - .orderByAsc("work_date") - .orderByAsc("start_time"); - if (artistId != null && artistId > 0) { - wrapper.eq("artist_id", artistId); - } - return artistScheduleMapper.selectList(wrapper); - } - - private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, List artists) { - Map artistNames = artists.stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a)); - PlanningScheduleVO vo = new PlanningScheduleVO(); - vo.setId(schedule.getId()); - vo.setArtistId(schedule.getArtistId()); - vo.setArtistName(artistNames.get(schedule.getArtistId())); - vo.setDate(schedule.getWorkDate() == null ? null : schedule.getWorkDate().toString()); - vo.setStartTime(schedule.getStartTime() == null ? null : schedule.getStartTime().toString()); - vo.setEndTime(schedule.getEndTime() == null ? null : schedule.getEndTime().toString()); - vo.setCapacity(schedule.getCapacity()); - vo.setStatus(schedule.getStatus()); - vo.setStatusText(Integer.valueOf(1).equals(schedule.getStatus()) ? "可预约" : "请假"); - vo.setRemark(schedule.getRemark()); - return vo; - } - - private List listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd, - Long artistId, List artists) { - QueryWrapper reservationWrapper = new QueryWrapper<>(); - reservationWrapper.eq("shop_id", shopId) - .eq("is_delete", 0) - .in("status", ACTIVE_RESERVATION_STATUS) - .lt("appointment_start_time", rangeEnd) - .gt("appointment_end_time", rangeStart) - .orderByAsc("appointment_start_time"); - if (artistId != null && artistId > 0) { - reservationWrapper.eq("artist_id", artistId); - } - List reservations = appointmentReservationMapper.selectList(reservationWrapper); - - QueryWrapper itemWrapper = new QueryWrapper<>(); - itemWrapper.eq("is_delete", 0) - .isNotNull("appointment_time") - .ge("appointment_time", rangeStart) - .lt("appointment_time", rangeEnd) - .orderByAsc("appointment_time"); - if (artistId != null && artistId > 0) { - itemWrapper.eq("artist_id", artistId); - } - List fallbackItems = orderItemMapper.selectList(itemWrapper); - - return buildAppointmentList(shopId, reservations, fallbackItems, artists); - } - - private List buildAppointmentList(Long shopId, List reservations, - List fallbackItems, List artists) { - Set itemIds = new HashSet<>(); - Set orderIds = new HashSet<>(); - for (AppointmentReservationDO reservation : safeList(reservations)) { - if (reservation.getOrderItemId() != null) { - itemIds.add(reservation.getOrderItemId()); - } - if (reservation.getOrderId() != null) { - orderIds.add(reservation.getOrderId()); - } - } - for (OrderItemDO item : safeList(fallbackItems)) { - if (item.getId() != null) { - itemIds.add(item.getId()); - } - if (item.getOrderId() != null) { - orderIds.add(item.getOrderId()); - } - } - - Map itemMap = loadOrderItems(itemIds); - Map orderMap = loadOrders(orderIds); - Set productIds = itemMap.values().stream() - .map(OrderItemDO::getProductId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Set customerIds = orderMap.values().stream() - .map(OrderDO::getUserId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Map productMap = loadProducts(productIds); - Map customerMap = loadUsers(customerIds); - Map artistMap = artists.stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - - List result = new ArrayList<>(); - Set reservationItemIds = new HashSet<>(); - for (AppointmentReservationDO reservation : safeList(reservations)) { - OrderItemDO item = itemMap.get(reservation.getOrderItemId()); - OrderDO order = orderMap.get(reservation.getOrderId()); - if (!isVisibleOrder(order, shopId)) { - continue; - } - ProductDO product = item == null ? null : productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); - result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap)); - if (reservation.getOrderItemId() != null) { - reservationItemIds.add(reservation.getOrderItemId()); - } - } - for (OrderItemDO item : safeList(fallbackItems)) { - if (item.getId() != null && reservationItemIds.contains(item.getId())) { - continue; - } - OrderDO order = orderMap.get(item.getOrderId()); - if (!isVisibleOrder(order, shopId)) { - continue; - } - ProductDO product = productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); - result.add(toAppointmentVO(null, item, order, product, customer, artistMap)); - } - result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo)) - .thenComparing(PlanningAppointmentVO::getArtistName, Comparator.nullsLast(String::compareTo))); - return result; - } - - private PlanningAppointmentVO toAppointmentVO(AppointmentReservationDO reservation, OrderItemDO item, OrderDO order, - ProductDO product, UserDO customer, Map artistMap) { - LocalDateTime start = reservation == null ? null : reservation.getAppointmentStartTime(); - if (start == null && item != null) { - start = item.getAppointmentTime(); - } - int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity()); - LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime(); - if (end == null && start != null) { - end = start.plusMinutes(durationMinutes); - } - - Long artistId = reservation != null && reservation.getArtistId() != null - ? reservation.getArtistId() - : item == null ? null : item.getArtistId(); - PlanningArtistVO artist = artistId == null ? null : artistMap.get(artistId); - - PlanningAppointmentVO vo = new PlanningAppointmentVO(); - vo.setOrderId(order == null ? null : order.getId()); - vo.setOrderNo(order == null ? null : order.getOrderNo()); - vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId()); - vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId()); - vo.setCustomerName(customer == null ? "到店客户" : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); - vo.setCustomerPhone(customer == null ? null : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); - vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId()); - vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle()) - ? reservation.getProductTitle() - : product == null ? "预约作品" : product.getTitle()); - vo.setArtistId(artistId); - vo.setArtistName(artist == null ? "未分配" : artist.getName()); - vo.setArtistColor(artist == null ? ARTIST_COLORS.get(0) : artist.getColor()); - vo.setDate(start == null ? null : start.toLocalDate().toString()); - vo.setStartTime(start == null ? null : DATE_TIME_FORMATTER.format(start)); - vo.setEndTime(end == null ? null : DATE_TIME_FORMATTER.format(end)); - vo.setStartMinute(start == null ? null : start.toLocalTime().toSecondOfDay() / 60); - vo.setDurationMinutes(start == null || end == null ? durationMinutes : Math.toIntExact(Duration.between(start, end).toMinutes())); - vo.setStatus(order == null ? null : order.getStatus()); - vo.setStatusText(statusText(order == null ? null : order.getStatus())); - String occupancyStatus = resolveOccupancyStatus(reservation, order); - vo.setOccupancyStatus(occupancyStatus); - vo.setCanEdit(canEditAppointment(order, occupancyStatus)); - vo.setCanCancel(canCancelAppointment(order, occupancyStatus)); - vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus)); - vo.setAmount(order == null ? null : order.getActualAmount()); - vo.setRemark(order == null ? null : order.getCustomerRemark()); - return vo; - } - - private List buildDaySummaries(LocalDate start, LocalDate end, List artists, - List schedules, List appointments) { - Map> appointmentsByDate = appointments.stream() - .filter(appointment -> appointment.getDate() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getDate)); - Map> schedulesByDate = schedules.stream() - .filter(schedule -> schedule.getWorkDate() != null) - .collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString())); - - List summaries = new ArrayList<>(); - LocalDate cursor = start; - while (!cursor.isAfter(end)) { - String date = cursor.toString(); - List dayAppointments = appointmentsByDate.getOrDefault(date, List.of()); - Map countByArtist = dayAppointments.stream() - .filter(appointment -> appointment.getArtistId() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); - List daySchedules = schedulesByDate.getOrDefault(date, List.of()); - Map scheduleByArtist = daySchedules.stream() - .collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a)); - - List artistCounts = new ArrayList<>(); - int workingArtistCount = 0; - int fullWorkingArtistCount = 0; - for (PlanningArtistVO artist : artists) { - int count = countByArtist.getOrDefault(artist.getId(), 0L).intValue(); - ArtistScheduleDO schedule = scheduleByArtist.get(artist.getId()); - List artistAppointments = dayAppointments.stream() - .filter(appointment -> Objects.equals(appointment.getArtistId(), artist.getId())) - .toList(); - String artistStatus = resolveArtistDayStatus(artist, schedule, artistAppointments); - if (!"rest".equals(artistStatus)) { - workingArtistCount++; - if ("full".equals(artistStatus)) { - fullWorkingArtistCount++; - } - } - PlanningArtistCountVO countVO = new PlanningArtistCountVO(); - countVO.setArtistId(artist.getId()); - countVO.setArtistName(artist.getName()); - countVO.setShortName(artist.getShortName()); - countVO.setColor(artist.getColor()); - countVO.setCount(count); - countVO.setStatus(artistStatus); - artistCounts.add(countVO); - } - int total = dayAppointments.size(); - boolean hasWorkingSchedule = workingArtistCount > 0; - boolean allFull = workingArtistCount > 0 && fullWorkingArtistCount == workingArtistCount; - - PlanningDaySummaryVO summary = new PlanningDaySummaryVO(); - summary.setDate(date); - summary.setTotalCount(total); - summary.setArtistCounts(artistCounts); - summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull)); - summaries.add(summary); - cursor = cursor.plusDays(1); - } - return summaries; - } - - private String resolveArtistDayStatus(PlanningArtistVO artist, ArtistScheduleDO schedule, List appointments) { - if (schedule != null && !Integer.valueOf(1).equals(schedule.getStatus())) { - return "rest"; - } - if (schedule == null || Integer.valueOf(0).equals(artist.getStatus())) { - return "rest"; - } - if (hasContinuousFreeWindow(schedule, appointments, MONTH_AVAILABLE_MINUTES)) { - return appointments.isEmpty() ? "free" : "working"; - } - return "full"; - } - - private boolean hasContinuousFreeWindow(ArtistScheduleDO schedule, List appointments, int requiredMinutes) { - if (schedule == null || schedule.getStartTime() == null || schedule.getEndTime() == null || requiredMinutes <= 0) { - return false; - } - int startMinute = schedule.getStartTime().toSecondOfDay() / 60; - int endMinute = schedule.getEndTime().toSecondOfDay() / 60; - if (endMinute - startMinute < requiredMinutes) { - return false; - } - int cursor = startMinute; - List ranges = appointments.stream() - .map(this::toTimeRange) - .filter(Objects::nonNull) - .filter(range -> range.endMinute() > startMinute && range.startMinute() < endMinute) - .map(range -> new TimeRange(Math.max(range.startMinute(), startMinute), Math.min(range.endMinute(), endMinute))) - .sorted(Comparator.comparing(TimeRange::startMinute).thenComparing(TimeRange::endMinute)) - .toList(); - for (TimeRange range : ranges) { - if (range.startMinute() - cursor >= requiredMinutes) { - return true; - } - cursor = Math.max(cursor, range.endMinute()); - } - return endMinute - cursor >= requiredMinutes; - } - - private TimeRange toTimeRange(PlanningAppointmentVO appointment) { - if (appointment == null) { - return null; - } - Integer startMinute = appointment.getStartMinute(); - Integer durationMinutes = appointment.getDurationMinutes(); - if (startMinute == null || durationMinutes == null || durationMinutes <= 0) { - return null; - } - return new TimeRange(startMinute, startMinute + durationMinutes); - } - - private record TimeRange(int startMinute, int endMinute) { - } - - private ProductDO requireActiveProduct(Long productId, Long shopId) { - if (productId == null) { - throw new RuntimeException("请选择预约作品"); - } - ProductDO product = productMapper.selectById(productId); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete()) || !shopId.equals(product.getShopId())) { - throw new RuntimeException("预约作品不存在或不属于当前店铺"); - } - return product; - } - - private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { - if (dto.getProductId() != null) { - return requireActiveProduct(dto.getProductId(), shopId); - } - return createManualAppointmentProduct(dto, shopId); - } - - private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { - String title = trimToNull(dto.getManualProductTitle()); - if (!hasText(title)) { - throw new RuntimeException("请选择预约作品或填写手动作品名称"); - } - BigDecimal price = dto.getManualProductPrice(); - if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { - throw new RuntimeException("手动作品价格不能小于0"); - } - int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); - ProductDO product = new ProductDO(); - product.setShopId(shopId); - product.setTitle(title); - product.setDescription(trimToNull(dto.getManualProductDescription())); - product.setTags(trimToNull(dto.getManualProductTags())); - product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); - product.setPrecautions(trimToNull(dto.getManualProductPrecautions())); - product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); - product.setPrice(price); - product.setLikeCount(0); - product.setCollectCount(0); - product.setApproximateDuration(durationMinutes + "分钟"); - product.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId())); - product.setFrontVisible(0); - product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT); - product.setIsDelete(0); - productMapper.insert(product); - return product; - } - - private int requireAppointmentDuration(Integer durationMinutes) { - if (durationMinutes == null || durationMinutes <= 0) { - throw new RuntimeException("预约时长不能为空且必须大于0分钟"); - } - return durationMinutes; - } - - private UserDO requireActiveArtist(Long artistId, Long shopId) { - if (artistId == null) { - throw new RuntimeException("请选择美甲师"); - } - UserDO artist = userMapper.selectById(artistId); - if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) - || !Integer.valueOf(3).equals(artist.getType()) || !shopId.equals(artist.getShopId())) { - throw new RuntimeException("美甲师不存在或不属于当前店铺"); - } - return artist; - } - - private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) { - if (dto.getCustomerUserId() != null) { - UserDO customer = userMapper.selectById(dto.getCustomerUserId()); - if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) { - throw new RuntimeException("客户不存在"); - } - return customer; - } - if (!hasText(dto.getPhone())) { - throw new RuntimeException("客户手机号不能为空"); - } - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("is_delete", 0) - .and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone())) - .last("LIMIT 1"); - UserDO existing = userMapper.selectOne(wrapper); - if (existing != null) { - return existing; - } - UserDO customer = new UserDO(); - customer.setShopId(shopId); - customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone())); - customer.setPhone(dto.getPhone()); - customer.setContactPhone(dto.getPhone()); - customer.setAccount(dto.getPhone()); - customer.setPassword(ENCODED_UNSET_PASSWORD); - customer.setType(0); - customer.setStatus(1); - customer.setIsDelete(0); - userMapper.insert(customer); - return customer; - } - - private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - throw new RuntimeException("订单不存在"); - } - adminScopeHelper.ensureShopAccessible(currentUser, order.getShopId(), "无权访问其他店铺预约"); - return order; - } - - private AppointmentReservationDO findActiveReservation(Long orderItemId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("order_item_id", orderItemId) - .eq("is_delete", 0) - .in("status", ACTIVE_RESERVATION_STATUS) - .orderByDesc("id") - .last("LIMIT 1"); - return appointmentReservationMapper.selectOne(wrapper); - } - - private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) { - ShopDO shop = shopMapper.selectById(shopId); - PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours()); - LocalTime start = startTime.toLocalTime(); - LocalTime end = endTime.toLocalTime(); - if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { - throw new RuntimeException("预约时间超出店铺营业时间"); - } - } - - private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) { - if (hasText(appointmentStartTime)) { - String normalized = appointmentStartTime.trim().replace('T', ' '); - if (normalized.length() == 16) { - normalized = normalized + ":00"; - } - try { - return LocalDateTime.parse(normalized, DATE_TIME_FORMATTER); - } catch (DateTimeParseException ignored) { - return LocalDateTime.parse(appointmentStartTime.trim()); - } - } - if (!hasText(appointmentDate) || !hasText(appointmentTime)) { - throw new RuntimeException("请选择预约日期和时间"); - } - LocalDate date = LocalDate.parse(appointmentDate.trim()); - LocalTime time = LocalTime.parse(appointmentTime.trim().length() == 5 ? appointmentTime.trim() + ":00" : appointmentTime.trim()); - return LocalDateTime.of(date, time); - } - - private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) { - if (overrideMinutes != null && overrideMinutes > 0) { - return overrideMinutes; - } - return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES); - } - - private boolean isVisibleOrder(OrderDO order, Long shopId) { - return order != null - && !Integer.valueOf(1).equals(order.getIsDelete()) - && shopId.equals(order.getShopId()) - && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); - } - - private Map loadOrderItems(Set itemIds) { - if (itemIds == null || itemIds.isEmpty()) { - return Map.of(); - } - return orderItemMapper.selectBatchIds(itemIds).stream() - .collect(Collectors.toMap(OrderItemDO::getId, Function.identity(), (a, b) -> a)); - } - - private Map loadOrders(Set orderIds) { - if (orderIds == null || orderIds.isEmpty()) { - return Map.of(); - } - return orderMapper.selectBatchIds(orderIds).stream() - .collect(Collectors.toMap(OrderDO::getId, Function.identity(), (a, b) -> a)); - } - - private Map loadProducts(Set productIds) { - if (productIds == null || productIds.isEmpty()) { - return Map.of(); - } - return productMapper.selectBatchIds(productIds).stream() - .collect(Collectors.toMap(ProductDO::getId, Function.identity(), (a, b) -> a)); - } - - private Map loadUsers(Set userIds) { - if (userIds == null || userIds.isEmpty()) { - return Map.of(); - } - return userMapper.selectBatchIds(userIds).stream() - .collect(Collectors.toMap(UserDO::getId, Function.identity(), (a, b) -> a)); - } - - private String colorForArtist(Long artistId, int index) { - if (artistId == null) { - return ARTIST_COLORS.get(index % ARTIST_COLORS.size()); - } - int colorIndex = Math.abs(artistId.hashCode()) % ARTIST_COLORS.size(); - return ARTIST_COLORS.get(colorIndex); - } - - private String statusText(Integer status) { - if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(status)) { - return "已确认"; - } - if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(status)) { - return "已完成"; - } - if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status)) { - return "已取消"; - } - if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(status)) { - return "待确认"; - } - return "未知"; - } - - private String resolveOccupancyStatus(AppointmentReservationDO reservation, OrderDO order) { - if (reservation != null && hasText(reservation.getStatus())) { - return reservation.getStatus(); - } - if (order != null && Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { - return RESERVATION_PENDING_QUOTE; - } - if (order != null && Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { - return RESERVATION_CONFIRMED; - } - if (order != null && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { - return "CANCELLED"; - } - if (order != null && Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { - return "COMPLETED"; - } - return "UNKNOWN"; - } - - private Boolean canEditAppointment(OrderDO order, String occupancyStatus) { - return order != null - && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) - && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) - && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); - } - - private Boolean canCancelAppointment(OrderDO order, String occupancyStatus) { - return order != null - && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) - && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) - && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); - } - - private String resolveAppointmentConflictReason(String occupancyStatus) { - if (RESERVATION_PENDING_QUOTE.equals(occupancyStatus)) { - return "该时段已有待报价预约占用"; - } - if (RESERVATION_CONFIRMED.equals(occupancyStatus)) { - return "该时段已有已确认预约占用"; - } - return null; - } - - private List safeList(List list) { - return list == null ? List.of() : list; - } - - private String firstNonBlank(String... values) { - for (String value : values) { - if (hasText(value)) { - return value.trim(); - } - } - return ""; - } - - private String trimToNull(String value) { - return hasText(value) ? value.trim() : null; - } - - private boolean hasText(String value) { - return value != null && !value.trim().isEmpty(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/support/PlanningCalendarSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/support/PlanningCalendarSupport.java deleted file mode 100644 index 342ffbfc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/support/PlanningCalendarSupport.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.support; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalTime; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public final class PlanningCalendarSupport { - - private static final LocalTime DEFAULT_START = LocalTime.of(10, 0); - private static final LocalTime DEFAULT_END = LocalTime.of(22, 0); - private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?)"); - - private PlanningCalendarSupport() { - } - - public static String shortName(String name) { - if (name == null || name.trim().isEmpty()) { - return "?"; - } - String normalized = name.trim(); - if (normalized.startsWith("小") && normalized.length() > 1) { - return normalized.substring(1, 2); - } - if (normalized.endsWith("老师") && normalized.length() > 2) { - return normalized.substring(0, 1); - } - return normalized.substring(0, 1).toUpperCase(); - } - - public static BusinessHours parseBusinessHours(String businessHours) { - if (businessHours == null || businessHours.trim().isEmpty()) { - return new BusinessHours(DEFAULT_START, DEFAULT_END); - } - String[] parts = businessHours.trim().split("-"); - if (parts.length != 2) { - return new BusinessHours(DEFAULT_START, DEFAULT_END); - } - try { - LocalTime start = LocalTime.parse(parts[0].trim()); - LocalTime end = LocalTime.parse(parts[1].trim()); - if (!start.isBefore(end)) { - return new BusinessHours(DEFAULT_START, DEFAULT_END); - } - return new BusinessHours(start, end); - } catch (RuntimeException ignored) { - return new BusinessHours(DEFAULT_START, DEFAULT_END); - } - } - - public static int parseDurationMinutes(String durationText, int defaultMinutes) { - if (durationText == null || durationText.trim().isEmpty()) { - return defaultMinutes; - } - Matcher matcher = NUMBER_PATTERN.matcher(durationText.trim()); - if (!matcher.find()) { - return defaultMinutes; - } - BigDecimal amount = new BigDecimal(matcher.group(1)); - if (durationText.contains("小时") || durationText.toLowerCase().contains("hour")) { - amount = amount.multiply(BigDecimal.valueOf(60)); - } - int minutes = amount.setScale(0, RoundingMode.HALF_UP).intValue(); - return minutes > 0 ? minutes : defaultMinutes; - } - - public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) { - if (!hasWorkingSchedule) { - return "rest"; - } - if (allWorkingArtistsBusy) { - return "full"; - } - if (totalCount <= 0) { - return "free"; - } - return "working"; - } - - public record BusinessHours(LocalTime start, LocalTime end) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java deleted file mode 100644 index b9e2d708..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -public class PlanningAppointmentVO { - private Long orderId; - private String orderNo; - private Long orderItemId; - private Long customerId; - private String customerName; - private String customerPhone; - private Long productId; - private String productTitle; - private Long artistId; - private String artistName; - private String artistColor; - private String date; - private String startTime; - private String endTime; - private Integer startMinute; - private Integer durationMinutes; - private Integer status; - private String statusText; - private String occupancyStatus; - private Boolean canEdit; - private Boolean canCancel; - private String conflictReason; - private BigDecimal amount; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningArtistCountVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningArtistCountVO.java deleted file mode 100644 index cfc39b96..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningArtistCountVO.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.vo; - -import lombok.Data; - -@Data -public class PlanningArtistCountVO { - private Long artistId; - private String artistName; - private String shortName; - private String color; - private Integer count; - private String status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningArtistVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningArtistVO.java deleted file mode 100644 index f55f06f1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningArtistVO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.vo; - -import lombok.Data; - -@Data -public class PlanningArtistVO { - private Long id; - private String name; - private String shortName; - private String phone; - private String avatar; - private String color; - private Integer status; - private String statusText; - private String workStartTime; - private String workEndTime; - private Integer rangeCount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningCalendarVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningCalendarVO.java deleted file mode 100644 index 115e24e7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningCalendarVO.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.vo; - -import lombok.Data; - -import java.util.List; - -@Data -public class PlanningCalendarVO { - private String businessStartTime; - private String businessEndTime; - private Integer slotMinutes; - private List artists; - private List schedules; - private List appointments; - private List daySummaries; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java deleted file mode 100644 index 2ea3d5f7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.vo; - -import lombok.Data; - -import java.util.List; - -@Data -public class PlanningDaySummaryVO { - private String date; - private Integer totalCount; - private List artistCounts; - private String dayStatus; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningScheduleVO.java deleted file mode 100644 index bbc341de..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningScheduleVO.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.planning.vo; - -import lombok.Data; - -@Data -public class PlanningScheduleVO { - private Long id; - private Long artistId; - private String artistName; - private String date; - private String startTime; - private String endTime; - private Integer capacity; - private Integer status; - private String statusText; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/EffectDiagramController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/EffectDiagramController.java deleted file mode 100644 index bbded020..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/EffectDiagramController.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.EffectDiagramDTO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.EffectDiagramVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.EffectDiagramService; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -/** - * 商品效果图信息表 Controller - * 对应数据库表 t_effect_diagram - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping({"/effect-diagram", "/api/effect-diagram"}) -@RequiredArgsConstructor -public class EffectDiagramController { - /** - * Variable `effectDiagramService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final EffectDiagramService effectDiagramService; - - /** - * 创建效果图 - * - * @param effectDiagramDTO 效果图DTO - * @return 效果图ID - */ - @PostMapping("/create") - public Result createEffectDiagram(@RequestBody EffectDiagramDTO effectDiagramDTO) { - Long id = effectDiagramService.createEffectDiagram(effectDiagramDTO); - return Result.success(id); - } - - /** - * 更新效果图 - * - * @param id 效果图ID - * @param effectDiagramDTO 效果图DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateEffectDiagram(@PathVariable Long id, @RequestBody EffectDiagramDTO effectDiagramDTO) { - boolean success = effectDiagramService.updateEffectDiagram(id, effectDiagramDTO); - return Result.success(success); - } - - /** - * 删除效果图 - * - * @param id 效果图ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteEffectDiagram(@PathVariable Long id) { - boolean success = effectDiagramService.deleteEffectDiagram(id); - return Result.success(success); - } - - /** - * 根据ID查询效果图 - * - * @param id 效果图ID - * @return 效果图VO - */ - @GetMapping("/get/{id}") - public Result getEffectDiagramById(@PathVariable Long id) { - EffectDiagramVO effectDiagramVO = effectDiagramService.getEffectDiagramById(id); - return Result.success(effectDiagramVO); - } - - /** - * 查询所有效果图 - * - * @return 效果图VO列表 - */ - @GetMapping("/list/all") - public Result> listAllEffectDiagrams() { - List effectDiagramVOs = effectDiagramService.listAllEffectDiagrams(); - return Result.success(effectDiagramVOs); - } - - /** - * 根据商品ID查询效果图 - * - * @param productId 商品ID - * @return 效果图VO列表 - */ - @GetMapping("/list/product/{productId}") - public Result> listEffectDiagramsByProductId(@PathVariable Long productId) { - List effectDiagramVOs = effectDiagramService.listEffectDiagramsByProductId(productId); - return Result.success(effectDiagramVOs); - } - - /** - * 根据类别查询效果图 - * - * @param category 类别 - * @return 效果图VO列表 - */ - @GetMapping("/list/category/{category}") - public Result> listEffectDiagramsByCategory(@PathVariable String category) { - List effectDiagramVOs = effectDiagramService.listEffectDiagramsByCategory(category); - return Result.success(effectDiagramVOs); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/ProductController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/ProductController.java deleted file mode 100644 index b7a2ae43..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/ProductController.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.ProductDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.ProductService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.support.security.UserSessionService; -import com.xiaowang.jacyucloudsalon.core.utils.JwtUtil; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.ProductVO; -import lombok.RequiredArgsConstructor; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@RestController -@RequestMapping("/product") -@RequiredArgsConstructor -/** - * ProductController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ProductController { - /** - * Purpose: AUTHORIZATION_HEADER supports ProductController.java by holding or executing the authorization header business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String AUTHORIZATION_HEADER = "Authorization"; - /** - * Purpose: BEARER_PREFIX supports ProductController.java by holding or executing the bearer prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String BEARER_PREFIX = "Bearer "; - - /** - * Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductService productService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - /** - * Purpose: jwtUtil supports ProductController.java by holding or executing the jwt util business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final JwtUtil jwtUtil; - /** - * Purpose: userSessionService supports ProductController.java by holding or executing the user session service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserSessionService userSessionService; - /** - * Purpose: userShopBindingSupport supports ProductController.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserShopBindingSupport userShopBindingSupport; - - @PostMapping("/create") - @RequirePermission("product:create") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param productDTO parameter `productDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); - Long id = productService.createProduct(productDTO); - return Result.success(id); - } - - @PutMapping("/update/{id}") - @RequirePermission("product:edit") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param productDTO parameter `productDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - ProductVO productVO = productService.getProductById(id); - if (productVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权编辑其他店铺商品"); - Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId(); - productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); - boolean success = productService.updateProduct(id, productDTO); - return Result.success(success); - } - - @DeleteMapping("/delete/{id}") - @RequirePermission("product:delete") - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - ProductVO productVO = productService.getProductById(id); - if (productVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权删除其他店铺商品"); - boolean success = productService.deleteProduct(id); - return Result.success(success); - } - - @GetMapping("/get/{id}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getProductById(@PathVariable Long id) { - ProductVO productVO = productService.getPublicProductById(id); - return Result.success(productVO); - } - - @GetMapping("/list/all") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listAllProducts(HttpServletRequest request) { - Long currentShopId = resolveOptionalCurrentShopId(request); - List productVOs = currentShopId == null - ? productService.listPublicProducts() - : productService.listPublicProductsByShopId(currentShopId); - return Result.success(productVOs); - } - - @GetMapping("/list/shop/{shopId}") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listProductsByShopId(@PathVariable Long shopId) { - List productVOs = productService.listPublicProductsByShopId(shopId); - return Result.success(productVOs); - } - - @GetMapping("/list/tag/{tag}") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tag parameter `tag` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listProductsByTag(HttpServletRequest request, @PathVariable String tag) { - List productVOs = productService.listProductsByTag(tag, resolveOptionalCurrentShopId(request)); - return Result.success(productVOs); - } - - @GetMapping("/list/search") - /** - * Purpose: searchProducts supports ProductController.java by holding or executing the search products business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> searchProducts(HttpServletRequest request, @RequestParam("keyword") String keyword) { - List productVOs = productService.searchProducts(keyword, resolveOptionalCurrentShopId(request)); - return Result.success(productVOs); - } - - @GetMapping("/list/page") - public Result> pagePublicProducts(HttpServletRequest request, - @RequestParam(defaultValue = "1") Integer page, - @RequestParam(defaultValue = "10") Integer size, - @RequestParam(required = false) String keyword, - @RequestParam(required = false) String tag, - @RequestParam(required = false) String tagIds) { - return Result.success(productService.pagePublicProducts(page, size, keyword, tag, tagIds, resolveOptionalCurrentShopId(request))); - } - - /** - * Purpose: resolveOptionalCurrentShopId supports ProductController.java by holding or executing the resolve optional current shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long resolveOptionalCurrentShopId(HttpServletRequest request) { - if (request == null) { - return null; - } - String authHeader = request.getHeader(AUTHORIZATION_HEADER); - if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(BEARER_PREFIX)) { - return null; - } - String token = authHeader.substring(BEARER_PREFIX.length()); - try { - if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) { - return null; - } - Long shopId = jwtUtil.getShopIdFromToken(token); - if (shopId == null || shopId <= 0) { - return null; - } - Long userId = jwtUtil.getUserIdFromToken(token); - String sessionId = jwtUtil.getSessionIdFromToken(token); - String jti = jwtUtil.getJtiFromToken(token); - if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { - return null; - } - return userShopBindingSupport.canUserAccessShop(userId, shopId, false, null) ? shopId : null; - } catch (RuntimeException exception) { - return null; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/TagController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/TagController.java deleted file mode 100644 index adcd8927..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/controller/front/TagController.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.TagDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.TagService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagFilterGroupVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * 系统标签信息表 Controller - * 对应数据库表 t_tag - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping("/tag") -@RequiredArgsConstructor -public class TagController { - /** - * Variable `tagService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TagService tagService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建标签 - * - * @param tagDTO 标签DTO - * @return 标签ID - */ - @PostMapping("/create") - @RequirePermission("tag:create") - public Result createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId())); - Long id = tagService.createTag(tagDTO); - return Result.success(id); - } - - /** - * 更新标签 - * - * @param id 标签ID - * @param tagDTO 标签DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - @RequirePermission("tag:edit") - public Result updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - TagVO tagVO = tagService.getTagById(id); - if (tagVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权编辑其他店铺标签"); - Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId(); - tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); - boolean success = tagService.updateTag(id, tagDTO); - return Result.success(success); - } - - /** - * 删除标签 - * - * @param id 标签ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("tag:delete") - public Result deleteTag(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - TagVO tagVO = tagService.getTagById(id); - if (tagVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权删除其他店铺标签"); - boolean success = tagService.deleteTag(id); - return Result.success(success); - } - - /** - * 根据ID查询标签 - * - * @param id 标签ID - * @return 标签VO - */ - @GetMapping("/get/{id}") - @RequirePermission("tag:view") - public Result getTagById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - TagVO tagVO = tagService.getTagById(id); - if (tagVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); - } - return Result.success(tagVO); - } - - /** - * 查询所有标签(公开接口,不需要权限) - * - * @return 标签VO列表 - */ - @GetMapping("/list/all") - public Result> listAllTags() { - List tagVOs = tagService.listAllTags(); - return Result.success(tagVOs); - } - - /** - * Purpose: listFilterOptions exposes customer-facing grouped tag filters. - * Usage: call it from public product pages, optionally passing shopId for a shop-scoped filter bar. - */ - @GetMapping("/list/filter-options") - public Result> listFilterOptions(@RequestParam(required = false) Long shopId) { - return Result.success(tagService.listFilterOptions(shopId)); - } - - /** - * 根据店铺ID查询标签 - * - * @param shopId 店铺ID - * @return 标签VO列表 - */ - @GetMapping("/list/by-shop/{shopId}") - @RequirePermission("tag:view") - public Result> listTagsByShopId(HttpServletRequest request, @PathVariable Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - List tagVOs = tagService.listTagsByShopId(shopId); - return Result.success(tagVOs); - } - - /** - * 根据标签名称查询标签 - * - * @param tagName 标签名称 - * @return 标签VO - */ - @GetMapping("/get/tagName/{tagName}") - @RequirePermission("tag:view") - public Result getTagByTagName(HttpServletRequest request, @PathVariable String tagName) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - TagVO tagVO = tagService.getTagByTagName(tagName); - if (tagVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); - } - return Result.success(tagVO); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/EffectDiagramDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/EffectDiagramDTO.java deleted file mode 100644 index 18250c06..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/EffectDiagramDTO.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -/** - * 商品效果图信息表 DTO - * 用于效果图信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class EffectDiagramDTO { - - /** - * 所属商品ID,关联商品表主键 - */ - private Long productId; - - /** - * 效果图类别 - */ - private String category; - - /** - * 图片文件ID集合,多ID以逗号分隔 - */ - private String imageFileIds; - - /** - * 效果图描述 - */ - private String description; - - /** - * 效果图对应服务价格 - */ - private BigDecimal price; - - /** - * 效果图对应服务耗时 - */ - private String duration; - - /** - * 效果图标签 - */ - private String tag; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/ProductDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/ProductDTO.java deleted file mode 100644 index b0b4b25f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/ProductDTO.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -/** - * 商品信息表 DTO - * 用于商品信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class ProductDTO { - - /** - * 所属店铺ID,关联店铺表主键 - */ - private Long shopId; - - /** - * 商品标题 - */ - private String title; - - /** - * 商品描述 - */ - private String description; - - /** - * 适合人群说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 - */ - private String targetAudience; - - /** - * 注意事项说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 - */ - private String precautions; - - /** - * 图片文件ID集合,多个ID以逗号分隔 - */ - private String imageFileIds; - - /** - * 商品价格,保留2位小数 - */ - private BigDecimal price; - - /** - * 标签集合,多个标签以逗号分隔,最多5个 - */ - private String tags; - - /** - * 鍟嗗搧鐐硅禐鏁? - */ - private Integer likeCount; - - /** - * 鍟嗗搧鏀惰棌鏁? - */ - private Integer collectCount; - - /** - * 商品对应的服务大约耗时(如"30分钟") - */ - private String approximateDuration; - - /** - * 可预约的美甲师ID集合,多个ID以逗号分隔 - */ - private String bookableArtists; - - /** - * 可用的优惠券ID集合,多个ID以逗号分隔 - */ - private String availableCoupons; - - /** - * 前台是否展示:0-隐藏,1-展示 - */ - private Integer frontVisible; - - /** - * 来源类型 - */ - private String sourceType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/TagDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/TagDTO.java deleted file mode 100644 index 5bcdb508..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/dto/TagDTO.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.dto; - -import lombok.Data; - -/** - * 系统标签信息表 DTO - * 用于标签信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class TagDTO { - - /** - * 标签名称 - */ - private String tagName; - - /** - * 标签文字颜色(16进制) - */ - private String textColor; - - /** - * 标签背景颜色(16进制) - */ - private String bgColor; - - /** - * 标签边框颜色(16进制) - */ - private String borderColor; - - /** - * Purpose: sceneGroup groups tags into customer-facing scene filters. - * Usage: submit it from admin tag forms; empty values are treated as the default public group. - */ - private String sceneGroup; - - /** - * Purpose: displayName is the short label customers see in filters. - * Usage: submit it from admin forms; empty values fall back to tagName. - */ - private String displayName; - - /** - * Purpose: sortOrder controls this tag's ordering inside its public filter group. - * Usage: lower values are shown first; omit it to use legacy ordering. - */ - private Integer sortOrder; - - /** - * Purpose: frontVisible marks whether the tag appears in public filter options. - * Usage: send 1 to show, 0 to hide; omitted values default to visible. - */ - private Integer frontVisible; - - /** - * 店铺ID - */ - private Long shopId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/EffectDiagramDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/EffectDiagramDO.java deleted file mode 100644 index 68fa8a1a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/EffectDiagramDO.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 商品效果图信息表 DO - * 对应数据库表 t_effect_diagram - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_effect_diagram") -public class EffectDiagramDO extends BaseEntity { - - /** - * 所属商品ID,关联商品表主键 - */ - @TableField("product_id") - private Long productId; - - /** - * 效果图类别 - */ - @TableField("category") - private String category; - - /** - * 图片文件ID集合,多ID以逗号分隔 - */ - @TableField("image_file_ids") - private String imageFileIds; - - /** - * 效果图描述 - */ - @TableField("description") - private String description; - - /** - * 效果图对应服务价格 - */ - @TableField("price") - private BigDecimal price; - - /** - * 效果图对应服务耗时 - */ - @TableField("duration") - private String duration; - - /** - * 效果图标签 - */ - @TableField("tag") - private String tag; - - /** - * 效果图点赞数 - */ - @TableField("like_count") - private Integer likeCount; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/ProductDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/ProductDO.java deleted file mode 100644 index 9e71ab65..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/ProductDO.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 商品信息表 DO - * 对应数据库表 t_product - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_product") -public class ProductDO extends BaseEntity { - - /** - * 所属店铺ID,关联店铺表主键 - */ - @TableField("shop_id") - private Long shopId; - - /** - * 商品标题 - */ - @TableField("title") - private String title; - - /** - * 商品描述 - */ - @TableField("description") - private String description; - - /** - * 适合人群说明;后台创建或编辑作品时填写,用户详情页有值时展示。 - */ - @TableField("target_audience") - private String targetAudience; - - /** - * 注意事项说明;后台创建或编辑作品时填写,用户详情页有值时展示。 - */ - @TableField("precautions") - private String precautions; - - /** - * 图片文件ID集合,多个ID以逗号分隔 - */ - @TableField("image_file_ids") - private String imageFileIds; - - /** - * 商品价格,保留2位小数 - */ - @TableField("price") - private BigDecimal price; - - /** - * 标签集合,多个标签以逗号分隔,最多5个 - */ - @TableField("tags") - private String tags; - - /** - * 商品点赞数 - */ - @TableField("like_count") - private Integer likeCount; - - /** - * 商品收藏数 - */ - @TableField("collect_count") - private Integer collectCount; - - /** - * 商品对应的服务大约耗时(如"30分钟") - */ - @TableField("approximate_duration") - private String approximateDuration; - - /** - * 可预约的美甲师ID集合,多个ID以逗号分隔 - */ - @TableField("bookable_artists") - private String bookableArtists; - - /** - * 可用的优惠券ID集合,多个ID以逗号分隔 - */ - @TableField("available_coupons") - private String availableCoupons; - - /** - * 前台是否展示:0-隐藏,1-展示 - */ - @TableField("front_visible") - private Integer frontVisible; - - /** - * 来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约 - */ - @TableField("source_type") - private String sourceType; - - /** - * 逻辑删除标识:0-未删除,1-已删除 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/TagDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/TagDO.java deleted file mode 100644 index 055f85da..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/entity/TagDO.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 系统标签信息表 DO - * 对应数据库表 t_tag - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_tag") -public class TagDO extends BaseEntity { - - /** - * 标签名称 - */ - @TableField("tag_name") - private String tagName; - - /** - * 标签文字颜色(16进制) - */ - @TableField("text_color") - private String textColor; - - /** - * 标签背景颜色(16进制) - */ - @TableField("bg_color") - private String bgColor; - - /** - * 标签边框颜色(16进制) - */ - @TableField("border_color") - private String borderColor; - - /** - * Purpose: sceneGroup stores the customer-facing filter group, such as style or occasion. - * Usage: set it from admin tag forms and read it from public filter-option APIs. - */ - @TableField("scene_group") - private String sceneGroup; - - /** - * Purpose: displayName stores the shorter public label shown in scene filters. - * Usage: leave it empty to fall back to tagName in frontend and mini-program filters. - */ - @TableField("display_name") - private String displayName; - - /** - * Purpose: sortOrder controls tag order inside public filter groups. - * Usage: lower numbers appear first; null uses the default legacy ordering. - */ - @TableField("sort_order") - private Integer sortOrder; - - /** - * Purpose: frontVisible decides whether this tag is visible in public scene filters. - * Usage: set to 1 for visible tags and 0 to hide admin-only/internal tags. - */ - @TableField("front_visible") - private Integer frontVisible; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - private Integer isDelete; - - /** - * 店铺ID - */ - @TableField("shop_id") - private Long shopId; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/EffectDiagramMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/EffectDiagramMapper.java deleted file mode 100644 index f3b213c2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/EffectDiagramMapper.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.EffectDiagramDO; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -/** - * 商品效果图信息表 Mapper - * 对应数据库表 t_effect_diagram - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface EffectDiagramMapper extends BaseMapper { - - @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") - Long countPublicImageReference(@Param("fileId") Long fileId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/ProductMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/ProductMapper.java deleted file mode 100644 index e091fce2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/ProductMapper.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; -import org.apache.ibatis.annotations.Update; - -/** - * 商品信息表 Mapper - * 对应数据库表 t_product - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface ProductMapper extends BaseMapper { - - /** - * 增加商品收藏数 - * - * @param productId 商品ID - * @return 影响行数 - */ - @Update("UPDATE t_product SET collect_count = collect_count + 1 WHERE id = #{productId}") - int incrementCollectCount(@Param("productId") Long productId); - - /** - * 减少商品收藏数 - * - * @param productId 商品ID - * @return 影响行数 - */ - @Update("UPDATE t_product SET collect_count = CASE WHEN collect_count > 0 THEN collect_count - 1 ELSE 0 END WHERE id = #{productId}") - int decrementCollectCount(@Param("productId") Long productId); - - /** - * 增加商品点赞数 - * - * @param productId 商品ID - * @return 影响行数 - */ - @Update("UPDATE t_product SET like_count = like_count + 1 WHERE id = #{productId}") - int incrementLikeCount(@Param("productId") Long productId); - - /** - * 减少商品点赞数 - * - * @param productId 商品ID - * @return 影响行数 - */ - @Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}") - int decrementLikeCount(@Param("productId") Long productId); - - @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") - Long countPublicImageReference(@Param("fileId") Long fileId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/TagMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/TagMapper.java deleted file mode 100644 index fc7931f6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/mapper/TagMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.TagDO; - -/** - * 系统标签信息表 Mapper - * 对应数据库表 t_tag - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface TagMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/EffectDiagramService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/EffectDiagramService.java deleted file mode 100644 index 30df53ec..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/EffectDiagramService.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.EffectDiagramDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.EffectDiagramDTO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.EffectDiagramVO; - -import java.util.List; - -/** - * 商品效果图信息表 Service - * 对应数据库表 t_effect_diagram - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface EffectDiagramService extends IService { - - /** - * 创建效果图 - * - * @param effectDiagramDTO 效果图DTO - * @return 效果图ID - */ - Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO); - - /** - * 更新效果图 - * - * @param id 效果图ID - * @param effectDiagramDTO 效果图DTO - * @return 是否更新成功 - */ - boolean updateEffectDiagram(Long id, EffectDiagramDTO effectDiagramDTO); - - /** - * 删除效果图 - * - * @param id 效果图ID - * @return 是否删除成功 - */ - boolean deleteEffectDiagram(Long id); - - /** - * 根据ID查询效果图 - * - * @param id 效果图ID - * @return 效果图VO - */ - EffectDiagramVO getEffectDiagramById(Long id); - - /** - * 查询所有效果图 - * - * @return 效果图VO列表 - */ - List listAllEffectDiagrams(); - - /** - * 根据商品ID查询效果图 - * - * @param productId 商品ID - * @return 效果图VO列表 - */ - List listEffectDiagramsByProductId(Long productId); - - /** - * 根据类别查询效果图 - * - * @param category 类别 - * @return 效果图VO列表 - */ - List listEffectDiagramsByCategory(String category); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/ProductService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/ProductService.java deleted file mode 100644 index 4de5409e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/ProductService.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.ProductDTO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.ProductVO; - -import java.util.List; - -/** - * 商品信息表 Service - * 对应数据库表 t_product - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface ProductService extends IService { - - /** - * 创建商品 - * - * @param productDTO 商品DTO - * @return 商品ID - */ - Long createProduct(ProductDTO productDTO); - - /** - * 更新商品 - * - * @param id 商品ID - * @param productDTO 商品DTO - * @return 是否更新成功 - */ - boolean updateProduct(Long id, ProductDTO productDTO); - - /** - * 增加商品点赞数 - * - * @param productId 商品ID - * @return 影响行数 - */ - int incrementLikeCount(Long productId); - - /** - * 减少商品点赞数 - * - * @param productId 商品ID - * @return 影响行数 - */ - int decrementLikeCount(Long productId); - - /** - * 删除商品 - * - * @param id 商品ID - * @return 是否删除成功 - */ - boolean deleteProduct(Long id); - - /** - * 根据ID查询商品 - * - * @param id 商品ID - * @return 商品VO - */ - ProductVO getProductById(Long id); - - ProductVO getPublicProductById(Long id); - - /** - * 查询所有商品 - * - * @return 商品VO列表 - */ - List listAllProducts(); - - List listPublicProducts(); - - /** - * 根据店铺ID查询商品 - * - * @param shopId 店铺ID - * @return 商品VO列表 - */ - List listProductsByShopId(Long shopId); - - List listPublicProductsByShopId(Long shopId); - - /** - * 根据标签查询商品 - * - * @param tag 标签 - * @return 商品VO列表 - */ - List listProductsByTag(String tag); - - List listProductsByTag(String tag, Long shopId); - - /** - * 前台按标题、描述、标签名搜索商品 - * - * @param keyword 搜索关键词 - * @return 商品列表 - */ - List searchProducts(String keyword); - - List searchProducts(String keyword, Long shopId); - - /** - * 分页查询商品 - * - * @param page 页码 - * @param size 每页大小 - * @param keyword 搜索关键词 - * @return 分页结果 - */ - PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId); - - PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo); - - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param tag parameter `tag` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag); - - PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId); - - /** - * Purpose: pagePublicProducts filters public product pages by legacy tag text and grouped tag ids. - * Usage: pass comma/semicolon separated tagIds from scene filters; keep tag for backward-compatible name filtering. - */ - PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/TagService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/TagService.java deleted file mode 100644 index 61d73ae9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/TagService.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.TagDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.TagDTO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagFilterGroupVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; - -import java.util.List; - -/** - * 系统标签信息表 Service - * 对应数据库表 t_tag - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface TagService extends IService { - - /** - * 创建标签 - * - * @param tagDTO 标签DTO - * @return 标签ID - */ - Long createTag(TagDTO tagDTO); - - /** - * 更新标签 - * - * @param id 标签ID - * @param tagDTO 标签DTO - * @return 是否更新成功 - */ - boolean updateTag(Long id, TagDTO tagDTO); - - /** - * 删除标签 - * - * @param id 标签ID - * @return 是否删除成功 - */ - boolean deleteTag(Long id); - - /** - * 根据ID查询标签 - * - * @param id 标签ID - * @return 标签VO - */ - TagVO getTagById(Long id); - - /** - * 查询所有标签 - * - * @return 标签VO列表 - */ - List listAllTags(); - - /** - * 根据标签名称查询标签 - * - * @param tagName 标签名称 - * @return 标签VO - */ - TagVO getTagByTagName(String tagName); - - /** - * 根据店铺ID查询标签 - * - * @param shopId 店铺ID - * @return 标签VO列表 - */ - List listTagsByShopId(Long shopId); - - /** - * Purpose: listFilterOptions returns public scene-filter groups for product browsing. - * Usage: call it from public Web or mini-program product pages, optionally scoped by shopId. - * - * @param shopId optional shop scope - * @return grouped public filter tags - */ - List listFilterOptions(Long shopId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/EffectDiagramServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/EffectDiagramServiceImpl.java deleted file mode 100644 index 1f88a944..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/EffectDiagramServiceImpl.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.EffectDiagramDTO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.EffectDiagramDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.EffectDiagramMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.EffectDiagramService; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.EffectDiagramVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * 商品效果图信息表 Service 实现 - * 对应数据库表 t_effect_diagram - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class EffectDiagramServiceImpl extends ServiceImpl implements EffectDiagramService { - /** - * Variable `effectDiagramMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final EffectDiagramMapper effectDiagramMapper; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO) { - EffectDiagramDO effectDiagramDO = new EffectDiagramDO(); - effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); - effectDiagramDO.setCategory(effectDiagramDTO.getCategory()); - effectDiagramDO.setImageFileIds(effectDiagramDTO.getImageFileIds()); - effectDiagramDO.setDescription(effectDiagramDTO.getDescription()); - effectDiagramDO.setPrice(effectDiagramDTO.getPrice()); - effectDiagramDO.setDuration(effectDiagramDTO.getDuration()); - effectDiagramDO.setTag(effectDiagramDTO.getTag()); - effectDiagramDO.setIsDelete(0); - effectDiagramMapper.insert(effectDiagramDO); - return effectDiagramDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateEffectDiagram(Long id, EffectDiagramDTO effectDiagramDTO) { - EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); - if (effectDiagramDO == null) { - return false; - } - effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); - effectDiagramDO.setCategory(effectDiagramDTO.getCategory()); - effectDiagramDO.setImageFileIds(effectDiagramDTO.getImageFileIds()); - effectDiagramDO.setDescription(effectDiagramDTO.getDescription()); - effectDiagramDO.setPrice(effectDiagramDTO.getPrice()); - effectDiagramDO.setDuration(effectDiagramDTO.getDuration()); - effectDiagramDO.setTag(effectDiagramDTO.getTag()); - return effectDiagramMapper.updateById(effectDiagramDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteEffectDiagram(Long id) { - EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); - if (effectDiagramDO == null) { - return false; - } - effectDiagramDO.setIsDelete(1); - return effectDiagramMapper.updateById(effectDiagramDO) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return EffectDiagramVO result consumed by the caller or returned to the frontend - */ - public EffectDiagramVO getEffectDiagramById(Long id) { - EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); - if (effectDiagramDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param effectDiagramDO parameter `effectDiagramDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(effectDiagramDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllEffectDiagrams() { - List effectDiagramDOs = effectDiagramMapper.selectList(null); - return effectDiagramDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listEffectDiagramsByProductId(Long productId) { - List effectDiagramDOs = effectDiagramMapper.selectList( - Wrappers.lambdaQuery(EffectDiagramDO.class) - .eq(EffectDiagramDO::getProductId, productId) - ); - return effectDiagramDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param category parameter `category` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listEffectDiagramsByCategory(String category) { - List effectDiagramDOs = effectDiagramMapper.selectList( - Wrappers.lambdaQuery(EffectDiagramDO.class) - .eq(EffectDiagramDO::getCategory, category) - ); - return effectDiagramDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 将 DO 转换为 VO - * - * @param effectDiagramDO 效果图DO - * @return 效果图VO - */ - private EffectDiagramVO convertToVO(EffectDiagramDO effectDiagramDO) { - EffectDiagramVO effectDiagramVO = new EffectDiagramVO(); - effectDiagramVO.setId(effectDiagramDO.getId()); - effectDiagramVO.setProductId(effectDiagramDO.getProductId()); - effectDiagramVO.setCategory(effectDiagramDO.getCategory()); - effectDiagramVO.setImageFileIds(effectDiagramDO.getImageFileIds()); - effectDiagramVO.setDescription(effectDiagramDO.getDescription()); - effectDiagramVO.setPrice(effectDiagramDO.getPrice()); - effectDiagramVO.setDuration(effectDiagramDO.getDuration()); - effectDiagramVO.setTag(effectDiagramDO.getTag()); - effectDiagramVO.setLikeCount(effectDiagramDO.getLikeCount()); - effectDiagramVO.setCreateTime(effectDiagramDO.getCreateTime()); - effectDiagramVO.setUpdateTime(effectDiagramDO.getUpdateTime()); - return effectDiagramVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/ProductServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/ProductServiceImpl.java deleted file mode 100644 index d580f66c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/ProductServiceImpl.java +++ /dev/null @@ -1,1312 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.fasterxml.jackson.core.type.TypeReference; -import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.ProductDTO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.CouponDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.TagDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.CouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.TagMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.ProductService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.support.BookableArtistSupport; -import com.xiaowang.jacyucloudsalon.core.support.cache.MultiLevelCacheService; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.ProductVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagInfo; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.time.Duration; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * ProductServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ProductServiceImpl extends ServiceImpl implements ProductService { - /** - * Purpose: PRODUCT_DETAIL_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product detail cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String PRODUCT_DETAIL_CACHE_PREFIX = "cache:product:detail:"; - /** - * Purpose: PRODUCT_LIST_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product list cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String PRODUCT_LIST_CACHE_PREFIX = "cache:product:list:"; - /** - * Purpose: PRODUCT_SEARCH_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product search cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String PRODUCT_SEARCH_CACHE_PREFIX = "cache:product:search:"; - /** - * Purpose: DEFAULT_PUBLIC_PAGE_SIZE supports ProductServiceImpl.java by holding or executing the default public page size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int DEFAULT_PUBLIC_PAGE_SIZE = 10; - /** - * Purpose: MAX_PUBLIC_PAGE_SIZE supports ProductServiceImpl.java by holding or executing the max public page size business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int MAX_PUBLIC_PAGE_SIZE = 30; - private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)"); - private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L; - private static final int FRONT_VISIBLE = 1; - private static final String SOURCE_TYPE_BACKEND = "BACKEND"; - /** - * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductMapper productMapper; - /** - * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageFileService objectStorageFileService; - private final ObjectStorageUrlSupport objectStorageUrlSupport; - /** - * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponMapper couponMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TagMapper tagMapper; - /** - * Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BookableArtistSupport bookableArtistSupport; - /** - * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MultiLevelCacheService multiLevelCacheService; - /** - * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AppCacheProperties appCacheProperties; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDTO parameter `productDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createProduct(ProductDTO productDTO) { - validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); - validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); - ProductDO productDO = new ProductDO(); - productDO.setShopId(productDTO.getShopId()); - productDO.setTitle(productDTO.getTitle()); - productDO.setDescription(productDTO.getDescription()); - productDO.setTargetAudience(productDTO.getTargetAudience()); - productDO.setPrecautions(productDTO.getPrecautions()); - productDO.setImageFileIds(productDTO.getImageFileIds()); - productDO.setPrice(productDTO.getPrice()); - productDO.setTags(productDTO.getTags()); - productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); - productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); - productDO.setApproximateDuration(productDTO.getApproximateDuration()); - productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); - productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible())); - productDO.setSourceType(resolveSourceType(productDTO.getSourceType())); - productDO.setIsDelete(0); - productMapper.insert(productDO); - evictPublicProductCaches(productDO.getId()); - return productDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param productDTO parameter `productDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateProduct(Long id, ProductDTO productDTO) { - ProductDO productDO = productMapper.selectById(id); - if (productDO == null) { - return false; - } - validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); - validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); - productDO.setShopId(productDTO.getShopId()); - productDO.setTitle(productDTO.getTitle()); - productDO.setDescription(productDTO.getDescription()); - productDO.setTargetAudience(productDTO.getTargetAudience()); - productDO.setPrecautions(productDTO.getPrecautions()); - productDO.setImageFileIds(productDTO.getImageFileIds()); - productDO.setPrice(productDTO.getPrice()); - productDO.setTags(productDTO.getTags()); - if (productDTO.getLikeCount() != null) { - productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); - } - if (productDTO.getCollectCount() != null) { - productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); - } - productDO.setApproximateDuration(productDTO.getApproximateDuration()); - productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); - productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible())); - productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); - boolean updated = productMapper.updateById(productDO) > 0; - if (updated) { - /** - * Run business method `evictPublicProductCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictPublicProductCaches(id); - } - return updated; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteProduct(Long id) { - ProductDO productDO = productMapper.selectById(id); - if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { - return false; - } - productDO.setIsDelete(1); - boolean deleted = productMapper.updateById(productDO) > 0; - if (deleted) { - /** - * Run business method `evictPublicProductCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictPublicProductCaches(id); - } - return deleted; - } - - @Override - /** - * Run business method `incrementLikeCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return int result consumed by the caller or returned to the frontend - */ - public int incrementLikeCount(Long productId) { - int updated = productMapper.incrementLikeCount(productId); - if (updated > 0) { - /** - * Run business method `evictPublicProductCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictPublicProductCaches(productId); - } - return updated; - } - - @Override - /** - * Run business method `decrementLikeCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return int result consumed by the caller or returned to the frontend - */ - public int decrementLikeCount(Long productId) { - int updated = productMapper.decrementLikeCount(productId); - if (updated > 0) { - /** - * Run business method `evictPublicProductCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictPublicProductCaches(productId); - } - return updated; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return ProductVO result consumed by the caller or returned to the frontend - */ - public ProductVO getProductById(Long id) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); - return multiLevelCacheService.getOrLoad( - PRODUCT_DETAIL_CACHE_PREFIX + id, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference() { - }, - () -> { - ProductDO productDO = productMapper.selectById(id); - if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDO parameter `productDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(productDO); - } - ); - } - - @Override - public ProductVO getPublicProductById(Long id) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); - return multiLevelCacheService.getOrLoad( - PRODUCT_DETAIL_CACHE_PREFIX + "public:" + id, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference() { - }, - () -> { - ProductDO productDO = productMapper.selectById(id); - if (productDO == null - || Integer.valueOf(1).equals(productDO.getIsDelete()) - || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible())) { - return null; - } - return convertToVO(productDO); - } - ); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllProducts() { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); - return multiLevelCacheService.getOrLoad( - PRODUCT_LIST_CACHE_PREFIX + "all", - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> toProductVOList(productMapper.selectList( - Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) - .orderByDesc(ProductDO::getCreateTime) - )) - ); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listProductsByShopId(Long shopId) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); - return multiLevelCacheService.getOrLoad( - PRODUCT_LIST_CACHE_PREFIX + "shop:" + shopId, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> { - List productDOs = productMapper.selectList( - Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getShopId, shopId) - .orderByDesc(ProductDO::getCreateTime) - ); - /** - * Run business method `toProductVOList`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDOs parameter `productDOs` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toProductVOList(productDOs); - } - ); - } - - @Override - public List listPublicProducts() { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); - return multiLevelCacheService.getOrLoad( - PRODUCT_LIST_CACHE_PREFIX + "public:all", - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> toProductVOList(productMapper.selectList(buildFrontQuery(null, null, null))) - ); - } - - @Override - public List listPublicProductsByShopId(Long shopId) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); - Long scopedShopId = normalizeShopId(shopId); - return multiLevelCacheService.getOrLoad( - PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "public", - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> toProductVOList(productMapper.selectList(buildFrontQuery(null, null, null, scopedShopId))) - ); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tag parameter `tag` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listProductsByTag(String tag) { - return listProductsByTag(tag, null); - } - - @Override - /** - * Purpose: listProductsByTag supports ProductServiceImpl.java by holding or executing the list products by tag business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listProductsByTag(String tag, Long shopId) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); - String normalizedTag = normalizeOptionalKeyword(tag); - Long scopedShopId = normalizeShopId(shopId); - return multiLevelCacheService.getOrLoad( - PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "tag:" + normalizedTag, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> loadProductsByTag(normalizedTag, scopedShopId) - ); - } - - @Override - /** - * Run business method `searchProducts`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keyword parameter `keyword` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List searchProducts(String keyword) { - return searchProducts(keyword, null); - } - - @Override - /** - * Purpose: searchProducts supports ProductServiceImpl.java by holding or executing the search products business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List searchProducts(String keyword, Long shopId) { - if (!StringUtils.hasText(keyword)) { - return new ArrayList<>(); - } - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductSearch(); - String trimmedKeyword = keyword.trim(); - Long scopedShopId = normalizeShopId(shopId); - return multiLevelCacheService.getOrLoad( - PRODUCT_SEARCH_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + trimmedKeyword.toLowerCase(Locale.ROOT), - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> searchFrontProducts(trimmedKeyword, scopedShopId) - ); - } - - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDO parameter `productDO` supplied by the caller - * @return private ProductVO result consumed by the caller or returned to the frontend - */ - private ProductVO convertToVO(ProductDO productDO) { - if (productDO == null) { - return null; - } - return toProductVOList(Collections.singletonList(productDO)).stream() - .findFirst() - .orElse(null); - } - - /** - * Run business method `toProductVOList`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDOs parameter `productDOs` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List toProductVOList(List productDOs) { - if (productDOs == null || productDOs.isEmpty()) { - return new ArrayList<>(); - } - ProductEnrichmentContext context = buildEnrichmentContext(productDOs); - return productDOs.stream() - .map(productDO -> convertToVO(productDO, context)) - .collect(Collectors.toList()); - } - - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDO parameter `productDO` supplied by the caller - * @param context parameter `context` supplied by the caller - * @return private ProductVO result consumed by the caller or returned to the frontend - */ - private ProductVO convertToVO(ProductDO productDO, ProductEnrichmentContext context) { - ProductVO productVO = new ProductVO(); - productVO.setId(productDO.getId()); - productVO.setShopId(productDO.getShopId()); - productVO.setShopName(context.shopNames().get(productDO.getShopId())); - productVO.setTitle(productDO.getTitle()); - productVO.setDescription(productDO.getDescription()); - productVO.setTargetAudience(productDO.getTargetAudience()); - productVO.setPrecautions(productDO.getPrecautions()); - productVO.setImageFileIds(productDO.getImageFileIds()); - productVO.setPrice(productDO.getPrice()); - productVO.setTags(productDO.getTags()); - productVO.setLikeCount(productDO.getLikeCount()); - productVO.setCollectCount(productDO.getCollectCount()); - productVO.setApproximateDuration(productDO.getApproximateDuration()); - productVO.setServiceDurationMinutes(resolveServiceDurationMinutes(productDO.getApproximateDuration())); - String validBookableArtists = bookableArtistSupport.filterValidBookableArtists(productDO.getShopId(), productDO.getBookableArtists()); - productVO.setBookableArtists(productDO.getBookableArtists()); - productVO.setAvailableBookableArtistCount(countBookableArtists(validBookableArtists)); - productVO.setBookableArtistRestricted(StringUtils.hasText(productDO.getBookableArtists())); - productVO.setAvailableCoupons(productDO.getAvailableCoupons()); - productVO.setFrontVisible(productDO.getFrontVisible()); - productVO.setSourceType(productDO.getSourceType()); - productVO.setCreateTime(productDO.getCreateTime()); - productVO.setUpdateTime(productDO.getUpdateTime()); - - List tagNames = new ArrayList<>(); - List tagInfos = new ArrayList<>(); - for (Long tagId : parseDelimitedLongIds(productDO.getTags(), ";")) { - TagDO tagDO = context.tags().get(tagId); - if (tagDO == null) { - continue; - } - tagNames.add(tagDO.getTagName()); - TagInfo tagInfo = new TagInfo(); - tagInfo.setId(tagId); - tagInfo.setTagName(tagDO.getTagName()); - tagInfo.setTextColor(tagDO.getTextColor()); - tagInfo.setBgColor(tagDO.getBgColor()); - tagInfo.setBorderColor(tagDO.getBorderColor()); - tagInfos.add(tagInfo); - } - productVO.setTagList(tagNames); - productVO.setTagInfos(tagInfos); - - List imageUrls = new ArrayList<>(); - for (Long fileId : parseDelimitedLongIds(productDO.getImageFileIds(), ",")) { - ObjectStorageFileVO fileVO = context.files().get(fileId); - if (fileVO != null && StringUtils.hasText(fileVO.getFileUrl())) { - imageUrls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); - } - } - productVO.setImageUrls(imageUrls); - return productVO; - } - - private long resolveServiceDurationMinutes(String approximateDuration) { - if (!StringUtils.hasText(approximateDuration)) { - return DEFAULT_SERVICE_DURATION_MINUTES; - } - Matcher matcher = DURATION_PATTERN.matcher(approximateDuration); - if (matcher.find()) { - try { - return Math.max(1L, Long.parseLong(matcher.group(1))); - } catch (NumberFormatException ignored) { - } - } - return DEFAULT_SERVICE_DURATION_MINUTES; - } - - /** - * Run business method `buildEnrichmentContext`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productDOs parameter `productDOs` supplied by the caller - * @return private ProductEnrichmentContext result consumed by the caller or returned to the frontend - */ - private ProductEnrichmentContext buildEnrichmentContext(List productDOs) { - Set shopIds = new LinkedHashSet<>(); - Set tagIds = new LinkedHashSet<>(); - Set fileIds = new LinkedHashSet<>(); - for (ProductDO productDO : productDOs) { - if (productDO == null) { - continue; - } - if (productDO.getShopId() != null && productDO.getShopId() > 0) { - shopIds.add(productDO.getShopId()); - } - tagIds.addAll(parseDelimitedLongIds(productDO.getTags(), ";")); - fileIds.addAll(parseDelimitedLongIds(productDO.getImageFileIds(), ",")); - } - return new ProductEnrichmentContext( - loadShopNameMap(shopIds), - loadTagMap(tagIds), - objectStorageFileService.getObjectStorageFileMapByIds(fileIds) - ); - } - - @Override - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId) { - return pageProducts(page, size, keyword, shopId, null, null, null, null, null); - } - - @Override - /** - * Purpose: pageProducts supports ProductServiceImpl.java by holding or executing the page products business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo) { - Page pageParam = new Page<>(page, size); - - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class); - wrapper.eq(ProductDO::getIsDelete, 0); - if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(ProductDO::getTitle, keyword) - .or().like(ProductDO::getDescription, keyword)); - } - if (shopId != null && shopId > 0) { - wrapper.eq(ProductDO::getShopId, shopId); - } - if (tagId != null) { - wrapper.like(ProductDO::getTags, String.valueOf(tagId)); - } - if (minPrice != null) { - wrapper.ge(ProductDO::getPrice, minPrice); - } - if (maxPrice != null) { - wrapper.le(ProductDO::getPrice, maxPrice); - } - LocalDateTime createdFromTime = parseDateTime(createdFrom); - LocalDateTime createdToTime = parseDateTime(createdTo); - if (createdFromTime != null) { - wrapper.ge(ProductDO::getCreateTime, createdFromTime); - } - if (createdToTime != null) { - wrapper.le(ProductDO::getCreateTime, createdToTime); - } - wrapper.orderByDesc(ProductDO::getCreateTime); - - Page productPage = productMapper.selectPage(pageParam, wrapper); - - PageResultVO result = new PageResultVO<>(); - result.setList(toProductVOList(productPage.getRecords())); - result.setTotal(productPage.getTotal()); - result.setPage(page); - result.setSize(size); - - return result; - } - - /** - * Purpose: parseDateTime supports ProductServiceImpl.java by holding or executing the parse date time business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime parseDateTime(String value) { - if (!StringUtils.hasText(value)) { - return null; - } - try { - return LocalDateTime.parse(value.replace(" ", "T")); - } catch (Exception ignored) { - try { - return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - } catch (Exception secondIgnored) { - return null; - } - } - } - - @Override - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param tag parameter `tag` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag) { - return pagePublicProducts(page, size, keyword, tag, null); - } - - @Override - /** - * Purpose: pagePublicProducts supports ProductServiceImpl.java by holding or executing the page public products business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId) { - return pagePublicProducts(page, size, keyword, tag, null, shopId); - } - - @Override - /** - * Purpose: pagePublicProducts supports grouped tag-id filters for public product browsing. - * Usage: pass tagIds from scene filter chips while keeping tag for legacy tag-name searches. - */ - public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId) { - int normalizedPage = normalizePage(page); - int normalizedSize = normalizePageSize(size); - String normalizedKeyword = normalizeOptionalKeyword(keyword); - String normalizedTag = normalizeOptionalKeyword(tag); - String normalizedTagIds = normalizeOptionalKeyword(tagIds); - Long scopedShopId = normalizeShopId(shopId); - AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword) - ? appCacheProperties.getProductSearch() - : appCacheProperties.getProductList(); - String cacheKey = PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "page:" + normalizedPage - + ":" + normalizedSize - + ":" + normalizedKeyword.toLowerCase(Locale.ROOT) - + ":" + normalizedTag.toLowerCase(Locale.ROOT) - + ":" + normalizedTagIds.toLowerCase(Locale.ROOT); - return multiLevelCacheService.getOrLoad( - cacheKey, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, normalizedTagIds, scopedShopId) - ); - } - - /** - * Run business method `validateBookableArtists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @param bookableArtists parameter `bookableArtists` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateBookableArtists(Long shopId, String bookableArtists) { - if (!StringUtils.hasText(bookableArtists)) { - return; - } - - if (shopId == null || shopId <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("配置可预约美甲师前必须先选择店铺"); - } - - for (String artistIdStr : bookableArtists.split(",")) { - if (!StringUtils.hasText(artistIdStr)) { - continue; - } - - Long artistId; - try { - artistId = Long.parseLong(artistIdStr.trim()); - } catch (NumberFormatException ex) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("可预约美甲师配置格式不正确"); - } - - if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("存在无效、已停用或不属于当前店铺的美甲师配置"); - } - } - } - - /** - * Run business method `validateAvailableCoupons`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @param availableCoupons parameter `availableCoupons` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateAvailableCoupons(Long shopId, String availableCoupons) { - if (!StringUtils.hasText(availableCoupons)) { - return; - } - - if (shopId == null || shopId <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("配置可用优惠券前必须先选择店铺"); - } - - for (String couponIdStr : availableCoupons.split(",")) { - if (!StringUtils.hasText(couponIdStr)) { - continue; - } - - Long couponId; - try { - couponId = Long.parseLong(couponIdStr.trim()); - } catch (NumberFormatException exception) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("可用优惠券配置格式不正确"); - } - - CouponDO couponDO = couponMapper.selectById(couponId); - if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("存在无效的优惠券配置"); - } - if (!Integer.valueOf(1).equals(couponDO.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("存在已失效的优惠券配置"); - } - if (couponDO.getShopId() == null || !shopId.equals(couponDO.getShopId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("不可跨店铺配置可用优惠券"); - } - } - } - - /** - * Run business method `countBookableArtists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bookableArtists parameter `bookableArtists` supplied by the caller - * @return private int result consumed by the caller or returned to the frontend - */ - private int countBookableArtists(String bookableArtists) { - if (!StringUtils.hasText(bookableArtists)) { - return 0; - } - return (int) java.util.Arrays.stream(bookableArtists.split(",")) - .map(String::trim) - .filter(StringUtils::hasText) - .count(); - } - - /** - * Run business method `normalizeInteractionCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param count parameter `count` supplied by the caller - * @return private Integer result consumed by the caller or returned to the frontend - */ - private Integer normalizeInteractionCount(Integer count) { - if (count == null || count < 0) { - return 0; - } - return count; - } - - /** - * Run business method `loadProductsByTag`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tag parameter `tag` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List loadProductsByTag(String tag, Long shopId) { - if (!StringUtils.hasText(tag)) { - return new ArrayList<>(); - } - Set matchedTagIds = findExactTagIds(tag); - if (matchedTagIds.isEmpty()) { - return new ArrayList<>(); - } - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) - .orderByDesc(ProductDO::getCreateTime); - if (shopId != null) { - wrapper.eq(ProductDO::getShopId, shopId); - } - /** - * Run business method `applyTagIdConditions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @param matchedTagIds parameter `matchedTagIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - applyTagIdConditions(wrapper, matchedTagIds); - return toProductVOList(productMapper.selectList(wrapper)); - } - - /** - * Run business method `searchFrontProducts`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keyword parameter `keyword` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List searchFrontProducts(String keyword, Long shopId) { - LambdaQueryWrapper wrapper = buildFrontQuery(keyword, null, null, shopId); - return toProductVOList(productMapper.selectList(wrapper)); - } - - /** - * Run business method `buildPublicProductPage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param tag parameter `tag` supplied by the caller - * @return private PageResultVO result consumed by the caller or returned to the frontend - */ - private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, Long shopId) { - return buildPublicProductPage(page, size, keyword, tag, null, shopId); - } - - /** - * Purpose: buildPublicProductPage creates the public product page with optional grouped tag ids. - * Usage: call from cache loaders after inputs have been normalized. - */ - private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, String tagIds, Long shopId) { - Set exactTagIds = null; - if (StringUtils.hasText(tag)) { - exactTagIds = findExactTagIds(tag); - if (exactTagIds.isEmpty()) { - /** - * Run business method `buildEmptyPageResult`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildEmptyPageResult(page, size); - } - } - Set selectedTagIds = parseTagIdFilter(tagIds); - - Page pageParam = new Page<>(page, size); - Page productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, selectedTagIds, shopId)); - PageResultVO result = new PageResultVO<>(); - result.setList(toProductVOList(productPage.getRecords())); - result.setTotal(productPage.getTotal()); - result.setPage(page); - result.setSize(size); - return result; - } - - /** - * Run business method `buildFrontQuery`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keyword parameter `keyword` supplied by the caller - * @param tag parameter `tag` supplied by the caller - * @param exactTagIds parameter `exactTagIds` supplied by the caller - * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend - */ - private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds) { - return buildFrontQuery(keyword, tag, exactTagIds, null); - } - - /** - * Purpose: buildFrontQuery supports ProductServiceImpl.java by holding or executing the build front query business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Long shopId) { - return buildFrontQuery(keyword, tag, exactTagIds, null, shopId); - } - - /** - * Purpose: buildFrontQuery adds product search, legacy tag, grouped tag-id, and shop filters. - * Usage: pass selectedTagIds when users tap scene-filter chips. - */ - private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getFrontVisible, FRONT_VISIBLE); - if (shopId != null) { - wrapper.eq(ProductDO::getShopId, shopId); - } - /** - * Run business method `applyKeywordFilter`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - applyKeywordFilter(wrapper, keyword); - if (StringUtils.hasText(tag)) { - applyTagIdConditions(wrapper, exactTagIds == null ? findExactTagIds(tag) : exactTagIds); - } - if (selectedTagIds != null && !selectedTagIds.isEmpty()) { - applyTagIdConditions(wrapper, selectedTagIds); - } - wrapper.orderByDesc(ProductDO::getCreateTime); - return wrapper; - } - - private Integer resolveFrontVisible(Integer frontVisible) { - return Integer.valueOf(0).equals(frontVisible) ? 0 : FRONT_VISIBLE; - } - - private String resolveSourceType(String sourceType) { - return StringUtils.hasText(sourceType) ? sourceType.trim() : SOURCE_TYPE_BACKEND; - } - - private Integer resolveUpdateFrontVisible(Integer currentFrontVisible, Integer nextFrontVisible) { - if (nextFrontVisible != null) { - return resolveFrontVisible(nextFrontVisible); - } - return currentFrontVisible == null ? FRONT_VISIBLE : currentFrontVisible; - } - - private String resolveUpdateSourceType(String currentSourceType, String nextSourceType) { - if (StringUtils.hasText(nextSourceType)) { - return resolveSourceType(nextSourceType); - } - return StringUtils.hasText(currentSourceType) ? currentSourceType : SOURCE_TYPE_BACKEND; - } - - /** - * Run business method `applyKeywordFilter`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void applyKeywordFilter(LambdaQueryWrapper wrapper, String keyword) { - if (!StringUtils.hasText(keyword)) { - return; - } - Set matchedTagIds = findLikeTagIds(keyword); - wrapper.and(w -> { - w.like(ProductDO::getTitle, keyword) - .or() - .like(ProductDO::getDescription, keyword); - /** - * Run business method `appendOrTagIdConditions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param w parameter `w` supplied by the caller - * @param matchedTagIds parameter `matchedTagIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - appendOrTagIdConditions(w, matchedTagIds); - }); - } - - /** - * Run business method `applyTagIdConditions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @param tagIds parameter `tagIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void applyTagIdConditions(LambdaQueryWrapper wrapper, Set tagIds) { - wrapper.and(w -> { - boolean appended = false; - if (tagIds != null) { - for (String tagId : tagIds) { - if (!StringUtils.hasText(tagId)) { - continue; - } - if (appended) { - w.or(); - } - w.apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagId); - appended = true; - } - } - if (!appended) { - w.apply("1 = 0"); - } - }); - } - - /** - * Run business method `appendOrTagIdConditions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @param tagIds parameter `tagIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void appendOrTagIdConditions(LambdaQueryWrapper wrapper, Set tagIds) { - if (tagIds == null || tagIds.isEmpty()) { - return; - } - for (String tagId : tagIds) { - if (!StringUtils.hasText(tagId)) { - continue; - } - wrapper.or().apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagId); - } - } - - /** - * Run business method `loadShopNameMap`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map loadShopNameMap(Set shopIds) { - if (shopIds == null || shopIds.isEmpty()) { - return Collections.emptyMap(); - } - return shopMapper.selectBatchIds(shopIds).stream() - .filter(shopDO -> !Integer.valueOf(1).equals(shopDO.getIsDelete())) - .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (left, right) -> left, LinkedHashMap::new)); - } - - /** - * Run business method `loadTagMap`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagIds parameter `tagIds` supplied by the caller - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map loadTagMap(Set tagIds) { - if (tagIds == null || tagIds.isEmpty()) { - return Collections.emptyMap(); - } - return tagMapper.selectBatchIds(tagIds).stream() - .filter(tagDO -> !Integer.valueOf(1).equals(tagDO.getIsDelete())) - .collect(Collectors.toMap(TagDO::getId, tagDO -> tagDO, (left, right) -> left, LinkedHashMap::new)); - } - - /** - * Run business method `parseDelimitedLongIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param rawValue parameter `rawValue` supplied by the caller - * @param delimiter parameter `delimiter` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List parseDelimitedLongIds(String rawValue, String delimiter) { - if (!StringUtils.hasText(rawValue)) { - return Collections.emptyList(); - } - List ids = new ArrayList<>(); - for (String value : rawValue.split(java.util.regex.Pattern.quote(delimiter))) { - if (!StringUtils.hasText(value)) { - continue; - } - try { - ids.add(Long.parseLong(value.trim())); - } catch (NumberFormatException ignored) { - // Ignore malformed ids in historical data and keep the rest of the product visible. - } - } - return ids; - } - - /** - * Purpose: parseTagIdFilter converts scene-filter tag ids into a query-safe set. - * Usage: pass comma or semicolon separated frontend values; invalid chunks are ignored. - */ - private Set parseTagIdFilter(String rawValue) { - if (!StringUtils.hasText(rawValue)) { - return Collections.emptySet(); - } - return java.util.Arrays.stream(rawValue.split("[,;]")) - .map(String::trim) - .filter(StringUtils::hasText) - .filter(value -> { - try { - Long.parseLong(value); - return true; - } catch (NumberFormatException exception) { - return false; - } - }) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - /** - * Run business method `findExactTagIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tag parameter `tag` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set findExactTagIds(String tag) { - if (!StringUtils.hasText(tag)) { - return Set.of(); - } - return tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(TagDO::getTagName, tag) - ).stream() - .map(TagDO::getId) - .map(String::valueOf) - .collect(Collectors.toCollection(HashSet::new)); - } - - /** - * Run business method `findLikeTagIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keyword parameter `keyword` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set findLikeTagIds(String keyword) { - if (!StringUtils.hasText(keyword)) { - return Set.of(); - } - return tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .like(TagDO::getTagName, keyword) - ).stream() - .map(TagDO::getId) - .map(String::valueOf) - .collect(Collectors.toCollection(HashSet::new)); - } - - /** - * Run business method `buildEmptyPageResult`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @return private PageResultVO result consumed by the caller or returned to the frontend - */ - private PageResultVO buildEmptyPageResult(int page, int size) { - PageResultVO result = new PageResultVO<>(); - result.setList(List.of()); - result.setTotal(0L); - result.setPage(page); - result.setSize(size); - return result; - } - - /** - * Run business method `normalizePage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @return private int result consumed by the caller or returned to the frontend - */ - private int normalizePage(Integer page) { - return page == null || page < 1 ? 1 : page; - } - - /** - * Run business method `normalizePageSize`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param size parameter `size` supplied by the caller - * @return private int result consumed by the caller or returned to the frontend - */ - private int normalizePageSize(Integer size) { - if (size == null || size < 1) { - return DEFAULT_PUBLIC_PAGE_SIZE; - } - return Math.min(size, MAX_PUBLIC_PAGE_SIZE); - } - - /** - * Run business method `normalizeOptionalKeyword`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param value parameter `value` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeOptionalKeyword(String value) { - return StringUtils.hasText(value) ? value.trim() : ""; - } - - /** - * Purpose: normalizeShopId supports ProductServiceImpl.java by holding or executing the normalize shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long normalizeShopId(Long shopId) { - return shopId != null && shopId > 0 ? shopId : null; - } - - /** - * Purpose: buildShopCacheSegment supports ProductServiceImpl.java by holding or executing the build shop cache segment business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildShopCacheSegment(Long shopId) { - return shopId == null ? "all:" : "shop:" + shopId + ":"; - } - - /** - * Run business method `evictPublicProductCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void evictPublicProductCaches(Long productId) { - if (productId != null) { - multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + productId); - multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + "public:" + productId); - } - multiLevelCacheService.evictByPrefix(PRODUCT_LIST_CACHE_PREFIX); - multiLevelCacheService.evictByPrefix(PRODUCT_SEARCH_CACHE_PREFIX); - } - - /** - * Purpose: ProductEnrichmentContext supports ProductServiceImpl.java by holding or executing the product enrichment context business role. - * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. - */ - private record ProductEnrichmentContext( - Map shopNames, - Map tags, - Map files - ) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/TagServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/TagServiceImpl.java deleted file mode 100644 index 232ff6c0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/service/impl/TagServiceImpl.java +++ /dev/null @@ -1,545 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.fasterxml.jackson.core.type.TypeReference; -import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties; -import com.xiaowang.jacyucloudsalon.core.modules.product.dto.TagDTO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.TagDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.TagMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.service.TagService; -import com.xiaowang.jacyucloudsalon.core.support.cache.MultiLevelCacheService; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagFilterGroupVO; -import com.xiaowang.jacyucloudsalon.core.modules.product.vo.TagVO; -import lombok.RequiredArgsConstructor; -import org.springframework.dao.DuplicateKeyException; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * 系统标签信息表 Service 实现 - * 对应数据库表 t_tag - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class TagServiceImpl extends ServiceImpl implements TagService { - /** - * Purpose: TAG_DETAIL_CACHE_PREFIX supports TagServiceImpl.java by holding or executing the tag detail cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TAG_DETAIL_CACHE_PREFIX = "cache:tag:detail:"; - /** - * Purpose: TAG_LIST_CACHE_PREFIX supports TagServiceImpl.java by holding or executing the tag list cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String TAG_LIST_CACHE_PREFIX = "cache:tag:list:"; - /** - * Purpose: DEFAULT_FILTER_GROUP is the public group used for legacy tags without a scene group. - * Usage: keep old tags visible in filters without requiring data migration edits. - */ - private static final String DEFAULT_FILTER_GROUP = "其他"; - /** - * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TagMapper tagMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MultiLevelCacheService multiLevelCacheService; - /** - * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AppCacheProperties appCacheProperties; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagDTO parameter `tagDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createTag(TagDTO tagDTO) { - String tagName = normalizeTagName(tagDTO.getTagName()); - Long shopId = requireShopId(tagDTO.getShopId()); - /** - * Run business method `ensureTagNameUniqueInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureTagNameUniqueInShop(tagName, shopId, null); - - TagDO tagDO = new TagDO(); - tagDO.setTagName(tagName); - tagDO.setTextColor(tagDTO.getTextColor()); - tagDO.setBgColor(tagDTO.getBgColor()); - tagDO.setBorderColor(tagDTO.getBorderColor()); - tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); - tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); - tagDO.setSortOrder(tagDTO.getSortOrder()); - tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); - tagDO.setShopId(shopId); - tagDO.setIsDelete(0); - try { - tagMapper.insert(tagDO); - } catch (DuplicateKeyException exception) { - /** - * Run business method `buildDuplicateTagException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return throw result consumed by the caller or returned to the frontend - */ - throw buildDuplicateTagException(tagName, shopId, null); - } - evictTagCaches(tagDO.getId(), shopId); - return tagDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param tagDTO parameter `tagDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateTag(Long id, TagDTO tagDTO) { - TagDO tagDO = tagMapper.selectById(id); - if (tagDO == null) { - return false; - } - String tagName = normalizeTagName(tagDTO.getTagName()); - Long shopId = requireShopId(tagDTO.getShopId()); - /** - * Run business method `ensureTagNameUniqueInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureTagNameUniqueInShop(tagName, shopId, id); - - tagDO.setTagName(tagName); - tagDO.setTextColor(tagDTO.getTextColor()); - tagDO.setBgColor(tagDTO.getBgColor()); - tagDO.setBorderColor(tagDTO.getBorderColor()); - tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); - tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); - tagDO.setSortOrder(tagDTO.getSortOrder()); - tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); - tagDO.setShopId(shopId); - try { - boolean updated = tagMapper.updateById(tagDO) > 0; - if (updated) { - /** - * Run business method `evictTagCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictTagCaches(id, shopId); - } - return updated; - } catch (DuplicateKeyException exception) { - /** - * Run business method `buildDuplicateTagException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return throw result consumed by the caller or returned to the frontend - */ - throw buildDuplicateTagException(tagName, shopId, id); - } - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteTag(Long id) { - TagDO tagDO = tagMapper.selectById(id); - if (tagDO == null) { - return false; - } - tagDO.setIsDelete(1); - boolean deleted = tagMapper.updateById(tagDO) > 0; - if (deleted) { - evictTagCaches(id, tagDO.getShopId()); - } - return deleted; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return TagVO result consumed by the caller or returned to the frontend - */ - public TagVO getTagById(Long id) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); - return multiLevelCacheService.getOrLoad( - TAG_DETAIL_CACHE_PREFIX + id, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference() { - }, - () -> { - TagDO tagDO = tagMapper.selectById(id); - if (tagDO == null || Integer.valueOf(1).equals(tagDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagDO parameter `tagDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(tagDO); - } - ); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllTags() { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); - return multiLevelCacheService.getOrLoad( - TAG_LIST_CACHE_PREFIX + "all", - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .orderByDesc(TagDO::getCreateTime) - ).stream() - .map(this::convertToVO) - .collect(Collectors.toList()) - ); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listTagsByShopId(Long shopId) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); - return multiLevelCacheService.getOrLoad( - TAG_LIST_CACHE_PREFIX + "shop:" + shopId, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(TagDO::getShopId, shopId) - .orderByDesc(TagDO::getCreateTime) - ).stream() - .map(this::convertToVO) - .collect(Collectors.toList()) - ); - } - - @Override - /** - * Purpose: listFilterOptions builds public scene-filter groups for customer browsing. - * Usage: call it from Web or mini-program product pages; pass shopId to limit groups to one shop. - */ - public List listFilterOptions(Long shopId) { - Long scopedShopId = shopId != null && shopId > 0 ? shopId : null; - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); - return multiLevelCacheService.getOrLoad( - TAG_LIST_CACHE_PREFIX + "filter:" + (scopedShopId == null ? "all" : scopedShopId), - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> buildFilterOptions(scopedShopId) - ); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @return TagVO result consumed by the caller or returned to the frontend - */ - public TagVO getTagByTagName(String tagName) { - TagDO tagDO = tagMapper.selectOne( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(TagDO::getTagName, tagName) - ); - if (tagDO == null) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagDO parameter `tagDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(tagDO); - } - - /** - * 将 DO 转换为 VO - * - * @param tagDO 标签DO - * @return 标签VO - */ - private TagVO convertToVO(TagDO tagDO) { - TagVO tagVO = new TagVO(); - tagVO.setId(tagDO.getId()); - tagVO.setTagName(tagDO.getTagName()); - tagVO.setTextColor(tagDO.getTextColor()); - tagVO.setBgColor(tagDO.getBgColor()); - tagVO.setBorderColor(tagDO.getBorderColor()); - tagVO.setSceneGroup(resolveSceneGroup(tagDO.getSceneGroup())); - tagVO.setDisplayName(resolveDisplayName(tagDO)); - tagVO.setSortOrder(tagDO.getSortOrder()); - tagVO.setFrontVisible(normalizeFrontVisible(tagDO.getFrontVisible())); - tagVO.setShopId(tagDO.getShopId()); - tagVO.setShopName(resolveShopName(tagDO.getShopId())); - tagVO.setCreateTime(tagDO.getCreateTime()); - tagVO.setUpdateTime(tagDO.getUpdateTime()); - return tagVO; - } - - /** - * Run business method `normalizeTagName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeTagName(String tagName) { - if (!StringUtils.hasText(tagName)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("标签名称不能为空"); - } - return tagName.trim(); - } - - /** - * Purpose: buildFilterOptions groups visible tags while preserving legacy tags in a default group. - * Usage: call it only through the cache-backed public listFilterOptions method. - */ - private List buildFilterOptions(Long shopId) { - List tags = tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(shopId != null, TagDO::getShopId, shopId) - ); - Map> groupedTags = new LinkedHashMap<>(); - tags.stream() - .filter(tagDO -> !Integer.valueOf(0).equals(tagDO.getFrontVisible())) - .sorted(Comparator - .comparing((TagDO tagDO) -> resolveSceneGroup(tagDO.getSceneGroup()).equals(DEFAULT_FILTER_GROUP) ? 1 : 0) - .thenComparing(tagDO -> resolveSceneGroup(tagDO.getSceneGroup())) - .thenComparing(tagDO -> tagDO.getSortOrder() == null ? Integer.MAX_VALUE : tagDO.getSortOrder()) - .thenComparing(TagDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())) - .thenComparing(TagDO::getId, Comparator.nullsLast(Long::compareTo))) - .forEach(tagDO -> groupedTags - .computeIfAbsent(resolveSceneGroup(tagDO.getSceneGroup()), ignored -> new ArrayList<>()) - .add(convertToVO(tagDO))); - return groupedTags.entrySet().stream() - .map(entry -> { - TagFilterGroupVO groupVO = new TagFilterGroupVO(); - groupVO.setGroupName(entry.getKey()); - groupVO.setTags(entry.getValue()); - return groupVO; - }) - .collect(Collectors.toList()); - } - - /** - * Purpose: normalizeOptionalText trims optional tag metadata. - * Usage: call before persisting sceneGroup or displayName so blank strings become null. - */ - private String normalizeOptionalText(String value) { - return StringUtils.hasText(value) ? value.trim() : null; - } - - /** - * Purpose: resolveSceneGroup keeps legacy tags usable in scene filters. - * Usage: call when serializing or grouping tags for public clients. - */ - private String resolveSceneGroup(String sceneGroup) { - return StringUtils.hasText(sceneGroup) ? sceneGroup.trim() : DEFAULT_FILTER_GROUP; - } - - /** - * Purpose: resolveDisplayName decides the public label for one tag. - * Usage: call when building TagVO so clients can render displayName directly. - */ - private String resolveDisplayName(TagDO tagDO) { - if (tagDO == null) { - return null; - } - return StringUtils.hasText(tagDO.getDisplayName()) ? tagDO.getDisplayName().trim() : tagDO.getTagName(); - } - - /** - * Purpose: normalizeFrontVisible defaults old rows to visible. - * Usage: call when saving and serializing the public visibility flag. - */ - private Integer normalizeFrontVisible(Integer frontVisible) { - return frontVisible == null ? 1 : frontVisible; - } - - /** - * Run business method `requireShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long requireShopId(Long shopId) { - if (shopId == null || shopId <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择所属店铺"); - } - return shopId; - } - - /** - * Run business method `ensureTagNameUniqueInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param excludeId parameter `excludeId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensureTagNameUniqueInShop(String tagName, Long shopId, Long excludeId) { - if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前店铺已存在同名标签"); - } - } - - /** - * Run business method `findActiveTagByNameAndShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param excludeId parameter `excludeId` supplied by the caller - * @return private TagDO result consumed by the caller or returned to the frontend - */ - private TagDO findActiveTagByNameAndShopId(String tagName, Long shopId, Long excludeId) { - return tagMapper.selectOne( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(TagDO::getShopId, shopId) - .eq(TagDO::getTagName, tagName) - .ne(excludeId != null, TagDO::getId, excludeId) - .last("LIMIT 1") - ); - } - - /** - * Run business method `buildDuplicateTagException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagName parameter `tagName` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param excludeId parameter `excludeId` supplied by the caller - * @return private RuntimeException result consumed by the caller or returned to the frontend - */ - private RuntimeException buildDuplicateTagException(String tagName, Long shopId, Long excludeId) { - if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return return new result consumed by the caller or returned to the frontend - */ - return new RuntimeException("当前店铺已存在同名标签"); - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return return new result consumed by the caller or returned to the frontend - */ - return new RuntimeException("数据库仍使用旧的标签全局唯一约束,请先执行本次提供的 SQL 补丁"); - } - - /** - * Run business method `resolveShopName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveShopName(Long shopId) { - if (shopId == null || shopId <= 0) { - return null; - } - ShopDO shopDO = shopMapper.selectById(shopId); - return shopDO == null ? null : shopDO.getShopName(); - } - - /** - * Run business method `evictTagCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param tagId parameter `tagId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void evictTagCaches(Long tagId, Long shopId) { - if (tagId != null) { - multiLevelCacheService.evict(TAG_DETAIL_CACHE_PREFIX + tagId); - } - if (shopId != null) { - multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "shop:" + shopId); - multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:" + shopId); - } - multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "all"); - multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:all"); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/EffectDiagramVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/EffectDiagramVO.java deleted file mode 100644 index 5061ecd0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/EffectDiagramVO.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -/** - * 商品效果图信息表 VO - * 用于前端展示效果图信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class EffectDiagramVO { - - /** - * 效果图唯一主键ID(雪花id) - */ - private Long id; - - /** - * 所属商品ID,关联商品表主键 - */ - private Long productId; - - /** - * 商品标题 - */ - private String productTitle; - - /** - * 效果图类别 - */ - private String category; - - /** - * 图片文件ID集合,多ID以逗号分隔 - */ - private String imageFileIds; - - /** - * 图片URL列表 - */ - private List imageUrls; - - /** - * 效果图描述 - */ - private String description; - - /** - * 效果图对应服务价格 - */ - private BigDecimal price; - - /** - * 效果图对应服务耗时 - */ - private String duration; - - /** - * 效果图标签 - */ - private String tag; - - /** - * 效果图点赞数 - */ - private Integer likeCount; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/HotProductVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/HotProductVO.java deleted file mode 100644 index fe7baa7e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/HotProductVO.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.vo; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -/** - * HotProductVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class HotProductVO { - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String title; - /** - * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal price; - /** - * Field `likeCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer likeCount; - /** - * Field `collectCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer collectCount; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/ProductVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/ProductVO.java deleted file mode 100644 index 8c45bb33..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/ProductVO.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.List; - -/** - * 商品信息表 VO - * 用于前端展示商品信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class ProductVO { - - /** - * 商品唯一主键ID(雪花id) - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long id; - - /** - * 所属店铺ID,关联店铺表主键 - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long shopId; - - /** - * 店铺名称 - */ - private String shopName; - - /** - * 商品标题 - */ - private String title; - - /** - * 商品描述 - */ - private String description; - - /** - * 适合人群说明;作品详情接口返回后由 Web/小程序在有值时展示。 - */ - private String targetAudience; - - /** - * 注意事项说明;作品详情接口返回后由 Web/小程序在有值时展示。 - */ - private String precautions; - - /** - * 图片文件ID集合,多个ID以逗号分隔 - */ - private String imageFileIds; - - /** - * 图片URL列表 - */ - private List imageUrls; - - /** - * 商品价格,保留2位小数 - */ - private BigDecimal price; - - /** - * 标签集合,多个标签以逗号分隔,最多5个 - */ - private String tags; - - /** - * 标签列表 - */ - private List tagList; - - /** - * 标签详情列表(包含样式信息) - */ - private List tagInfos; - - /** - * 商品点赞数 - */ - private Integer likeCount; - - /** - * 商品收藏数 - */ - private Integer collectCount; - - /** - * 商品对应的服务大约耗时(如"30分钟") - */ - private String approximateDuration; - - /** - * 实际用于预约排期计算的服务时长(分钟) - */ - private Long serviceDurationMinutes; - - /** - * 可预约的美甲师ID集合,多个ID以逗号分隔 - */ - private String bookableArtists; - - /** - * 当前仍可预约的美甲师数量 - */ - private Integer availableBookableArtistCount; - - /** - * 商品是否配置了限定美甲师 - */ - private Boolean bookableArtistRestricted; - - /** - * 可用的优惠券ID集合,多个ID以逗号分隔 - */ - private String availableCoupons; - - /** - * 前台是否展示:0-隐藏,1-展示 - */ - private Integer frontVisible; - - /** - * 来源类型 - */ - private String sourceType; - - /** - * 商品创建时间 - */ - private LocalDateTime createTime; - - /** - * 商品信息最后更新时间 - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagFilterGroupVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagFilterGroupVO.java deleted file mode 100644 index b829072c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagFilterGroupVO.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.vo; - -import lombok.Data; - -import java.util.ArrayList; -import java.util.List; - -/** - * Purpose: TagFilterGroupVO groups public tags for customer scene filters. - * Usage: return it from `/tag/list/filter-options` and render each group as one filter row. - */ -@Data -public class TagFilterGroupVO { - - /** - * Purpose: groupName is the customer-facing group title. - * Usage: display it above the group's tag chips. - */ - private String groupName; - - /** - * Purpose: tags holds visible tags in the current filter group. - * Usage: use each tag id for product filtering and displayName/tagName for chip text. - */ - private List tags = new ArrayList<>(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagInfo.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagInfo.java deleted file mode 100644 index 78b2f96c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagInfo.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.vo; - -import lombok.Data; - -/** - * 标签信息 VO - * 用于前端展示标签,包含样式信息 - * - * @author xiaowang - * @date 2026-02-14 - */ -@Data -public class TagInfo { - - /** - * 标签ID - */ - private Long id; - - /** - * 标签名称 - */ - private String tagName; - - /** - * 标签文字颜色(16进制) - */ - private String textColor; - - /** - * 标签背景颜色(16进制) - */ - private String bgColor; - - /** - * 标签边框颜色(16进制) - */ - private String borderColor; - - public TagInfo() { - } - - public TagInfo(Long id, String tagName, String textColor, String bgColor, String borderColor) { - this.id = id; - this.tagName = tagName; - this.textColor = textColor; - this.bgColor = bgColor; - this.borderColor = borderColor; - } -} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagVO.java deleted file mode 100644 index 49c6997f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/product/vo/TagVO.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.product.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 系统标签信息表 VO - * 用于前端展示标签信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class TagVO { - - /** - * 标签唯一主键ID - */ - private Long id; - - /** - * 标签名称 - */ - private String tagName; - - /** - * 标签文字颜色(16进制) - */ - private String textColor; - - /** - * 标签背景颜色(16进制) - */ - private String bgColor; - - /** - * 标签边框颜色(16进制) - */ - private String borderColor; - - /** - * Purpose: sceneGroup tells clients which public filter group this tag belongs to. - * Usage: read it from tag list APIs and group filter chips by this value. - */ - private String sceneGroup; - - /** - * Purpose: displayName is the public-facing tag label. - * Usage: show this value in filters; fall back to tagName if it is empty. - */ - private String displayName; - - /** - * Purpose: sortOrder controls the public order inside a group. - * Usage: sort lower values before higher values when rendering grouped filters. - */ - private Integer sortOrder; - - /** - * Purpose: frontVisible indicates whether the tag should appear in public filters. - * Usage: public filter APIs only return visible tags; admin screens may still display it. - */ - private Integer frontVisible; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; - - /** - * 店铺ID - */ - private Long shopId; - - /** - * 店铺名称 - */ - private String shopName; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/controller/front/PermissionController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/controller/front/PermissionController.java deleted file mode 100644 index 90a14f42..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/controller/front/PermissionController.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.PermissionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.UserPermissionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.PermissionService; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.PermissionVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * 系统权限表 Controller - * 对应数据库表 t_permission - * - * @author xiaowang - * @date 2026-02-25 - */ -@RestController -@RequestMapping({"/permission", "/api/permission"}) -@RequiredArgsConstructor -public class PermissionController { - /** - * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final PermissionService permissionService; - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - /** - * 创建权限 - * - * @param permissionDTO 权限DTO - * @return 权限ID - */ - @PostMapping("/create") - @RequirePermission("permission:create") - public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); - Long id = permissionService.createPermission(permissionDTO); - return Result.success(id); - } - - /** - * 更新权限 - * - * @param id 权限ID - * @param permissionDTO 权限DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - @RequirePermission("permission:edit") - public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); - boolean success = permissionService.updatePermission(id, permissionDTO); - return Result.success(success); - } - - /** - * 删除权限 - * - * @param id 权限ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("permission:delete") - public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); - boolean success = permissionService.deletePermission(id); - return Result.success(success); - } - - /** - * 根据ID查询权限 - * - * @param id 权限ID - * @return 权限VO - */ - @GetMapping("/get/{id}") - @RequirePermission("permission:view") - public Result getPermissionById(@PathVariable Long id) { - PermissionVO permissionVO = permissionService.getPermissionById(id); - return Result.success(permissionVO); - } - - /** - * 查询所有权限 - * - * @return 权限VO列表 - */ - @GetMapping("/list/all") - @RequirePermission("permission:view") - public Result> listAllPermissions() { - List permissionVOs = permissionService.listAllPermissions(); - return Result.success(permissionVOs); - } - - /** - * 根据权限分组查询权限 - * - * @param permissionGroup 权限分组 - * @return 权限VO列表 - */ - @GetMapping("/list/group/{permissionGroup}") - @RequirePermission("permission:view") - public Result> listPermissionsByGroup(@PathVariable String permissionGroup) { - List permissionVOs = permissionService.listPermissionsByGroup(permissionGroup); - return Result.success(permissionVOs); - } - - /** - * 查询用户的权限列表 - * - * @param userId 用户ID - * @return 权限VO列表 - */ - @GetMapping("/list/user/{userId}") - @RequirePermission("permission:view") - public Result> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - if (!adminScopeHelper.isPlatformAdmin(currentUser)) { - UserDO targetUser = userService.getById(userId); - if (targetUser == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标用户不存在"); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); - } - List permissionVOs = permissionService.listUserPermissions(userId); - return Result.success(permissionVOs); - } - - /** - * 分配权限给用户 - * - * @param userPermissionDTO 用户权限分配DTO - * @return 是否分配成功 - */ - @PostMapping("/assign") - @RequirePermission("permission:assign") - public Result assignPermissions(HttpServletRequest request, @RequestBody UserPermissionDTO userPermissionDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - if (!adminScopeHelper.isPlatformAdmin(currentUser)) { - UserDO targetUser = userService.getById(userPermissionDTO.getUserId()); - if (targetUser == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标用户不存在"); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "无权给其他店铺用户分配权限"); - } - Long userId = (Long) request.getAttribute("userId"); - boolean success = permissionService.assignPermissions(userPermissionDTO, userId); - return Result.success(success); - } - - /** - * 获取当前登录用户的权限列表 - * - * @return 权限列表 - */ - @GetMapping("/list/user/current") - public Result> getCurrentUserPermissions(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - List permissions = permissionService.listUserPermissions(userId); - return Result.success(permissions); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/PermissionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/PermissionDTO.java deleted file mode 100644 index 7e1a089c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/PermissionDTO.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.dto; - -import lombok.Data; - -/** - * 系统权限表 DTO - * 用于权限信息的传输 - * - * @author xiaowang - * @date 2026-02-25 - */ -@Data -public class PermissionDTO { - - /** - * 权限编码(唯一标识) - */ - private String permissionCode; - - /** - * 权限名称 - */ - private String permissionName; - - /** - * 权限分组(商品管理、用户管理等) - */ - private String permissionGroup; - - /** - * 权限描述 - */ - private String description; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/ShopRoleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/ShopRoleDTO.java deleted file mode 100644 index a1acc653..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/ShopRoleDTO.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import java.util.List; - -@Data -/** - * ShopRoleDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ShopRoleDTO { - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @NotBlank(message = "角色名不能为空") - /** - * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String roleName; - - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - /** - * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List permissionIds; - /** - * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List userIds; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/UserPermissionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/UserPermissionDTO.java deleted file mode 100644 index 77039d98..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/dto/UserPermissionDTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.dto; - -import lombok.Data; - -import java.util.List; - -/** - * 用户权限分配 DTO - * 用于给用户分配权限 - * - * @author xiaowang - * @date 2026-02-25 - */ -@Data -public class UserPermissionDTO { - - /** - * 用户ID - */ - private Long userId; - - /** - * 权限ID列表 - */ - private List permissionIds; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/PermissionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/PermissionDO.java deleted file mode 100644 index c76e1d62..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/PermissionDO.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 系统权限表 DO - * 对应数据库表 t_permission - * - * @author xiaowang - * @date 2026-02-25 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_permission") -public class PermissionDO extends BaseEntity { - - /** - * 权限编码(唯一标识) - */ - @TableField("permission_code") - private String permissionCode; - - /** - * 权限名称 - */ - @TableField("permission_name") - private String permissionName; - - /** - * 权限分组(商品管理、用户管理等) - */ - @TableField("permission_group") - private String permissionGroup; - - /** - * 权限描述 - */ - @TableField("description") - private String description; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/SecurityAuditLogDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/SecurityAuditLogDO.java deleted file mode 100644 index d98104eb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/SecurityAuditLogDO.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; - -@Getter -@Setter -@TableName("t_security_audit_log") -/** - * Purpose: SecurityAuditLogDO supports SecurityAuditLogDO.java by holding or executing the security audit log do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SecurityAuditLogDO extends BaseEntity { - - @TableField("user_id") - /** - * Purpose: userId supports SecurityAuditLogDO.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - - @TableField("account") - /** - * Purpose: account supports SecurityAuditLogDO.java by holding or executing the account business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String account; - - @TableField("action") - /** - * Purpose: action supports SecurityAuditLogDO.java by holding or executing the action business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String action; - - @TableField("result") - /** - * Purpose: result supports SecurityAuditLogDO.java by holding or executing the result business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String result; - - @TableField("reason") - /** - * Purpose: reason supports SecurityAuditLogDO.java by holding or executing the reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String reason; - - @TableField("ip_address") - /** - * Purpose: ipAddress supports SecurityAuditLogDO.java by holding or executing the ip address business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String ipAddress; - - @TableField("device_id") - /** - * Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - - @TableField("operate_time") - /** - * Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime operateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/ShopRoleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/ShopRoleDO.java deleted file mode 100644 index b22c415c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/ShopRoleDO.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_shop_role") -/** - * ShopRoleDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ShopRoleDO extends BaseEntity { - - @TableField("shop_id") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @TableField("role_name") - /** - * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String roleName; - - @TableField("creator_id") - /** - * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long creatorId; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - @TableField("remark") - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - - @TableField("sort_order") - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/ShopRolePermissionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/ShopRolePermissionDO.java deleted file mode 100644 index 231be986..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/ShopRolePermissionDO.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_shop_role_permission") -/** - * ShopRolePermissionDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ShopRolePermissionDO extends BaseEntity { - - @TableField("role_id") - /** - * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long roleId; - - @TableField("permission_id") - /** - * Field `permissionId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long permissionId; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/UserPermissionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/UserPermissionDO.java deleted file mode 100644 index 0b6ac697..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/UserPermissionDO.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 用户权限关联表 DO - * 对应数据库表 t_user_permission - * - * @author xiaowang - * @date 2026-02-25 - */ -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_user_permission") -public class UserPermissionDO extends BaseEntity { - - /** - * 用户ID - */ - @TableField("user_id") - private Long userId; - - /** - * 权限ID - */ - @TableField("permission_id") - private Long permissionId; - - /** - * 创建人ID - */ - @TableField("create_by") - private Long createBy; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/UserShopRoleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/UserShopRoleDO.java deleted file mode 100644 index 38caa345..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/entity/UserShopRoleDO.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_user_shop_role") -/** - * UserShopRoleDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserShopRoleDO extends BaseEntity { - - @TableField("user_id") - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - @TableField("shop_id") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @TableField("role_id") - /** - * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long roleId; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/PermissionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/PermissionMapper.java deleted file mode 100644 index 44c40d60..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/PermissionMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO; -import org.apache.ibatis.annotations.Mapper; - -/** - * 系统权限表 Mapper - * 对应数据库表 t_permission - * - * @author xiaowang - * @date 2026-02-25 - */ -@Mapper -public interface PermissionMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/SecurityAuditLogMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/SecurityAuditLogMapper.java deleted file mode 100644 index 5e90d0ed..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/SecurityAuditLogMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.SecurityAuditLogDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * Purpose: SecurityAuditLogMapper supports SecurityAuditLogMapper.java by holding or executing the security audit log mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface SecurityAuditLogMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/ShopRoleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/ShopRoleMapper.java deleted file mode 100644 index d2f0aa68..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/ShopRoleMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.ShopRoleDO; - -/** - * ShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface ShopRoleMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/ShopRolePermissionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/ShopRolePermissionMapper.java deleted file mode 100644 index 15677240..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/ShopRolePermissionMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.ShopRolePermissionDO; - -/** - * ShopRolePermissionMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface ShopRolePermissionMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/UserPermissionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/UserPermissionMapper.java deleted file mode 100644 index 4e3308c0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/UserPermissionMapper.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserPermissionDO; -import org.apache.ibatis.annotations.Mapper; - -/** - * 用户权限关联表 Mapper - * 对应数据库表 t_user_permission - * - * @author xiaowang - * @date 2026-02-25 - */ -@Mapper -public interface UserPermissionMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/UserShopRoleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/UserShopRoleMapper.java deleted file mode 100644 index e4406841..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/mapper/UserShopRoleMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserShopRoleDO; - -/** - * UserShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface UserShopRoleMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/PermissionService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/PermissionService.java deleted file mode 100644 index 6055e4fa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/PermissionService.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.PermissionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.UserPermissionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.PermissionVO; - -import java.util.List; - -/** - * 系统权限表 Service - * 对应数据库表 t_permission - * - * @author xiaowang - * @date 2026-02-25 - */ -public interface PermissionService extends IService { - - /** - * 创建权限 - * - * @param permissionDTO 权限DTO - * @return 权限ID - */ - Long createPermission(PermissionDTO permissionDTO); - - /** - * 更新权限 - * - * @param id 权限ID - * @param permissionDTO 权限DTO - * @return 是否更新成功 - */ - boolean updatePermission(Long id, PermissionDTO permissionDTO); - - /** - * 删除权限 - * - * @param id 权限ID - * @return 是否删除成功 - */ - boolean deletePermission(Long id); - - /** - * 根据ID查询权限 - * - * @param id 权限ID - * @return 权限VO - */ - PermissionVO getPermissionById(Long id); - - /** - * 查询所有权限 - * - * @return 权限VO列表 - */ - List listAllPermissions(); - - /** - * 根据权限分组查询权限 - * - * @param permissionGroup 权限分组 - * @return 权限VO列表 - */ - List listPermissionsByGroup(String permissionGroup); - - /** - * 查询用户的权限列表 - * - * @param userId 用户ID - * @return 权限VO列表 - */ - List listUserPermissions(Long userId); - - /** - * 查询当前操作人可给目标用户分配的权限ID列表 - * - * @param targetUserId 目标用户ID - * @param currentUserId 当前操作人ID - * @return 可分配的权限ID列表 - */ - List listAssignablePermissionIds(Long targetUserId, Long currentUserId); - - /** - * 给用户分配权限 - * - * @param userPermissionDTO 用户权限分配DTO - * @param currentUserId 当前操作人ID - * @return 是否分配成功 - */ - boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId); - - /** - * 检查用户是否拥有指定权限 - * - * @param userId 用户ID - * @param permissionCode 权限编码 - * @return 是否拥有权限 - */ - boolean hasPermission(Long userId, String permissionCode); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/SecurityAuditLogService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/SecurityAuditLogService.java deleted file mode 100644 index a4055ef0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/SecurityAuditLogService.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.service; - -import javax.servlet.http.HttpServletRequest; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.SecurityAuditLogVO; - -/** - * Purpose: SecurityAuditLogService supports SecurityAuditLogService.java by holding or executing the security audit log service business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface SecurityAuditLogService { - - void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request); - - PageResultVO pageLogs(String account, - String action, - String result, - LocalDateTime startTime, - LocalDateTime endTime, - Integer page, - Integer size); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/ShopRoleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/ShopRoleService.java deleted file mode 100644 index 153d8a1e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/ShopRoleService.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.InviteCodeDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.ShopRoleDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.UserRelationUpdateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.ShopRoleDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.InviteCodeVO; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.ShopRoleVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserRelationVO; - -import java.util.List; - -/** - * ShopRoleService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface ShopRoleService extends IService { - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listRoles(UserDO currentUser, Long shopId); - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long createRole(UserDO currentUser, ShopRoleDTO dto); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto); - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean deleteRole(UserDO currentUser, Long id); - /** - * Run business method `assignPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param permissionIds parameter `permissionIds` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds); - /** - * Run business method `assignUsers`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param userIds parameter `userIds` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean assignUsers(UserDO currentUser, Long id, List userIds); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listRelationOptions(UserDO currentUser, Long shopId); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto); - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listInviteCodes(UserDO currentUser, Long shopId); - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long createInviteCode(UserDO currentUser, InviteCodeDTO dto); - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status); - /** - * Run business method `resolveInviteCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param code parameter `code` supplied by the caller - * @return InviteCodeVO result consumed by the caller or returned to the frontend - */ - InviteCodeVO resolveInviteCode(String code); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/PermissionServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/PermissionServiceImpl.java deleted file mode 100644 index 52e2403f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/PermissionServiceImpl.java +++ /dev/null @@ -1,688 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.PermissionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.UserPermissionDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserPermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.ShopRolePermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserShopRoleDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.PermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.UserPermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.ShopRolePermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.UserShopRoleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.PermissionService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionCatalog; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionPolicy; -import com.xiaowang.jacyucloudsalon.core.support.RequestShopContext; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.PermissionVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDateTime; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * PermissionServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class PermissionServiceImpl extends ServiceImpl implements PermissionService { - - private static final Set SHOP_BOOTSTRAP_PERMISSION_CODES = Set.of( - "shop:view", - "shop:create" - ); - /** - * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final PermissionMapper permissionMapper; - /** - * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserPermissionMapper userPermissionMapper; - /** - * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopRolePermissionMapper shopRolePermissionMapper; - /** - * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopRoleMapper userShopRoleMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - - @Override - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param permissionDTO parameter `permissionDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createPermission(PermissionDTO permissionDTO) { - PermissionDO permissionDO = new PermissionDO(); - permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); - permissionDO.setPermissionName(permissionDTO.getPermissionName()); - permissionDO.setPermissionGroup(permissionDTO.getPermissionGroup()); - permissionDO.setDescription(permissionDTO.getDescription()); - permissionDO.setIsDelete(0); - permissionMapper.insert(permissionDO); - return permissionDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param permissionDTO parameter `permissionDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updatePermission(Long id, PermissionDTO permissionDTO) { - PermissionDO permissionDO = permissionMapper.selectById(id); - if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { - return false; - } - if (permissionDTO.getPermissionCode() != null) { - permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); - } - if (permissionDTO.getPermissionName() != null) { - permissionDO.setPermissionName(permissionDTO.getPermissionName()); - } - if (permissionDTO.getPermissionGroup() != null) { - permissionDO.setPermissionGroup(permissionDTO.getPermissionGroup()); - } - if (permissionDTO.getDescription() != null) { - permissionDO.setDescription(permissionDTO.getDescription()); - } - permissionDO.setUpdateTime(LocalDateTime.now()); - return permissionMapper.updateById(permissionDO) > 0; - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deletePermission(Long id) { - PermissionDO permissionDO = permissionMapper.selectById(id); - if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { - return false; - } - permissionDO.setIsDelete(1); - permissionDO.setUpdateTime(LocalDateTime.now()); - return permissionMapper.updateById(permissionDO) > 0; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return PermissionVO result consumed by the caller or returned to the frontend - */ - public PermissionVO getPermissionById(Long id) { - PermissionDO permissionDO = permissionMapper.selectById(id); - if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param permissionDO parameter `permissionDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(permissionDO); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllPermissions() { - return permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getIsDelete, 0) - ).stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param permissionGroup parameter `permissionGroup` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listPermissionsByGroup(String permissionGroup) { - return permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getPermissionGroup, permissionGroup) - .eq(PermissionDO::getIsDelete, 0) - ).stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listUserPermissions(Long userId) { - UserDO userDO = userMapper.selectById(userId); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return List.of(); - } - if (isShopBootstrapAdmin(userDO)) { - return listAllPermissions().stream() - .filter(permission -> PermissionCatalog.isAllowedForPlatformOverview(permission.getPermissionCode())) - .collect(Collectors.toList()); - } - - List activeShopRoles = listActiveShopRoles(userId); - if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { - return listPermissionsByIds(listPermissionIdsByShopRoles(activeShopRoles)).stream() - .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) - .collect(Collectors.toList()); - } - - List userPermissions = userPermissionMapper.selectList( - Wrappers.lambdaQuery(UserPermissionDO.class) - .eq(UserPermissionDO::getUserId, userId) - ); - if (userPermissions.isEmpty()) { - return List.of(); - } - - List permissionIds = userPermissions.stream() - .map(UserPermissionDO::getPermissionId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - if (permissionIds.isEmpty()) { - return List.of(); - } - - List permissionVOs = permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .in(PermissionDO::getId, permissionIds) - .eq(PermissionDO::getIsDelete, 0) - ).stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - - return permissionVOs.stream() - .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetUserId parameter `targetUserId` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listAssignablePermissionIds(Long targetUserId, Long currentUserId) { - UserDO currentUser = userMapper.selectById(currentUserId); - if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前用户不存在"); - } - - UserDO targetUser = userMapper.selectById(targetUserId); - if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标用户不存在"); - } - - if (!hasPermission(currentUserId, "permission:assign")) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("权限不足,无法分配权限"); - } - - boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); - Long currentShopId = RequestShopContext.getCurrentShopId(); - if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前角色不能维护该用户的权限"); - } - - if (!platformAdmin) { - if (currentUserId.equals(targetUserId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("不允许给自己调整权限"); - } - if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(targetUserId, currentShopId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只能给本店铺用户分配权限"); - } - } - - Set baseAllowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); - Set operatorPermissionCodes = platformAdmin - ? Collections.emptySet() - : listPermissionCodesByUserId(currentUserId); - Set assignablePermissionCodes = platformAdmin - ? baseAllowedPermissionCodes - : baseAllowedPermissionCodes.stream() - .filter(operatorPermissionCodes::contains) - .collect(Collectors.toSet()); - - return permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getIsDelete, 0) - ).stream() - .filter(permission -> assignablePermissionCodes.contains(permission.getPermissionCode())) - .map(PermissionDO::getId) - .collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `assignPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userPermissionDTO parameter `userPermissionDTO` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId) { - Long userId = userPermissionDTO.getUserId(); - List permissionIds = userPermissionDTO.getPermissionIds() == null - ? Collections.emptyList() - : userPermissionDTO.getPermissionIds().stream() - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - - UserDO currentUser = userMapper.selectById(currentUserId); - if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前用户不存在"); - } - - UserDO targetUser = userMapper.selectById(userId); - if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标用户不存在"); - } - - if (!hasPermission(currentUserId, "permission:assign")) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("权限不足,无法分配权限"); - } - - boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); - Long currentShopId = RequestShopContext.getCurrentShopId(); - if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前角色不能维护该用户的权限"); - } - - if (!platformAdmin) { - if (currentUserId.equals(userId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("不允许给自己调整权限"); - } - if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(userId, currentShopId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("只能给本店铺用户分配权限"); - } - } - - Set requestedPermissionCodes = resolvePermissionCodes(permissionIds); - Set allowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); - if (!allowedPermissionCodes.containsAll(requestedPermissionCodes)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标角色的权限配置超出允许范围"); - } - - if (!platformAdmin) { - Set operatorPermissionCodes = listPermissionCodesByUserId(currentUserId); - if (!operatorPermissionCodes.containsAll(requestedPermissionCodes)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("不能分配超出自己已有的权限"); - } - } - - userPermissionMapper.delete( - Wrappers.lambdaQuery(UserPermissionDO.class) - .eq(UserPermissionDO::getUserId, userId) - ); - - for (Long permissionId : permissionIds) { - UserPermissionDO userPermissionDO = new UserPermissionDO(); - userPermissionDO.setUserId(userId); - userPermissionDO.setPermissionId(permissionId); - userPermissionDO.setCreateBy(currentUserId); - userPermissionMapper.insert(userPermissionDO); - } - - return true; - } - - @Override - /** - * Run business method `hasPermission`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param permissionCode parameter `permissionCode` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean hasPermission(Long userId, String permissionCode) { - UserDO userDO = userMapper.selectById(userId); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return false; - } - if (isShopBootstrapAdmin(userDO)) { - return PermissionCatalog.isAllowedForPlatformOverview(permissionCode); - } - if (!isPermissionAllowedForUserType(userDO, permissionCode)) { - return false; - } - - List activeShopRoles = listActiveShopRoles(userId); - if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { - return hasShopRolePermission(activeShopRoles, permissionCode); - } - - List userPermissions = userPermissionMapper.selectList( - Wrappers.lambdaQuery(UserPermissionDO.class) - .eq(UserPermissionDO::getUserId, userId) - ); - if (userPermissions.isEmpty()) { - return false; - } - - List permissionIds = userPermissions.stream() - .map(UserPermissionDO::getPermissionId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - if (permissionIds.isEmpty()) { - return false; - } - - PermissionDO permissionDO = permissionMapper.selectOne( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getPermissionCode, permissionCode) - .eq(PermissionDO::getIsDelete, 0) - ); - if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) { - return false; - } - - return true; - } - - /** - * Purpose: hasShopRolePermission supports PermissionServiceImpl.java by holding or executing the has shop role permission business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean hasShopRolePermission(List activeShopRoles, String permissionCode) { - List permissionIds = listPermissionIdsByShopRoles(activeShopRoles); - if (permissionIds.isEmpty()) { - return false; - } - PermissionDO permissionDO = permissionMapper.selectOne( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getPermissionCode, permissionCode) - .eq(PermissionDO::getIsDelete, 0) - .last("limit 1")); - return permissionDO != null && permissionIds.contains(permissionDO.getId()); - } - - /** - * Run business method `resolvePermissionCodes`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param permissionIds parameter `permissionIds` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set resolvePermissionCodes(List permissionIds) { - if (permissionIds == null || permissionIds.isEmpty()) { - return Collections.emptySet(); - } - - List permissionDOs = permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .in(PermissionDO::getId, permissionIds) - .eq(PermissionDO::getIsDelete, 0) - ); - if (permissionDOs.size() != permissionIds.size()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("存在无效的权限配置"); - } - - return permissionDOs.stream() - .map(PermissionDO::getPermissionCode) - .collect(Collectors.toSet()); - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set listPermissionCodesByUserId(Long userId) { - return listUserPermissions(userId).stream() - .map(PermissionVO::getPermissionCode) - .collect(Collectors.toSet()); - } - - /** - * Purpose: listActiveShopRoles supports PermissionServiceImpl.java by holding or executing the list active shop roles business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List listActiveShopRoles(Long userId) { - if (userId == null) { - return List.of(); - } - - Long currentShopId = RequestShopContext.getCurrentShopId(); - List activeShopRoles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class) - .eq(UserShopRoleDO::getUserId, userId) - .eq(currentShopId != null, UserShopRoleDO::getShopId, currentShopId) - .eq(UserShopRoleDO::getIsDelete, 0) - .eq(UserShopRoleDO::getStatus, 1)); - if (currentShopId == null) { - return activeShopRoles; - } - return activeShopRoles.stream() - .filter(role -> Objects.equals(currentShopId, role.getShopId())) - .collect(Collectors.toList()); - } - - /** - * Purpose: listPermissionIdsByShopRoles supports PermissionServiceImpl.java by holding or executing the list permission ids by shop roles business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List listPermissionIdsByShopRoles(List activeShopRoles) { - if (activeShopRoles == null || activeShopRoles.isEmpty()) { - return List.of(); - } - - List roleIds = activeShopRoles.stream() - .map(UserShopRoleDO::getRoleId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - if (roleIds.isEmpty()) { - return List.of(); - } - - return shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class) - .in(ShopRolePermissionDO::getRoleId, roleIds) - .eq(ShopRolePermissionDO::getIsDelete, 0)) - .stream() - .filter(permission -> roleIds.contains(permission.getRoleId())) - .map(ShopRolePermissionDO::getPermissionId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - } - - /** - * Purpose: listPermissionsByIds supports PermissionServiceImpl.java by holding or executing the list permissions by ids business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List listPermissionsByIds(List permissionIds) { - if (permissionIds == null || permissionIds.isEmpty()) { - return List.of(); - } - - return permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .in(PermissionDO::getId, permissionIds) - .eq(PermissionDO::getIsDelete, 0) - ).stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * Purpose: usesShopRoleEffectivePermissions supports PermissionServiceImpl.java by holding or executing the uses shop role effective permissions business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean usesShopRoleEffectivePermissions(UserDO userDO, List activeShopRoles) { - return !isPlatformAdmin(userDO) && activeShopRoles != null && !activeShopRoles.isEmpty(); - } - - /** - * Purpose: isPermissionAllowedForUserType supports PermissionServiceImpl.java by holding or executing the is permission allowed for user type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isPermissionAllowedForUserType(UserDO userDO, String permissionCode) { - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return false; - } - if (isPlatformAdmin(userDO)) { - return true; - } - return PermissionPolicy.getDefaultPermissionCodeSet(userDO.getType()).contains(permissionCode); - } - - /** - * Purpose: isPlatformAdmin supports PermissionServiceImpl.java by holding or executing the is platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isPlatformAdmin(UserDO userDO) { - return userDO != null && Integer.valueOf(4).equals(userDO.getType()); - } - - /** - * Run business method `isShopBootstrapAdmin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isShopBootstrapAdmin(UserDO userDO) { - return userDO != null - && Integer.valueOf(4).equals(userDO.getType()) - && RequestShopContext.getCurrentShopId() == null; - } - - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param permissionDO parameter `permissionDO` supplied by the caller - * @return private PermissionVO result consumed by the caller or returned to the frontend - */ - private PermissionVO convertToVO(PermissionDO permissionDO) { - PermissionVO permissionVO = new PermissionVO(); - permissionVO.setId(permissionDO.getId()); - permissionVO.setPermissionCode(permissionDO.getPermissionCode()); - permissionVO.setPermissionName(permissionDO.getPermissionName()); - permissionVO.setPermissionGroup(permissionDO.getPermissionGroup()); - permissionVO.setDescription(permissionDO.getDescription()); - permissionVO.setCreateTime(permissionDO.getCreateTime()); - permissionVO.setUpdateTime(permissionDO.getUpdateTime()); - return permissionVO; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java deleted file mode 100644 index 7b8686d1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.SecurityAuditLogDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.SecurityAuditLogMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.SecurityAuditLogService; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestThrottleService; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.SecurityAuditLogVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import javax.servlet.http.HttpServletRequest; -import java.time.LocalDateTime; - -@Service -@RequiredArgsConstructor -/** - * Purpose: SecurityAuditLogServiceImpl supports SecurityAuditLogServiceImpl.java by holding or executing the security audit log service impl business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { - - /** - * Purpose: auditLogMapper supports SecurityAuditLogServiceImpl.java by holding or executing the audit log mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SecurityAuditLogMapper auditLogMapper; - - @Override - /** - * Purpose: record supports SecurityAuditLogServiceImpl.java by holding or executing the record business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request) { - try { - SecurityAuditLogDO log = new SecurityAuditLogDO(); - log.setUserId(userId); - log.setAccount(limit(account, 80)); - log.setAction(limit(action, 80)); - log.setResult(limit(result, 20)); - log.setReason(limit(reason, 500)); - log.setIpAddress(limit(resolveClientIp(request), 80)); - log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120)); - log.setOperateTime(LocalDateTime.now()); - auditLogMapper.insert(log); - } catch (Exception ignored) { - // Audit failure must never block the main user flow. - } - } - - @Override - public PageResultVO pageLogs(String account, - String action, - String result, - LocalDateTime startTime, - LocalDateTime endTime, - Integer page, - Integer size) { - int pageNo = page == null || page < 1 ? 1 : page; - int pageSize = size == null || size < 1 ? 20 : Math.min(size, 100); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - if (StringUtils.hasText(account)) { - wrapper.like(SecurityAuditLogDO::getAccount, account.trim()); - } - if (StringUtils.hasText(action)) { - wrapper.eq(SecurityAuditLogDO::getAction, action.trim()); - } - if (StringUtils.hasText(result)) { - wrapper.eq(SecurityAuditLogDO::getResult, result.trim()); - } - if (startTime != null) { - wrapper.ge(SecurityAuditLogDO::getOperateTime, startTime); - } - if (endTime != null) { - wrapper.le(SecurityAuditLogDO::getOperateTime, endTime); - } - wrapper.orderByDesc(SecurityAuditLogDO::getOperateTime).orderByDesc(SecurityAuditLogDO::getId); - Page logPage = auditLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper); - - PageResultVO resultVO = new PageResultVO<>(); - resultVO.setList(logPage.getRecords().stream().map(this::toVO).toList()); - resultVO.setTotal(logPage.getTotal()); - resultVO.setPage(pageNo); - resultVO.setSize(pageSize); - return resultVO; - } - - /** - * Purpose: toVO supports SecurityAuditLogServiceImpl.java by holding or executing the to vo business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private SecurityAuditLogVO toVO(SecurityAuditLogDO log) { - SecurityAuditLogVO vo = new SecurityAuditLogVO(); - vo.setId(log.getId()); - vo.setUserId(log.getUserId()); - vo.setAccount(log.getAccount()); - vo.setAction(log.getAction()); - vo.setResult(log.getResult()); - vo.setReason(log.getReason()); - vo.setIpAddress(log.getIpAddress()); - vo.setDeviceId(log.getDeviceId()); - vo.setOperateTime(log.getOperateTime()); - return vo; - } - - /** - * Purpose: resolveClientIp supports SecurityAuditLogServiceImpl.java by holding or executing the resolve client ip business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveClientIp(HttpServletRequest request) { - if (request == null) { - return null; - } - String forwarded = request.getHeader("X-Forwarded-For"); - if (StringUtils.hasText(forwarded)) { - return forwarded.split(",")[0].trim(); - } - String realIp = request.getHeader("X-Real-IP"); - return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); - } - - /** - * Purpose: limit supports SecurityAuditLogServiceImpl.java by holding or executing the limit business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String limit(String value, int max) { - if (value == null || value.length() <= max) { - return value; - } - return value.substring(0, max); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/ShopRoleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/ShopRoleServiceImpl.java deleted file mode 100644 index 713fbfa2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/service/impl/ShopRoleServiceImpl.java +++ /dev/null @@ -1,546 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.InviteCodeDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.dto.ShopRoleDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.UserRelationUpdateDTO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.ShopRoleDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.ShopRolePermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserInviteCodeDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserRelationDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserShopRoleDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.PermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.ShopRoleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.ShopRolePermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserInviteCodeMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserRelationMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.UserShopRoleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.ShopRoleService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.InviteCodeVO; -import com.xiaowang.jacyucloudsalon.core.modules.security.vo.ShopRoleVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserRelationVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.time.LocalDateTime; -import java.util.*; -import java.util.stream.Collectors; - -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; -@Service -@RequiredArgsConstructor -/** - * ShopRoleServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ShopRoleServiceImpl extends ServiceImpl implements ShopRoleService { - /** - * Variable `shopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopRoleMapper shopRoleMapper; - /** - * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopRolePermissionMapper shopRolePermissionMapper; - /** - * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopRoleMapper userShopRoleMapper; - /** - * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserRelationMapper userRelationMapper; - /** - * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserInviteCodeMapper userInviteCodeMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final PermissionMapper permissionMapper; - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingMapper userShopBindingMapper; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listRoles(UserDO currentUser, Long shopId) { - Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - return shopRoleMapper.selectList(new LambdaQueryWrapper() - .eq(ShopRoleDO::getIsDelete, 0) - .eq(scopedShopId != null, ShopRoleDO::getShopId, scopedShopId) - .orderByAsc(ShopRoleDO::getSortOrder) - .orderByDesc(ShopRoleDO::getCreateTime)) - .stream().map(this::toVO).collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createRole(UserDO currentUser, ShopRoleDTO dto) { - Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); - if (shopId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择店铺"); - } - adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权创建其他店铺角色"); - ShopRoleDO role = new ShopRoleDO(); - role.setShopId(shopId); - role.setRoleName(dto.getRoleName().trim()); - role.setCreatorId(currentUser.getId()); - role.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); - role.setRemark(dto.getRemark()); - role.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); - role.setIsDelete(0); - shopRoleMapper.insert(role); - syncPermissions(role.getId(), dto.getPermissionIds()); - syncUsers(role.getId(), dto.getUserIds(), shopId); - return role.getId(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto) { - ShopRoleDO role = requireRole(id); - adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权修改其他店铺角色"); - if (StringUtils.hasText(dto.getRoleName())) { - role.setRoleName(dto.getRoleName().trim()); - } - if (dto.getStatus() != null) { - role.setStatus(dto.getStatus() == 0 ? 0 : 1); - } - if (dto.getRemark() != null) { - role.setRemark(dto.getRemark()); - } - if (dto.getSortOrder() != null) { - role.setSortOrder(dto.getSortOrder()); - } - role.setUpdateTime(LocalDateTime.now()); - shopRoleMapper.updateById(role); - if (dto.getPermissionIds() != null) { - syncPermissions(role.getId(), dto.getPermissionIds()); - } - if (dto.getUserIds() != null) { - syncUsers(role.getId(), dto.getUserIds(), role.getShopId()); - } - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean deleteRole(UserDO currentUser, Long id) { - ShopRoleDO role = requireRole(id); - adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权删除其他店铺角色"); - role.setIsDelete(1); - role.setUpdateTime(LocalDateTime.now()); - shopRoleMapper.updateById(role); - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `assignPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param permissionIds parameter `permissionIds` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds) { - ShopRoleDO role = requireRole(id); - adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权分配其他店铺角色"); - /** - * Run business method `syncPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param permissionIds parameter `permissionIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - syncPermissions(id, permissionIds); - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `assignUsers`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param userIds parameter `userIds` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean assignUsers(UserDO currentUser, Long id, List userIds) { - ShopRoleDO role = requireRole(id); - adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权绑定其他店铺员工"); - syncUsers(id, userIds, role.getShopId()); - return true; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listRelationOptions(UserDO currentUser, Long shopId) { - Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - List users = userMapper.selectList(new LambdaQueryWrapper().eq(UserDO::getIsDelete, 0)); - if (scopedShopId != null) { - Set userIds = userShopBindingMapper.selectList(new LambdaQueryWrapper<>()) - .stream().filter(b -> Objects.equals(scopedShopId, b.getShopId()) && Integer.valueOf(1).equals(b.getStatus())) - .map(b -> b.getUserId()).collect(Collectors.toSet()); - users = users.stream().filter(u -> userIds.contains(u.getId())).collect(Collectors.toList()); - } - return users.stream().map(u -> { - UserRelationVO vo = new UserRelationVO(); - vo.setUserId(u.getId()); - vo.setShopId(scopedShopId); - vo.setParentUserId(null); - vo.setParentUserName(u.getNickname()); - vo.setParentRoleType(u.getType()); - vo.setParentRoleTypeName(typeName(u.getType())); - vo.setSourceType("MANUAL"); - vo.setSourceTypeName("手动维护"); - return vo; - }).collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户不存在"); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权修改所属关系"); - UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() - .eq(UserRelationDO::getUserId, userId) - .eq(UserRelationDO::getIsDelete, 0) - .last("limit 1")); - if (relation == null) { - relation = new UserRelationDO(); - relation.setUserId(userId); - relation.setIsDelete(0); - userRelationMapper.insert(relation); - } - relation.setShopId(dto.getShopId() == null ? user.getShopId() : dto.getShopId()); - relation.setParentUserId(dto.getParentUserId()); - relation.setParentRoleType(dto.getParentRoleType()); - relation.setSourceType(dto.getSourceType()); - relation.setCreatorId(currentUser.getId()); - relation.setUpdateTime(LocalDateTime.now()); - userRelationMapper.updateById(relation); - return true; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listInviteCodes(UserDO currentUser, Long shopId) { - Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - return userInviteCodeMapper.selectList(new LambdaQueryWrapper() - .eq(UserInviteCodeDO::getIsDelete, 0) - .eq(scopedShopId != null, UserInviteCodeDO::getShopId, scopedShopId) - .orderByDesc(UserInviteCodeDO::getCreateTime)) - .stream().map(this::toInviteVO).collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createInviteCode(UserDO currentUser, InviteCodeDTO dto) { - Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); - if (shopId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择店铺"); - } - UserInviteCodeDO code = new UserInviteCodeDO(); - code.setInviteCode(dto.getInviteCode().trim()); - code.setOwnerUserId(dto.getOwnerUserId()); - code.setShopId(shopId); - code.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); - code.setUseCount(dto.getUseCount() == null ? 0 : dto.getUseCount()); - code.setExpireTime(dto.getExpireTime()); - code.setIsDelete(0); - userInviteCodeMapper.insert(code); - return code.getId(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Boolean result consumed by the caller or returned to the frontend - */ - public Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status) { - UserInviteCodeDO code = userInviteCodeMapper.selectById(id); - if (code == null || Integer.valueOf(1).equals(code.getIsDelete())) { - return false; - } - adminScopeHelper.ensureShopAccessible(currentUser, code.getShopId(), "无权修改其他店铺邀请码"); - code.setStatus(status == null || status == 0 ? 0 : 1); - code.setUpdateTime(LocalDateTime.now()); - userInviteCodeMapper.updateById(code); - return true; - } - - @Override - /** - * Run business method `resolveInviteCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param code parameter `code` supplied by the caller - * @return InviteCodeVO result consumed by the caller or returned to the frontend - */ - public InviteCodeVO resolveInviteCode(String code) { - if (!StringUtils.hasText(code)) { - return null; - } - UserInviteCodeDO entity = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() - .eq(UserInviteCodeDO::getInviteCode, code.trim()) - .eq(UserInviteCodeDO::getIsDelete, 0) - .last("limit 1")); - return entity == null ? null : toInviteVO(entity); - } - - /** - * Run business method `syncPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param roleId parameter `roleId` supplied by the caller - * @param permissionIds parameter `permissionIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void syncPermissions(Long roleId, List permissionIds) { - // 保存角色权限时采用“先清空再重建”的方式: - // 表单里传来的 permissionIds 就是最终状态,避免残留上一次勾选的权限。 - shopRolePermissionMapper.delete(new LambdaQueryWrapper().eq(ShopRolePermissionDO::getRoleId, roleId)); - if (permissionIds == null) { - return; - } - for (Long permissionId : permissionIds.stream().filter(Objects::nonNull).distinct().toList()) { - ShopRolePermissionDO item = new ShopRolePermissionDO(); - item.setRoleId(roleId); - item.setPermissionId(permissionId); - item.setIsDelete(0); - shopRolePermissionMapper.insert(item); - } - } - - /** - * Run business method `syncUsers`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param roleId parameter `roleId` supplied by the caller - * @param userIds parameter `userIds` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void syncUsers(Long roleId, List userIds, Long shopId) { - userShopRoleMapper.delete(new LambdaQueryWrapper().eq(UserShopRoleDO::getRoleId, roleId)); - if (userIds == null) { - return; - } - for (Long userId : userIds.stream().filter(Objects::nonNull).distinct().toList()) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { - continue; - } - long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0)); - if (!Objects.equals(shopId, user.getShopId()) && bindingCount <= 0) { - continue; - } - UserShopRoleDO item = new UserShopRoleDO(); - item.setRoleId(roleId); - item.setUserId(userId); - item.setShopId(shopId); - item.setStatus(1); - item.setIsDelete(0); - userShopRoleMapper.insert(item); - } - } - - /** - * Run business method `toVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param role parameter `role` supplied by the caller - * @return private ShopRoleVO result consumed by the caller or returned to the frontend - */ - private ShopRoleVO toVO(ShopRoleDO role) { - ShopRoleVO vo = new ShopRoleVO(); - vo.setId(role.getId()); - vo.setShopId(role.getShopId()); - ShopDO shop = shopMapper.selectById(role.getShopId()); - vo.setShopName(shop == null ? null : shop.getShopName()); - vo.setRoleName(role.getRoleName()); - vo.setCreatorId(role.getCreatorId()); - UserDO creator = role.getCreatorId() == null ? null : userMapper.selectById(role.getCreatorId()); - vo.setCreatorName(creator == null ? null : creator.getNickname()); - vo.setStatus(role.getStatus()); - vo.setRemark(role.getRemark()); - vo.setSortOrder(role.getSortOrder()); - vo.setCreateTime(role.getCreateTime()); - vo.setUpdateTime(role.getUpdateTime()); - List permissions = shopRolePermissionMapper.selectList(new LambdaQueryWrapper() - .eq(ShopRolePermissionDO::getRoleId, role.getId()) - .eq(ShopRolePermissionDO::getIsDelete, 0)); - vo.setPermissionIds(permissions.stream().map(ShopRolePermissionDO::getPermissionId).collect(Collectors.toList())); - Set permissionIds = vo.getPermissionIds().stream().collect(Collectors.toSet()); - if (!permissionIds.isEmpty()) { - vo.setPermissionCodes(permissionMapper.selectBatchIds(permissionIds).stream().map(PermissionDO::getPermissionCode).collect(Collectors.toList())); - } else { - vo.setPermissionCodes(List.of()); - } - vo.setUserIds(userShopRoleMapper.selectList(new LambdaQueryWrapper() - .eq(UserShopRoleDO::getRoleId, role.getId()) - .eq(UserShopRoleDO::getIsDelete, 0)) - .stream().map(UserShopRoleDO::getUserId).collect(Collectors.toList())); - return vo; - } - - /** - * Run business method `toInviteVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param code parameter `code` supplied by the caller - * @return private InviteCodeVO result consumed by the caller or returned to the frontend - */ - private InviteCodeVO toInviteVO(UserInviteCodeDO code) { - InviteCodeVO vo = new InviteCodeVO(); - vo.setId(code.getId()); - vo.setInviteCode(code.getInviteCode()); - vo.setOwnerUserId(code.getOwnerUserId()); - vo.setOwnerUserName(code.getOwnerUserId() == null ? null : Optional.ofNullable(userMapper.selectById(code.getOwnerUserId())).map(UserDO::getNickname).orElse(null)); - vo.setShopId(code.getShopId()); - vo.setShopName(code.getShopId() == null ? null : Optional.ofNullable(shopMapper.selectById(code.getShopId())).map(ShopDO::getShopName).orElse(null)); - vo.setStatus(code.getStatus()); - vo.setUseCount(code.getUseCount()); - vo.setExpireTime(code.getExpireTime()); - vo.setCreateTime(code.getCreateTime()); - return vo; - } - - /** - * Run business method `requireRole`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return private ShopRoleDO result consumed by the caller or returned to the frontend - */ - private ShopRoleDO requireRole(Long id) { - ShopRoleDO role = shopRoleMapper.selectById(id); - if (role == null || Integer.valueOf(1).equals(role.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("角色不存在"); - } - return role; - } - - /** - * Run business method `typeName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param type parameter `type` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String typeName(Integer type) { - return switch (type == null ? -1 : type) { - case 0 -> "普通用户"; - case 2 -> "店长"; - case 3 -> "美甲师"; - case 4 -> "管理员"; - default -> "未知"; - }; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/AdminScopeHelper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/AdminScopeHelper.java deleted file mode 100644 index f95b8667..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/AdminScopeHelper.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.support; - -import com.xiaowang.jacyucloudsalon.core.common.BusinessException; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; - -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.support.RequestShopContext; -@Component -@RequiredArgsConstructor -/** - * Purpose: AdminScopeHelper supports AdminScopeHelper.java by holding or executing the admin scope helper business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class AdminScopeHelper { - - /** - * Purpose: userService supports AdminScopeHelper.java by holding or executing the user service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserService userService; - /** - * Purpose: userShopBindingSupport supports AdminScopeHelper.java by holding or executing the user shop binding support business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserShopBindingSupport userShopBindingSupport; - - /** - * Purpose: getCurrentUser supports AdminScopeHelper.java by holding or executing the get current user business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public UserDO getCurrentUser(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - if (userId == null) { - throw new RuntimeException("未获取到当前用户信息"); - } - - UserDO currentUser = userService.getById(userId); - if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { - throw new RuntimeException("当前用户不存在或已失效"); - } - - Long currentShopId = RequestShopContext.getCurrentShopId(request); - currentUser.setShopId(currentShopId); - - return currentUser; - } - - /** - * Purpose: isPlatformAdmin supports AdminScopeHelper.java by holding or executing the is platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isPlatformAdmin(UserDO currentUser) { - return currentUser != null && Integer.valueOf(4).equals(currentUser.getType()); - } - - /** - * Purpose: isPlatformOverviewMode supports AdminScopeHelper.java by holding or executing the is platform overview mode business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isPlatformOverviewMode(UserDO currentUser) { - return isPlatformAdmin(currentUser) - && (currentUser.getShopId() == null || currentUser.getShopId() <= 0); - } - - /** - * Purpose: requireShopContext supports AdminScopeHelper.java by holding or executing the require shop context business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void requireShopContext(UserDO currentUser) { - requireShopContext(currentUser, "请先选择店铺后再管理店铺细节"); - } - - /** - * Purpose: requireShopContext supports AdminScopeHelper.java by holding or executing the require shop context business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void requireShopContext(UserDO currentUser, String message) { - if (isPlatformOverviewMode(currentUser)) { - throw new RuntimeException(message); - } - if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) { - throw new RuntimeException(message); - } - } - - /** - * Purpose: getManagedShopId supports AdminScopeHelper.java by holding or executing the get managed shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Long getManagedShopId(UserDO currentUser) { - if (isPlatformAdmin(currentUser)) { - return null; - } - - if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) { - throw new RuntimeException("当前账号未绑定店铺,无法访问后台业务数据"); - } - - return currentUser.getShopId(); - } - - /** - * Purpose: resolveShopScope supports AdminScopeHelper.java by holding or executing the resolve shop scope business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Long resolveShopScope(UserDO currentUser, Long requestedShopId) { - Long managedShopId = getManagedShopId(currentUser); - if (managedShopId != null) { - return managedShopId; - } - if (requestedShopId != null && requestedShopId > 0) { - return requestedShopId; - } - if (currentUser != null && currentUser.getShopId() != null && currentUser.getShopId() > 0) { - return currentUser.getShopId(); - } - return null; - } - - /** - * Purpose: ensureShopAccessible supports AdminScopeHelper.java by holding or executing the ensure shop accessible business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void ensureShopAccessible(UserDO currentUser, Long targetShopId, String message) { - Long managedShopId = getManagedShopId(currentUser); - if (managedShopId != null && !managedShopId.equals(targetShopId)) { - throw new BusinessException(403, message); - } - } - - /** - * Purpose: ensureUserAccessibleInCurrentShop supports AdminScopeHelper.java by holding or executing the ensure user accessible in current shop business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void ensureUserAccessibleInCurrentShop(UserDO currentUser, Long targetUserId, String message) { - if (currentUser == null || targetUserId == null) { - throw new RuntimeException(message); - } - if (isPlatformAdmin(currentUser)) { - return; - } - Long managedShopId = getManagedShopId(currentUser); - if (!userShopBindingSupport.isUserAccessibleInShop(targetUserId, managedShopId)) { - throw new BusinessException(403, message); - } - } - - /** - * Purpose: requirePlatformAdmin supports AdminScopeHelper.java by holding or executing the require platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void requirePlatformAdmin(UserDO currentUser, String message) { - if (!isPlatformAdmin(currentUser)) { - throw new RuntimeException(message); - } - } - - /** - * Purpose: ensureAssignableUserType supports AdminScopeHelper.java by holding or executing the ensure assignable user type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void ensureAssignableUserType(UserDO currentUser, Integer targetType) { - if (targetType == null) { - throw new RuntimeException("用户类型不能为空"); - } - - if (isPlatformAdmin(currentUser)) { - return; - } - - if (Integer.valueOf(2).equals(currentUser.getType())) { - if (Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType)) { - return; - } - throw new RuntimeException("店长只能创建或维护普通用户、美甲师"); - } - - if (Integer.valueOf(3).equals(currentUser.getType())) { - if (Integer.valueOf(0).equals(targetType)) { - return; - } - throw new RuntimeException("美甲师只能创建或维护普通用户"); - } - - throw new RuntimeException("当前角色无权维护后台用户"); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/PermissionCatalog.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/PermissionCatalog.java deleted file mode 100644 index 2855ab17..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/PermissionCatalog.java +++ /dev/null @@ -1,313 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.support; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * 权限目录是后台权限编码、中文展示文案和默认角色矩阵的唯一真源。 - */ -public final class PermissionCatalog { - - private static final Map DEFINITIONS = buildDefinitions(); - - private static final List ADMIN_DEFAULT_PERMISSION_CODES = List.of( - "home:view", - "dashboard:view", - "workbench:view", - "user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete", - "user:balance:view", "user:balance:manage", "user:vip:manage", - "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", - "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", - "shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage", - "permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign", - "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", - "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", - "comment:view", "comment:delete", - "order:view", "order:process", "order:edit", "order:delete", "order:artist-change", - "nail_artist:view", "nail_artist:edit", - "message:view", "message:create", "message:delete", - "announcement:view", "announcement:create", "announcement:delete", - "messagehub:config:manage", - "security:audit:view", - "legal_agreement:manage", - "schedule:view", "schedule:edit", - "payment:view", "payment:manage", "refund:view", "refund:manage", - "after_sale:view", "after_sale:audit", - "inventory:view", "inventory:manage", - "campaign:view", "campaign:manage", - "growth:view", "analytics:view", "performance:view" - ); - - private static final List SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of( - "home:view", - "dashboard:view", - "workbench:view", - "user:view", "user:create", "user:edit", "user:unbind", "user:reset_password", - "user:balance:view", "user:balance:manage", "user:vip:manage", - "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", - "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", - "shop:view", "shop:edit", "shop:staff:manage", - "permission:view", "permission:assign", - "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", - "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", - "comment:view", "comment:delete", - "order:view", "order:process", "order:edit", "order:delete", "order:artist-change", - "nail_artist:view", "nail_artist:edit", - "message:view", "message:create", - "announcement:view", "announcement:create", - "schedule:view", "schedule:edit", - "payment:view", "refund:view", - "after_sale:view", "after_sale:audit", - "inventory:view", "inventory:manage", - "campaign:view", "campaign:manage", - "analytics:view", "performance:view" - ); - - private static final List NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of( - "home:view", - "workbench:view", - "user:view", - "user:balance:view", - "product:view", - "shop:view", - "tag:view", - "coupon:view", - "comment:view", - "order:view", "order:process", "order:artist-change", - "schedule:view", "after_sale:view", "performance:view" - ); - - private static final Set PLATFORM_OVERVIEW_PREFIXES = Set.of( - "user:", - "shop:", - "permission:", - "message:", - "announcement:" - ); - - private static final Set PLATFORM_OVERVIEW_PERMISSIONS = Set.of( - "messagehub:config:manage", - "security:audit:view", - "legal_agreement:manage" - ); - - private static final Set MANAGED_PERMISSION_CODES = buildManagedPermissionCodes(); - - private PermissionCatalog() { - } - - /** - * Purpose: getDefaultPermissionCodes supports PermissionCatalog.java by holding or executing the get default permission codes business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static List getDefaultPermissionCodes(Integer userType) { - return switch (userType == null ? -1 : userType) { - case 4 -> ADMIN_DEFAULT_PERMISSION_CODES; - case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES; - case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES; - default -> List.of(); - }; - } - - /** - * Purpose: getDefaultPermissionCodeSet supports PermissionCatalog.java by holding or executing the get default permission code set business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Set getDefaultPermissionCodeSet(Integer userType) { - return Set.copyOf(getDefaultPermissionCodes(userType)); - } - - /** - * Purpose: getManagedPermissionCodes supports PermissionCatalog.java by holding or executing the get managed permission codes business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Set getManagedPermissionCodes() { - return MANAGED_PERMISSION_CODES; - } - - /** - * Purpose: getManagedDefinitions supports PermissionCatalog.java by holding or executing the get managed definitions business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Collection getManagedDefinitions() { - return MANAGED_PERMISSION_CODES.stream() - .map(PermissionCatalog::getRequiredDefinition) - .toList(); - } - - /** - * Purpose: getDefinitionsByCode supports PermissionCatalog.java by holding or executing the get definitions by code business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Map getDefinitionsByCode() { - return DEFINITIONS; - } - - /** - * Purpose: getRequiredDefinition supports PermissionCatalog.java by holding or executing the get required definition business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static PermissionDefinition getRequiredDefinition(String permissionCode) { - PermissionDefinition definition = DEFINITIONS.get(permissionCode); - if (definition == null) { - throw new IllegalArgumentException("Unknown permission code: " + permissionCode); - } - return definition; - } - - /** - * Purpose: isAllowedForPlatformOverview supports PermissionCatalog.java by holding or executing the is allowed for platform overview business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static boolean isAllowedForPlatformOverview(String permissionCode) { - if (permissionCode == null || permissionCode.isBlank()) { - return true; - } - if ("dashboard:view".equals(permissionCode) || permissionCode.endsWith(":view")) { - return true; - } - if (PLATFORM_OVERVIEW_PERMISSIONS.contains(permissionCode)) { - return true; - } - return PLATFORM_OVERVIEW_PREFIXES.stream().anyMatch(permissionCode::startsWith); - } - - /** - * Purpose: canManageUserType supports PermissionCatalog.java by holding or executing the can manage user type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static boolean canManageUserType(Integer operatorType, Integer targetType) { - if (operatorType == null || targetType == null) { - return false; - } - - return switch (operatorType) { - case 4 -> true; - case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType); - case 3 -> Integer.valueOf(0).equals(targetType); - default -> false; - }; - } - - /** - * Purpose: buildManagedPermissionCodes supports PermissionCatalog.java by holding or executing the build managed permission codes business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private static Set buildManagedPermissionCodes() { - LinkedHashSet permissionCodes = new LinkedHashSet<>(); - permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES); - permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES); - permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES); - return Set.copyOf(permissionCodes); - } - - /** - * Purpose: buildDefinitions supports PermissionCatalog.java by holding or executing the build definitions business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private static Map buildDefinitions() { - LinkedHashMap definitions = new LinkedHashMap<>(); - put(definitions, "home:view", "查看首页", "首页", "查看系统首页入口与概览"); - put(definitions, "dashboard:view", "查看仪表盘", "仪表盘", "查看后台仪表盘统计"); - put(definitions, "user:view", "查看用户", "用户管理", "查看用户列表与详情"); - put(definitions, "user:create", "新增用户", "用户管理", "创建用户账号"); - put(definitions, "user:edit", "编辑用户", "用户管理", "修改用户基础信息"); - put(definitions, "user:disable", "启停用户", "用户管理", "启用或禁用用户账号"); - put(definitions, "user:unbind", "解绑用户", "用户管理", "解绑用户与当前店铺的关系"); - put(definitions, "user:reset_password", "重置密码", "用户管理", "重置用户密码"); - put(definitions, "user:delete", "删除用户", "用户管理", "删除用户账号"); - put(definitions, "user:balance:view", "查看余额资产", "用户资产", "查看用户余额、累计充值与流水"); - put(definitions, "user:balance:manage", "调整余额", "用户资产", "充值、手工加减余额与关联订单"); - put(definitions, "user:vip:manage", "管理VIP", "用户资产", "手工设置VIP等级或恢复自动判级"); - put(definitions, "role:view", "查看店铺角色", "角色管理", "查看店铺自定义角色"); - put(definitions, "role:create", "新增店铺角色", "角色管理", "创建店铺自定义角色"); - put(definitions, "role:edit", "编辑店铺角色", "角色管理", "编辑角色权限和绑定员工"); - put(definitions, "role:delete", "删除店铺角色", "角色管理", "删除店铺自定义角色"); - put(definitions, "user:relation:view", "查看用户所属", "用户管理", "查看用户归属关系"); - put(definitions, "user:relation:edit", "编辑用户所属", "用户管理", "调整用户店铺和直属上级"); - put(definitions, "product:view", "查看商品", "商品管理", "查看商品列表与详情"); - put(definitions, "product:create", "新增商品", "商品管理", "创建商品"); - put(definitions, "product:edit", "编辑商品", "商品管理", "编辑商品信息"); - put(definitions, "product:delete", "删除商品", "商品管理", "删除商品"); - put(definitions, "product:category:manage", "管理商品分类", "商品管理", "维护商品分类与归类信息"); - put(definitions, "shop:view", "查看店铺", "店铺管理", "查看店铺列表与详情"); - put(definitions, "shop:create", "新增店铺", "店铺管理", "创建店铺"); - put(definitions, "shop:edit", "编辑店铺", "店铺管理", "编辑店铺信息"); - put(definitions, "shop:delete", "删除店铺", "店铺管理", "删除店铺"); - put(definitions, "shop:staff:manage", "管理员工", "店铺管理", "管理店铺员工与归属"); - put(definitions, "permission:view", "查看权限", "权限管理", "查看权限清单"); - put(definitions, "permission:create", "新增权限", "权限管理", "新增系统权限定义"); - put(definitions, "permission:edit", "编辑权限", "权限管理", "编辑系统权限定义"); - put(definitions, "permission:delete", "删除权限", "权限管理", "删除系统权限定义"); - put(definitions, "permission:assign", "分配权限", "权限管理", "给用户分配后台权限"); - put(definitions, "tag:view", "查看标签", "标签管理", "查看标签列表与详情"); - put(definitions, "tag:create", "新增标签", "标签管理", "创建标签"); - put(definitions, "tag:edit", "编辑标签", "标签管理", "编辑标签"); - put(definitions, "tag:delete", "删除标签", "标签管理", "删除标签"); - put(definitions, "tag:assign", "分配标签", "标签管理", "给商品或优惠券分配标签"); - put(definitions, "coupon:view", "查看优惠券", "优惠券管理", "查看优惠券与发放情况"); - put(definitions, "coupon:create", "新增优惠券", "优惠券管理", "创建优惠券模板"); - put(definitions, "coupon:edit", "编辑优惠券", "优惠券管理", "编辑优惠券模板"); - put(definitions, "coupon:delete", "删除优惠券", "优惠券管理", "删除优惠券模板"); - put(definitions, "coupon:assign", "发放优惠券", "优惠券管理", "向用户发放普通优惠券"); - put(definitions, "comment:view", "查看评论", "评论管理", "查看作品评论与回复"); - put(definitions, "comment:delete", "删除评论", "评论管理", "删除不合规作品评论"); - put(definitions, "order:view", "查看订单", "订单管理", "查看订单列表与详情"); - put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单"); - put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限"); - put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限"); - put(definitions, "order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请"); - put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口"); - put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息"); - put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知"); - put(definitions, "message:create", "发布消息", "消息管理", "发布站内消息"); - put(definitions, "message:delete", "撤回消息", "消息管理", "撤回已发布站内消息"); - put(definitions, "announcement:view", "查看公告", "公告管理", "查看公告列表与详情"); - put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告"); - put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告"); - put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数"); - put(definitions, "security:audit:view", "查看安全审计", "安全审计", "查看高危操作和登录安全审计日志"); - put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本"); - put(definitions, "schedule:view", "查看排班", "排班管理", "查看美甲师排班和可约时段"); - put(definitions, "schedule:edit", "编辑排班", "排班管理", "维护美甲师班次、休息日和预约容量"); - put(definitions, "payment:view", "查看支付", "支付退款", "查看订单支付状态和支付单"); - put(definitions, "payment:manage", "确认支付", "支付退款", "手工确认支付或处理支付异常"); - put(definitions, "refund:view", "查看退款", "支付退款", "查看退款申请和退款单"); - put(definitions, "refund:manage", "处理退款", "支付退款", "手工确认退款或处理退款异常"); - put(definitions, "after_sale:view", "查看售后", "售后管理", "查看订单售后和客户反馈"); - put(definitions, "after_sale:audit", "处理售后", "售后管理", "审批或驳回售后申请"); - put(definitions, "inventory:view", "查看库存", "库存管理", "查看门店耗材库存和预警"); - put(definitions, "inventory:manage", "调整库存", "库存管理", "维护耗材、入库和库存调整"); - put(definitions, "campaign:view", "查看活动", "活动管理", "查看营销活动和推荐位"); - put(definitions, "campaign:manage", "管理活动", "活动管理", "创建、编辑和发布营销活动"); - put(definitions, "growth:view", "查看成长", "用户成长", "查看用户成长值和会员权益进度"); - put(definitions, "analytics:view", "查看经营分析", "经营分析", "查看订单漏斗和经营指标"); - put(definitions, "performance:view", "查看绩效", "绩效统计", "查看门店和美甲师服务绩效"); - put(definitions, "workbench:view", "查看工作台", "门店工作台", "查看今日订单、售后待办、排班和绩效摘要"); - return Map.copyOf(definitions); - } - - /** - * Purpose: put supports PermissionCatalog.java by holding or executing the put business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private static void put(Map definitions, String code, String name, String group, String description) { - definitions.put(code, new PermissionDefinition(code, name, group, description)); - } - - /** - * Purpose: PermissionDefinition supports PermissionCatalog.java by holding or executing the permission definition business role. - * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. - */ - public record PermissionDefinition( - String permissionCode, - String permissionName, - String permissionGroup, - String description - ) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/PermissionPolicy.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/PermissionPolicy.java deleted file mode 100644 index de189a59..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/PermissionPolicy.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.support; - -import java.util.List; -import java.util.Set; - -/** - * 后台角色默认权限与可分配策略。 - */ -public final class PermissionPolicy { - - private PermissionPolicy() { - } - - /** - * Purpose: getDefaultPermissionCodes supports PermissionPolicy.java by holding or executing the get default permission codes business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static List getDefaultPermissionCodes(Integer userType) { - return PermissionCatalog.getDefaultPermissionCodes(userType); - } - - /** - * Purpose: getDefaultPermissionCodeSet supports PermissionPolicy.java by holding or executing the get default permission code set business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Set getDefaultPermissionCodeSet(Integer userType) { - return PermissionCatalog.getDefaultPermissionCodeSet(userType); - } - - /** - * Purpose: getManagedDefaultPermissionCodes supports PermissionPolicy.java by holding or executing the get managed default permission codes business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Set getManagedDefaultPermissionCodes() { - return PermissionCatalog.getManagedPermissionCodes(); - } - - /** - * Purpose: canManageUserType supports PermissionPolicy.java by holding or executing the can manage user type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static boolean canManageUserType(Integer operatorType, Integer targetType) { - return PermissionCatalog.canManageUserType(operatorType, targetType); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/SecurityAuditActions.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/SecurityAuditActions.java deleted file mode 100644 index 7b8fff25..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/SecurityAuditActions.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.support; - -/** - * Purpose: SecurityAuditActions supports SecurityAuditActions.java by holding or executing the security audit actions business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public final class SecurityAuditActions { - - /** - * Purpose: SUCCESS supports SecurityAuditActions.java by holding or executing the success business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String SUCCESS = "SUCCESS"; - /** - * Purpose: FAIL supports SecurityAuditActions.java by holding or executing the fail business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String FAIL = "FAIL"; - - /** - * Purpose: ORDER_PROCESS supports SecurityAuditActions.java by holding or executing the order process business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String ORDER_PROCESS = "ORDER_PROCESS"; - /** - * Purpose: ARTIST_CHANGE_APPROVE supports SecurityAuditActions.java by holding or executing the artist change approve business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String ARTIST_CHANGE_APPROVE = "ARTIST_CHANGE_APPROVE"; - /** - * Purpose: ARTIST_CHANGE_REJECT supports SecurityAuditActions.java by holding or executing the artist change reject business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String ARTIST_CHANGE_REJECT = "ARTIST_CHANGE_REJECT"; - /** - * Purpose: SHOP_DELETE_BLOCKED supports SecurityAuditActions.java by holding or executing the shop delete blocked business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String SHOP_DELETE_BLOCKED = "SHOP_DELETE_BLOCKED"; - /** - * Purpose: SHOP_STATUS_UPDATE supports SecurityAuditActions.java by holding or executing the shop status update business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String SHOP_STATUS_UPDATE = "SHOP_STATUS_UPDATE"; - /** - * Purpose: PERMISSION_CREATE supports SecurityAuditActions.java by holding or executing the permission create business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String PERMISSION_CREATE = "PERMISSION_CREATE"; - /** - * Purpose: PERMISSION_UPDATE supports SecurityAuditActions.java by holding or executing the permission update business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String PERMISSION_UPDATE = "PERMISSION_UPDATE"; - /** - * Purpose: PERMISSION_DELETE supports SecurityAuditActions.java by holding or executing the permission delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String PERMISSION_DELETE = "PERMISSION_DELETE"; - /** - * Purpose: PERMISSION_ASSIGN supports SecurityAuditActions.java by holding or executing the permission assign business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String PERMISSION_ASSIGN = "PERMISSION_ASSIGN"; - /** - * Purpose: USER_STATUS_UPDATE supports SecurityAuditActions.java by holding or executing the user status update business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_STATUS_UPDATE = "USER_STATUS_UPDATE"; - /** - * Purpose: USER_RESET_PASSWORD supports SecurityAuditActions.java by holding or executing the user reset password business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_RESET_PASSWORD = "USER_RESET_PASSWORD"; - /** - * Purpose: USER_DELETE supports SecurityAuditActions.java by holding or executing the user delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_DELETE = "USER_DELETE"; - /** - * Purpose: USER_UNBIND supports SecurityAuditActions.java by holding or executing the user unbind business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_UNBIND = "USER_UNBIND"; - /** - * Purpose: USER_BALANCE_CHANGE supports SecurityAuditActions.java by holding or executing the user balance change business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_BALANCE_CHANGE = "USER_BALANCE_CHANGE"; - /** - * Purpose: USER_VIP_OVERRIDE supports SecurityAuditActions.java by holding or executing the user vip override business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_VIP_OVERRIDE = "USER_VIP_OVERRIDE"; - /** - * Purpose: USER_VIP_RECALCULATE supports SecurityAuditActions.java by holding or executing the user vip recalculate business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_VIP_RECALCULATE = "USER_VIP_RECALCULATE"; - public static final String SCHEDULE_UPDATE = "SCHEDULE_UPDATE"; - public static final String PAYMENT_MANUAL_CONFIRM = "PAYMENT_MANUAL_CONFIRM"; - public static final String REFUND_MANUAL_CONFIRM = "REFUND_MANUAL_CONFIRM"; - public static final String AFTER_SALE_CREATE = "AFTER_SALE_CREATE"; - public static final String AFTER_SALE_APPROVE = "AFTER_SALE_APPROVE"; - public static final String AFTER_SALE_REJECT = "AFTER_SALE_REJECT"; - public static final String INVENTORY_ADJUST = "INVENTORY_ADJUST"; - public static final String CAMPAIGN_PUBLISH = "CAMPAIGN_PUBLISH"; - public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW"; - public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW"; - - private SecurityAuditActions() { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/SecurityAuditSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/SecurityAuditSupport.java deleted file mode 100644 index 5d83cd20..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/support/SecurityAuditSupport.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.support; - -import com.xiaowang.jacyucloudsalon.core.modules.security.service.SecurityAuditLogService; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; - -@Component -@RequiredArgsConstructor -/** - * Purpose: SecurityAuditSupport supports SecurityAuditSupport.java by holding or executing the security audit support business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SecurityAuditSupport { - - /** - * Purpose: securityAuditLogService supports SecurityAuditSupport.java by holding or executing the security audit log service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SecurityAuditLogService securityAuditLogService; - - /** - * Purpose: success supports SecurityAuditSupport.java by holding or executing the success business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void success(HttpServletRequest request, String action, String reason) { - record(request, action, SecurityAuditActions.SUCCESS, reason); - } - - /** - * Purpose: fail supports SecurityAuditSupport.java by holding or executing the fail business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void fail(HttpServletRequest request, String action, String reason) { - record(request, action, SecurityAuditActions.FAIL, reason); - } - - /** - * Purpose: record supports SecurityAuditSupport.java by holding or executing the record business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void record(HttpServletRequest request, String action, String result, String reason) { - try { - Long userId = request == null ? null : asLong(request.getAttribute("userId")); - String account = request == null ? null : asString(request.getAttribute("account")); - securityAuditLogService.record(userId, account, action, result, reason, request); - } catch (Exception ignored) { - // Audit failure must never block the guarded business operation. - } - } - - /** - * Purpose: asLong supports SecurityAuditSupport.java by holding or executing the as long business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long asLong(Object value) { - if (value instanceof Long) { - return (Long) value; - } - if (value instanceof Number) { - return ((Number) value).longValue(); - } - return null; - } - - /** - * Purpose: asString supports SecurityAuditSupport.java by holding or executing the as string business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String asString(Object value) { - return value == null ? null : String.valueOf(value); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/PermissionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/PermissionVO.java deleted file mode 100644 index 871acd54..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/PermissionVO.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -/** - * 系统权限表 VO - * 用于前端展示权限信息 - * - * @author xiaowang - * @date 2026-02-25 - */ -@Data -public class PermissionVO { - - /** - * 权限唯一主键ID - */ - private Long id; - - /** - * 权限编码(唯一标识) - */ - private String permissionCode; - - /** - * 权限名称 - */ - private String permissionName; - - /** - * 权限分组(商品管理、用户管理等) - */ - private String permissionGroup; - - /** - * 权限描述 - */ - private String description; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/SecurityAuditLogVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/SecurityAuditLogVO.java deleted file mode 100644 index db390946..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/SecurityAuditLogVO.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -/** - * Purpose: SecurityAuditLogVO supports SecurityAuditLogVO.java by holding or executing the security audit log vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SecurityAuditLogVO { - - /** - * Purpose: id supports SecurityAuditLogVO.java by holding or executing the id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long id; - /** - * Purpose: userId supports SecurityAuditLogVO.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - /** - * Purpose: account supports SecurityAuditLogVO.java by holding or executing the account business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String account; - /** - * Purpose: action supports SecurityAuditLogVO.java by holding or executing the action business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String action; - /** - * Purpose: result supports SecurityAuditLogVO.java by holding or executing the result business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String result; - /** - * Purpose: reason supports SecurityAuditLogVO.java by holding or executing the reason business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String reason; - /** - * Purpose: ipAddress supports SecurityAuditLogVO.java by holding or executing the ip address business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String ipAddress; - /** - * Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - /** - * Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime operateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/ShopRoleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/ShopRoleVO.java deleted file mode 100644 index 7b15612e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/security/vo/ShopRoleVO.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.security.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.time.LocalDateTime; -import java.util.List; - -@Data -/** - * ShopRoleVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ShopRoleVO { - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - /** - * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String roleName; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long creatorId; - /** - * Field `creatorName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String creatorName; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; - /** - * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer sortOrder; - /** - * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List permissionIds; - /** - * Field `permissionCodes` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List permissionCodes; - /** - * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List userIds; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; - /** - * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/controller/front/ContactInfoController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/controller/front/ContactInfoController.java deleted file mode 100644 index fa2d3a10..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/controller/front/ContactInfoController.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.shop.service.ContactInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ContactInfoVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/contact-info", "/api/contact-info"}) -/** - * ContactInfoController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ContactInfoController { - /** - * Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ContactInfoService contactInfoService; - - @GetMapping("/shop/{shopId}/manager") - /** - * Run business method `shopManager`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result shopManager(HttpServletRequest request, @PathVariable Long shopId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(contactInfoService.getShopManagerContact(userId, shopId)); - } - - @GetMapping("/product/{productId}/artist/{artistId}") - /** - * Run business method `productArtist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param productId parameter `productId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId)); - } - - @GetMapping("/order/{orderId}/artist") - /** - * Purpose: orderArtist supports ContactInfoController.java by holding or executing the order artist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId)); - } - - @GetMapping("/platform") - /** - * Run business method `platform`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return Result result consumed by the caller or returned to the frontend - */ - public Result platform() { - return Result.success(contactInfoService.getPlatformContact()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/controller/front/ShopController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/controller/front/ShopController.java deleted file mode 100644 index 2f73dd2c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/controller/front/ShopController.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.shop.dto.ShopDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.service.ShopService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopTrustProfileVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopVO; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - -@RestController -@RequestMapping("/shop") -@RequiredArgsConstructor -/** - * ShopController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ShopController { - /** - * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopService shopService; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - - @PostMapping("/create") - @RequirePermission("shop:create") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param shopDTO parameter `shopDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺"); - Long id = shopService.createShop(shopDTO); - return Result.success(id); - } - - @PutMapping("/update/{id}") - @RequirePermission("shop:edit") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param shopDTO parameter `shopDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - ShopVO shopVO = shopService.getShopById(id); - if (shopVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); - if (!adminScopeHelper.isPlatformAdmin(currentUser)) { - shopDTO.setAuthorizationExpireTime(shopVO.getAuthorizationExpireTime()); - } - boolean success = shopService.updateShop(id, shopDTO); - return Result.success(success); - } - - @DeleteMapping("/delete/{id}") - @RequirePermission("shop:delete") - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); - boolean success = shopService.deleteShop(id); - return Result.success(success); - } - - @PutMapping("/status/{id}") - @RequirePermission("shop:edit") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param statusRequest parameter `statusRequest` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); - boolean success = shopService.updateShopStatus(id, statusRequest.getStatus()); - return Result.success(success); - } - - @GetMapping("/get/{id}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getShopById(@PathVariable Long id) { - ShopVO shopVO = shopService.getShopById(id); - return Result.success(shopVO); - } - - @GetMapping("/trust-profile/{id}") - /** - * Purpose: getShopTrustProfile returns public confidence signals for a shop detail page. - * Usage: anonymous clients can call this endpoint; phone data remains behind contact-info APIs. - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getShopTrustProfile(@PathVariable Long id) { - return Result.success(shopService.getShopTrustProfile(id)); - } - - @GetMapping("/list/all") - @RequirePermission("shop:view") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listAllShops(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - List shopVOs; - if (adminScopeHelper.isPlatformAdmin(currentUser)) { - shopVOs = shopService.listAllShopsForAdmin(); - } else { - ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser)); - shopVOs = currentShop == null ? List.of() : List.of(currentShop); - } - return Result.success(shopVOs); - } - - @GetMapping("/list/shopName/{shopName}") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopName parameter `shopName` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listShopsByShopName(@PathVariable String shopName) { - List shopVOs = shopService.listShopsByShopName(shopName); - return Result.success(shopVOs); - } - - @GetMapping("/list/simple") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listShopsSimple() { - List shopVOs = shopService.listAllShops(); - List simpleVOs = shopVOs.stream() - .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) - .collect(Collectors.toList()); - return Result.success(simpleVOs); - } - - @GetMapping("/list") - /** - * Purpose: listPublicShopsCompat keeps the legacy /shop/list public catalog URL usable for anonymous clients. - * Usage: call from old Web or mini-program builds that still request /api/shop/list; new code may prefer /shop/list/public. - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listPublicShopsCompat() { - return Result.success(shopService.listAllShops()); - } - - @GetMapping("/list/public") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listPublicShops() { - return Result.success(shopService.listAllShops()); - } - - @Data - /** - * Purpose: StatusRequest supports ShopController.java by holding or executing the status request business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class StatusRequest { - /** - * Purpose: status supports ShopController.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer status; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/dto/ShopDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/dto/ShopDTO.java deleted file mode 100644 index a8a9a474..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/dto/ShopDTO.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.dto; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; - -/** - * 店铺信息表 DTO - * 用于店铺信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class ShopDTO { - - /** - * 店铺名称 - */ - private String shopName; - - /** - * 店铺描述 - */ - private String description; - - /** - * 店铺地址 - */ - private String address; - - /** - * Purpose: mapProvider supports ShopDTO.java by holding or executing the map provider business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String mapProvider; - - /** - * Purpose: longitude supports ShopDTO.java by holding or executing the longitude business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal longitude; - - /** - * Purpose: latitude supports ShopDTO.java by holding or executing the latitude business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal latitude; - - /** - * 店铺营业时间 - */ - private String businessHours; - - /** - * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 - */ - private String coverImageFileId; - - /** - * 店铺图片文件ID集合,多个ID以逗号分隔 - */ - private String imageFileIds; - - /** - * Purpose: themePrimaryColor supports ShopDTO.java by holding or executing the theme primary color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themePrimaryColor; - - /** - * Purpose: themeSecondaryColor supports ShopDTO.java by holding or executing the theme secondary color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeSecondaryColor; - - /** - * Purpose: themeAccentColor supports ShopDTO.java by holding or executing the theme accent color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeAccentColor; - - /** - * Purpose: themePageBgColor supports ShopDTO.java by holding or executing the theme page bg color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themePageBgColor; - - /** - * Purpose: themeCardBgColor supports ShopDTO.java by holding or executing the theme card bg color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeCardBgColor; - - /** - * Purpose: themeBackgroundImageFileId supports ShopDTO.java by holding or executing the theme background image file id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeBackgroundImageFileId; - - /** - * 店铺状态:1-启用,0-停用 - */ - private Integer status; - - /** - * Purpose: authorizationStartDate supports ShopDTO.java by holding or executing the authorization start date business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDate authorizationStartDate; - - /** - * Purpose: authorizationDays supports ShopDTO.java by holding or executing the authorization days business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer authorizationDays; - - /** - * 店铺授权有效期;为空表示长期有效。 - */ - private LocalDateTime authorizationExpireTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/entity/ShopDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/entity/ShopDO.java deleted file mode 100644 index c0f67d6b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/entity/ShopDO.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 店铺信息表 DO - * 对应数据库表 t_shop - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@TableName("t_shop") -public class ShopDO extends BaseEntity { - - /** - * 店铺唯一主键ID(雪花ID) - */ - @TableId(type = IdType.ASSIGN_ID) - private Long id; - - /** - * 店铺名称 - */ - @TableField("shop_name") - private String shopName; - - /** - * 店铺描述 - */ - @TableField("description") - private String description; - - /** - * 店铺地址 - */ - @TableField("address") - private String address; - - @TableField("map_provider") - /** - * Purpose: mapProvider supports ShopDO.java by holding or executing the map provider business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String mapProvider; - - @TableField("longitude") - /** - * Purpose: longitude supports ShopDO.java by holding or executing the longitude business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal longitude; - - @TableField("latitude") - /** - * Purpose: latitude supports ShopDO.java by holding or executing the latitude business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal latitude; - - /** - * 店铺营业时间 - */ - @TableField("business_hours") - private String businessHours; - - /** - * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 - */ - @TableField("cover_image_file_id") - private String coverImageFileId; - - /** - * 店铺图片文件ID集合,多个ID以逗号分隔 - */ - @TableField("image_file_ids") - private String imageFileIds; - - @TableField("theme_primary_color") - /** - * Purpose: themePrimaryColor supports ShopDO.java by holding or executing the theme primary color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themePrimaryColor; - - @TableField("theme_secondary_color") - /** - * Purpose: themeSecondaryColor supports ShopDO.java by holding or executing the theme secondary color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeSecondaryColor; - - @TableField("theme_accent_color") - /** - * Purpose: themeAccentColor supports ShopDO.java by holding or executing the theme accent color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeAccentColor; - - @TableField("theme_page_bg_color") - /** - * Purpose: themePageBgColor supports ShopDO.java by holding or executing the theme page bg color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themePageBgColor; - - @TableField("theme_card_bg_color") - /** - * Purpose: themeCardBgColor supports ShopDO.java by holding or executing the theme card bg color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeCardBgColor; - - @TableField("theme_background_image_file_id") - /** - * Purpose: themeBackgroundImageFileId supports ShopDO.java by holding or executing the theme background image file id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeBackgroundImageFileId; - - /** - * 店铺状态:1-启用,0-停用 - */ - @TableField("status") - private Integer status; - - @TableField("authorization_start_date") - /** - * Purpose: authorizationStartDate supports ShopDO.java by holding or executing the authorization start date business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDate authorizationStartDate; - - @TableField("authorization_days") - /** - * Purpose: authorizationDays supports ShopDO.java by holding or executing the authorization days business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer authorizationDays; - - /** - * 店铺授权有效期;为空表示长期有效。 - */ - @TableField("authorization_expire_time") - private LocalDateTime authorizationExpireTime; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/entity/UserShopBindingDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/entity/UserShopBindingDO.java deleted file mode 100644 index 58592035..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/entity/UserShopBindingDO.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 用户与店铺绑定关系。 - */ -@Getter -@Setter -@TableName("t_user_shop_binding") -public class UserShopBindingDO extends BaseEntity { - - @TableId(type = IdType.ASSIGN_ID) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - - @TableField("user_id") - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - @TableField("shop_id") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - /** - * 绑定状态:1-正常,0-禁用。 - */ - @TableField("status") - private Integer status; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/mapper/ShopMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/mapper/ShopMapper.java deleted file mode 100644 index 7d847bba..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/mapper/ShopMapper.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import org.apache.ibatis.annotations.Param; -import org.apache.ibatis.annotations.Select; - -/** - * 店铺信息表 Mapper - * 对应数据库表 t_shop - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface ShopMapper extends BaseMapper { - - @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") - Long countPublicImageReference(@Param("fileId") Long fileId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/mapper/UserShopBindingMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/mapper/UserShopBindingMapper.java deleted file mode 100644 index a7ddcf8b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/mapper/UserShopBindingMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; - -/** - * UserShopBindingMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface UserShopBindingMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/ContactInfoService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/ContactInfoService.java deleted file mode 100644 index 2fd8d32a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/ContactInfoService.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.service; - -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ContactInfoVO; - -/** - * ContactInfoService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface ContactInfoService { - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - ContactInfoVO getShopManagerContact(Long userId, Long shopId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param orderId parameter `orderId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - ContactInfoVO getPlatformContact(); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/ShopService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/ShopService.java deleted file mode 100644 index c81af633..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/ShopService.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.dto.ShopDTO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopTrustProfileVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopVO; - -import java.util.List; - -/** - * 店铺信息表 Service - * 对应数据库表 t_shop - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface ShopService extends IService { - - /** - * 创建店铺 - * - * @param shopDTO 店铺DTO - * @return 店铺ID - */ - Long createShop(ShopDTO shopDTO); - - /** - * 更新店铺 - * - * @param id 店铺ID - * @param shopDTO 店铺DTO - * @return 是否更新成功 - */ - boolean updateShop(Long id, ShopDTO shopDTO); - - /** - * 删除店铺 - * - * @param id 店铺ID - * @return 是否删除成功 - */ - boolean deleteShop(Long id); - - /** - * 根据ID查询店铺 - * - * @param id 店铺ID - * @return 店铺VO - */ - ShopVO getShopById(Long id); - - /** - * Purpose: getShopTrustProfile aggregates public shop confidence signals. - * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. - * - * @param id shop id to inspect - * @return public trust profile or null when the shop cannot be viewed - */ - ShopTrustProfileVO getShopTrustProfile(Long id); - - /** - * 查询所有店铺 - * - * @return 店铺VO列表 - */ - List listAllShops(); - - /** - * 查询后台全部店铺(含停用,不含删除) - * - * @return 店铺列表 - */ - List listAllShopsForAdmin(); - - /** - * 根据店铺名称查询店铺 - * - * @param shopName 店铺名称 - * @return 店铺VO列表 - */ - List listShopsByShopName(String shopName); - - /** - * 分页查询店铺 - * - * @param page 页码 - * @param size 每页大小 - * @param keyword 搜索关键词 - * @return 分页结果 - */ - PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId); - - /** - * 更新店铺状态 - * - * @param id 店铺ID - * @param status 状态:1-启用,0-停用 - * @return 是否成功 - */ - boolean updateShopStatus(Long id, Integer status); - - /** - * 店铺是否已超过授权有效期。 - */ - boolean isAuthorizationExpired(Long shopId); - - /** - * 前台可用:未删除、启用、且授权未到期。 - */ - boolean isFrontendAvailable(Long shopId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/impl/ContactInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/impl/ContactInfoServiceImpl.java deleted file mode 100644 index e60ab352..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/impl/ContactInfoServiceImpl.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.service.ContactInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ContactInfoVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -@Service -@RequiredArgsConstructor -/** - * ContactInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class ContactInfoServiceImpl implements ContactInfoService { - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductMapper productMapper; - /** - * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final OrderMapper orderMapper; - /** - * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final OrderItemMapper orderItemMapper; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - /** - * Variable `objectStorageUrlSupport`: converts stored QR image URLs into frontend-safe signed URLs. - */ - private final ObjectStorageUrlSupport objectStorageUrlSupport; - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - public ContactInfoVO getShopManagerContact(Long userId, Long shopId) { - if (shopId == null || shopId <= 0) throw new RuntimeException("店铺ID不能为空"); - /** - * Run business method `ensureUserCanSeeShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureUserCanSeeShop(userId, shopId); - UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() - .eq(UserDO::getType, 2) - .eq(UserDO::getShopId, shopId) - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getStatus, 1) - .last("LIMIT 1")); - /** - * Run business method `toContact`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param manager parameter `manager` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toContact(manager, "店长"); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - public ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId) { - ProductDO product = productMapper.selectById(productId); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) throw new RuntimeException("作品不存在"); - if (artistId == null || artistId <= 0) throw new RuntimeException("请选择美甲师"); - ensureArtistAllowed(product.getBookableArtists(), artistId); - return toContact(userMapper.selectById(artistId), "美甲师"); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param orderId parameter `orderId` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - public ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId) { - OrderDO order = orderMapper.selectById(orderId); - if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || !userId.equals(order.getUserId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("订单不存在或无权查看"); - } - OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper() - .eq(OrderItemDO::getOrderId, orderId) - .eq(OrderItemDO::getIsDelete, 0) - .eq(artistId != null && artistId > 0, OrderItemDO::getArtistId, artistId) - .isNotNull(OrderItemDO::getArtistId) - .last("LIMIT 1")) - .stream() - .findFirst() - .orElseThrow(() -> new RuntimeException("订单暂无可联系美甲师")); - return toContact(userMapper.selectById(item.getArtistId()), "美甲师"); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return ContactInfoVO result consumed by the caller or returned to the frontend - */ - public ContactInfoVO getPlatformContact() { - UserDO admin = userMapper.selectOne(new LambdaQueryWrapper() - .eq(UserDO::getType, 4) - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getStatus, 1) - .isNotNull(UserDO::getPhone) - .last("LIMIT 1")); - /** - * Run business method `toContact`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param admin parameter `admin` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toContact(admin, "平台客服"); - } - - /** - * Run business method `ensureUserCanSeeShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensureUserCanSeeShop(Long userId, Long shopId) { - if (userId == null) return; - UserDO user = userMapper.selectById(userId); - if (user != null && shopId.equals(user.getShopId())) return; - if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { - // 店铺详情是公开入口,未绑定用户仍允许看联系方式。 - } - } - - /** - * Run business method `ensureArtistAllowed`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller - * @param artistId parameter `artistId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensureArtistAllowed(String rawBookableArtists, Long artistId) { - if (!StringUtils.hasText(rawBookableArtists)) return; - boolean allowed = java.util.Arrays.stream(rawBookableArtists.split(",")) - .map(String::trim) - .filter(StringUtils::hasText) - .anyMatch(id -> id.equals(String.valueOf(artistId))); - if (!allowed) throw new RuntimeException("该美甲师不可预约当前作品"); - } - - /** - * Run business method `toContact`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param roleLabel parameter `roleLabel` supplied by the caller - * @return private ContactInfoVO result consumed by the caller or returned to the frontend - */ - private ContactInfoVO toContact(UserDO user, String roleLabel) { - ContactInfoVO vo = new ContactInfoVO(); - vo.setPlatformContactAvailable(false); - vo.setPlatformContactText("平台联系暂未接入"); - vo.setRoleLabel(roleLabel); - if (user == null) { - vo.setContactName(roleLabel); - vo.setPhoneAvailable(false); - return vo; - } - vo.setContactUserId(user.getId()); - vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); - String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone(); - vo.setPhone(contactPhone); - vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); - vo.setWechatId(user.getWechatId()); - vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); - vo.setWechatQrCode(StringUtils.hasText(user.getWechatQrCode()) - ? objectStorageUrlSupport.toAccessibleUrl(user.getWechatQrCode()) - : null); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/impl/ShopServiceImpl.java deleted file mode 100644 index de2d3691..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/service/impl/ShopServiceImpl.java +++ /dev/null @@ -1,896 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.fasterxml.jackson.core.type.TypeReference; -import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties; -import com.xiaowang.jacyucloudsalon.core.modules.shop.dto.ShopDTO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistReviewDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.product.entity.TagDO; -import com.xiaowang.jacyucloudsalon.core.modules.content.mapper.CommentMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.CouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistReviewMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.TagMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.UserCouponMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.CouponService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MapService; -import com.xiaowang.jacyucloudsalon.core.modules.artist.service.NailArtistInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService; -import com.xiaowang.jacyucloudsalon.core.modules.shop.service.ShopService; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.ShopThemeSupport; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.support.cache.MultiLevelCacheService; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopTrustProfileVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * 店铺信息表 Service 实现 - * 对应数据库表 t_shop - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class ShopServiceImpl extends ServiceImpl implements ShopService { - /** - * Purpose: SHOP_DETAIL_CACHE_PREFIX supports ShopServiceImpl.java by holding or executing the shop detail cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:"; - /** - * Purpose: SHOP_LIST_CACHE_PREFIX supports ShopServiceImpl.java by holding or executing the shop list cache prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:"; - /** - * Purpose: SHOP_DELETE_DISABLED_MESSAGE supports ShopServiceImpl.java by holding or executing the shop delete disabled message business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SHOP_DELETE_DISABLED_MESSAGE = "店铺删除已停用,请使用停用封存"; - /** - * Purpose: DISABLED_SHOP_ARCHIVED_MESSAGE supports ShopServiceImpl.java by holding or executing the disabled shop archived message business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String DISABLED_SHOP_ARCHIVED_MESSAGE = "停用店铺已封存,仅允许重新启用"; - private static final Set FEATURED_PRODUCT_TAG_NAMES = Set.of("特色作品", "热门"); - /** - * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopMapper shopMapper; - /** - * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponService couponService; - /** - * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CouponMapper couponMapper; - /** - * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ProductMapper productMapper; - /** - * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TagMapper tagMapper; - /** - * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final CommentMapper commentMapper; - /** - * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserCouponMapper userCouponMapper; - /** - * Variable `orderArtistReviewMapper`: Spring-injected collaborator used by this class to aggregate public shop review trust signals. - */ - private final OrderArtistReviewMapper orderArtistReviewMapper; - /** - * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to resolve public image URLs for trust cards. - */ - private final ObjectStorageFileService objectStorageFileService; - /** - * Variable `objectStorageUrlSupport`: converts stored object URLs into frontend-accessible signed URLs. - */ - private final ObjectStorageUrlSupport objectStorageUrlSupport; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - private final NailArtistInfoService nailArtistInfoService; - /** - * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MultiLevelCacheService multiLevelCacheService; - /** - * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AppCacheProperties appCacheProperties; - /** - * Purpose: mapService supports ShopServiceImpl.java by holding or executing the map service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final MapService mapService; - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopDTO parameter `shopDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - public Long createShop(ShopDTO shopDTO) { - ShopDO shopDO = new ShopDO(); - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); - shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); - shopDO.setLongitude(shopDTO.getLongitude()); - shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); - applyTheme(shopDO, shopDTO); - applyAuthorization(shopDO, shopDTO); - shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); - shopDO.setIsDelete(0); - shopMapper.insert(shopDO); - couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); - evictShopCaches(shopDO.getId()); - return shopDO.getId(); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopDTO parameter `shopDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateShop(Long id, ShopDTO shopDTO) { - ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null) { - return false; - } - if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { - throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); - } - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); - shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); - shopDO.setLongitude(shopDTO.getLongitude()); - shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); - applyTheme(shopDO, shopDTO); - applyAuthorization(shopDO, shopDTO); - if (shopDTO.getStatus() != null) { - shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); - } - boolean updated = shopMapper.updateById(shopDO) > 0; - if (updated) { - /** - * Run business method `evictShopCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictShopCaches(id); - } - return updated; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteShop(Long id) { - throw new RuntimeException(SHOP_DELETE_DISABLED_MESSAGE); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateShopStatus(Long id, Integer status) { - ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { - return false; - } - shopDO.setStatus(normalizeStatus(status)); - boolean updated = shopMapper.updateById(shopDO) > 0; - if (updated) { - /** - * Run business method `evictShopCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - evictShopCaches(id); - } - return updated; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return ShopVO result consumed by the caller or returned to the frontend - */ - public ShopVO getShopById(Long id) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); - return multiLevelCacheService.getOrLoad( - SHOP_DETAIL_CACHE_PREFIX + id, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference() { - }, - () -> { - ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopDO parameter `shopDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(shopDO); - } - ); - } - - @Override - /** - * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. - * Usage: pass a valid shop id; the returned profile never exposes contact phone data. - */ - public ShopTrustProfileVO getShopTrustProfile(Long id) { - if (id == null || id <= 0) { - return null; - } - ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { - return null; - } - - long productCount = countActiveProducts(id); - long artistCount = countShopArtists(id); - List featuredProducts = listFeaturedProducts(id); - List recentReviews = listSubmittedReviews(id, 3); - BigDecimal averageRating = calculateAverageRating(id); - long reviewCount = countSubmittedReviews(id); - - Set fileIds = new LinkedHashSet<>(); - fileIds.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); - fileIds.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); - featuredProducts.forEach(product -> fileIds.addAll(parseLongIds(product.getImageFileIds(), ","))); - recentReviews.forEach(review -> fileIds.addAll(parseLongIds(review.getImageFileIds(), ","))); - Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); - - ShopTrustProfileVO profile = new ShopTrustProfileVO(); - profile.setShopId(shopDO.getId()); - profile.setShopName(shopDO.getShopName()); - profile.setBusinessHoursText(StringUtils.hasText(shopDO.getBusinessHours()) ? shopDO.getBusinessHours() : "营业时间待补充"); - profile.setBusinessStatusText(Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) ? "正常营业" : "暂不可预约"); - boolean locationAvailable = shopDO.getLatitude() != null && shopDO.getLongitude() != null; - profile.setLocationAvailable(locationAvailable); - profile.setNavigationAvailable(locationAvailable); - profile.setDistanceCapabilityText(locationAvailable ? "开启定位后可查看距离" : "门店暂未设置地图位置"); - profile.setEnvironmentImages(resolveImageUrls(fileIdsForShop(shopDO), fileMap)); - - ShopTrustProfileVO.Stats stats = new ShopTrustProfileVO.Stats(); - stats.setProductCount(productCount); - stats.setArtistCount(artistCount); - stats.setReviewCount(reviewCount); - stats.setAverageRating(averageRating); - stats.setRecentReviewCount(recentReviews.size()); - profile.setStats(stats); - - profile.setFeaturedProducts(featuredProducts.stream() - .map(product -> buildFeaturedProduct(product, fileMap)) - .collect(Collectors.toList())); - profile.setRecentReviews(recentReviews.stream() - .map(review -> buildRecentReview(review, featuredProducts, fileMap)) - .collect(Collectors.toList())); - profile.setAvailabilitySummary(buildAvailabilitySummary(shopDO, productCount)); - profile.setContactSummary(buildContactSummary()); - return profile; - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllShops() { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); - return multiLevelCacheService.getOrLoad( - SHOP_LIST_CACHE_PREFIX + "active", - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> shopMapper.selectList( - Wrappers.lambdaQuery(ShopDO.class) - .eq(ShopDO::getIsDelete, 0) - .eq(ShopDO::getStatus, 1) - .orderByDesc(ShopDO::getCreateTime) - ).stream() - .filter(this::isAuthorizationValid) - .map(this::convertToVO) - .collect(Collectors.toList()) - ); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - public List listAllShopsForAdmin() { - List shopDOs = shopMapper.selectList( - Wrappers.lambdaQuery(ShopDO.class) - .eq(ShopDO::getIsDelete, 0) - .orderByDesc(ShopDO::getCreateTime) - ); - return shopDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopName parameter `shopName` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listShopsByShopName(String shopName) { - AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); - String normalizedShopName = StringUtils.hasText(shopName) ? shopName.trim() : ""; - return multiLevelCacheService.getOrLoad( - SHOP_LIST_CACHE_PREFIX + "name:" + normalizedShopName, - Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), - Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), - new TypeReference>() { - }, - () -> { - List shopDOs = shopMapper.selectList( - Wrappers.lambdaQuery(ShopDO.class) - .eq(ShopDO::getIsDelete, 0) - .eq(ShopDO::getStatus, 1) - .like(ShopDO::getShopName, normalizedShopName) - ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); - return shopDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - ); - } - - @Override - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - public PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId) { - Page pageParam = new Page<>(page, size); - - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ShopDO.class); - wrapper.eq(ShopDO::getIsDelete, 0); - if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(ShopDO::getShopName, keyword) - .or().like(ShopDO::getDescription, keyword) - .or().like(ShopDO::getAddress, keyword)); - } - if (shopId != null && shopId > 0) { - wrapper.eq(ShopDO::getId, shopId); - } - wrapper.orderByDesc(ShopDO::getCreateTime); - - Page shopPage = shopMapper.selectPage(pageParam, wrapper); - - PageResultVO result = new PageResultVO<>(); - result.setList(shopPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); - result.setTotal(shopPage.getTotal()); - result.setPage(page); - result.setSize(size); - - return result; - } - - /** - * Purpose: countActiveProducts counts products that can contribute to a public shop trust profile. - * Usage: call it with a valid shop id before rendering product trust metrics. - */ - private long countActiveProducts(Long shopId) { - Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0)); - return count == null ? 0L : count; - } - - private long countShopArtists(Long shopId) { - return nailArtistInfoService.getByShopId(shopId).size(); - } - - /** - * Purpose: listFeaturedProducts returns representative active products for shop detail trust cards. - * Usage: render at most three products and navigate to product detail when tapped. - */ - private List listFeaturedProducts(Long shopId) { - Set featuredTagTokens = findFeaturedProductTagTokens(shopId); - if (featuredTagTokens.isEmpty()) { - return Collections.emptyList(); - } - return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0) - .and(wrapper -> applyProductTagTokenConditions(wrapper, featuredTagTokens)) - .orderByDesc(ProductDO::getCollectCount) - .orderByDesc(ProductDO::getLikeCount) - .orderByDesc(ProductDO::getCreateTime) - .last("LIMIT 3")) - .stream() - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - private Set findFeaturedProductTagTokens(Long shopId) { - Set tokens = new LinkedHashSet<>(FEATURED_PRODUCT_TAG_NAMES); - List tags = tagMapper.selectList(Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .and(wrapper -> wrapper.eq(TagDO::getShopId, shopId) - .or() - .isNull(TagDO::getShopId) - .or() - .eq(TagDO::getShopId, 0L)) - .and(wrapper -> wrapper.in(TagDO::getTagName, FEATURED_PRODUCT_TAG_NAMES) - .or() - .in(TagDO::getDisplayName, FEATURED_PRODUCT_TAG_NAMES))); - tags.stream() - .map(TagDO::getId) - .filter(Objects::nonNull) - .map(String::valueOf) - .forEach(tokens::add); - return tokens.stream() - .filter(StringUtils::hasText) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - private void applyProductTagTokenConditions(LambdaQueryWrapper wrapper, Set tagTokens) { - boolean appended = false; - for (String tagToken : tagTokens) { - if (!StringUtils.hasText(tagToken)) { - continue; - } - if (appended) { - wrapper.or(); - } - wrapper.apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagToken); - appended = true; - } - if (!appended) { - wrapper.apply("1 = 0"); - } - } - - /** - * Purpose: listSubmittedReviews loads privacy-safe submitted review rows for the shop. - * Usage: only status=1 reviews should feed public trust display. - */ - private List listSubmittedReviews(Long shopId, int limit) { - return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) - .eq(OrderArtistReviewDO::getShopId, shopId) - .eq(OrderArtistReviewDO::getStatus, 1) - .eq(OrderArtistReviewDO::getIsDelete, 0) - .orderByDesc(OrderArtistReviewDO::getSubmittedAt) - .orderByDesc(OrderArtistReviewDO::getCreateTime) - .last("LIMIT " + Math.max(1, limit))) - .stream() - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - /** - * Purpose: countSubmittedReviews counts reviews that are visible in public shop trust sections. - * Usage: render it beside average rating so customers can judge sample size. - */ - private long countSubmittedReviews(Long shopId) { - Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) - .eq(OrderArtistReviewDO::getShopId, shopId) - .eq(OrderArtistReviewDO::getStatus, 1) - .eq(OrderArtistReviewDO::getIsDelete, 0)); - return count == null ? 0L : count; - } - - /** - * Purpose: calculateAverageRating derives the public average rating for a shop. - * Usage: use submitted reviews only and return zero when no rating exists. - */ - private BigDecimal calculateAverageRating(Long shopId) { - List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) - .eq(OrderArtistReviewDO::getShopId, shopId) - .eq(OrderArtistReviewDO::getStatus, 1) - .eq(OrderArtistReviewDO::getIsDelete, 0) - .isNotNull(OrderArtistReviewDO::getRatingScore)); - if (reviews == null || reviews.isEmpty()) { - return BigDecimal.ZERO; - } - BigDecimal total = reviews.stream() - .map(OrderArtistReviewDO::getRatingScore) - .filter(Objects::nonNull) - .reduce(BigDecimal.ZERO, BigDecimal::add); - long count = reviews.stream().map(OrderArtistReviewDO::getRatingScore).filter(Objects::nonNull).count(); - if (count == 0) { - return BigDecimal.ZERO; - } - return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); - } - - /** - * Purpose: buildFeaturedProduct converts a product row into a compact trust card. - * Usage: keep this card small and do not include unpublished product internals. - */ - private ShopTrustProfileVO.FeaturedProduct buildFeaturedProduct(ProductDO product, Map fileMap) { - ShopTrustProfileVO.FeaturedProduct featured = new ShopTrustProfileVO.FeaturedProduct(); - featured.setId(product.getId()); - featured.setTitle(product.getTitle()); - featured.setPrice(product.getPrice()); - featured.setLikeCount(product.getLikeCount() == null ? 0 : product.getLikeCount()); - featured.setCollectCount(product.getCollectCount() == null ? 0 : product.getCollectCount()); - int artistCount = countBookableArtists(product.getBookableArtists()); - featured.setAvailableBookableArtistCount(artistCount); - featured.setBookingHint(artistCount > 0 ? artistCount + " 位美甲师可预约" : "到店后由门店安排美甲师"); - featured.setImageUrl(resolveFirstImageUrl(product.getImageFileIds(), fileMap)); - featured.setImageFileIds(product.getImageFileIds()); - return featured; - } - - /** - * Purpose: buildRecentReview converts a submitted review row into a privacy-safe card. - * Usage: never include customer phone, account, or full order identifiers here. - */ - private ShopTrustProfileVO.RecentReview buildRecentReview(OrderArtistReviewDO review, - List featuredProducts, - Map fileMap) { - ShopTrustProfileVO.RecentReview item = new ShopTrustProfileVO.RecentReview(); - item.setId(review.getId()); - item.setProductId(review.getProductId()); - item.setProductTitle(resolveProductTitle(review.getProductId(), featuredProducts)); - item.setRatingScore(review.getRatingScore()); - item.setContent(review.getContent()); - item.setSubmittedAt(review.getSubmittedAt() == null ? review.getCreateTime() : review.getSubmittedAt()); - item.setImageUrls(resolveImageUrls(parseLongIds(review.getImageFileIds(), ","), fileMap)); - return item; - } - - /** - * Purpose: buildAvailabilitySummary gives a coarse booking-readiness summary for the public page. - * Usage: clients must still rely on order creation for final schedule validation. - */ - private ShopTrustProfileVO.AvailabilitySummary buildAvailabilitySummary(ShopDO shopDO, long productCount) { - ShopTrustProfileVO.AvailabilitySummary summary = new ShopTrustProfileVO.AvailabilitySummary(); - boolean active = Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) && productCount > 0; - summary.setAvailable(active); - if (!Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus()))) { - summary.setSummaryText("门店暂不可预约"); - } else if (productCount <= 0) { - summary.setSummaryText("暂无可预约作品"); - } else { - summary.setSummaryText("当前有 " + productCount + " 个作品可预约,提交订单前会再次校验档期"); - summary.setNextSlots(buildCoarseSlotHints(shopDO.getBusinessHours())); - } - return summary; - } - - /** - * Purpose: buildContactSummary documents the explicit contact flow without public phone leakage. - * Usage: tests assert phoneExposed is false for the public trust endpoint. - */ - private ShopTrustProfileVO.ContactSummary buildContactSummary() { - ShopTrustProfileVO.ContactSummary contact = new ShopTrustProfileVO.ContactSummary(); - contact.setActionText("点击联系店长后获取联系方式"); - contact.setPhoneExposed(false); - contact.setPhone(null); - return contact; - } - - /** - * Purpose: buildCoarseSlotHints creates simple near-term booking hints from business hours. - * Usage: render these as guidance only, not as guaranteed appointment slots. - */ - private List buildCoarseSlotHints(String businessHours) { - String hours = StringUtils.hasText(businessHours) ? businessHours.trim() : "营业时间内"; - List hints = new ArrayList<>(); - hints.add("今天 " + hours); - hints.add("明天 " + hours); - hints.add("后天 " + hours); - return hints; - } - - /** - * Purpose: fileIdsForShop returns cover and environment image ids in display order. - * Usage: resolve these ids into environment image URLs for shop detail pages. - */ - private List fileIdsForShop(ShopDO shopDO) { - List ids = new ArrayList<>(); - ids.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); - ids.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); - return ids; - } - - /** - * Purpose: resolveFirstImageUrl returns the first available image URL from a delimited file id string. - * Usage: use it for compact product cards where only one thumbnail is needed. - */ - private String resolveFirstImageUrl(String fileIds, Map fileMap) { - return resolveImageUrls(parseLongIds(fileIds, ","), fileMap).stream().findFirst().orElse(null); - } - - /** - * Purpose: resolveImageUrls maps file ids to public URLs while preserving order. - * Usage: call it for shop environment, product thumbnails, and review thumbnails. - */ - private List resolveImageUrls(List fileIds, Map fileMap) { - if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { - return Collections.emptyList(); - } - List urls = new ArrayList<>(); - for (Long fileId : fileIds) { - ObjectStorageFileVO file = fileMap.get(fileId); - if (file != null && StringUtils.hasText(file.getFileUrl())) { - urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); - } - } - return urls; - } - - /** - * Purpose: resolveProductTitle returns the title for a reviewed product. - * Usage: prefer already-loaded featured products and fall back to one product lookup. - */ - private String resolveProductTitle(Long productId, List featuredProducts) { - if (productId == null) { - return null; - } - for (ProductDO product : featuredProducts) { - if (product != null && productId.equals(product.getId())) { - return product.getTitle(); - } - } - ProductDO product = productMapper.selectById(productId); - return product == null || Integer.valueOf(1).equals(product.getIsDelete()) ? null : product.getTitle(); - } - - /** - * Purpose: parseLongIds parses comma or semicolon separated numeric ids. - * Usage: feed image/product/tag id strings into batch lookup helpers. - */ - private List parseLongIds(String value, String delimiter) { - if (!StringUtils.hasText(value)) { - return Collections.emptyList(); - } - List ids = new ArrayList<>(); - String regex = ",".equals(delimiter) ? "[,;]" : delimiter; - for (String part : value.split(regex)) { - if (!StringUtils.hasText(part)) { - continue; - } - try { - ids.add(Long.parseLong(part.trim())); - } catch (NumberFormatException ignored) { - // Ignore dirty historical file id fragments instead of failing the public shop page. - } - } - return ids; - } - - /** - * Purpose: countBookableArtists counts the configured artist ids for a product. - * Usage: render a compact availability hint without validating live schedules. - */ - private int countBookableArtists(String bookableArtists) { - if (!StringUtils.hasText(bookableArtists)) { - return 0; - } - return (int) parseLongIds(bookableArtists, ",").stream().distinct().count(); - } - - /** - * 将 DO 转换为 VO - * - * @param shopDO 店铺DO - * @return 店铺VO - */ - private ShopVO convertToVO(ShopDO shopDO) { - ShopVO shopVO = new ShopVO(); - shopVO.setId(shopDO.getId()); - shopVO.setShopName(shopDO.getShopName()); - shopVO.setDescription(shopDO.getDescription()); - shopVO.setAddress(shopDO.getAddress()); - shopVO.setMapProvider(mapService.normalizeProvider(shopDO.getMapProvider())); - shopVO.setLongitude(shopDO.getLongitude()); - shopVO.setLatitude(shopDO.getLatitude()); - shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); - shopVO.setBusinessHours(shopDO.getBusinessHours()); - shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); - shopVO.setCoverImageUrls(new java.util.ArrayList<>()); - shopVO.setImageFileIds(shopDO.getImageFileIds()); - shopVO.setImageUrls(new java.util.ArrayList<>()); - shopVO.setThemePrimaryColor(shopDO.getThemePrimaryColor()); - shopVO.setThemeSecondaryColor(shopDO.getThemeSecondaryColor()); - shopVO.setThemeAccentColor(shopDO.getThemeAccentColor()); - shopVO.setThemePageBgColor(shopDO.getThemePageBgColor()); - shopVO.setThemeCardBgColor(shopDO.getThemeCardBgColor()); - shopVO.setThemeBackgroundImageFileId(shopDO.getThemeBackgroundImageFileId()); - shopVO.setStatus(normalizeStatus(shopDO.getStatus())); - shopVO.setAuthorizationStartDate(shopDO.getAuthorizationStartDate()); - shopVO.setAuthorizationDays(shopDO.getAuthorizationDays()); - shopVO.setAuthorizationExpireTime(shopDO.getAuthorizationExpireTime()); - boolean expired = isAuthorizationExpired(shopDO); - shopVO.setAuthorizationExpired(expired); - shopVO.setAuthorizationStatusText(expired ? "已到期" : "有效"); - shopVO.setCreateTime(shopDO.getCreateTime()); - shopVO.setUpdateTime(shopDO.getUpdateTime()); - return shopVO; - } - - @Override - /** - * Run business method `isAuthorizationExpired`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean isAuthorizationExpired(Long shopId) { - if (shopId == null || shopId <= 0) { - return false; - } - return isAuthorizationExpired(shopMapper.selectById(shopId)); - } - - @Override - /** - * Run business method `isFrontendAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean isFrontendAvailable(Long shopId) { - if (shopId == null || shopId <= 0) { - return false; - } - ShopDO shopDO = shopMapper.selectById(shopId); - return shopDO != null - && !Integer.valueOf(1).equals(shopDO.getIsDelete()) - && Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) - && isAuthorizationValid(shopDO); - } - - /** - * Run business method `isAuthorizationValid`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopDO parameter `shopDO` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isAuthorizationValid(ShopDO shopDO) { - return !isAuthorizationExpired(shopDO); - } - - /** - * Run business method `isAuthorizationExpired`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopDO parameter `shopDO` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isAuthorizationExpired(ShopDO shopDO) { - return shopDO != null - && shopDO.getAuthorizationExpireTime() != null - && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); - } - - /** - * Run business method `normalizeStatus`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param status parameter `status` supplied by the caller - * @return private Integer result consumed by the caller or returned to the frontend - */ - private Integer normalizeStatus(Integer status) { - return Integer.valueOf(0).equals(status) ? 0 : 1; - } - - /** - * Purpose: applyAuthorization supports ShopServiceImpl.java by holding or executing the apply authorization business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void applyAuthorization(ShopDO shopDO, ShopDTO shopDTO) { - LocalDate startDate = shopDTO.getAuthorizationStartDate(); - Integer days = shopDTO.getAuthorizationDays(); - shopDO.setAuthorizationStartDate(startDate); - shopDO.setAuthorizationDays(days); - if (startDate != null && days != null && days > 0) { - shopDO.setAuthorizationExpireTime(startDate.plusDays(days - 1L).atTime(23, 59, 59)); - return; - } - shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime()); - } - - /** - * Purpose: applyTheme supports ShopServiceImpl.java by holding or executing the apply theme business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void applyTheme(ShopDO shopDO, ShopDTO shopDTO) { - shopDO.setThemePrimaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePrimaryColor(), "themePrimaryColor")); - shopDO.setThemeSecondaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeSecondaryColor(), "themeSecondaryColor")); - shopDO.setThemeAccentColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeAccentColor(), "themeAccentColor")); - shopDO.setThemePageBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePageBgColor(), "themePageBgColor")); - shopDO.setThemeCardBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeCardBgColor(), "themeCardBgColor")); - shopDO.setThemeBackgroundImageFileId(StringUtils.hasText(shopDTO.getThemeBackgroundImageFileId()) - ? shopDTO.getThemeBackgroundImageFileId().trim() - : null); - } - - /** - * Run business method `evictShopCaches`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void evictShopCaches(Long shopId) { - if (shopId != null) { - multiLevelCacheService.evict(SHOP_DETAIL_CACHE_PREFIX + shopId); - } - multiLevelCacheService.evictByPrefix(SHOP_LIST_CACHE_PREFIX); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/support/ShopThemeSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/support/ShopThemeSupport.java deleted file mode 100644 index ba9ebb6f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/support/ShopThemeSupport.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.support; - -import org.springframework.util.StringUtils; - -import java.util.Locale; -import java.util.regex.Pattern; - -/** - * Purpose: ShopThemeSupport supports ShopThemeSupport.java by holding or executing the shop theme support business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public final class ShopThemeSupport { - private static final Pattern HEX_COLOR = Pattern.compile("^#[0-9a-fA-F]{6}$"); - - private ShopThemeSupport() { - } - - /** - * Purpose: normalizeColor supports ShopThemeSupport.java by holding or executing the normalize color business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static String normalizeColor(String color, String fieldName) { - if (!StringUtils.hasText(color)) { - return null; - } - String value = color.trim(); - if (!HEX_COLOR.matcher(value).matches()) { - throw new IllegalArgumentException(fieldName + " must be a #RRGGBB color"); - } - return value.toUpperCase(Locale.ROOT); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/support/UserShopBindingSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/support/UserShopBindingSupport.java deleted file mode 100644 index 599566d0..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/support/UserShopBindingSupport.java +++ /dev/null @@ -1,635 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.support; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDateTime; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * 用户-店铺绑定关系支撑类。 - */ -@Component -@RequiredArgsConstructor -public class UserShopBindingSupport { - - /** - * Purpose: userShopBindingMapper supports UserShopBindingSupport.java by holding or executing the user shop binding mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserShopBindingMapper userShopBindingMapper; - /** - * Purpose: shopMapper supports UserShopBindingSupport.java by holding or executing the shop mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final ShopMapper shopMapper; - /** - * Purpose: userMapper supports UserShopBindingSupport.java by holding or executing the user mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserMapper userMapper; - - /** - * Purpose: listBindingsByUserId supports UserShopBindingSupport.java by holding or executing the list bindings by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listBindingsByUserId(Long userId, boolean includeDeleted) { - if (userId == null) { - return List.of(); - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .orderByAsc(UserShopBindingDO::getCreateTime) - .orderByAsc(UserShopBindingDO::getId); - if (!includeDeleted) { - wrapper.eq(UserShopBindingDO::getIsDelete, 0); - } - return userShopBindingMapper.selectList(wrapper); - } - - /** - * Purpose: hasBindingHistory supports UserShopBindingSupport.java by holding or executing the has binding history business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean hasBindingHistory(Long userId) { - if (userId == null) { - return false; - } - return userShopBindingMapper.selectCount(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId)) > 0; - } - - /** - * Purpose: listActiveBindingsByUserId supports UserShopBindingSupport.java by holding or executing the list active bindings by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listActiveBindingsByUserId(Long userId) { - return listBindingsByUserId(userId, false).stream() - .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) - .filter(binding -> isShopActive(binding.getShopId())) - .sorted(Comparator.comparing(UserShopBindingDO::getCreateTime, Comparator.nullsLast(LocalDateTime::compareTo)) - .thenComparing(UserShopBindingDO::getId, Comparator.nullsLast(Long::compareTo))) - .collect(Collectors.toList()); - } - - /** - * Purpose: listActiveShopIdsByUserId supports UserShopBindingSupport.java by holding or executing the list active shop ids by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listActiveShopIdsByUserId(Long userId) { - return listShopIdsByUserId(userId, true, true); - } - - /** - * Purpose: listActiveShopOptionsByUserId supports UserShopBindingSupport.java by holding or executing the list active shop options by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listActiveShopOptionsByUserId(Long userId) { - return listShopOptionsByUserId(userId, true, true); - } - - /** - * Purpose: listAllActiveShopOptions supports UserShopBindingSupport.java by holding or executing the list all active shop options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listAllActiveShopOptions() { - return toShopOptions(fetchAllShopMap(true)); - } - - /** - * Purpose: listShopIdsByUserId supports UserShopBindingSupport.java by holding or executing the list shop ids by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listShopIdsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) { - return listShopOptionsByUserId(userId, onlyActiveBindings, onlyActiveShops).stream() - .map(ShopSimpleVO::getId) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - /** - * Purpose: listShopOptionsByUserId supports UserShopBindingSupport.java by holding or executing the list shop options by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listShopOptionsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) { - return listShopOptionsByUserIds(List.of(userId), onlyActiveBindings, onlyActiveShops) - .getOrDefault(userId, List.of()); - } - - /** - * Purpose: hasActiveBinding supports UserShopBindingSupport.java by holding or executing the has active binding business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean hasActiveBinding(Long userId, Long shopId) { - if (userId == null || shopId == null || shopId <= 0) { - return false; - } - return listActiveBindingsByUserId(userId).stream() - .anyMatch(binding -> shopId.equals(binding.getShopId())); - } - - /** - * Purpose: hasBindingInShop supports UserShopBindingSupport.java by holding or executing the has binding in shop business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean hasBindingInShop(Long userId, Long shopId) { - if (userId == null || shopId == null || shopId <= 0) { - return false; - } - return userShopBindingMapper.selectCount(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0)) > 0; - } - - /** - * Purpose: isShopActive supports UserShopBindingSupport.java by holding or executing the is shop active business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isShopActive(Long shopId) { - return isShopEnabledIgnoringAuthorization(shopId) && !isShopAuthorizationExpired(shopId); - } - - /** - * Purpose: isShopEnabledIgnoringAuthorization supports UserShopBindingSupport.java by holding or executing the is shop enabled ignoring authorization business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isShopEnabledIgnoringAuthorization(Long shopId) { - if (shopId == null || shopId <= 0) { - return false; - } - ShopDO shopDO = shopMapper.selectById(shopId); - return shopDO != null - && !Integer.valueOf(1).equals(shopDO.getIsDelete()) - && Integer.valueOf(1).equals(normalizeShopStatus(shopDO.getStatus())); - } - - /** - * Purpose: isShopAuthorizationExpired supports UserShopBindingSupport.java by holding or executing the is shop authorization expired business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isShopAuthorizationExpired(Long shopId) { - if (shopId == null || shopId <= 0) { - return false; - } - ShopDO shopDO = shopMapper.selectById(shopId); - return shopDO != null - && shopDO.getAuthorizationExpireTime() != null - && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); - } - - /** - * Purpose: pickPrimaryShopId supports UserShopBindingSupport.java by holding or executing the pick primary shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Long pickPrimaryShopId(Long userId) { - return listActiveBindingsByUserId(userId).stream() - .map(UserShopBindingDO::getShopId) - .findFirst() - .orElse(null); - } - - /** - * Purpose: listActiveShopOptionsByUserIds supports UserShopBindingSupport.java by holding or executing the list active shop options by user ids business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Map> listActiveShopOptionsByUserIds(Collection userIds) { - return listShopOptionsByUserIds(userIds, true, true); - } - - public Map> listShopOptionsByUserIds( - Collection userIds, - boolean onlyActiveBindings, - boolean onlyActiveShops - ) { - if (userIds == null || userIds.isEmpty()) { - return Collections.emptyMap(); - } - List normalizedUserIds = userIds.stream() - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - if (normalizedUserIds.isEmpty()) { - return Collections.emptyMap(); - } - - List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() - .in(UserShopBindingDO::getUserId, normalizedUserIds) - .eq(UserShopBindingDO::getIsDelete, 0) - .orderByAsc(UserShopBindingDO::getCreateTime) - .orderByAsc(UserShopBindingDO::getId)); - if (bindings.isEmpty()) { - return Collections.emptyMap(); - } - - if (onlyActiveBindings) { - bindings = bindings.stream() - .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) - .collect(Collectors.toList()); - if (bindings.isEmpty()) { - return Collections.emptyMap(); - } - } - - Map shopMap = fetchShopMap(bindings.stream() - .map(UserShopBindingDO::getShopId) - .collect(Collectors.toSet()), onlyActiveShops); - Map> result = new LinkedHashMap<>(); - for (UserShopBindingDO binding : bindings) { - ShopDO shopDO = shopMap.get(binding.getShopId()); - if (shopDO == null) { - continue; - } - result.computeIfAbsent(binding.getUserId(), key -> new java.util.ArrayList<>()) - .add(new ShopSimpleVO(shopDO.getId(), shopDO.getShopName())); - } - return result; - } - - /** - * Purpose: listUserIdsByShopId supports UserShopBindingSupport.java by holding or executing the list user ids by shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listUserIdsByShopId(Long shopId, boolean onlyActiveBindings) { - if (shopId == null || shopId <= 0) { - return List.of(); - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0); - if (onlyActiveBindings) { - wrapper.eq(UserShopBindingDO::getStatus, 1); - } - return userShopBindingMapper.selectList(wrapper).stream() - .map(UserShopBindingDO::getUserId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - } - - /** - * Purpose: countUsersByShopId supports UserShopBindingSupport.java by holding or executing the count users by shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public long countUsersByShopId(Long shopId, boolean onlyActiveBindings) { - return listUserIdsByShopId(shopId, onlyActiveBindings).size(); - } - - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: ensureUserBoundToShop supports UserShopBindingSupport.java by holding or executing the ensure user bound to shop business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void ensureUserBoundToShop(Long userId, Long shopId) { - if (userId == null || shopId == null || shopId <= 0) { - throw new RuntimeException("店铺绑定信息不完整"); - } - if (!isShopActive(shopId)) { - throw new RuntimeException("所选店铺不存在或已停用"); - } - - UserShopBindingDO existing = userShopBindingMapper.selectOne(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .last("limit 1")); - if (existing == null) { - UserShopBindingDO binding = new UserShopBindingDO(); - binding.setUserId(userId); - binding.setShopId(shopId); - binding.setStatus(1); - binding.setIsDelete(0); - userShopBindingMapper.insert(binding); - refreshLegacyPrimaryShop(userId); - return; - } - - existing.setStatus(1); - existing.setIsDelete(0); - existing.setUpdateTime(LocalDateTime.now()); - userShopBindingMapper.updateById(existing); - refreshLegacyPrimaryShop(userId); - } - - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: syncUserShopBindings supports UserShopBindingSupport.java by holding or executing the sync user shop bindings business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void syncUserShopBindings(Long userId, Collection shopIds) { - if (userId == null) { - return; - } - - Set desiredShopIds = normalizeActiveShopIds(shopIds); - List existingBindings = listBindingsByUserId(userId, true); - Map bindingMap = existingBindings.stream() - .filter(binding -> binding.getShopId() != null) - .collect(Collectors.toMap(UserShopBindingDO::getShopId, binding -> binding, (left, right) -> right, LinkedHashMap::new)); - - for (Long shopId : desiredShopIds) { - UserShopBindingDO existing = bindingMap.remove(shopId); - if (existing == null) { - UserShopBindingDO binding = new UserShopBindingDO(); - binding.setUserId(userId); - binding.setShopId(shopId); - binding.setStatus(1); - binding.setIsDelete(0); - userShopBindingMapper.insert(binding); - continue; - } - existing.setStatus(1); - existing.setIsDelete(0); - existing.setUpdateTime(LocalDateTime.now()); - userShopBindingMapper.updateById(existing); - } - - for (UserShopBindingDO staleBinding : bindingMap.values()) { - staleBinding.setIsDelete(1); - staleBinding.setUpdateTime(LocalDateTime.now()); - userShopBindingMapper.updateById(staleBinding); - } - - refreshLegacyPrimaryShop(userId); - } - - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: updateBindingStatus supports UserShopBindingSupport.java by holding or executing the update binding status business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean updateBindingStatus(Long userId, Long shopId, Integer status) { - if (userId == null || shopId == null || shopId <= 0) { - return false; - } - long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0)); - if (bindingCount <= 0) { - return false; - } - Integer normalizedStatus = Integer.valueOf(1).equals(status) ? 1 : 0; - LocalDateTime now = LocalDateTime.now(); - int updated = userShopBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0) - .set(UserShopBindingDO::getStatus, normalizedStatus) - .set(UserShopBindingDO::getUpdateTime, now) - ); - refreshLegacyPrimaryShop(userId); - return updated > 0; - } - - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: deleteBinding supports UserShopBindingSupport.java by holding or executing the delete binding business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean deleteBinding(Long userId, Long shopId) { - if (userId == null || shopId == null || shopId <= 0) { - return false; - } - long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0)); - if (bindingCount <= 0) { - return false; - } - LocalDateTime now = LocalDateTime.now(); - int updated = userShopBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0) - .set(UserShopBindingDO::getIsDelete, 1) - .set(UserShopBindingDO::getUpdateTime, now) - ); - refreshLegacyPrimaryShop(userId); - return updated > 0; - } - - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: deleteBindingsByShopId supports UserShopBindingSupport.java by holding or executing the delete bindings by shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void deleteBindingsByShopId(Long shopId) { - if (shopId == null || shopId <= 0) { - return; - } - List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0)); - if (bindings.isEmpty()) { - return; - } - Set affectedUserIds = new LinkedHashSet<>(); - for (UserShopBindingDO binding : bindings) { - affectedUserIds.add(binding.getUserId()); - } - LocalDateTime now = LocalDateTime.now(); - userShopBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserShopBindingDO::getShopId, shopId) - .eq(UserShopBindingDO::getIsDelete, 0) - .set(UserShopBindingDO::getIsDelete, 1) - .set(UserShopBindingDO::getUpdateTime, now) - ); - affectedUserIds.forEach(this::refreshLegacyPrimaryShop); - } - - /** - * Purpose: canUserAccessShop supports UserShopBindingSupport.java by holding or executing the can user access shop business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean canUserAccessShop(Long userId, Long shopId, boolean adminLogin, Integer userType) { - if (Integer.valueOf(4).equals(userType)) { - if (shopId == null || shopId <= 0) { - return Boolean.TRUE.equals(adminLogin); - } - return isShopSelectableForPlatformAdmin(shopId); - } - if (shopId == null || shopId <= 0) { - return false; - } - if (Boolean.TRUE.equals(adminLogin)) { - if (!isShopEnabledIgnoringAuthorization(shopId)) { - return false; - } - } else if (!isShopActive(shopId)) { - return false; - } - return hasActiveBinding(userId, shopId); - } - - /** - * Purpose: isShopSelectableForPlatformAdmin supports UserShopBindingSupport.java by holding or executing the is shop selectable for platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isShopSelectableForPlatformAdmin(Long shopId) { - if (shopId == null || shopId <= 0) { - return false; - } - ShopDO shopDO = shopMapper.selectById(shopId); - return shopDO != null - && !Integer.valueOf(1).equals(shopDO.getIsDelete()) - && (shopDO.getAuthorizationExpireTime() == null - || !shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now())); - } - - /** - * Purpose: isUserAccessibleInShop supports UserShopBindingSupport.java by holding or executing the is user accessible in shop business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isUserAccessibleInShop(Long userId, Long shopId) { - return hasActiveBinding(userId, shopId); - } - - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: deleteBindingsByUserId supports UserShopBindingSupport.java by holding or executing the delete bindings by user id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void deleteBindingsByUserId(Long userId) { - if (userId == null) { - return; - } - LocalDateTime now = LocalDateTime.now(); - userShopBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserShopBindingDO::getUserId, userId) - .eq(UserShopBindingDO::getIsDelete, 0) - .set(UserShopBindingDO::getIsDelete, 1) - .set(UserShopBindingDO::getUpdateTime, now) - ); - refreshLegacyPrimaryShop(userId); - } - - /** - * Purpose: normalizeActiveShopIds supports UserShopBindingSupport.java by holding or executing the normalize active shop ids business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Set normalizeActiveShopIds(Collection shopIds) { - if (shopIds == null || shopIds.isEmpty()) { - return Collections.emptySet(); - } - Set normalizedShopIds = new LinkedHashSet<>(); - for (Long shopId : shopIds) { - if (shopId == null || shopId <= 0) { - continue; - } - if (!isShopActive(shopId)) { - throw new RuntimeException("所选店铺不存在或已停用"); - } - normalizedShopIds.add(shopId); - } - return normalizedShopIds; - } - - /** - * Purpose: refreshLegacyPrimaryShop supports UserShopBindingSupport.java by holding or executing the refresh legacy primary shop business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void refreshLegacyPrimaryShop(Long userId) { - if (userId == null) { - return; - } - UserDO userDO = userMapper.selectById(userId); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return; - } - Long primaryShopId = pickPrimaryShopId(userId); - if (Objects.equals(userDO.getShopId(), primaryShopId)) { - return; - } - LocalDateTime now = LocalDateTime.now(); - userMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserDO::getId, userId) - .set(UserDO::getShopId, primaryShopId) - .set(UserDO::getUpdateTime, now) - ); - } - - /** - * Purpose: fetchAllShopMap supports UserShopBindingSupport.java by holding or executing the fetch all shop map business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map fetchAllShopMap(boolean onlyActiveShops) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(ShopDO::getIsDelete, 0); - if (onlyActiveShops) { - wrapper.eq(ShopDO::getStatus, 1); - } - return shopMapper.selectList(wrapper).stream() - .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) - .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); - } - - /** - * Purpose: fetchShopMap supports UserShopBindingSupport.java by holding or executing the fetch shop map business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map fetchShopMap(Collection shopIds, boolean onlyActiveShops) { - if (shopIds == null || shopIds.isEmpty()) { - return Collections.emptyMap(); - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .in(ShopDO::getId, shopIds) - .eq(ShopDO::getIsDelete, 0); - if (onlyActiveShops) { - wrapper.eq(ShopDO::getStatus, 1); - } - return shopMapper.selectList(wrapper) - .stream() - .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) - .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); - } - - /** - * Purpose: toShopOptions supports UserShopBindingSupport.java by holding or executing the to shop options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List toShopOptions(Map shopMap) { - return shopMap.values().stream() - .sorted(Comparator.comparing(ShopDO::getShopName, Comparator.nullsLast(String::compareTo)) - .thenComparing(ShopDO::getId, Comparator.nullsLast(Long::compareTo))) - .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) - .collect(Collectors.toList()); - } - - /** - * Purpose: normalizeShopStatus supports UserShopBindingSupport.java by holding or executing the normalize shop status business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer normalizeShopStatus(Integer status) { - return status == null ? 1 : status; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ContactInfoVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ContactInfoVO.java deleted file mode 100644 index 9d28fdaf..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ContactInfoVO.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.vo; - -import lombok.Data; - -@Data -/** - * ContactInfoVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ContactInfoVO { - /** - * Field `contactUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long contactUserId; - /** - * Field `contactName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String contactName; - /** - * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String roleLabel; - /** - * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String phone; - /** - * Field `phoneAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean phoneAvailable; - /** - * Field `wechatId` (String): contact WeChat ID for quick copy/open actions. - */ - private String wechatId; - /** - * Field `wechatAvailable` (Boolean): whether the contact exposes a WeChat ID. - */ - private Boolean wechatAvailable; - /** - * Field `wechatQrCode` (String): accessible WeChat QR code image URL. - */ - private String wechatQrCode; - /** - * Field `platformContactAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean platformContactAvailable; - /** - * Field `platformContactText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String platformContactText; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopSimpleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopSimpleVO.java deleted file mode 100644 index 82e44607..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopSimpleVO.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -/** - * ShopSimpleVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class ShopSimpleVO { - - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopTrustProfileVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopTrustProfileVO.java deleted file mode 100644 index 0b0304c5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopTrustProfileVO.java +++ /dev/null @@ -1,290 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -/** - * Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page. - * Usage: return this VO from /shop/trust-profile/{shopId}; clients render it without exposing phone numbers. - */ -@Data -public class ShopTrustProfileVO { - /** - * Purpose: shopId identifies the shop whose trust profile is being rendered. - * Usage: clients use it to keep the profile matched to the visible shop. - */ - private Long shopId; - - /** - * Purpose: shopName gives the profile a stable display label. - * Usage: render it in accessibility labels or fallback section titles. - */ - private String shopName; - - /** - * Purpose: businessHoursText describes when the shop says it is open. - * Usage: show it near booking and navigation actions. - */ - private String businessHoursText; - - /** - * Purpose: businessStatusText summarizes whether the shop can currently be viewed and booked. - * Usage: display this short text in trust summary chips. - */ - private String businessStatusText; - - /** - * Purpose: locationAvailable reports whether map coordinates exist. - * Usage: hide navigation/distance affordances when false. - */ - private Boolean locationAvailable; - - /** - * Purpose: distanceCapabilityText explains whether distance can be calculated on the client. - * Usage: show this text until the client has user location permission. - */ - private String distanceCapabilityText; - - /** - * Purpose: navigationAvailable reports whether navigation URLs can be offered. - * Usage: clients use it to enable map buttons. - */ - private Boolean navigationAvailable; - - /** - * Purpose: stats contains public aggregate numbers for customer confidence. - * Usage: render as compact metrics on the shop detail page. - */ - private Stats stats = new Stats(); - - /** - * Purpose: environmentImages contains public shop environment image URLs. - * Usage: render thumbnails or a carousel; it must not include contact data. - */ - private List environmentImages = new ArrayList<>(); - - /** - * Purpose: featuredProducts lists representative products from this shop. - * Usage: render as quick inspection or booking entry cards. - */ - private List featuredProducts = new ArrayList<>(); - - /** - * Purpose: recentReviews lists recent submitted reviews only. - * Usage: show social proof while keeping customer identity private. - */ - private List recentReviews = new ArrayList<>(); - - /** - * Purpose: availabilitySummary gives a safe booking summary without reserving slots. - * Usage: render it near booking actions and keep final conflict checks in order creation. - */ - private AvailabilitySummary availabilitySummary = new AvailabilitySummary(); - - /** - * Purpose: contactSummary tells clients how to request contact details without exposing phone data. - * Usage: render the action hint and fetch phone only through the explicit contact endpoint. - */ - private ContactSummary contactSummary = new ContactSummary(); - - /** - * Purpose: Stats groups aggregate shop trust metrics. - * Usage: serialize inside ShopTrustProfileVO.stats for frontend summary cards. - */ - @Data - public static class Stats { - /** - * Purpose: averageRating is the submitted-review average for this shop. - * Usage: display with one decimal place when reviewCount is greater than zero. - */ - private BigDecimal averageRating = BigDecimal.ZERO; - - /** - * Purpose: reviewCount is the number of submitted, public reviews. - * Usage: render beside averageRating to avoid showing score without sample size. - */ - private Long reviewCount = 0L; - - /** - * Purpose: productCount is the number of active products in this shop. - * Usage: render as a confidence signal and empty-state condition. - */ - private Long productCount = 0L; - - /** - * Purpose: artistCount is the number of active nail artist users bound to this shop. - * Usage: render as the staff confidence signal on shop detail pages. - */ - private Long artistCount = 0L; - - /** - * Purpose: recentReviewCount is the number of review cards included in this response. - * Usage: clients use it for section labels and empty states. - */ - private Integer recentReviewCount = 0; - } - - /** - * Purpose: FeaturedProduct is a compact public product card for shop trust display. - * Usage: render these cards on shop detail pages without fetching full product detail first. - */ - @Data - public static class FeaturedProduct { - /** - * Purpose: id identifies the product for detail navigation. - * Usage: pass it to product detail routes when the customer taps the card. - */ - private Long id; - - /** - * Purpose: title names the featured product. - * Usage: render as the card title. - */ - private String title; - - /** - * Purpose: imageUrl provides the first public product image. - * Usage: render as a thumbnail and fall back gracefully when blank. - */ - private String imageUrl; - - /** - * Purpose: imageFileIds provides product image file ids for clients that need signed image URLs. - * Usage: clients may resolve the first id into a stable thumbnail URL. - */ - private String imageFileIds; - - /** - * Purpose: price carries the current product price. - * Usage: show it as a current quote, not as historical order price. - */ - private BigDecimal price; - - /** - * Purpose: likeCount is the current like count. - * Usage: render as a lightweight popularity signal. - */ - private Integer likeCount; - - /** - * Purpose: collectCount is the current wishlist count. - * Usage: render as a lightweight popularity signal. - */ - private Integer collectCount; - - /** - * Purpose: availableBookableArtistCount tells whether this product has available artists configured. - * Usage: show concise booking hints without exposing artist schedules. - */ - private Integer availableBookableArtistCount; - - /** - * Purpose: bookingHint is a customer-facing availability hint for this product. - * Usage: display below the product title. - */ - private String bookingHint; - } - - /** - * Purpose: RecentReview is a privacy-safe submitted review summary. - * Usage: render public review snippets without customer account or phone fields. - */ - @Data - public static class RecentReview { - /** - * Purpose: id identifies the review row. - * Usage: use it as a frontend list key. - */ - private Long id; - - /** - * Purpose: productId links the review to the reviewed product. - * Usage: optionally navigate to the product detail page. - */ - private Long productId; - - /** - * Purpose: productTitle names the product reviewed. - * Usage: display as context for the review. - */ - private String productTitle; - - /** - * Purpose: ratingScore is the submitted rating. - * Usage: render with one decimal place. - */ - private BigDecimal ratingScore; - - /** - * Purpose: content stores the submitted review text. - * Usage: display a short snippet and hide the section when blank if desired. - */ - private String content; - - /** - * Purpose: imageUrls contains public review image URLs. - * Usage: render thumbnails without exposing customer identity. - */ - private List imageUrls = new ArrayList<>(); - - /** - * Purpose: submittedAt records when the review was submitted. - * Usage: render relative or formatted review time. - */ - private LocalDateTime submittedAt; - } - - /** - * Purpose: AvailabilitySummary summarizes booking readiness for the shop. - * Usage: clients render it as guidance while final validation remains server-side on order creation. - */ - @Data - public static class AvailabilitySummary { - /** - * Purpose: available states whether the shop currently has active products to book. - * Usage: enable or soften booking entry copy. - */ - private Boolean available = false; - - /** - * Purpose: summaryText gives the customer a direct booking-readiness sentence. - * Usage: render as the availability card body. - */ - private String summaryText = "暂无可预约作品"; - - /** - * Purpose: nextSlots gives coarse upcoming booking hints when available. - * Usage: render as chips; clients must not treat these as reserved slots. - */ - private List nextSlots = new ArrayList<>(); - } - - /** - * Purpose: ContactSummary describes the explicit contact action without leaking phone data. - * Usage: render the action label and call contact-info only after the user taps contact. - */ - @Data - public static class ContactSummary { - /** - * Purpose: actionText is the label for the explicit contact action. - * Usage: render on the contact button or helper text. - */ - private String actionText = "点击联系店长后获取联系方式"; - - /** - * Purpose: phoneExposed records whether this public profile includes phone data. - * Usage: assert false in tests and use contact-info endpoint for phone data. - */ - private Boolean phoneExposed = false; - - /** - * Purpose: phone is intentionally null in this public profile. - * Usage: clients must ignore it and call the explicit contact endpoint instead. - */ - private String phone; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopVO.java deleted file mode 100644 index e3d42cef..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/shop/vo/ShopVO.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.shop.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Map; - -/** - * 店铺信息表 VO - * 用于前端展示店铺信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class ShopVO { - - /** - * 店铺唯一主键ID - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long id; - - /** - * 店铺名称 - */ - private String shopName; - - /** - * 店铺描述 - */ - private String description; - - /** - * 店铺地址 - */ - private String address; - - /** - * Purpose: mapProvider supports ShopVO.java by holding or executing the map provider business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String mapProvider; - - /** - * Purpose: longitude supports ShopVO.java by holding or executing the longitude business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal longitude; - - /** - * Purpose: latitude supports ShopVO.java by holding or executing the latitude business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private BigDecimal latitude; - - /** - * Purpose: navigationUrls supports ShopVO.java by holding or executing the navigation urls business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map navigationUrls; - - /** - * 店铺营业时间 - */ - private String businessHours; - - /** - * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 - */ - private String coverImageFileId; - - /** - * 店铺封面图URL列表(Banner图) - */ - private List coverImageUrls; - - /** - * 店铺图片文件ID集合,多个ID以逗号分隔 - */ - private String imageFileIds; - - /** - * 店铺图片URL列表 - */ - private List imageUrls; - - /** - * Purpose: themePrimaryColor supports ShopVO.java by holding or executing the theme primary color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themePrimaryColor; - - /** - * Purpose: themeSecondaryColor supports ShopVO.java by holding or executing the theme secondary color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeSecondaryColor; - - /** - * Purpose: themeAccentColor supports ShopVO.java by holding or executing the theme accent color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeAccentColor; - - /** - * Purpose: themePageBgColor supports ShopVO.java by holding or executing the theme page bg color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themePageBgColor; - - /** - * Purpose: themeCardBgColor supports ShopVO.java by holding or executing the theme card bg color business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeCardBgColor; - - /** - * Purpose: themeBackgroundImageFileId supports ShopVO.java by holding or executing the theme background image file id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String themeBackgroundImageFileId; - - /** - * 店铺状态:1-启用,0-停用 - */ - private Integer status; - - /** - * Purpose: authorizationStartDate supports ShopVO.java by holding or executing the authorization start date business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDate authorizationStartDate; - - /** - * Purpose: authorizationDays supports ShopVO.java by holding or executing the authorization days business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer authorizationDays; - - /** - * 店铺授权有效期;为空表示长期有效。 - */ - private LocalDateTime authorizationExpireTime; - - /** - * 当前时间是否已超过授权有效期。 - */ - private Boolean authorizationExpired; - - /** - * 给前端直接展示的授权状态文案。 - */ - private String authorizationStatusText; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/HealthController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/HealthController.java deleted file mode 100644 index e5c5ebe6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/HealthController.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.controller.front; - -import com.xiaowang.jacyucloudsalon.core.common.Result; -import lombok.RequiredArgsConstructor; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.core.env.Environment; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * 健康检查控制器 - * - * @author xiaowang - * @date 2026-02-12 - */ -@RestController -@RequestMapping("/health") -@RequiredArgsConstructor -public class HealthController { - /** - * Variable `dataSource`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final DataSource dataSource; - /** - * Variable `stringRedisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final StringRedisTemplate stringRedisTemplate; - /** - * Variable `discoveryClient`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final DiscoveryClient discoveryClient; - /** - * Variable `environment`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final Environment environment; - - /** - * 服务状态检查 - */ - @GetMapping("/check") - public Result check() { - return Result.success("JC-ArtList-Core is running"); - } - - @GetMapping("/diagnostics") - /** - * Run business method `diagnostics`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> diagnostics() { - Map diagnostics = new LinkedHashMap<>(); - diagnostics.put("service", environment.getProperty("spring.application.name", "jc-artlist-core")); - diagnostics.put("port", environment.getProperty("server.port", "")); - diagnostics.put("database", checkDatabase()); - diagnostics.put("redis", checkRedis()); - diagnostics.put("discovery", checkDiscovery()); - return Result.success(diagnostics); - } - - /** - * Run business method `checkDatabase`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map checkDatabase() { - Map result = new LinkedHashMap<>(); - try (Connection connection = dataSource.getConnection()) { - result.put("ok", connection.isValid(2)); - result.put("catalog", connection.getCatalog()); - result.put("product", connection.getMetaData().getDatabaseProductName()); - } catch (Exception exception) { - result.put("ok", false); - result.put("error", exception.getClass().getSimpleName()); - } - return result; - } - - /** - * Run business method `checkRedis`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map checkRedis() { - Map result = new LinkedHashMap<>(); - try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) { - String pong = connection.ping(); - result.put("ok", "PONG".equalsIgnoreCase(pong)); - } catch (Exception exception) { - result.put("ok", false); - result.put("error", exception.getClass().getSimpleName()); - } - return result; - } - - /** - * Run business method `checkDiscovery`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private Map result consumed by the caller or returned to the frontend - */ - private Map checkDiscovery() { - Map result = new LinkedHashMap<>(); - try { - String serviceName = environment.getProperty("spring.application.name", "jc-artlist-core"); - List instances = discoveryClient.getInstances(serviceName); - result.put("ok", !instances.isEmpty()); - result.put("service", serviceName); - result.put("instanceCount", instances.size()); - } catch (Exception exception) { - result.put("ok", false); - result.put("error", exception.getClass().getSimpleName()); - } - return result; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/LegalAgreementController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/LegalAgreementController.java deleted file mode 100644 index 59e8b17d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/LegalAgreementController.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.system.dto.LegalAgreementDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.system.service.LegalAgreementService; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.SecurityAuditLogService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestThrottleService; -import com.xiaowang.jacyucloudsalon.core.modules.system.vo.LegalAgreementVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAgreementConsentVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/legal-agreement", "/api/legal-agreement"}) -/** - * Purpose: LegalAgreementController supports LegalAgreementController.java by holding or executing the legal agreement controller business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class LegalAgreementController { - - /** - * Purpose: legalAgreementService supports LegalAgreementController.java by holding or executing the legal agreement service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final LegalAgreementService legalAgreementService; - /** - * Purpose: adminScopeHelper supports LegalAgreementController.java by holding or executing the admin scope helper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final AdminScopeHelper adminScopeHelper; - /** - * Purpose: securityAuditLogService supports LegalAgreementController.java by holding or executing the security audit log service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SecurityAuditLogService securityAuditLogService; - /** - * Purpose: requestThrottleService supports LegalAgreementController.java by holding or executing the request throttle service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final RequestThrottleService requestThrottleService; - - @GetMapping("/current") - /** - * Purpose: listCurrent supports LegalAgreementController.java by holding or executing the list current business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listCurrent(HttpServletRequest request) { - requestThrottleService.checkAgreementRead(request, "ALL"); - return Result.success(legalAgreementService.listCurrentAgreements()); - } - - @GetMapping("/current/{type}") - /** - * Purpose: getCurrent supports LegalAgreementController.java by holding or executing the get current business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result getCurrent(HttpServletRequest request, @PathVariable String type) { - requestThrottleService.checkAgreementRead(request, type); - return Result.success(legalAgreementService.getCurrentAgreement(type)); - } - - @GetMapping("/admin/list") - @RequirePermission("legal_agreement:manage") - /** - * Purpose: listAdmin supports LegalAgreementController.java by holding or executing the list admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listAdmin(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(legalAgreementService.listAdminAgreements(currentUser)); - } - - @PostMapping("/admin/create") - @RequirePermission("legal_agreement:manage") - @OperationGuard(action = "legal-agreement-create", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") - /** - * Purpose: create supports LegalAgreementController.java by holding or executing the create business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result create(HttpServletRequest request, @Valid @RequestBody LegalAgreementDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long id = legalAgreementService.createAgreement(currentUser, dto); - securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_CREATE", "SUCCESS", dto.getAgreementType(), request); - return Result.success(id); - } - - @PutMapping("/admin/{id}") - @RequirePermission("legal_agreement:manage") - @OperationGuard(action = "legal-agreement-update", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") - /** - * Purpose: update supports LegalAgreementController.java by holding or executing the update business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody LegalAgreementDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Boolean result = legalAgreementService.updateAgreement(currentUser, id, dto); - securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_UPDATE", "SUCCESS", String.valueOf(id), request); - return Result.success(result); - } - - @PutMapping("/admin/{id}/publish") - @RequirePermission("legal_agreement:manage") - @OperationGuard(action = "legal-agreement-publish", ttlSeconds = 8, message = "协议发布处理中,请勿重复提交") - /** - * Purpose: publish supports LegalAgreementController.java by holding or executing the publish business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result publish(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Boolean result = legalAgreementService.publishAgreement(currentUser, id); - securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_PUBLISH", "SUCCESS", String.valueOf(id), request); - return Result.success(result); - } - - @PutMapping("/admin/{id}/disable") - @RequirePermission("legal_agreement:manage") - @OperationGuard(action = "legal-agreement-disable", ttlSeconds = 8, message = "协议停用处理中,请勿重复提交") - /** - * Purpose: disable supports LegalAgreementController.java by holding or executing the disable business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result disable(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Boolean result = legalAgreementService.disableAgreement(currentUser, id); - securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_DISABLE", "SUCCESS", String.valueOf(id), request); - return Result.success(result); - } - - @GetMapping("/user/agreement-consent/me") - /** - * Purpose: getMyConsent supports LegalAgreementController.java by holding or executing the get my consent business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result getMyConsent(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(legalAgreementService.getMyConsent(userId)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/SystemParameterConfigController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/SystemParameterConfigController.java deleted file mode 100644 index f16a6c8b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/controller/front/SystemParameterConfigController.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.jacyucloudsalon.core.modules.system.dto.SystemParameterConfigDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.system.service.SystemParameterConfigService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.system.support.AdminDefaultPasswordSupport; -import com.xiaowang.jacyucloudsalon.core.modules.system.vo.SystemParameterConfigVO; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@RestController -@RequiredArgsConstructor -@RequestMapping({"/system-parameter-config", "/api/system-parameter-config", "/admin/system-parameter-config"}) -/** - * Purpose: SystemParameterConfigController supports SystemParameterConfigController.java by holding or executing the system parameter config controller business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SystemParameterConfigController { - - /** - * Purpose: configService supports SystemParameterConfigController.java by holding or executing the config service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SystemParameterConfigService configService; - /** - * Purpose: adminScopeHelper supports SystemParameterConfigController.java by holding or executing the admin scope helper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final AdminScopeHelper adminScopeHelper; - - @GetMapping("/admin/list") - @RequirePermission("messagehub:config:manage") - public Result> list(HttpServletRequest request, - @RequestParam(required = false) String configGroup) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.listConfigs(currentUser, configGroup)); - } - - @PostMapping("/admin/save") - @RequirePermission("messagehub:config:manage") - @OperationGuard(action = "system-parameter-config-save", ttlSeconds = 8, message = "系统参数保存处理中,请勿重复提交") - /** - * Purpose: save supports SystemParameterConfigController.java by holding or executing the save business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result save(HttpServletRequest request, @Valid @RequestBody SystemParameterConfigDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(configService.saveConfig(currentUser, dto)); - } - - @GetMapping("/admin/tencent-map") - /** - * Purpose: getTencentMapKey supports SystemParameterConfigController.java by holding or executing the get tencent map key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> getTencentMapKey(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); - return Result.success(result); - } - - @GetMapping("/admin/map-config") - /** - * Purpose: getMapConfig supports SystemParameterConfigController.java by holding or executing the get map config business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> getMapConfig(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - String provider = configService.getEnabledValue("MAP", "MAP_PROVIDER"); - result.put("provider", "AMAP".equalsIgnoreCase(provider) ? "AMAP" : "TENCENT"); - result.put("tencentWebKey", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); - result.put("amapWebKey", configService.getEnabledValue("MAP", "AMAP_WEB_KEY")); - result.put("amapMiniKey", configService.getEnabledValue("MAP", "AMAP_MINI_KEY")); - return Result.success(result); - } - - @GetMapping("/admin/user-default-password") - @RequirePermission("user:create") - public Result> getUserDefaultPassword(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - String configuredDefaultPassword = configService.getEnabledValue( - AdminDefaultPasswordSupport.CONFIG_GROUP, - AdminDefaultPasswordSupport.CONFIG_KEY - ); - result.put("password", AdminDefaultPasswordSupport.resolveDefaultPassword(configuredDefaultPassword)); - return Result.success(result); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/dto/LegalAgreementDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/dto/LegalAgreementDTO.java deleted file mode 100644 index 58e1bb3b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/dto/LegalAgreementDTO.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - -@Data -/** - * Purpose: LegalAgreementDTO supports LegalAgreementDTO.java by holding or executing the legal agreement dto business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class LegalAgreementDTO { - - @NotBlank(message = "协议类型不能为空") - /** - * Purpose: agreementType supports LegalAgreementDTO.java by holding or executing the agreement type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String agreementType; - - @NotBlank(message = "协议标题不能为空") - @Size(max = 100, message = "协议标题不能超过100个字符") - /** - * Purpose: title supports LegalAgreementDTO.java by holding or executing the title business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String title; - - @NotBlank(message = "协议版本不能为空") - @Size(max = 40, message = "协议版本不能超过40个字符") - /** - * Purpose: version supports LegalAgreementDTO.java by holding or executing the version business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String version; - - @NotBlank(message = "协议内容不能为空") - /** - * Purpose: content supports LegalAgreementDTO.java by holding or executing the content business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String content; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/dto/SystemParameterConfigDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/dto/SystemParameterConfigDTO.java deleted file mode 100644 index cfe91c44..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/dto/SystemParameterConfigDTO.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - -@Data -/** - * Purpose: SystemParameterConfigDTO supports SystemParameterConfigDTO.java by holding or executing the system parameter config dto business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SystemParameterConfigDTO { - - @NotBlank(message = "配置分组不能为空") - @Size(max = 50, message = "配置分组不能超过50个字符") - /** - * Purpose: configGroup supports SystemParameterConfigDTO.java by holding or executing the config group business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configGroup; - - @NotBlank(message = "配置键不能为空") - @Size(max = 100, message = "配置键不能超过100个字符") - /** - * Purpose: configKey supports SystemParameterConfigDTO.java by holding or executing the config key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configKey; - - @NotBlank(message = "配置名称不能为空") - @Size(max = 100, message = "配置名称不能超过100个字符") - /** - * Purpose: configName supports SystemParameterConfigDTO.java by holding or executing the config name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configName; - - @Size(max = 1000, message = "配置值不能超过1000个字符") - /** - * Purpose: configValue supports SystemParameterConfigDTO.java by holding or executing the config value business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configValue; - - /** - * Purpose: enabled supports SystemParameterConfigDTO.java by holding or executing the enabled business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer enabled = 1; - - @Size(max = 255, message = "备注不能超过255个字符") - /** - * Purpose: remark supports SystemParameterConfigDTO.java by holding or executing the remark business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/entity/LegalAgreementDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/entity/LegalAgreementDO.java deleted file mode 100644 index 83b5bcf4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/entity/LegalAgreementDO.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Getter -@Setter -@TableName("t_legal_agreement") -/** - * Purpose: LegalAgreementDO supports LegalAgreementDO.java by holding or executing the legal agreement do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class LegalAgreementDO extends BaseEntity { - - @TableField("agreement_type") - /** - * Purpose: agreementType supports LegalAgreementDO.java by holding or executing the agreement type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String agreementType; - - @TableField("title") - /** - * Purpose: title supports LegalAgreementDO.java by holding or executing the title business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String title; - - @TableField("version") - /** - * Purpose: version supports LegalAgreementDO.java by holding or executing the version business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String version; - - @TableField("content") - /** - * Purpose: content supports LegalAgreementDO.java by holding or executing the content business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String content; - - @TableField("status") - /** - * Purpose: status supports LegalAgreementDO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer status; - - @TableField("effective_time") - /** - * Purpose: effectiveTime supports LegalAgreementDO.java by holding or executing the effective time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime effectiveTime; - - @TableField("is_delete") - @TableLogic - /** - * Purpose: isDelete supports LegalAgreementDO.java by holding or executing the is delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/entity/SystemParameterConfigDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/entity/SystemParameterConfigDO.java deleted file mode 100644 index 5cf8c12c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/entity/SystemParameterConfigDO.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_system_parameter_config") -/** - * Purpose: SystemParameterConfigDO supports SystemParameterConfigDO.java by holding or executing the system parameter config do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SystemParameterConfigDO extends BaseEntity { - - @TableField("config_group") - /** - * Purpose: configGroup supports SystemParameterConfigDO.java by holding or executing the config group business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configGroup; - - @TableField("config_key") - /** - * Purpose: configKey supports SystemParameterConfigDO.java by holding or executing the config key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configKey; - - @TableField("config_name") - /** - * Purpose: configName supports SystemParameterConfigDO.java by holding or executing the config name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configName; - - @TableField("config_value") - /** - * Purpose: configValue supports SystemParameterConfigDO.java by holding or executing the config value business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configValue; - - @TableField("enabled") - /** - * Purpose: enabled supports SystemParameterConfigDO.java by holding or executing the enabled business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer enabled; - - @TableField("remark") - /** - * Purpose: remark supports SystemParameterConfigDO.java by holding or executing the remark business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String remark; - - @TableField("is_delete") - @TableLogic - /** - * Purpose: isDelete supports SystemParameterConfigDO.java by holding or executing the is delete business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/mapper/LegalAgreementMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/mapper/LegalAgreementMapper.java deleted file mode 100644 index cc111176..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/mapper/LegalAgreementMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.system.entity.LegalAgreementDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * Purpose: LegalAgreementMapper supports LegalAgreementMapper.java by holding or executing the legal agreement mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface LegalAgreementMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/mapper/SystemParameterConfigMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/mapper/SystemParameterConfigMapper.java deleted file mode 100644 index c3c9343f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/mapper/SystemParameterConfigMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.system.entity.SystemParameterConfigDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * Purpose: SystemParameterConfigMapper supports SystemParameterConfigMapper.java by holding or executing the system parameter config mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface SystemParameterConfigMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/LegalAgreementService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/LegalAgreementService.java deleted file mode 100644 index b552b7bf..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/LegalAgreementService.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.service; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -import com.xiaowang.jacyucloudsalon.core.modules.system.dto.LegalAgreementDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.system.vo.LegalAgreementVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAgreementConsentVO; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * Purpose: LegalAgreementService supports LegalAgreementService.java by holding or executing the legal agreement service business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface LegalAgreementService { - - List listAdminAgreements(UserDO currentUser); - - Long createAgreement(UserDO currentUser, LegalAgreementDTO dto); - - Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto); - - Boolean publishAgreement(UserDO currentUser, Long id); - - Boolean disableAgreement(UserDO currentUser, Long id); - - List listCurrentAgreements(); - - LegalAgreementVO getCurrentAgreement(String agreementType); - - UserAgreementConsentVO getMyConsent(Long userId); - - void requireAccepted(AgreementAwareRequest request); - - void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/SystemParameterConfigService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/SystemParameterConfigService.java deleted file mode 100644 index 07ab3daa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/SystemParameterConfigService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.service; - -import com.xiaowang.jacyucloudsalon.core.modules.system.dto.SystemParameterConfigDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.system.vo.SystemParameterConfigVO; - -import java.util.List; - -/** - * Purpose: SystemParameterConfigService supports SystemParameterConfigService.java by holding or executing the system parameter config service business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface SystemParameterConfigService { - - List listConfigs(UserDO currentUser, String configGroup); - - Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto); - - String getEnabledValue(String configGroup, String configKey); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/LegalAgreementServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/LegalAgreementServiceImpl.java deleted file mode 100644 index 3c931d7f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/LegalAgreementServiceImpl.java +++ /dev/null @@ -1,348 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -import com.xiaowang.jacyucloudsalon.core.modules.system.dto.LegalAgreementDTO; -import com.xiaowang.jacyucloudsalon.core.modules.system.entity.LegalAgreementDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserAgreementConsentDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.system.mapper.LegalAgreementMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserAgreementConsentMapper; -import com.xiaowang.jacyucloudsalon.core.modules.system.service.LegalAgreementService; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestThrottleService; -import com.xiaowang.jacyucloudsalon.core.modules.system.vo.LegalAgreementVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAgreementConsentVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import javax.servlet.http.HttpServletRequest; -import java.time.LocalDateTime; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * Purpose: LegalAgreementServiceImpl supports LegalAgreementServiceImpl.java by holding or executing the legal agreement service impl business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class LegalAgreementServiceImpl implements LegalAgreementService { - - /** - * Purpose: USER_TERMS supports LegalAgreementServiceImpl.java by holding or executing the user terms business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String USER_TERMS = "USER_TERMS"; - /** - * Purpose: PRIVACY_POLICY supports LegalAgreementServiceImpl.java by holding or executing the privacy policy business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String PRIVACY_POLICY = "PRIVACY_POLICY"; - - /** - * Purpose: agreementMapper supports LegalAgreementServiceImpl.java by holding or executing the agreement mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final LegalAgreementMapper agreementMapper; - /** - * Purpose: consentMapper supports LegalAgreementServiceImpl.java by holding or executing the consent mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UserAgreementConsentMapper consentMapper; - - @Override - /** - * Purpose: listAdminAgreements supports LegalAgreementServiceImpl.java by holding or executing the list admin agreements business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listAdminAgreements(UserDO currentUser) { - ensurePlatformAdmin(currentUser); - return agreementMapper.selectList(new LambdaQueryWrapper() - .eq(LegalAgreementDO::getIsDelete, 0) - .orderByDesc(LegalAgreementDO::getEffectiveTime) - .orderByDesc(LegalAgreementDO::getCreateTime)) - .stream() - .map(this::toVO) - .collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: createAgreement supports LegalAgreementServiceImpl.java by holding or executing the create agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Long createAgreement(UserDO currentUser, LegalAgreementDTO dto) { - ensurePlatformAdmin(currentUser); - LegalAgreementDO agreement = new LegalAgreementDO(); - apply(agreement, dto); - agreement.setStatus(0); - agreement.setIsDelete(0); - agreementMapper.insert(agreement); - return agreement.getId(); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: updateAgreement supports LegalAgreementServiceImpl.java by holding or executing the update agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto) { - ensurePlatformAdmin(currentUser); - LegalAgreementDO agreement = requireAgreement(id); - apply(agreement, dto); - agreementMapper.updateById(agreement); - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: publishAgreement supports LegalAgreementServiceImpl.java by holding or executing the publish agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Boolean publishAgreement(UserDO currentUser, Long id) { - ensurePlatformAdmin(currentUser); - LegalAgreementDO agreement = requireAgreement(id); - agreementMapper.update(null, new LambdaUpdateWrapper() - .eq(LegalAgreementDO::getAgreementType, agreement.getAgreementType()) - .eq(LegalAgreementDO::getIsDelete, 0) - .set(LegalAgreementDO::getStatus, 0)); - agreement.setStatus(1); - agreement.setEffectiveTime(LocalDateTime.now()); - agreementMapper.updateById(agreement); - return true; - } - - @Override - /** - * Purpose: disableAgreement supports LegalAgreementServiceImpl.java by holding or executing the disable agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Boolean disableAgreement(UserDO currentUser, Long id) { - ensurePlatformAdmin(currentUser); - LegalAgreementDO agreement = requireAgreement(id); - agreement.setStatus(0); - agreementMapper.updateById(agreement); - return true; - } - - @Override - /** - * Purpose: listCurrentAgreements supports LegalAgreementServiceImpl.java by holding or executing the list current agreements business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listCurrentAgreements() { - return List.of(USER_TERMS, PRIVACY_POLICY).stream() - .map(this::getCurrentAgreement) - .collect(Collectors.toList()); - } - - @Override - /** - * Purpose: getCurrentAgreement supports LegalAgreementServiceImpl.java by holding or executing the get current agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public LegalAgreementVO getCurrentAgreement(String agreementType) { - LegalAgreementDO agreement = findCurrentAgreement(normalizeType(agreementType)); - if (agreement == null) { - throw new RuntimeException("当前协议未配置,请联系管理员"); - } - return toVO(agreement); - } - - @Override - /** - * Purpose: getMyConsent supports LegalAgreementServiceImpl.java by holding or executing the get my consent business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public UserAgreementConsentVO getMyConsent(Long userId) { - Map versions = consentMapper.selectList(new LambdaQueryWrapper() - .eq(UserAgreementConsentDO::getUserId, userId)) - .stream() - .collect(Collectors.toMap(UserAgreementConsentDO::getAgreementType, UserAgreementConsentDO::getVersion, (left, right) -> right, LinkedHashMap::new)); - return new UserAgreementConsentVO(versions); - } - - @Override - /** - * Purpose: requireAccepted supports LegalAgreementServiceImpl.java by holding or executing the require accepted business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void requireAccepted(AgreementAwareRequest request) { - if (request == null || !Boolean.TRUE.equals(request.getAgreementAccepted())) { - throw new RuntimeException("请先阅读并同意用户协议和隐私政策"); - } - Map versions = request.getAgreementVersions(); - requireVersion(versions, USER_TERMS); - requireVersion(versions, PRIVACY_POLICY); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: recordConsent supports LegalAgreementServiceImpl.java by holding or executing the record consent business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest) { - if (userId == null || request == null || request.getAgreementVersions() == null) { - return; - } - String clientType = StringUtils.hasText(request.getClientType()) ? request.getClientType().trim().toUpperCase() : "WEB"; - request.getAgreementVersions().forEach((type, version) -> upsertConsent( - userId, - normalizeType(type), - version, - entry, - clientType, - resolveClientIp(httpRequest), - httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER) - )); - } - - /** - * Purpose: requireVersion supports LegalAgreementServiceImpl.java by holding or executing the require version business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void requireVersion(Map versions, String type) { - LegalAgreementDO current = findCurrentAgreement(type); - if (current == null) { - throw new RuntimeException("当前协议未配置,请联系管理员"); - } - String submittedVersion = versions == null ? null : versions.get(type); - if (!StringUtils.hasText(submittedVersion) || !current.getVersion().equals(submittedVersion.trim())) { - throw new RuntimeException("协议版本已更新,请重新阅读并同意"); - } - } - - /** - * Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) { - if (!StringUtils.hasText(version)) { - return; - } - UserAgreementConsentDO existing = consentMapper.selectOne(new LambdaQueryWrapper() - .eq(UserAgreementConsentDO::getUserId, userId) - .eq(UserAgreementConsentDO::getAgreementType, type) - .last("limit 1")); - UserAgreementConsentDO consent = existing == null ? new UserAgreementConsentDO() : existing; - consent.setUserId(userId); - consent.setAgreementType(type); - consent.setVersion(version.trim()); - consent.setEntry(entry); - consent.setClientType(clientType); - consent.setIpAddress(ip); - consent.setDeviceId(deviceId); - consent.setConsentTime(LocalDateTime.now()); - if (existing == null) { - consentMapper.insert(consent); - } else { - consentMapper.updateById(consent); - } - } - - /** - * Purpose: findCurrentAgreement supports LegalAgreementServiceImpl.java by holding or executing the find current agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private LegalAgreementDO findCurrentAgreement(String type) { - return agreementMapper.selectOne(new LambdaQueryWrapper() - .eq(LegalAgreementDO::getAgreementType, normalizeType(type)) - .eq(LegalAgreementDO::getStatus, 1) - .eq(LegalAgreementDO::getIsDelete, 0) - .orderByDesc(LegalAgreementDO::getEffectiveTime) - .last("limit 1")); - } - - /** - * Purpose: requireAgreement supports LegalAgreementServiceImpl.java by holding or executing the require agreement business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private LegalAgreementDO requireAgreement(Long id) { - LegalAgreementDO agreement = agreementMapper.selectById(id); - if (agreement == null || Integer.valueOf(1).equals(agreement.getIsDelete())) { - throw new RuntimeException("协议不存在"); - } - return agreement; - } - - /** - * Purpose: apply supports LegalAgreementServiceImpl.java by holding or executing the apply business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void apply(LegalAgreementDO agreement, LegalAgreementDTO dto) { - agreement.setAgreementType(normalizeType(dto.getAgreementType())); - agreement.setTitle(dto.getTitle().trim()); - agreement.setVersion(dto.getVersion().trim()); - agreement.setContent(dto.getContent().trim()); - } - - /** - * Purpose: normalizeType supports LegalAgreementServiceImpl.java by holding or executing the normalize type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String normalizeType(String type) { - if (!StringUtils.hasText(type)) { - throw new RuntimeException("协议类型不能为空"); - } - String normalized = type.trim().toUpperCase(); - if (!USER_TERMS.equals(normalized) && !PRIVACY_POLICY.equals(normalized)) { - throw new RuntimeException("协议类型不正确"); - } - return normalized; - } - - /** - * Purpose: ensurePlatformAdmin supports LegalAgreementServiceImpl.java by holding or executing the ensure platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void ensurePlatformAdmin(UserDO currentUser) { - if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { - throw new RuntimeException("仅平台管理员可以管理协议"); - } - } - - /** - * Purpose: resolveClientIp supports LegalAgreementServiceImpl.java by holding or executing the resolve client ip business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveClientIp(HttpServletRequest request) { - if (request == null) { - return null; - } - String forwarded = request.getHeader("X-Forwarded-For"); - if (StringUtils.hasText(forwarded)) { - return forwarded.split(",")[0].trim(); - } - String realIp = request.getHeader("X-Real-IP"); - return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); - } - - /** - * Purpose: toVO supports LegalAgreementServiceImpl.java by holding or executing the to vo business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private LegalAgreementVO toVO(LegalAgreementDO agreement) { - LegalAgreementVO vo = new LegalAgreementVO(); - vo.setId(agreement.getId()); - vo.setAgreementType(agreement.getAgreementType()); - vo.setAgreementTypeName(USER_TERMS.equals(agreement.getAgreementType()) ? "用户协议" : "隐私政策"); - vo.setTitle(agreement.getTitle()); - vo.setVersion(agreement.getVersion()); - vo.setContent(agreement.getContent()); - vo.setStatus(agreement.getStatus()); - vo.setStatusText(Integer.valueOf(1).equals(agreement.getStatus()) ? "已发布" : "草稿/停用"); - vo.setEffectiveTime(agreement.getEffectiveTime()); - vo.setCreateTime(agreement.getCreateTime()); - vo.setUpdateTime(agreement.getUpdateTime()); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java deleted file mode 100644 index b4b82638..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.xiaowang.jacyucloudsalon.core.modules.system.dto.SystemParameterConfigDTO; -import com.xiaowang.jacyucloudsalon.core.modules.system.entity.SystemParameterConfigDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.system.mapper.SystemParameterConfigMapper; -import com.xiaowang.jacyucloudsalon.core.modules.system.service.SystemParameterConfigService; -import com.xiaowang.jacyucloudsalon.core.modules.system.support.AdminDefaultPasswordSupport; -import com.xiaowang.jacyucloudsalon.core.modules.system.vo.SystemParameterConfigVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; - -@Service -@RequiredArgsConstructor -/** - * Purpose: SystemParameterConfigServiceImpl supports SystemParameterConfigServiceImpl.java by holding or executing the system parameter config service impl business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SystemParameterConfigServiceImpl implements SystemParameterConfigService { - - /** - * Purpose: configMapper supports SystemParameterConfigServiceImpl.java by holding or executing the config mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SystemParameterConfigMapper configMapper; - - @Override - /** - * Purpose: listConfigs supports SystemParameterConfigServiceImpl.java by holding or executing the list configs business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public List listConfigs(UserDO currentUser, String configGroup) { - ensurePlatformAdmin(currentUser); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(SystemParameterConfigDO::getIsDelete, 0) - .orderByAsc(SystemParameterConfigDO::getConfigGroup) - .orderByAsc(SystemParameterConfigDO::getConfigKey); - if (StringUtils.hasText(configGroup)) { - wrapper.eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)); - } - return configMapper.selectList(wrapper).stream().map(this::toVO).collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Purpose: saveConfig supports SystemParameterConfigServiceImpl.java by holding or executing the save config business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto) { - ensurePlatformAdmin(currentUser); - String group = normalize(dto.getConfigGroup()); - String key = normalize(dto.getConfigKey()); - if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) { - AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue()); - } - SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() - .eq(SystemParameterConfigDO::getConfigGroup, group) - .eq(SystemParameterConfigDO::getConfigKey, key) - .eq(SystemParameterConfigDO::getIsDelete, 0) - .last("LIMIT 1")); - if (config == null) { - config = new SystemParameterConfigDO(); - config.setConfigGroup(group); - config.setConfigKey(key); - config.setIsDelete(0); - } - config.setConfigName(dto.getConfigName().trim()); - config.setConfigValue(StringUtils.hasText(dto.getConfigValue()) ? dto.getConfigValue().trim() : ""); - config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); - config.setRemark(dto.getRemark()); - if (config.getId() == null) { - configMapper.insert(config); - } else { - configMapper.updateById(config); - } - return true; - } - - @Override - /** - * Purpose: getEnabledValue supports SystemParameterConfigServiceImpl.java by holding or executing the get enabled value business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String getEnabledValue(String configGroup, String configKey) { - if (!StringUtils.hasText(configGroup) || !StringUtils.hasText(configKey)) { - return ""; - } - SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() - .eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)) - .eq(SystemParameterConfigDO::getConfigKey, normalize(configKey)) - .eq(SystemParameterConfigDO::getEnabled, 1) - .eq(SystemParameterConfigDO::getIsDelete, 0) - .last("LIMIT 1")); - return config == null ? "" : config.getConfigValue(); - } - - /** - * Purpose: ensurePlatformAdmin supports SystemParameterConfigServiceImpl.java by holding or executing the ensure platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void ensurePlatformAdmin(UserDO currentUser) { - if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { - throw new RuntimeException("仅平台管理员可以管理系统参数"); - } - } - - /** - * Purpose: normalize supports SystemParameterConfigServiceImpl.java by holding or executing the normalize business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String normalize(String value) { - return value.trim().toUpperCase(Locale.ROOT); - } - - /** - * Purpose: toVO supports SystemParameterConfigServiceImpl.java by holding or executing the to vo business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private SystemParameterConfigVO toVO(SystemParameterConfigDO config) { - SystemParameterConfigVO vo = new SystemParameterConfigVO(); - vo.setId(config.getId()); - vo.setConfigGroup(config.getConfigGroup()); - vo.setConfigKey(config.getConfigKey()); - vo.setConfigName(config.getConfigName()); - vo.setConfigValue(config.getConfigValue()); - vo.setEnabled(config.getEnabled()); - vo.setRemark(config.getRemark()); - vo.setCreateTime(config.getCreateTime()); - vo.setUpdateTime(config.getUpdateTime()); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/support/AdminDefaultPasswordSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/support/AdminDefaultPasswordSupport.java deleted file mode 100644 index acf7615e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/support/AdminDefaultPasswordSupport.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.support; - -import org.springframework.util.StringUtils; - -import java.util.Locale; - -public final class AdminDefaultPasswordSupport { - - public static final String CONFIG_GROUP = "USER"; - public static final String CONFIG_KEY = "DEFAULT_PASSWORD"; - public static final String FALLBACK_DEFAULT_PASSWORD = "Fingertip@123"; - - private AdminDefaultPasswordSupport() { - } - - public static String resolveCreatePassword(String requestedPassword, String configuredDefaultPassword) { - String resolvedPassword = StringUtils.hasText(requestedPassword) - ? requestedPassword.trim() - : resolveDefaultPassword(configuredDefaultPassword); - validatePasswordStrength(resolvedPassword); - return resolvedPassword; - } - - public static String resolveDefaultPassword(String configuredDefaultPassword) { - if (!StringUtils.hasText(configuredDefaultPassword)) { - return FALLBACK_DEFAULT_PASSWORD; - } - String defaultPassword = configuredDefaultPassword.trim(); - validateDefaultPassword(defaultPassword); - return defaultPassword; - } - - public static void validatePasswordStrength(String password) { - validatePasswordStrength(password, "密码"); - } - - public static void validateDefaultPassword(String password) { - validatePasswordStrength(password, "默认密码"); - } - - public static boolean isDefaultPasswordConfig(String configGroup, String configKey) { - return CONFIG_GROUP.equals(normalize(configGroup)) && CONFIG_KEY.equals(normalize(configKey)); - } - - private static void validatePasswordStrength(String password, String label) { - if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { - throw new RuntimeException(label + "长度需为 8-32 位"); - } - int count = 0; - if (password.matches(".*\\d.*")) { - count++; - } - if (password.matches(".*[a-z].*")) { - count++; - } - if (password.matches(".*[A-Z].*")) { - count++; - } - if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { - count++; - } - if (count < 3) { - throw new RuntimeException(label + "需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); - } - } - - private static String normalize(String value) { - return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/vo/LegalAgreementVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/vo/LegalAgreementVO.java deleted file mode 100644 index 800c7c59..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/vo/LegalAgreementVO.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -/** - * Purpose: LegalAgreementVO supports LegalAgreementVO.java by holding or executing the legal agreement vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class LegalAgreementVO { - - /** - * Purpose: id supports LegalAgreementVO.java by holding or executing the id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long id; - - /** - * Purpose: agreementType supports LegalAgreementVO.java by holding or executing the agreement type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String agreementType; - - /** - * Purpose: agreementTypeName supports LegalAgreementVO.java by holding or executing the agreement type name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String agreementTypeName; - - /** - * Purpose: title supports LegalAgreementVO.java by holding or executing the title business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String title; - - /** - * Purpose: version supports LegalAgreementVO.java by holding or executing the version business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String version; - - /** - * Purpose: content supports LegalAgreementVO.java by holding or executing the content business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String content; - - /** - * Purpose: status supports LegalAgreementVO.java by holding or executing the status business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer status; - - /** - * Purpose: statusText supports LegalAgreementVO.java by holding or executing the status text business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String statusText; - - /** - * Purpose: effectiveTime supports LegalAgreementVO.java by holding or executing the effective time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime effectiveTime; - - /** - * Purpose: createTime supports LegalAgreementVO.java by holding or executing the create time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime createTime; - - /** - * Purpose: updateTime supports LegalAgreementVO.java by holding or executing the update time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/vo/SystemParameterConfigVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/vo/SystemParameterConfigVO.java deleted file mode 100644 index d44dd83a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/vo/SystemParameterConfigVO.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.system.vo; - -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -/** - * Purpose: SystemParameterConfigVO supports SystemParameterConfigVO.java by holding or executing the system parameter config vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class SystemParameterConfigVO { - - /** - * Purpose: id supports SystemParameterConfigVO.java by holding or executing the id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long id; - /** - * Purpose: configGroup supports SystemParameterConfigVO.java by holding or executing the config group business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configGroup; - /** - * Purpose: configKey supports SystemParameterConfigVO.java by holding or executing the config key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configKey; - /** - * Purpose: configName supports SystemParameterConfigVO.java by holding or executing the config name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configName; - /** - * Purpose: configValue supports SystemParameterConfigVO.java by holding or executing the config value business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String configValue; - /** - * Purpose: enabled supports SystemParameterConfigVO.java by holding or executing the enabled business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer enabled; - /** - * Purpose: remark supports SystemParameterConfigVO.java by holding or executing the remark business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String remark; - /** - * Purpose: createTime supports SystemParameterConfigVO.java by holding or executing the create time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime createTime; - /** - * Purpose: updateTime supports SystemParameterConfigVO.java by holding or executing the update time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime updateTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java deleted file mode 100644 index d2514d94..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java +++ /dev/null @@ -1,1069 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.controller.front; - -import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; -import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; -import com.xiaowang.jacyucloudsalon.core.common.Result; -import com.xiaowang.fingertipdesigner.core.common.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.artist.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.auth.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.content.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.file.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.integration.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.message.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.order.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.payment.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.planning.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.product.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.security.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.shop.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.system.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.user.dto.*; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.ChunkUploadService; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; -import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ChunkUploadSessionVO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginShopSelectionVO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAssetVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserRelationVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.InviteCodeVO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.WechatMiniLoginResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.file.service.PrimaryObjectStorageService; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserAssetService; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.ShopRoleService; -import com.xiaowang.jacyucloudsalon.core.modules.auth.service.VerificationCodeService; -import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniAuthService; -import com.xiaowang.jacyucloudsalon.core.modules.system.service.LegalAgreementService; -import com.xiaowang.jacyucloudsalon.core.modules.security.service.SecurityAuditLogService; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.support.security.RequestThrottleService; -import com.xiaowang.jacyucloudsalon.core.utils.AccountValidationUtils; -import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; - -import org.springframework.web.multipart.MultipartFile; -import javax.validation.Valid; -import javax.servlet.http.HttpServletRequest; -import java.io.FileInputStream; -import java.util.List; -import java.util.stream.Collectors; - -import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.BindEmailRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.BindPhoneRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.PhoneLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.RefreshTokenRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.RegisterRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.ResetPasswordRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.SendVerificationCodeRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.SwitchShopRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.UpdatePhoneRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadCompleteRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadInitRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.UserDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAgreementConsentVO; -/** - * 系统用户信息表 Controller - * 对应数据库表 t_user - * - * @author xiaowang - * @date 2026-02-13 - */ -@RestController -@RequestMapping("/user") -@RequiredArgsConstructor -public class UserController { - /** - * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; - /** - * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final PrimaryObjectStorageService primaryObjectStorageService; - /** - * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ChunkUploadService chunkUploadService; - /** - * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VerificationCodeService verificationCodeService; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final AdminScopeHelper adminScopeHelper; - /** - * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopRoleService shopRoleService; - /** - * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - /** - * Variable `wechatMiniAuthService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final WechatMiniAuthService wechatMiniAuthService; - /** - * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageUrlSupport objectStorageUrlSupport; - /** - * Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final RequestThrottleService requestThrottleService; - /** - * Purpose: legalAgreementService supports UserController.java by holding or executing the legal agreement service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final LegalAgreementService legalAgreementService; - /** - * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final SecurityAuditLogService securityAuditLogService; - - /** - * 创建用户 - * - * @param userDTO 用户DTO - * @return 用户ID - */ - @PostMapping("/create") - @RequirePermission("user:create") - @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); - if (!adminScopeHelper.isPlatformAdmin(currentUser)) { - Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); - userDTO.setShopId(managedShopId); - userDTO.setShopIds(List.of(managedShopId)); - } - Long id = userService.createUser(userDTO); - return Result.success(id); - } - - /** - * 更新用户 - * - * @param id 用户ID - * @param userDTO 用户DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - @RequirePermission("user:edit") - @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权编辑其他店铺用户"); - if (userDTO.getType() != null) { - adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); - } - if (!adminScopeHelper.isPlatformAdmin(currentUser)) { - userDTO.setShopId(null); - userDTO.setShopIds(null); - } - boolean success = userService.updateUser(id, userDTO); - return Result.success(success); - } - - /** - * 删除用户 - * - * @param id 用户ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("user:delete") - @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作进行中,请勿重复点击") - public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权删除其他店铺用户"); - if (Integer.valueOf(4).equals(targetUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("管理员账号不允许删除"); - } - boolean success = userService.deleteUser(id); - return Result.success(success); - } - - @PutMapping("/unbind/{id}") - @RequirePermission("user:unbind") - @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作进行中,请勿重复点击") - /** - * Run business method `unbindUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权解绑其他店铺用户"); - adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType()); - if (Integer.valueOf(4).equals(targetUser.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("管理员账号不允许解绑"); - } - boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); - return Result.success(success); - } - - @GetMapping("/asset/me") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getMyAsset(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.getUserAsset(userId)); - } - - @GetMapping("/balance/history/me") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getMyBalanceHistory(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.listBalanceHistory(userId)); - } - - /** - * 根据ID查询用户 - * - * @param id 用户ID - * @return 用户VO - */ - @GetMapping("/get/{id}") - @RequirePermission("user:view") - public Result getUserById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO userVO = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户"); - return Result.success(userVO); - } - - /** - * 查询所有用户 - * - * @return 用户VO列表 - */ - @GetMapping("/list/all") - @RequirePermission("user:view") - public Result> listAllUsers(HttpServletRequest request) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - List userVOs = adminScopeHelper.isPlatformAdmin(currentUser) - ? userService.listAllUsers() - : userService.listUsersByShopId(adminScopeHelper.getManagedShopId(currentUser)); - return Result.success(userVOs); - } - - /** - * 根据店铺ID查询用户 - * - * @param shopId 店铺ID - * @return 用户VO列表 - */ - @GetMapping("/list/shop/{shopId}") - @RequirePermission("user:view") - public Result> listUsersByShopId(HttpServletRequest request, @PathVariable Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - List userVOs = userService.listUsersByShopId(shopId); - return Result.success(userVOs); - } - - /** - * 根据用户类型查询用户 - * - * @param type 用户类型 - * @return 用户VO列表 - */ - @GetMapping("/list/type/{type}") - public Result> listUsersByType(@PathVariable Integer type) { - if (!Integer.valueOf(3).equals(type)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("仅支持查询可预约的美甲师列表"); - } - List userVOs = userService.listUsersByType(type).stream() - .filter(user -> Integer.valueOf(1).equals(user.getStatus())) - .map(this::sanitizePublicArtist) - .collect(Collectors.toList()); - return Result.success(userVOs); - } - - /** - * 根据账号查询用户 - * - * @param account 账号 - * @return 用户VO - */ - @GetMapping("/get/account/{account}") - @RequirePermission("user:view") - public Result getUserByAccount(HttpServletRequest request, @PathVariable String account) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO userVO = userService.getUserByAccount(AccountValidationUtils.requireValidAccount(account)); - if (userVO != null) { - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "无权查看其他店铺用户"); - } - return Result.success(userVO); - } - - @GetMapping("/check/account/{account}") - /** - * Run business method `checkAccountAvailability`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result checkAccountAvailability(@PathVariable String account) { - String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); - boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); - String message = available ? "账号可用" : "账号已被注册"; - return Result.success(new AvailabilityVO(available, message)); - } - - @GetMapping("/check/login-account/{account}") - /** - * Run business method `checkLoginAccountAvailability`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result checkLoginAccountAvailability(@PathVariable String account) { - String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - boolean exists = userDO != null; - String nickname = exists ? userDO.getNickname() : null; - String message = exists - ? (nickname != null && !nickname.isEmpty() ? "该账号已注册,昵称:" + nickname : "该账号已注册,可继续登录") - : "该账号不存在"; - return Result.success(new LoginAccountAvailabilityVO(exists, nickname, message)); - } - - @GetMapping("/check/login-shops/account/{account}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getLoginShopsByAccount(@PathVariable String account) { - return Result.success(userService.getLoginShopSelectionByAccount(AccountValidationUtils.requireValidAccount(account))); - } - - @GetMapping("/check/login-shops/phone/{phone}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getLoginShopsByPhone(@PathVariable String phone) { - return Result.success(userService.getLoginShopSelectionByPhone(phone)); - } - - @GetMapping("/check/phone/{phone}") - /** - * Run business method `checkPhoneAvailability`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result checkPhoneAvailability(@PathVariable String phone) { - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - ); - boolean available = userDO == null; - String message = available ? "手机号可用" : "该手机号已被注册"; - return Result.success(new AvailabilityVO(available, message)); - } - - /** - * 用户登录 - * - * @param loginRequestDTO 登录请求DTO - * @return 登录响应VO - */ - @PostMapping("/login") - @OperationGuard(action = "user-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { - requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); - legalAgreementService.requireAccepted(loginRequestDTO); - try { - LoginResponseVO loginResponseVO = userService.login(loginRequestDTO); - legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), loginRequestDTO, "USER_PASSWORD_LOGIN", request); - requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount()); - securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "USER_LOGIN", "SUCCESS", null, request); - return Result.success(loginResponseVO); - } catch (RuntimeException exception) { - requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount()); - securityAuditLogService.record(null, loginRequestDTO.getAccount(), "USER_LOGIN", "FAIL", exception.getMessage(), request); - throw exception; - } - } - - /** - * 手机号验证码登录 - * - * @param phoneLoginRequestDTO 手机号验证码登录请求DTO - * @return 登录响应VO - */ - @PostMapping("/phone-login") - @OperationGuard(action = "user-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - public Result phoneLogin(HttpServletRequest request, @RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) { - requestThrottleService.checkLogin(request, phoneLoginRequestDTO.getPhone()); - legalAgreementService.requireAccepted(phoneLoginRequestDTO); - try { - LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO); - legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO, "USER_PHONE_LOGIN", request); - requestThrottleService.clearLoginFailure(request, phoneLoginRequestDTO.getPhone()); - securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "SUCCESS", null, request); - return Result.success(loginResponseVO); - } catch (RuntimeException exception) { - requestThrottleService.recordLoginFailure(request, phoneLoginRequestDTO.getPhone()); - securityAuditLogService.record(null, phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "FAIL", exception.getMessage(), request); - throw exception; - } - } - - @PostMapping("/wechat-mini/auto-login") - @OperationGuard(action = "wechat-mini-auto-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - /** - * Run business method `wechatMiniAutoLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { - return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); - } - - @PostMapping("/wechat-mini/phone-login") - @OperationGuard(action = "wechat-mini-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - /** - * Run business method `wechatMiniPhoneLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result wechatMiniPhoneLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) { - requestThrottleService.checkWechatMiniLogin(request, "wechat-mini-phone"); - legalAgreementService.requireAccepted(requestDTO); - WechatMiniLoginResultVO result = wechatMiniAuthService.phoneLogin(requestDTO); - recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_PHONE_LOGIN", request); - return Result.success(result); - } - - @PostMapping("/wechat-mini/confirm-login") - @OperationGuard(action = "wechat-mini-confirm-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - /** - * Run business method `confirmWechatMiniLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result confirmWechatMiniLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) { - requestThrottleService.checkWechatMiniLogin(request, requestDTO.getTicket()); - legalAgreementService.requireAccepted(requestDTO); - WechatMiniLoginResultVO result = wechatMiniAuthService.confirmLogin(requestDTO); - recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_CONFIRM_LOGIN", request); - return Result.success(result); - } - - @PostMapping("/switch-shop") - @OperationGuard(action = "user-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") - /** - * Run business method `switchShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); - } - - /** - * 用户注册 - * - * @param registerRequestDTO 注册请求DTO - * @return 是否注册成功 - */ - @PostMapping("/register") - @OperationGuard(action = "user-register", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - public Result register(HttpServletRequest request, @Valid @RequestBody RegisterRequestDTO registerRequestDTO) { - requestThrottleService.checkRegister(request, registerRequestDTO.getAccount()); - legalAgreementService.requireAccepted(registerRequestDTO); - try { - boolean success = userService.register(registerRequestDTO); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - if (userDO != null) { - legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request); - securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request); - } - return Result.success(success); - } catch (RuntimeException exception) { - securityAuditLogService.record(null, registerRequestDTO.getAccount(), "USER_REGISTER", "FAIL", exception.getMessage(), request); - throw exception; - } - } - - @GetMapping("/relation/me") - /** - * Run business method `relationMe`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result relationMe(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.getCurrentUserRelation(userId)); - } - - @GetMapping("/invite-code/resolve") - /** - * Run business method `resolveInviteCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param code parameter `code` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result resolveInviteCode(@RequestParam String code) { - return Result.success(shopRoleService.resolveInviteCode(code)); - } - - /** - * 发送验证码 - * - * @param sendVerificationCodeRequestDTO 发送验证码请求DTO - * @return 是否发送成功 - */ - @PostMapping("/send-verification-code") - @OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试") - public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { - requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); - if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param 1 parameter `1` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); - } - verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); - return Result.success(true); - } - - /** - * 通过手机号验证码重置密码 - * - * @param resetPasswordRequestDTO 重置密码请求DTO - * @return 是否重置成功 - */ - @PostMapping("/reset-password-by-phone") - @OperationGuard(action = "reset-password-by-phone", ttlSeconds = 8, message = "操作进行中,请勿重复点击") - public Result resetPasswordByPhone(HttpServletRequest request, @RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) { - requestThrottleService.checkResetPassword(request, resetPasswordRequestDTO.getPhone()); - boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO); - securityAuditLogService.record(null, resetPasswordRequestDTO.getPhone(), "RESET_PASSWORD_BY_PHONE", success ? "SUCCESS" : "FAIL", null, request); - return Result.success(success); - } - - /** - * 刷新Token - * - * @param refreshTokenRequestDTO 刷新Token请求DTO - * @return 新的Token - */ - @PostMapping("/refresh-token") - public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { - LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); - return Result.success(loginResponseVO); - } - - /** - * 用户登出 - * - * @return 是否登出成功 - */ - @PostMapping("/logout") - @OperationGuard(action = "user-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) - public Result logout(HttpServletRequest request) { - boolean success = userService.logout((String) request.getAttribute("sessionId")); - return Result.success(success); - } - - @GetMapping("/agreement-consent/me") - public Result getMyAgreementConsent(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(legalAgreementService.getMyConsent(userId)); - } - - private void recordWechatConsentIfLoggedIn(WechatMiniLoginResultVO result, - AgreementAwareRequest dto, - String entry, - HttpServletRequest request) { - if (result != null && result.getUserInfo() != null) { - legalAgreementService.recordConsent(result.getUserInfo().getId(), dto, entry, request); - securityAuditLogService.record(result.getUserInfo().getId(), null, entry, "SUCCESS", null, request); - } - } - - /** - * 获取当前用户信息 - * - * @return 用户VO - */ - @GetMapping("/info") - public Result getCurrentUserInfo(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - UserVO userVO = userService.getUserById(userId); - return Result.success(userVO); - } - - /** - * 更新当前用户信息 - * - * @param userDTO 用户DTO - * @return 是否更新成功 - */ - @PutMapping({"/update", "/info"}) - @OperationGuard(action = "user-update-info", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updateCurrentUserInfo(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = userService.updateCurrentUserInfo(userId, userDTO); - return Result.success(success); - } - - /** - * 绑定手机号 - * - * @param bindPhoneRequestDTO 绑定手机号请求DTO - * @return 是否绑定成功 - */ - @PostMapping("/bind-phone") - @OperationGuard(action = "user-bind-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result bindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO bindPhoneRequestDTO) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = userService.bindPhone(userId, bindPhoneRequestDTO); - return Result.success(success); - } - - /** - * 绑定邮箱 - * - * @param bindEmailRequestDTO 绑定邮箱请求DTO - * @return 是否绑定成功 - */ - @PostMapping("/bind-email") - @OperationGuard(action = "user-bind-email", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result bindEmail(HttpServletRequest request, @RequestBody BindEmailRequestDTO bindEmailRequestDTO) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = userService.bindEmail(userId, bindEmailRequestDTO); - return Result.success(success); - } - - /** - * 上传头像 - * - * @param file 头像文件 - * @return 头像URL - */ - @PostMapping("/upload-avatar/init") - @OperationGuard(action = "user-avatar-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") - public Result initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO)); - } - - @PostMapping("/upload-avatar/chunk") - @OperationGuard(action = "user-avatar-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) - public Result uploadAvatarChunk(HttpServletRequest request, - @RequestParam("uploadId") String uploadId, - @RequestParam("chunkIndex") Integer chunkIndex, - @RequestParam("totalChunks") Integer totalChunks, - @RequestParam("chunk") MultipartFile chunkFile) { - Long userId = (Long) request.getAttribute("userId"); - chunkUploadService.uploadUserAvatarChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); - return Result.success(true); - } - - @PostMapping("/upload-avatar/complete") - @OperationGuard(action = "user-avatar-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - /** - * Complete a business action. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param requestDTO parameter `requestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - try (ChunkUploadService.PreparedUploadFile preparedUploadFile = - chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId()); - FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { - String originalFilename = preparedUploadFile.getFileName(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - - String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); - userService.updateUserAvatar(userId, avatarUrl); - chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); - return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("头像上传失败: " + e.getMessage()); - } - } - - @DeleteMapping("/upload-avatar/{uploadId}") - @OperationGuard(action = "user-avatar-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - /** - * Run business method `cancelAvatarUpload`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param uploadId parameter `uploadId` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) { - Long userId = (Long) request.getAttribute("userId"); - chunkUploadService.clearUserAvatarUpload(userId, uploadId); - return Result.success(true); - } - - @PostMapping("/upload-avatar") - @OperationGuard(action = "user-avatar-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - /** - * Purpose: uploadAvatar supports UserController.java by holding or executing the upload avatar business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) { - try { - Long userId = (Long) request.getAttribute("userId"); - String originalFilename = file.getOriginalFilename(); - String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - - String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName); - userService.updateUserAvatar(userId, avatarUrl); - - return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("头像上传失败: " + e.getMessage()); - } - } - - /** - * 重置用户密码为88888888 - * - * @param userId 目标用户ID - * @return 是否重置成功 - */ - /** - * 上传个人资料图片,不直接修改头像或资料字段。 - */ - @PostMapping("/upload-profile-image/init") - @OperationGuard(action = "user-profile-image-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") - public Result initProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(chunkUploadService.initUserProfileImageUpload(userId, requestDTO)); - } - - @PostMapping("/upload-profile-image/chunk") - @OperationGuard(action = "user-profile-image-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) - public Result uploadProfileImageChunk(HttpServletRequest request, - @RequestParam("uploadId") String uploadId, - @RequestParam("chunkIndex") Integer chunkIndex, - @RequestParam("totalChunks") Integer totalChunks, - @RequestParam("chunk") MultipartFile chunkFile) { - Long userId = (Long) request.getAttribute("userId"); - chunkUploadService.uploadUserProfileImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); - return Result.success(true); - } - - @PostMapping("/upload-profile-image/complete") - @OperationGuard(action = "user-profile-image-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { - Long userId = (Long) request.getAttribute("userId"); - try (ChunkUploadService.PreparedUploadFile preparedUploadFile = - chunkUploadService.prepareUserProfileImageFile(userId, requestDTO.getUploadId()); - FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { - String originalFilename = preparedUploadFile.getFileName(); - String fileExtension = ""; - if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { - fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - } - String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); - chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId()); - return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("资料图片上传失败: " + e.getMessage()); - } - } - - @DeleteMapping("/upload-profile-image/{uploadId}") - @OperationGuard(action = "user-profile-image-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result cancelProfileImageUpload(HttpServletRequest request, @PathVariable String uploadId) { - Long userId = (Long) request.getAttribute("userId"); - chunkUploadService.clearUserProfileImageUpload(userId, uploadId); - return Result.success(true); - } - - @PostMapping("/upload-profile-image") - @OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") - public Result uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { - try { - if (file == null || file.isEmpty()) { - return Result.error("请选择要上传的图片"); - } - Long userId = (Long) request.getAttribute("userId"); - String originalFilename = file.getOriginalFilename(); - String fileExtension = ""; - if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { - fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); - } - String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String imageUrl = primaryObjectStorageService.uploadFile(file, objectName); - return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); - } catch (Exception e) { - e.printStackTrace(); - return Result.error("资料图片上传失败: " + e.getMessage()); - } - } - - /** - * 重置用户密码。 - */ - @PostMapping("/reset-password/{userId}") - @RequirePermission("user:reset_password") - @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作进行中,请勿重复点击") - public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - /** - * Run business method `requireAccessibleUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - requireAccessibleUser(currentUser, userId, "无权重置其他店铺用户密码"); - Long currentUserId = (Long) request.getAttribute("userId"); - boolean success = userService.resetPassword(userId, currentUserId); - return Result.success(success); - } - - /** - * 更新用户密码 - * - * @param request 请求对象 - * @param passwordDTO 密码DTO - * @return 是否更新成功 - */ - @PutMapping("/password") - @OperationGuard(action = "user-update-password", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updatePassword(HttpServletRequest request, @RequestBody PasswordDTO passwordDTO) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = userService.updatePassword(userId, passwordDTO.getPassword(), passwordDTO.getVerificationCode()); - return Result.success(success); - } - - /** - * 修改手机号 - * - * @param request 请求对象 - * @param updatePhoneDTO 修改手机号DTO - * @return 是否修改成功 - */ - @PutMapping("/phone") - @OperationGuard(action = "user-update-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updatePhone(HttpServletRequest request, @RequestBody UpdatePhoneRequestDTO updatePhoneDTO) { - Long userId = (Long) request.getAttribute("userId"); - boolean success = userService.updatePhone(userId, updatePhoneDTO); - return Result.success(success); - } - - /** - * 注销账号 - * - * @param request 请求对象 - * @return 是否注销成功 - */ - @DeleteMapping("/deactivate") - @OperationGuard(action = "user-deactivate", ttlSeconds = 10, message = "操作进行中,请勿重复点击") - public Result deactivateAccount(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - - // 获取用户信息 - UserDO userDO = userMapper.selectById(userId); - if (userDO == null) { - return Result.error("用户不存在"); - } - - // 管理员账号无法注销 - if (userDO.getType() == 4) { - return Result.error("管理员账号无法注销"); - } - - boolean success = userService.deleteUser(userId); - return Result.success(success); - } - - /** - * Run business method `requireAccessibleUser`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param currentUser parameter `currentUser` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param message parameter `message` supplied by the caller - * @return private UserVO result consumed by the caller or returned to the frontend - */ - private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标用户不存在"); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message); - return targetUser; - } - - /** - * Run business method `sanitizePublicArtist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userVO parameter `userVO` supplied by the caller - * @return private UserVO result consumed by the caller or returned to the frontend - */ - private UserVO sanitizePublicArtist(UserVO userVO) { - UserVO sanitized = new UserVO(); - sanitized.setId(userVO.getId()); - sanitized.setShopId(userVO.getShopId()); - sanitized.setShopName(userVO.getShopName()); - sanitized.setShopIds(userVO.getShopIds()); - sanitized.setShopNames(userVO.getShopNames()); - sanitized.setNickname(userVO.getNickname()); - sanitized.setAvatar(userVO.getAvatar()); - sanitized.setType(userVO.getType()); - sanitized.setStatus(userVO.getStatus()); - sanitized.setCreateTime(userVO.getCreateTime()); - sanitized.setUpdateTime(userVO.getUpdateTime()); - return sanitized; - } - - @Data - /** - * Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class PasswordDTO { - /** - * Purpose: password supports UserController.java by holding or executing the password business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String password; - /** - * Purpose: verificationCode supports UserController.java by holding or executing the verification code business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String verificationCode; - } - - @Data - /** - * Purpose: AvailabilityVO supports UserController.java by holding or executing the availability vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class AvailabilityVO { - /** - * Variable `available`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final boolean available; - /** - * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String message; - } - - @Data - /** - * Purpose: LoginAccountAvailabilityVO supports UserController.java by holding or executing the login account availability vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class LoginAccountAvailabilityVO { - /** - * Variable `exists`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final boolean exists; - /** - * Variable `nickname`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String nickname; - /** - * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final String message; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/AdminUserBalanceChangeDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/AdminUserBalanceChangeDTO.java deleted file mode 100644 index 94f47af1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/AdminUserBalanceChangeDTO.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.dto; - -import lombok.Data; - -import java.math.BigDecimal; - -@Data -/** - * AdminUserBalanceChangeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class AdminUserBalanceChangeDTO { - - /** - * Field `amount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal amount; - - /** - * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String changeScene; - - /** - * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long relatedOrderId; - - /** - * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String externalOrderNo; - - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/AdminUserVipOverrideDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/AdminUserVipOverrideDTO.java deleted file mode 100644 index 16f5a0f1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/AdminUserVipOverrideDTO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.dto; - -import lombok.Data; - -@Data -/** - * AdminUserVipOverrideDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class AdminUserVipOverrideDTO { - - /** - * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String vipLevel; - - /** - * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/InviteCodeDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/InviteCodeDTO.java deleted file mode 100644 index 5928d240..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/InviteCodeDTO.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; -import java.time.LocalDateTime; - -@Data -/** - * InviteCodeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class InviteCodeDTO { - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long ownerUserId; - - @NotBlank(message = "邀请码不能为空") - /** - * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String inviteCode; - - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer useCount; - /** - * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime expireTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/UserDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/UserDTO.java deleted file mode 100644 index 06bce22b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/UserDTO.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.dto; - -import com.xiaowang.jacyucloudsalon.core.utils.AccountValidationUtils; -import lombok.Data; - -import javax.validation.constraints.Pattern; -import java.time.LocalDate; -import java.util.List; - -/** - * 系统用户信息表 DTO - * 用于用户信息的传输 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class UserDTO { - - /** - * 所属店铺ID,关联店铺表主键(0表示无所属店铺) - */ - private Long shopId; - - /** - * 绑定店铺ID列表 - */ - private List shopIds; - - /** - * 用户昵称 - */ - private String nickname; - - /** - * 用户账号(登录用) - */ - @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") - private String account; - - /** - * 用户密码(加密存储) - */ - private String password; - - /** - * 用户头像URL - */ - private String avatar; - - /** - * 用户签名 - */ - private String signature; - - /** - * 用户等级 - */ - private String level; - - /** - * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) - */ - private Integer type; - - /** - * 关联VIP信息表主键(0表示非VIP) - */ - private Long vipId; - - /** - * 手机号 - */ - private String phone; - - /** - * 联系电话 - */ - private String contactPhone; - - /** - * 生日 - */ - private LocalDate birthday; - - /** - * 微信号 - */ - private String wechatId; - - /** - * 微信二维码 - */ - private String wechatQrCode; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/UserRelationUpdateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/UserRelationUpdateDTO.java deleted file mode 100644 index 4d8f9e92..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/dto/UserRelationUpdateDTO.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.dto; - -import lombok.Data; - -@Data -/** - * UserRelationUpdateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserRelationUpdateDTO { - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long parentUserId; - /** - * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer parentRoleType; - /** - * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserAgreementConsentDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserAgreementConsentDO.java deleted file mode 100644 index ff1b960d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserAgreementConsentDO.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Getter -@Setter -@TableName("t_user_agreement_consent") -/** - * Purpose: UserAgreementConsentDO supports UserAgreementConsentDO.java by holding or executing the user agreement consent do business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class UserAgreementConsentDO extends BaseEntity { - - @TableField("user_id") - /** - * Purpose: userId supports UserAgreementConsentDO.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - - @TableField("agreement_type") - /** - * Purpose: agreementType supports UserAgreementConsentDO.java by holding or executing the agreement type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String agreementType; - - @TableField("version") - /** - * Purpose: version supports UserAgreementConsentDO.java by holding or executing the version business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String version; - - @TableField("entry") - /** - * Purpose: entry supports UserAgreementConsentDO.java by holding or executing the entry business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String entry; - - @TableField("client_type") - /** - * Purpose: clientType supports UserAgreementConsentDO.java by holding or executing the client type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String clientType; - - @TableField("ip_address") - /** - * Purpose: ipAddress supports UserAgreementConsentDO.java by holding or executing the ip address business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String ipAddress; - - @TableField("device_id") - /** - * Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - - @TableField("consent_time") - /** - * Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private LocalDateTime consentTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserDO.java deleted file mode 100644 index 8dd3d94d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserDO.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Getter; -import lombok.Setter; -import lombok.EqualsAndHashCode; - -import java.time.LocalDate; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -/** - * 系统用户信息表 DO - * 对应数据库表 t_user - * - * @author xiaowang - * @date 2026-02-13 - */ -@Getter -@Setter -@EqualsAndHashCode(callSuper = true) -@TableName("t_user") -public class UserDO extends BaseEntity { - - /** - * 用户唯一主键ID(雪花ID) - */ - @TableId(type = IdType.ASSIGN_ID) - private Long id; - - /** - * 所属店铺ID,关联店铺表主键(0表示无所属店铺) - */ - @TableField("shop_id") - private Long shopId; - - /** - * 用户昵称 - */ - @TableField("nickname") - private String nickname; - - /** - * 用户账号(登录用) - */ - @TableField("account") - private String account; - - /** - * 手机号 - */ - @TableField("phone") - private String phone; - - /** - * 联系电话 - */ - @TableField("contact_phone") - private String contactPhone; - - /** - * 生日 - */ - @TableField("birthday") - private LocalDate birthday; - - /** - * 微信号 - */ - @TableField("wechat_id") - private String wechatId; - - /** - * 微信二维码 - */ - @TableField("wechat_qr_code") - private String wechatQrCode; - - /** - * 邮箱 - */ - @TableField("email") - private String email; - - /** - * 手机号是否已验证:0-未验证,1-已验证 - */ - @TableField("phone_verified") - private Integer phoneVerified; - - /** - * 邮箱是否已验证:0-未验证,1-已验证 - */ - @TableField("email_verified") - private Integer emailVerified; - - /** - * 用户密码(加密存储) - */ - @TableField("password") - private String password; - - /** - * 用户头像URL - */ - @TableField("avatar") - private String avatar; - - /** - * 用户签名 - */ - @TableField("signature") - private String signature; - - /** - * 用户等级 - */ - @TableField("level") - private String level; - - /** - * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) - */ - @TableField("type") - private Integer type; - - /** - * 关联VIP信息表主键(0表示非VIP) - */ - @TableField("vip_id") - private Long vipId; - - /** - * 逻辑删除:0-未删,1-已删 - */ - @TableField("is_delete") - @TableLogic - private Integer isDelete; - - /** - * 用户状态:1-正常,0-禁用 - */ - @TableField("status") - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserGrowthRecordDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserGrowthRecordDO.java deleted file mode 100644 index 681ad1fc..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserGrowthRecordDO.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_user_growth_record") -public class UserGrowthRecordDO extends BaseEntity { - @TableField("user_id") - private Long userId; - @TableField("source_type") - private String sourceType; - @TableField("source_id") - private Long sourceId; - @TableField("growth_value") - private Integer growthValue; - @TableField("remark") - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserInviteCodeDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserInviteCodeDO.java deleted file mode 100644 index eb1e2429..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserInviteCodeDO.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.time.LocalDateTime; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_user_invite_code") -/** - * UserInviteCodeDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserInviteCodeDO extends BaseEntity { - - @TableField("invite_code") - /** - * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String inviteCode; - - @TableField("owner_user_id") - /** - * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long ownerUserId; - - @TableField("shop_id") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @TableField("status") - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - - @TableField("use_count") - /** - * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer useCount; - - @TableField("expire_time") - /** - * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime expireTime; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserRelationDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserRelationDO.java deleted file mode 100644 index f13163a5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/entity/UserRelationDO.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; -@Data -@EqualsAndHashCode(callSuper = true) -@TableName("t_user_relation") -/** - * UserRelationDO maps to a database table row. Mapper classes persist and query this object. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserRelationDO extends BaseEntity { - - @TableField("user_id") - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - @TableField("shop_id") - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - - @TableField("parent_user_id") - /** - * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long parentUserId; - - @TableField("parent_role_type") - /** - * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer parentRoleType; - - @TableField("source_type") - /** - * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceType; - - @TableField("creator_id") - /** - * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long creatorId; - - @TableField("is_delete") - @TableLogic - /** - * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer isDelete; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserAgreementConsentMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserAgreementConsentMapper.java deleted file mode 100644 index b98aea15..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserAgreementConsentMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserAgreementConsentDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -/** - * Purpose: UserAgreementConsentMapper supports UserAgreementConsentMapper.java by holding or executing the user agreement consent mapper business role. - * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. - */ -public interface UserAgreementConsentMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserGrowthRecordMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserGrowthRecordMapper.java deleted file mode 100644 index f7969434..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserGrowthRecordMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserGrowthRecordDO; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface UserGrowthRecordMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserInviteCodeMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserInviteCodeMapper.java deleted file mode 100644 index 470ee954..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserInviteCodeMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserInviteCodeDO; - -/** - * UserInviteCodeMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface UserInviteCodeMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserMapper.java deleted file mode 100644 index e5a33610..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserMapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; - -/** - * 系统用户信息表 Mapper - * 对应数据库表 t_user - * - * @author xiaowang - * @date 2026-02-13 - */ -public interface UserMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserRelationMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserRelationMapper.java deleted file mode 100644 index 9a4492c2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/mapper/UserRelationMapper.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserRelationDO; - -/** - * UserRelationMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public interface UserRelationMapper extends BaseMapper { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserAssetService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserAssetService.java deleted file mode 100644 index 2005d669..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserAssetService.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.service; - -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.AdminUserBalanceChangeDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.AdminUserVipOverrideDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAssetVO; - -import java.util.List; - -/** - * UserAssetService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface UserAssetService { - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - UserAssetVO getUserAsset(Long userId); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listBalanceHistory(Long userId); - - /** - * Run business method `changeBalance`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param operatorId parameter `operatorId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request); - - /** - * Run business method `overrideVip`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param operatorId parameter `operatorId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request); - - /** - * Run business method `recalculateVip`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param operatorId parameter `operatorId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - UserAssetVO recalculateVip(Long operatorId, Long userId); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java deleted file mode 100644 index 452c6976..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java +++ /dev/null @@ -1,397 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.service; - -import com.baomidou.mybatisplus.extension.service.IService; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.BindEmailRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.BindPhoneRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.PhoneLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningManagerRegisterDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.RegisterRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.ResetPasswordRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.UpdatePhoneRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.UserDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginShopSelectionVO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserStatisticsVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserRelationVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserVO; - -import java.util.List; - -/** - * UserService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface UserService extends IService { - - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDTO parameter `userDTO` supplied by the caller - * @return Long result consumed by the caller or returned to the frontend - */ - Long createUser(UserDTO userDTO); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param userDTO parameter `userDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updateUser(Long id, UserDTO userDTO); - - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean deleteUser(Long id); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @return UserVO result consumed by the caller or returned to the frontend - */ - UserVO getUserById(Long id); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return List result consumed by the caller or returned to the frontend - */ - List listAllUsers(); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listUsersByShopId(Long shopId); - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param type parameter `type` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - List listUsersByType(Integer type); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return UserVO result consumed by the caller or returned to the frontend - */ - UserVO getUserByAccount(String account); - - /** - * Run the login flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO login(LoginRequestDTO loginRequestDTO); - - /** - * Run business method `phoneLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO); - - /** - * Run the login flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO loginByVerifiedPhone(String phone, Long shopId); - - /** - * Run the login flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO loginByUserId(Long userId, Long shopId); - - /** - * Run business method `adminLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - LoginShopSelectionVO getLoginShopSelectionByAccount(String account); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - LoginShopSelectionVO getLoginShopSelectionByPhone(String phone); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - LoginShopSelectionVO getAdminLoginShopSelection(String account); - - /** - * Run business method `switchShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param previousSessionId parameter `previousSessionId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId); - - /** - * Run business method `switchAdminShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param previousSessionId parameter `previousSessionId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId); - - /** - * Run business method `syncManagedPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - */ - void syncManagedPermissions(Long userId); - - /** - * Run the registration flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean register(RegisterRequestDTO registerRequestDTO); - - LoginResponseVO registerPlanningManager(PlanningManagerRegisterDTO registerDTO); - - /** - * Run business method `refreshToken`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param refreshToken parameter `refreshToken` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - LoginResponseVO refreshToken(String refreshToken); - - /** - * Run business method `logout`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionId parameter `sessionId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean logout(String sessionId); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return UserVO result consumed by the caller or returned to the frontend - */ - UserVO getCurrentUserInfo(); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userDTO parameter `userDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updateCurrentUserInfo(Long userId, UserDTO userDTO); - - /** - * Run business method `bindPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO); - - /** - * Run business method `bindEmail`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO); - - /** - * Run business method `resetPassword`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetUserId parameter `targetUserId` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean resetPassword(Long targetUserId, Long currentUserId); - - /** - * Run business method `resetPasswordByPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO); - - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type); - - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @param roleId parameter `roleId` supplied by the caller - * @param parentUserId parameter `parentUserId` supplied by the caller - * @param sourceType parameter `sourceType` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param vipLevel parameter `vipLevel` supplied by the caller - * @param createdFrom parameter `createdFrom` supplied by the caller - * @param createdTo parameter `createdTo` supplied by the caller - * @param hasPhone parameter `hasPhone` supplied by the caller - * @param hasOrder parameter `hasOrder` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); - - /** - * Run business method `statisticsUsers`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @param roleId parameter `roleId` supplied by the caller - * @param parentUserId parameter `parentUserId` supplied by the caller - * @param sourceType parameter `sourceType` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param vipLevel parameter `vipLevel` supplied by the caller - * @param createdFrom parameter `createdFrom` supplied by the caller - * @param createdTo parameter `createdTo` supplied by the caller - * @param hasPhone parameter `hasPhone` supplied by the caller - * @param hasOrder parameter `hasOrder` supplied by the caller - * @return UserStatisticsVO result consumed by the caller or returned to the frontend - */ - UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return UserRelationVO result consumed by the caller or returned to the frontend - */ - UserRelationVO getCurrentUserRelation(Long userId); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updateUserStatus(Long id, Integer status); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updateUserStatusInShop(Long id, Integer status, Long shopId); - - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean deleteUserInShop(Long id, Long shopId); - - /** - * Run business method `unbindUserInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean unbindUserInShop(Long id, Long shopId); - - /** - * Run business method `unbindUserInShopWithOperator`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param operatorType parameter `operatorType` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param avatarUrl parameter `avatarUrl` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updateUserAvatar(Long userId, String avatarUrl); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param password parameter `password` supplied by the caller - * @param verificationCode parameter `verificationCode` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updatePassword(Long userId, String password, String verificationCode); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserAssetServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserAssetServiceImpl.java deleted file mode 100644 index ef045c67..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserAssetServiceImpl.java +++ /dev/null @@ -1,630 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.service.impl; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.AdminUserBalanceChangeDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.AdminUserVipOverrideDTO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceChangeDetailDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.entity.BalanceDO; -import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipBenefitDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipInfoDO; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.entity.VipRechargePlanDO; -import com.xiaowang.jacyucloudsalon.core.modules.payment.mapper.BalanceChangeDetailMapper; -import com.xiaowang.jacyucloudsalon.core.modules.payment.mapper.BalanceMapper; -import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.VipBenefitMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.VipInfoMapper; -import com.xiaowang.jacyucloudsalon.core.modules.marketing.mapper.VipRechargePlanMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserAssetService; -import com.xiaowang.jacyucloudsalon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAssetVO; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.math.BigDecimal; -import java.time.LocalDateTime; -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -import com.xiaowang.jacyucloudsalon.core.modules.marketing.service.impl.VipRechargePlanServiceImpl; -@Service -@RequiredArgsConstructor -/** - * UserAssetServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class UserAssetServiceImpl implements UserAssetService { - - /** - * Purpose: VIP_LEVEL_NORMAL supports UserAssetServiceImpl.java by holding or executing the vip level normal business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String VIP_LEVEL_NORMAL = "普通"; - /** - * Purpose: SCENE_RECHARGE supports UserAssetServiceImpl.java by holding or executing the scene recharge business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SCENE_RECHARGE = "RECHARGE"; - /** - * Purpose: SCENE_MANUAL_ADD supports UserAssetServiceImpl.java by holding or executing the scene manual add business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SCENE_MANUAL_ADD = "MANUAL_ADD"; - /** - * Purpose: SCENE_MANUAL_DEDUCT supports UserAssetServiceImpl.java by holding or executing the scene manual deduct business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SCENE_MANUAL_DEDUCT = "MANUAL_DEDUCT"; - /** - * Purpose: SCENE_ORDER_CONSUME supports UserAssetServiceImpl.java by holding or executing the scene order consume business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SCENE_ORDER_CONSUME = "ORDER_CONSUME"; - /** - * Purpose: SCENE_ORDER_REFUND supports UserAssetServiceImpl.java by holding or executing the scene order refund business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SCENE_ORDER_REFUND = "ORDER_REFUND"; - /** - * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceMapper balanceMapper; - /** - * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final BalanceChangeDetailMapper balanceChangeDetailMapper; - /** - * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipInfoMapper vipInfoMapper; - /** - * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VipBenefitMapper vipBenefitMapper; - /** - * Purpose: vipRechargePlanMapper supports UserAssetServiceImpl.java by holding or executing the vip recharge plan mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final VipRechargePlanMapper vipRechargePlanMapper; - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - /** - * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final OrderMapper orderMapper; - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - public UserAssetVO getUserAsset(Long userId) { - UserDO user = getAvailableUser(userId); - BalanceDO balance = ensureBalance(userId); - VipInfoDO vipInfo = getVipInfo(userId); - VipBenefitDO benefit = vipInfo != null && vipInfo.getBenefitId() != null - ? vipBenefitMapper.selectById(vipInfo.getBenefitId()) - : null; - /** - * Run business method `toAssetVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param balance parameter `balance` supplied by the caller - * @param vipInfo parameter `vipInfo` supplied by the caller - * @param benefit parameter `benefit` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return toAssetVO(user, balance, vipInfo, benefit); - } - - @Override - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ - public List listBalanceHistory(Long userId) { - UserDO user = getAvailableUser(userId); - return balanceChangeDetailMapper.selectList( - Wrappers.lambdaQuery(BalanceChangeDetailDO.class) - .eq(BalanceChangeDetailDO::getUserId, userId) - .orderByDesc(BalanceChangeDetailDO::getChangeTime) - .orderByDesc(BalanceChangeDetailDO::getId)) - .stream() - .map(detail -> toBalanceHistoryVO(detail, user.getNickname())) - .collect(Collectors.toList()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `changeBalance`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param operatorId parameter `operatorId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - public UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request) { - if (request == null || request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param 0 parameter `0` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("变动金额必须大于 0"); - } - if (!StringUtils.hasText(request.getChangeScene())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("变动场景不能为空"); - } - - UserDO user = getAvailableUser(userId); - BalanceDO balance = ensureBalance(userId); - LocalDateTime now = LocalDateTime.now(); - - BigDecimal beforeBalance = defaultDecimal(balance.getAmount()); - BigDecimal delta = normalizeDelta(request.getAmount(), request.getChangeScene()); - BigDecimal afterBalance = beforeBalance.add(delta); - if (afterBalance.compareTo(BigDecimal.ZERO) < 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("余额不足,无法执行扣减"); - } - - OrderDO relatedOrder = null; - String relatedOrderNo = null; - if (request.getRelatedOrderId() != null) { - relatedOrder = orderMapper.selectById(request.getRelatedOrderId()); - if (relatedOrder == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("关联系统订单不存在"); - } - if (!userId.equals(relatedOrder.getUserId())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("所选订单不属于当前用户"); - } - relatedOrderNo = relatedOrder.getOrderNo(); - } - - if (isDeductScene(request.getChangeScene()) - && relatedOrder == null - && !StringUtils.hasText(request.getExternalOrderNo())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("扣减余额时必须关联系统订单或填写外部订单号"); - } - - balance.setAmount(afterBalance); - balance.setLastUpdateTime(now); - if (SCENE_RECHARGE.equals(request.getChangeScene())) { - balance.setTotalRechargeAmount(defaultDecimal(balance.getTotalRechargeAmount()).add(request.getAmount())); - balance.setLastRechargeTime(now); - } - balanceMapper.updateById(balance); - - BalanceChangeDetailDO detail = new BalanceChangeDetailDO(); - detail.setUserId(userId); - detail.setAmount(delta); - detail.setType(request.getChangeScene()); - detail.setCurrentBalance(afterBalance); - detail.setBeforeBalance(beforeBalance); - detail.setAfterBalance(afterBalance); - detail.setChangeScene(request.getChangeScene()); - detail.setRelatedOrderId(relatedOrder != null ? relatedOrder.getId() : null); - detail.setRelatedOrderNo(relatedOrderNo); - detail.setExternalOrderNo(StringUtils.hasText(request.getExternalOrderNo()) ? request.getExternalOrderNo().trim() : null); - detail.setOperatorId(operatorId); - detail.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null); - detail.setChangeTime(now); - balanceChangeDetailMapper.insert(detail); - - if (SCENE_RECHARGE.equals(request.getChangeScene())) { - /** - * Run business method `recalculateVipInternal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param false parameter `false` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - recalculateVipInternal(user, false); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return getUserAsset(userId); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `overrideVip`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param operatorId parameter `operatorId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - public UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request) { - if (request == null || !StringUtils.hasText(request.getVipLevel())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("VIP 等级不能为空"); - } - - UserDO user = getAvailableUser(userId); - String targetLevel = request.getVipLevel().trim(); - VipInfoDO vipInfo = getOrCreateVipInfo(userId); - vipInfo.setActivationMethod("MANUAL_OVERRIDE"); - vipInfo.setManualOverride(1); - vipInfo.setStartTime(LocalDateTime.now()); - - VipBenefitDO benefit = null; - if (!VIP_LEVEL_NORMAL.equals(targetLevel)) { - benefit = vipBenefitMapper.selectOne( - Wrappers.lambdaQuery(VipBenefitDO.class) - .eq(VipBenefitDO::getRequiredVipLevel, targetLevel) - .eq(VipBenefitDO::getStatus, 1) - .last("limit 1")); - if (benefit == null && !isVipLevelAvailable(targetLevel)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标 VIP 等级未配置有效规则"); - } - vipInfo.setBenefitId(benefit != null ? benefit.getId() : null); - } else { - vipInfo.setBenefitId(null); - } - vipInfo.setVipLevel(targetLevel); - vipInfoMapper.updateById(vipInfo); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param vipInfo parameter `vipInfo` supplied by the caller - * @param targetLevel parameter `targetLevel` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateUserVipFields(user, vipInfo, targetLevel); - return toAssetVO(userMapper.selectById(userId), ensureBalance(userId), vipInfo, benefit); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `recalculateVip`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param operatorId parameter `operatorId` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return UserAssetVO result consumed by the caller or returned to the frontend - */ - public UserAssetVO recalculateVip(Long operatorId, Long userId) { - UserDO user = getAvailableUser(userId); - /** - * Run business method `recalculateVipInternal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param true parameter `true` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - recalculateVipInternal(user, true); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return getUserAsset(userId); - } - - /** - * Run business method `recalculateVipInternal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param clearManualOverride parameter `clearManualOverride` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void recalculateVipInternal(UserDO user, boolean clearManualOverride) { - BalanceDO balance = ensureBalance(user.getId()); - VipBenefitDO matchedBenefit = vipBenefitMapper.selectList( - Wrappers.lambdaQuery(VipBenefitDO.class) - .eq(VipBenefitDO::getStatus, 1) - .orderByAsc(VipBenefitDO::getLevelRank) - .orderByAsc(VipBenefitDO::getRechargeThreshold)) - .stream() - .filter(benefit -> defaultDecimal(balance.getTotalRechargeAmount()) - .compareTo(defaultDecimal(benefit.getRechargeThreshold())) >= 0) - .max(Comparator.comparing(VipBenefitDO::getLevelRank, Comparator.nullsLast(Integer::compareTo)) - .thenComparing(VipBenefitDO::getRechargeThreshold, Comparator.nullsLast(BigDecimal::compareTo))) - .orElse(null); - - VipInfoDO vipInfo = getVipInfo(user.getId()); - if (vipInfo != null && Integer.valueOf(1).equals(vipInfo.getManualOverride()) && !clearManualOverride) { - return; - } - if (vipInfo == null && matchedBenefit == null) { - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param VIP_LEVEL_NORMAL parameter `VIP_LEVEL_NORMAL` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateUserVipFields(user, null, VIP_LEVEL_NORMAL); - return; - } - - vipInfo = vipInfo == null ? getOrCreateVipInfo(user.getId()) : vipInfo; - vipInfo.setActivationMethod("AUTO_RECALCULATE"); - vipInfo.setManualOverride(clearManualOverride ? 0 : vipInfo.getManualOverride()); - vipInfo.setStartTime(LocalDateTime.now()); - - String targetLevel = matchedBenefit != null ? matchedBenefit.getRequiredVipLevel() : VIP_LEVEL_NORMAL; - vipInfo.setVipLevel(targetLevel); - vipInfo.setBenefitId(matchedBenefit != null ? matchedBenefit.getId() : null); - vipInfoMapper.updateById(vipInfo); - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param vipInfo parameter `vipInfo` supplied by the caller - * @param targetLevel parameter `targetLevel` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - updateUserVipFields(user, vipInfo, targetLevel); - } - - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param vipInfo parameter `vipInfo` supplied by the caller - * @param vipLevel parameter `vipLevel` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void updateUserVipFields(UserDO user, VipInfoDO vipInfo, String vipLevel) { - user.setLevel(StringUtils.hasText(vipLevel) ? vipLevel : VIP_LEVEL_NORMAL); - user.setVipId(VIP_LEVEL_NORMAL.equals(user.getLevel()) || vipInfo == null ? 0L : vipInfo.getId()); - user.setUpdateTime(LocalDateTime.now()); - userMapper.updateById(user); - } - - /** - * Run business method `normalizeDelta`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param amount parameter `amount` supplied by the caller - * @param changeScene parameter `changeScene` supplied by the caller - * @return private BigDecimal result consumed by the caller or returned to the frontend - */ - private BigDecimal normalizeDelta(BigDecimal amount, String changeScene) { - if (isDeductScene(changeScene)) { - return amount.negate(); - } - if (SCENE_RECHARGE.equals(changeScene) || SCENE_MANUAL_ADD.equals(changeScene) || SCENE_ORDER_REFUND.equals(changeScene)) { - return amount; - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("不支持的余额变动场景"); - } - - /** - * Run business method `isDeductScene`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param changeScene parameter `changeScene` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isDeductScene(String changeScene) { - return SCENE_MANUAL_DEDUCT.equals(changeScene) || SCENE_ORDER_CONSUME.equals(changeScene); - } - - /** - * Run business method `ensureBalance`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private BalanceDO result consumed by the caller or returned to the frontend - */ - private BalanceDO ensureBalance(Long userId) { - BalanceDO balance = balanceMapper.selectOne( - Wrappers.lambdaQuery(BalanceDO.class) - .eq(BalanceDO::getUserId, userId) - .last("limit 1")); - if (balance != null) { - if (balance.getAmount() == null) { - balance.setAmount(BigDecimal.ZERO); - } - if (balance.getTotalRechargeAmount() == null) { - balance.setTotalRechargeAmount(BigDecimal.ZERO); - } - return balance; - } - - balance = new BalanceDO(); - balance.setUserId(userId); - balance.setAmount(BigDecimal.ZERO); - balance.setTotalRechargeAmount(BigDecimal.ZERO); - balance.setLastUpdateTime(LocalDateTime.now()); - balanceMapper.insert(balance); - return balance; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private VipInfoDO result consumed by the caller or returned to the frontend - */ - private VipInfoDO getVipInfo(Long userId) { - return vipInfoMapper.selectOne( - Wrappers.lambdaQuery(VipInfoDO.class) - .eq(VipInfoDO::getUserId, userId) - .last("limit 1")); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private VipInfoDO result consumed by the caller or returned to the frontend - */ - private VipInfoDO getOrCreateVipInfo(Long userId) { - VipInfoDO vipInfo = getVipInfo(userId); - if (vipInfo != null) { - return vipInfo; - } - vipInfo = new VipInfoDO(); - vipInfo.setUserId(userId); - vipInfo.setVipLevel(VIP_LEVEL_NORMAL); - vipInfo.setManualOverride(0); - vipInfo.setActivationMethod("INIT"); - vipInfo.setStartTime(LocalDateTime.now()); - vipInfoMapper.insert(vipInfo); - return vipInfo; - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO getAvailableUser(Long userId) { - UserDO user = userMapper.selectById(userId); - if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户不存在"); - } - return user; - } - - /** - * Purpose: isVipLevelAvailable supports UserAssetServiceImpl.java by holding or executing the is vip level available business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isVipLevelAvailable(String vipLevel) { - if (!StringUtils.hasText(vipLevel)) { - return false; - } - if (VipRechargePlanServiceImpl.DEFAULT_VIP_LEVELS.contains(vipLevel.trim())) { - return true; - } - Long count = vipRechargePlanMapper.selectCount( - Wrappers.lambdaQuery(VipRechargePlanDO.class) - .eq(VipRechargePlanDO::getVipLevel, vipLevel.trim()) - .eq(VipRechargePlanDO::getStatus, 1) - .eq(VipRechargePlanDO::getIsDelete, 0)); - return count != null && count > 0; - } - - /** - * Run business method `defaultDecimal`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param value parameter `value` supplied by the caller - * @return private BigDecimal result consumed by the caller or returned to the frontend - */ - private BigDecimal defaultDecimal(BigDecimal value) { - return value == null ? BigDecimal.ZERO : value; - } - - /** - * Run business method `toAssetVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param user parameter `user` supplied by the caller - * @param balance parameter `balance` supplied by the caller - * @param vipInfo parameter `vipInfo` supplied by the caller - * @param benefit parameter `benefit` supplied by the caller - * @return private UserAssetVO result consumed by the caller or returned to the frontend - */ - private UserAssetVO toAssetVO(UserDO user, BalanceDO balance, VipInfoDO vipInfo, VipBenefitDO benefit) { - UserAssetVO vo = new UserAssetVO(); - vo.setUserId(user.getId()); - vo.setNickname(user.getNickname()); - vo.setBalance(defaultDecimal(balance != null ? balance.getAmount() : null)); - vo.setTotalRechargeAmount(defaultDecimal(balance != null ? balance.getTotalRechargeAmount() : null)); - vo.setLastRechargeTime(balance != null ? balance.getLastRechargeTime() : null); - vo.setVipInfoId(vipInfo != null ? vipInfo.getId() : null); - vo.setVipLevel(StringUtils.hasText(user.getLevel()) ? user.getLevel() : VIP_LEVEL_NORMAL); - vo.setBenefitId(vipInfo != null ? vipInfo.getBenefitId() : null); - vo.setBenefitInfo(benefit != null ? benefit.getBenefitInfo() : null); - vo.setManualOverride(vipInfo != null && Integer.valueOf(1).equals(vipInfo.getManualOverride())); - vo.setVipStartTime(vipInfo != null ? vipInfo.getStartTime() : null); - vo.setVipExpireTime(vipInfo != null ? vipInfo.getExpireTime() : null); - return vo; - } - - /** - * Run business method `toBalanceHistoryVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param detail parameter `detail` supplied by the caller - * @param nickname parameter `nickname` supplied by the caller - * @return private BalanceChangeDetailVO result consumed by the caller or returned to the frontend - */ - private BalanceChangeDetailVO toBalanceHistoryVO(BalanceChangeDetailDO detail, String nickname) { - BalanceChangeDetailVO vo = new BalanceChangeDetailVO(); - vo.setId(detail.getId()); - vo.setUserId(detail.getUserId()); - vo.setUserNickname(nickname); - vo.setAmount(detail.getAmount()); - vo.setType(detail.getType()); - vo.setCurrentBalance(detail.getCurrentBalance()); - vo.setBeforeBalance(detail.getBeforeBalance()); - vo.setAfterBalance(detail.getAfterBalance()); - vo.setChangeScene(detail.getChangeScene()); - vo.setRelatedOrderId(detail.getRelatedOrderId()); - vo.setRelatedOrderNo(detail.getRelatedOrderNo()); - vo.setExternalOrderNo(detail.getExternalOrderNo()); - vo.setOperatorId(detail.getOperatorId()); - vo.setRemark(detail.getRemark()); - vo.setChangeTime(detail.getChangeTime()); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java deleted file mode 100644 index 864e562a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,3259 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.xiaowang.jacyucloudsalon.core.config.BrandProperties; -import com.xiaowang.fingertipdesigner.core.common.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.artist.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.auth.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.content.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.file.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.integration.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.message.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.order.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.payment.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.planning.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.product.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.security.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.shop.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.system.dto.*; -import com.xiaowang.fingertipdesigner.core.modules.user.dto.*; -import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserPermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserRelationDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserInviteCodeDO; -import com.xiaowang.jacyucloudsalon.core.modules.security.entity.UserShopRoleDO; -import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.WechatMiniBindingDO; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; -import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.UserPermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.PermissionMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserRelationMapper; -import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserInviteCodeMapper; -import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.UserShopRoleMapper; -import com.xiaowang.jacyucloudsalon.core.modules.integration.mapper.WechatMiniBindingMapper; -import com.xiaowang.jacyucloudsalon.core.modules.artist.service.NailArtistInfoService; -import com.xiaowang.jacyucloudsalon.core.modules.shop.service.ShopService; -import com.xiaowang.jacyucloudsalon.core.modules.system.service.SystemParameterConfigService; -import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; -import com.xiaowang.jacyucloudsalon.core.modules.auth.service.VerificationCodeService; -import com.xiaowang.jacyucloudsalon.core.modules.system.support.AdminDefaultPasswordSupport; -import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionCatalog; -import com.xiaowang.jacyucloudsalon.core.support.security.UserSessionService; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionPolicy; -import com.xiaowang.jacyucloudsalon.core.support.RequestShopContext; -import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; -import com.xiaowang.jacyucloudsalon.core.modules.user.support.UserProfileFieldSupport; -import com.xiaowang.jacyucloudsalon.core.utils.AccountValidationUtils; -import com.xiaowang.jacyucloudsalon.core.utils.JwtUtil; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginShopSelectionVO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jacyucloudsalon.core.common.vo.PageResultVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserVO; -import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserRelationVO; -import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserStatisticsVO; -import lombok.RequiredArgsConstructor; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; - -import java.math.BigDecimal; -import java.time.Duration; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.BindEmailRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.BindPhoneRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.PhoneLoginRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.RegisterRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.ResetPasswordRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.UpdatePhoneRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningManagerRegisterDTO; -import com.xiaowang.jacyucloudsalon.core.modules.user.dto.UserDTO; -/** - * 系统用户信息表 Service 实现 - * 对应数据库表 t_user - * - * @author xiaowang - * @date 2026-02-13 - */ -@Service -@RequiredArgsConstructor -public class UserServiceImpl extends ServiceImpl implements UserService { - /** - * Purpose: VIP_LEVEL_NORMAL supports UserServiceImpl.java by holding or executing the vip level normal business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String VIP_LEVEL_NORMAL = "普通"; - /** - * Purpose: PHONE_REGEX supports UserServiceImpl.java by holding or executing the phone regex business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; - /** - * Purpose: DEFAULT_AVATAR_URL supports UserServiceImpl.java by holding or executing the default avatar url business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; - private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5); - /** - * Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String DELETED_PHONE_MARKER = "_deleted_"; - /** - * Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String LOGIN_FAIL_KEY_PREFIX = "user:login:failed:"; - /** - * Purpose: MAX_LOGIN_FAILURES supports UserServiceImpl.java by holding or executing the max login failures business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final int MAX_LOGIN_FAILURES = 5; - private static final Duration LOGIN_FAIL_EXPIRE = Duration.ofDays(7); - /** - * Purpose: SYSTEM_PERMISSION_ASSIGNER_ID supports UserServiceImpl.java by holding or executing the system permission assigner id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L; - private static final Set MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes(); - private static final Map DEFAULT_PERMISSION_SEEDS = PermissionCatalog.getDefinitionsByCode(); - /** - * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserMapper userMapper; - private final ShopMapper shopMapper; - /** - * Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final JwtUtil jwtUtil; - /** - * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ShopService shopService; - /** - * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserPermissionMapper userPermissionMapper; - /** - * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final PermissionMapper permissionMapper; - /** - * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserRelationMapper userRelationMapper; - /** - * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserInviteCodeMapper userInviteCodeMapper; - private final BrandProperties brandProperties; - /** - * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopRoleMapper userShopRoleMapper; - /** - * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final NailArtistInfoService nailArtistInfoService; - private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - /** - * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final VerificationCodeService verificationCodeService; - /** - * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserShopBindingSupport userShopBindingSupport; - /** - * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final ObjectStorageUrlSupport objectStorageUrlSupport; - /** - * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final StringRedisTemplate redisTemplate; - /** - * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; - /** - * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final WechatMiniBindingMapper wechatMiniBindingMapper; - /** - * Variable `userSessionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserSessionService userSessionService; - private final SystemParameterConfigService systemParameterConfigService; - - /** - * Run business method `synchronizeManagedDefaultPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void synchronizeManagedDefaultPermissions(Long userId, Integer userType) { - List desiredPermissionCodes = getDefaultPermissionCodes(userType); - List managedPermissions = permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .eq(PermissionDO::getIsDelete, 0) - .in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES) - ); - - if (managedPermissions.isEmpty()) { - return; - } - - Map permissionIdByCode = managedPermissions.stream() - .collect(Collectors.toMap(PermissionDO::getPermissionCode, PermissionDO::getId, (left, right) -> left)); - List managedPermissionIds = managedPermissions.stream() - .map(PermissionDO::getId) - .collect(Collectors.toList()); - Set desiredPermissionIds = desiredPermissionCodes.stream() - .map(permissionIdByCode::get) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - - List currentPermissions = userPermissionMapper.selectList( - Wrappers.lambdaQuery(UserPermissionDO.class) - .eq(UserPermissionDO::getUserId, userId) - .in(UserPermissionDO::getPermissionId, managedPermissionIds) - ); - - Set currentPermissionIds = currentPermissions.stream() - .map(UserPermissionDO::getPermissionId) - .collect(Collectors.toSet()); - List stalePermissionIds = currentPermissions.stream() - .map(UserPermissionDO::getPermissionId) - .filter(permissionId -> !desiredPermissionIds.contains(permissionId)) - .distinct() - .collect(Collectors.toList()); - - if (!stalePermissionIds.isEmpty()) { - userPermissionMapper.delete( - Wrappers.lambdaQuery(UserPermissionDO.class) - .eq(UserPermissionDO::getUserId, userId) - .in(UserPermissionDO::getPermissionId, stalePermissionIds) - ); - } - - for (Long permissionId : desiredPermissionIds) { - if (currentPermissionIds.contains(permissionId)) { - continue; - } - UserPermissionDO userPermissionDO = new UserPermissionDO(); - userPermissionDO.setUserId(userId); - userPermissionDO.setPermissionId(permissionId); - userPermissionDO.setCreateBy(SYSTEM_PERMISSION_ASSIGNER_ID); - userPermissionMapper.insert(userPermissionDO); - } - } - - /** - * Run business method `ensurePermissionDefinitions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensurePermissionDefinitions() { - List existingPermissions = permissionMapper.selectList( - Wrappers.lambdaQuery(PermissionDO.class) - .in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES) - ); - - Map existingByCode = existingPermissions.stream() - .collect(Collectors.toMap(PermissionDO::getPermissionCode, permission -> permission, (left, right) -> left)); - - for (String permissionCode : MANAGED_DEFAULT_PERMISSION_CODES) { - PermissionCatalog.PermissionDefinition permissionSeed = DEFAULT_PERMISSION_SEEDS.get(permissionCode); - if (permissionSeed == null) { - continue; - } - - PermissionDO permissionDO = existingByCode.get(permissionCode); - if (permissionDO == null) { - permissionDO = new PermissionDO(); - permissionDO.setPermissionCode(permissionCode); - permissionDO.setPermissionName(permissionSeed.permissionName()); - permissionDO.setPermissionGroup(permissionSeed.permissionGroup()); - permissionDO.setDescription(permissionSeed.description()); - permissionDO.setIsDelete(0); - permissionDO.setUpdateTime(LocalDateTime.now()); - permissionMapper.insert(permissionDO); - continue; - } - - if (isPermissionDefinitionCurrent(permissionDO, permissionSeed)) { - continue; - } - - permissionDO.setPermissionName(permissionSeed.permissionName()); - permissionDO.setPermissionGroup(permissionSeed.permissionGroup()); - permissionDO.setDescription(permissionSeed.description()); - permissionDO.setIsDelete(0); - permissionDO.setUpdateTime(LocalDateTime.now()); - permissionMapper.updateById(permissionDO); - } - } - - private boolean isPermissionDefinitionCurrent(PermissionDO permissionDO, PermissionCatalog.PermissionDefinition permissionSeed) { - return Objects.equals(permissionDO.getPermissionName(), permissionSeed.permissionName()) - && Objects.equals(permissionDO.getPermissionGroup(), permissionSeed.permissionGroup()) - && Objects.equals(permissionDO.getDescription(), permissionSeed.description()) - && Objects.equals(permissionDO.getIsDelete(), 0); - } - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userType parameter `userType` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List getDefaultPermissionCodes(Integer userType) { - return PermissionPolicy.getDefaultPermissionCodes(userType); - } - - /** - * Run business method `assignDefaultPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assignDefaultPermissions(Long userId, Integer userType) { - if (getDefaultPermissionCodes(userType).isEmpty()) { - return; - } - /** - * Run business method `syncDefaultPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - syncDefaultPermissions(userId, userType); - } - - /** - * 创建新用户 - * @param userDTO 用户数据传输对象 - * @return 新创建用户的ID - */ - @Override - @Transactional(rollbackFor = Exception.class) - public Long createUser(UserDTO userDTO) { - String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); - // 检查账号是否已存在 - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) - .eq(UserDO::getIsDelete, 0) - ); - if (existingUser != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("账号已存在"); - } - - List validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); - Long validatedShopId = pickPrimaryShopId(validatedShopIds); - String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); - Integer userType = userDTO.getType(); - String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); - UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); - - /** - * Run business method `ensureShopBindingRequirement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userType parameter `userType` supplied by the caller - * @param validatedShopIds parameter `validatedShopIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureShopBindingRequirement(userType, validatedShopIds); - - // 创建用户实体并设置属性 - UserDO userDO = new UserDO(); - userDO.setShopId(validatedShopId); - userDO.setNickname(userDTO.getNickname()); - userDO.setAccount(validatedAccount); - String resolvedPassword = AdminDefaultPasswordSupport.resolveCreatePassword( - userDTO.getPassword(), - getConfiguredAdminDefaultPassword() - ); - validatePasswordStrength(resolvedPassword); - userDO.setPassword(passwordEncoder.encode(resolvedPassword)); - userDO.setPhone(validatedPhone); - userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); - userDO.setBirthday(userDTO.getBirthday()); - userDO.setWechatId(validatedWechatId); - userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); - userDO.setSignature(userDTO.getSignature()); - userDO.setLevel(userDTO.getLevel()); - userDO.setType(userType); - userDO.setVipId(userDTO.getVipId()); - userDO.setIsDelete(0); - userDO.setStatus(1); - if (StringUtils.hasText(userDTO.getAvatar())) { - userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); - } else { - userDO.setAvatar(DEFAULT_AVATAR_URL); - } - - if (Integer.valueOf(0).equals(userDO.getType())) { - if (!StringUtils.hasText(userDO.getLevel())) { - userDO.setLevel(VIP_LEVEL_NORMAL); - } - if (userDO.getVipId() == null) { - userDO.setVipId(0L); - } - } - - try { - // 插入用户数据 - userMapper.insert(userDO); - } catch (Exception e) { - // 捕获重复账号异常 - if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("账号已被使用"); - } - throw e; - } - - // 分配默认权限 - assignDefaultPermissions(userDO.getId(), userDO.getType()); - userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds); - - // 如果是美甲师,创建对应的美甲师信息记录 - if (userDO.getType() == 3) { - NailArtistInfoDTO nailArtistInfoDTO = new NailArtistInfoDTO(); - nailArtistInfoDTO.setUserId(userDO.getId()); - nailArtistInfoDTO.setIdentity(""); // 默认身份为空 - nailArtistInfoDTO.setExperience(0); // 默认经验为0 - nailArtistInfoDTO.setSkills(""); // 默认技能为空 - nailArtistInfoDTO.setRating(DEFAULT_NAIL_ARTIST_RATING); // 默认评分为4.5 - nailArtistInfoDTO.setStatus(1); // 默认状态为营业中 - nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空 - nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); - } - - return userDO.getId(); - } - - /** - * 分配默认权限 - * @param userId 用户ID - * @param userType 用户类型 - */ - private void syncDefaultPermissions(Long userId, Integer userType) { - if (userId == null) { - return; - } - - /** - * Run business method `ensurePermissionDefinitions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return result consumed by the caller or returned to the frontend - */ - ensurePermissionDefinitions(); - /** - * Run business method `synchronizeManagedDefaultPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userType parameter `userType` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - synchronizeManagedDefaultPermissions(userId, userType); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `syncManagedPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - */ - public void syncManagedPermissions(Long userId) { - if (userId == null) { - return; - } - UserDO userDO = userMapper.selectById(userId); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return; - } - syncDefaultPermissions(userDO.getId(), userDO.getType()); - } - - /** - * 更新用户信息 - * @param id 用户ID - * @param userDTO 用户数据传输对象 - * @return 更新是否成功 - */ - @Override - @Transactional(rollbackFor = Exception.class) - public boolean updateUser(Long id, UserDTO userDTO) { - // 查询用户是否存在 - UserDO userDO = userMapper.selectById(id); - if (userDO == null) { - return false; - } - - // 更新账号(如果提供且变更) - String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount()); - if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - ); - if (existingUser != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("账号已存在"); - } - userDO.setAccount(normalizedAccount); - } - - // 更新其他字段(如果提供) - if (userDTO.getShopId() != null) { - userDO.setShopId(validateAndNormalizeShopId(userDTO.getShopId())); - } - if (userDTO.getNickname() != null) { - userDO.setNickname(userDTO.getNickname()); - } - if (userDTO.getPassword() != null) { - validatePasswordStrength(userDTO.getPassword()); - userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); - } - if (userDTO.getPhone() != null) { - userDO.setPhone(validateUserPhone(userDTO.getPhone(), id, true)); - } - if (userDTO.getContactPhone() != null) { - userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); - } - if (userDTO.getBirthday() != null) { - userDO.setBirthday(userDTO.getBirthday()); - } - if (userDTO.getWechatId() != null) { - userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); - } - if (userDTO.getWechatQrCode() != null) { - userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); - } - if (userDTO.getAvatar() != null) { - if (userDTO.getAvatar().isEmpty()) { - userDO.setAvatar(null); - } else { - userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); - } - } - if (userDTO.getSignature() != null) { - userDO.setSignature(userDTO.getSignature()); - } - if (userDTO.getLevel() != null) { - userDO.setLevel(userDTO.getLevel()); - } - if (userDTO.getType() != null) { - userDO.setType(userDTO.getType()); - } - if (userDTO.getVipId() != null) { - userDO.setVipId(userDTO.getVipId()); - } - Integer targetUserType = userDO.getType(); - UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); - List validatedShopIds = null; - boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; - if (shopBindingChanged) { - validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); - /** - * Run business method `ensureShopBindingRequirement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetUserType parameter `targetUserType` supplied by the caller - * @param validatedShopIds parameter `validatedShopIds` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensureShopBindingRequirement(targetUserType, validatedShopIds); - userDO.setShopId(pickPrimaryShopId(validatedShopIds)); - } - userDO.setUpdateTime(LocalDateTime.now()); - boolean updated = userMapper.updateById(userDO) > 0; - if (updated) { - if (shopBindingChanged) { - userShopBindingSupport.syncUserShopBindings(id, validatedShopIds); - } - if (userDTO.getPassword() != null) { - userSessionService.revokeAllUserSessions(id); - } - /** - * Run business method `syncDefaultPermissions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param targetUserType parameter `targetUserType` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - syncDefaultPermissions(id, targetUserType); - } - return updated; - } - - /** - * 删除用户 - * @param id 用户ID - * @return 删除是否成功 - */ - @Override - public boolean deleteUser(Long id) { - UserDO userDO = userMapper.selectById(id); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return false; - } - - clearLoginFailureCount(userDO.getAccount()); - userSessionService.revokeAllUserSessions(id); - userShopBindingSupport.deleteBindingsByUserId(id); - wechatMiniBindingMapper.update( - null, - new LambdaUpdateWrapper() - .eq(WechatMiniBindingDO::getUserId, id) - .set(WechatMiniBindingDO::getStatus, 0) - .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) - ); - LocalDateTime now = LocalDateTime.now(); - return userMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserDO::getId, id) - .eq(UserDO::getIsDelete, 0) - .set(UserDO::getAccount, buildDeletedAccount(userDO)) - .set(UserDO::getPhone, buildDeletedPhone(userDO)) - .set(UserDO::getStatus, 0) - .set(UserDO::getIsDelete, 1) - .set(UserDO::getUpdateTime, now) - ) > 0; - } - - /** - * 根据ID获取用户信息 - * @param id 用户ID - * @return 用户视图对象 - */ - @Override - public UserVO getUserById(Long id) { - UserDO userDO = userMapper.selectById(id); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(userDO); - } - - /** - * 获取所有用户列表 - * @return 用户视图对象列表 - */ - @Override - public List listAllUsers() { - List userDOs = userMapper.selectList( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getIsDelete, 0) - ); - return userDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 根据店铺ID获取用户列表 - * @param shopId 店铺ID - * @return 用户视图对象列表 - */ - @Override - public List listUsersByShopId(Long shopId) { - List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); - if (userIds.isEmpty()) { - return List.of(); - } - List userDOs = userMapper.selectList( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getIsDelete, 0) - .in(UserDO::getId, userIds) - ); - return userDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 根据用户类型获取用户列表 - * @param type 用户类型 - * @return 用户视图对象列表 - */ - @Override - public List listUsersByType(Integer type) { - List userDOs = userMapper.selectList( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getType, type) - ); - return userDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); - } - - /** - * 根据账号获取用户信息 - * @param account 用户账号 - * @return 用户视图对象 - */ - @Override - public UserVO getUserByAccount(String account) { - String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - ); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return null; - } - /** - * Run business method `convertToVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return convertToVO(userDO); - } - - /** - * 将 DO 转换为 VO - * @param userDO 用户DO - * @param userDO 用户DO - * @return 用户VO - */ - private UserVO convertToVO(UserDO userDO) { - UserVO userVO = new UserVO(); - userVO.setId(userDO.getId()); - List shopOptions = resolveShopOptions(userDO, true, false); - Long scopedShopId = RequestShopContext.getCurrentShopId(); - if (scopedShopId != null) { - shopOptions.stream() - .filter(shop -> Objects.equals(shop.getId(), scopedShopId)) - .findFirst() - .ifPresent(shop -> { - shopOptions.remove(shop); - shopOptions.add(0, shop); - }); - } - Long primaryShopId = !shopOptions.isEmpty() ? shopOptions.get(0).getId() : normalizeShopId(userDO.getShopId()); - String primaryShopName = !shopOptions.isEmpty() ? shopOptions.get(0).getShopName() : null; - userVO.setShopId(primaryShopId); - userVO.setShopName(primaryShopName); - userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); - userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); - userVO.setNickname(userDO.getNickname()); - userVO.setAccount(userDO.getAccount()); - userVO.setPhone(userDO.getPhone()); - userVO.setContactPhone(userDO.getContactPhone()); - userVO.setBirthday(userDO.getBirthday()); - userVO.setWechatId(userDO.getWechatId()); - userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); - userVO.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); - userVO.setSignature(userDO.getSignature()); - userVO.setLevel(userDO.getLevel()); - userVO.setType(userDO.getType()); - userVO.setTypeName(resolveUserTypeName(userDO.getType())); - userVO.setVipId(userDO.getVipId()); - userVO.setCreateTime(userDO.getCreateTime()); - userVO.setUpdateTime(userDO.getUpdateTime()); - userVO.setStatus(userDO.getStatus() != null ? userDO.getStatus() : 1); - userVO.setEmail(userDO.getEmail()); - userVO.setMaskedPhone(maskPhone(userDO.getPhone())); - userVO.setMaskedEmail(maskEmail(userDO.getEmail())); - applyRelationInfo(userVO, userDO.getId()); - return userVO; - } - - /** - * Run business method `resolveAccessibleAvatar`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param avatarUrl parameter `avatarUrl` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveAccessibleAvatar(String avatarUrl) { - if (!StringUtils.hasText(avatarUrl)) { - return DEFAULT_AVATAR_URL; - } - return objectStorageUrlSupport.toAccessibleUrl(avatarUrl); - } - - /** - * Run business method `normalizeStoredAvatar`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param avatarUrl parameter `avatarUrl` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String normalizeStoredAvatar(String avatarUrl) { - if (!StringUtils.hasText(avatarUrl)) { - return avatarUrl; - } - return objectStorageUrlSupport.toStoredUrl(avatarUrl); - } - - private String resolveAccessibleProfileImage(String imageUrl) { - if (!StringUtils.hasText(imageUrl)) { - return imageUrl; - } - return objectStorageUrlSupport.toAccessibleUrl(imageUrl); - } - - private String normalizeStoredProfileImage(String imageUrl) { - if (!StringUtils.hasText(imageUrl)) { - return null; - } - return objectStorageUrlSupport.toStoredUrl(imageUrl); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) { - String normalizedAccount = account == null ? "" : account.trim(); - if (!StringUtils.hasText(normalizedAccount)) { - return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺"); - } - AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); - - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - if (userDO == null) { - return buildLoginShopSelection(List.of(), false, "该账号不存在"); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); - } - - if (Integer.valueOf(4).equals(userDO.getType())) { - List shops = listSelectableShopOptionsForPlatformAdmin(); - String message = shops.isEmpty() - ? "当前暂无店铺,可直接登录" - : "平台管理员可选择任意店铺作为本次登录店铺"; - return buildLoginShopSelection(shops, true, message); - } - - List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); - if (!shops.isEmpty()) { - return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); - } - - if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { - return buildLoginShopSelection( - userShopBindingSupport.listAllActiveShopOptions(), - false, - "该账号首次登录,请先选择店铺" - ); - } - - return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理"); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - public LoginShopSelectionVO getLoginShopSelectionByPhone(String phone) { - String normalizedPhone = phone == null ? "" : phone.trim(); - if (!StringUtils.hasText(normalizedPhone)) { - return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺"); - } - - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - if (userDO == null) { - return buildLoginShopSelection( - userShopBindingSupport.listAllActiveShopOptions(), - false, - "新手机号首次登录需要选择店铺" - ); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); - } - - if (Integer.valueOf(4).equals(userDO.getType())) { - List shops = listSelectableShopOptionsForPlatformAdmin(); - String message = shops.isEmpty() - ? "当前暂无店铺,可直接登录" - : "平台管理员可选择任意店铺作为本次登录店铺"; - return buildLoginShopSelection(shops, true, message); - } - - List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); - if (!shops.isEmpty()) { - return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); - } - - if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { - return buildLoginShopSelection( - userShopBindingSupport.listAllActiveShopOptions(), - false, - "该手机号账号首次登录,请先选择店铺" - ); - } - - return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理"); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - public LoginShopSelectionVO getAdminLoginShopSelection(String account) { - String normalizedAccount = account == null ? "" : account.trim(); - if (!StringUtils.hasText(normalizedAccount)) { - return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺"); - } - AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); - - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - if (userDO == null) { - return buildLoginShopSelection(List.of(), false, "该账号不存在"); - } - if (userDO.getType() == null || userDO.getType() < 2) { - return buildLoginShopSelection(List.of(), false, "该账号不是后台管理账号"); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); - } - - if (Integer.valueOf(4).equals(userDO.getType())) { - List shops = listSelectableShopOptionsForPlatformAdmin(); - String message = shops.isEmpty() - ? "当前暂无可选店铺,可直接进入平台总览模式" - : "平台管理员可直接进入平台总览,也可选择任意店铺作为本次登录店铺"; - /** - * Run business method `buildLoginShopSelection`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shops parameter `shops` supplied by the caller - * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller - * @param message parameter `message` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildLoginShopSelection(shops, true, message); - } - - List shops = listEnabledShopOptionsForUser(userDO.getId()); - if (!shops.isEmpty()) { - return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); - } - return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系平台管理员"); - } - - @Override - /** - * Run the login flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO login(LoginRequestDTO loginRequestDTO) { - String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); - - /** - * Run business method `assertLoginAccountAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertLoginAccountAvailable(userDO); - - // 检查是否为未设置密码的账号 - if (ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请使用手机号验证码登录,并在个人中心设置密码"); - } - - if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { - /** - * Run business method `handleLoginPasswordFailure`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - handleLoginPasswordFailure(userDO); - } - - Long resolvedShopId = resolveUserLoginShopId(userDO, loginRequestDTO.getShopId()); - clearLoginFailureCount(userDO.getAccount()); - /** - * Run business method `buildLoginResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param resolvedShopId parameter `resolvedShopId` supplied by the caller - * @param false parameter `false` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); - } - - @Override - /** - * Run business method `phoneLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO) { - if (!verificationCodeService.verifyCode(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getVerificationCode())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("验证码错误或已过期"); - } - - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) - .eq(UserDO::getIsDelete, 0) - ); - - if (userDO == null) { - if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("首次登录需要选择店铺"); - } - userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId()); - } else { - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - clearLoginFailureCount(userDO.getAccount()); - } - - Long resolvedShopId = resolveUserLoginShopId(userDO, phoneLoginRequestDTO.getShopId()); - return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), Boolean.TRUE.equals(phoneLoginRequestDTO.getRememberMe())); - } - - // 未设置密码的特殊标识 - @Override - /** - * Run the login flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - - if (userDO == null) { - if (shopId == null || shopId == 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("首次登录需要选择店铺"); - } - userDO = registerByPhone(phone, shopId); - } else { - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - clearLoginFailureCount(userDO.getAccount()); - } - - Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); - return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); - } - - @Override - /** - * Run the login flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO loginByUserId(Long userId, Long shopId) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - clearLoginFailureCount(userDO.getAccount()); - Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); - return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); - } - - /** - * Purpose: UNSET_PASSWORD_MARKER supports UserServiceImpl.java by holding or executing the unset password marker business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String UNSET_PASSWORD_MARKER = "__UNSET_PASSWORD__"; - /** - * Purpose: ENCODED_UNSET_PASSWORD supports UserServiceImpl.java by holding or executing the encoded unset password business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识 - - /** - * Run the registration flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return private UserDO result consumed by the caller or returned to the frontend - */ - private UserDO registerByPhone(String phone, Long shopId) { - Long validatedShopId = validateAndNormalizeShopId(shopId); - if (validatedShopId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("首次登录需要选择店铺"); - } - UserDO userDO = new UserDO(); - userDO.setAccount(phone); - userDO.setPhone(phone); - userDO.setPhoneVerified(1); - userDO.setNickname("用户" + phone.substring(7)); - userDO.setType(0); - userDO.setLevel(VIP_LEVEL_NORMAL); - userDO.setVipId(0L); - userDO.setShopId(validatedShopId); - userDO.setIsDelete(0); - userDO.setStatus(1); - userDO.setCreateTime(LocalDateTime.now()); - userDO.setUpdateTime(LocalDateTime.now()); - userDO.setPassword(ENCODED_UNSET_PASSWORD); - - userMapper.insert(userDO); - syncDefaultPermissions(userDO.getId(), userDO.getType()); - userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); - return userDO; - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `adminLogin`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) { - String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); - - /** - * Run business method `assertLoginAccountAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertLoginAccountAvailable(userDO); - - if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { - /** - * Run business method `handleLoginPasswordFailure`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - handleLoginPasswordFailure(userDO); - } - - Integer userType = userDO.getType(); - if (userType == null || userType < 2) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号不是后台管理账号"); - } - - Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); - clearLoginFailureCount(userDO.getAccount()); - /** - * Run business method `buildLoginResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param resolvedShopId parameter `resolvedShopId` supplied by the caller - * @param false parameter `false` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); - } - - @Override - /** - * Run business method `switchShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param previousSessionId parameter `previousSessionId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - Integer userType = userDO.getType(); - if (userType != null && userType >= 2 && !Integer.valueOf(4).equals(userType)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号请使用后台切换店铺"); - } - Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); - return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), previousSessionId); - } - - @Override - /** - * Run business method `switchAdminShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param previousSessionId parameter `previousSessionId` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - Integer userType = userDO.getType(); - if (userType == null || userType < 2) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("您没有后台管理权限"); - } - Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId); - /** - * Run business method `buildLoginResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param resolvedShopId parameter `resolvedShopId` supplied by the caller - * @param false parameter `false` supplied by the caller - * @param previousSessionId parameter `previousSessionId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildLoginResponse(userDO, resolvedShopId, false, previousSessionId); - } - - /** - * Run business method `resolveAdminLoginShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param requestedShopId parameter `requestedShopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) { - Long normalizedRequestedShopId = normalizeShopId(requestedShopId); - if (Integer.valueOf(4).equals(userDO.getType())) { - if (normalizedRequestedShopId == null) { - return null; - } - boolean canSelectShop = listSelectableShopOptionsForPlatformAdmin().stream() - .map(ShopSimpleVO::getId) - .anyMatch(shopId -> Objects.equals(shopId, normalizedRequestedShopId)); - if (!canSelectShop) { - throw new RuntimeException("当前账号无权登录所选店铺"); - } - return normalizedRequestedShopId; - } - - List activeShopIds = listEnabledShopOptionsForUser(userDO.getId()).stream() - .map(ShopSimpleVO::getId) - .collect(Collectors.toList()); - if (activeShopIds.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员"); - } - if (normalizedRequestedShopId != null) { - if (!activeShopIds.contains(normalizedRequestedShopId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号无权登录所选店铺"); - } - return normalizedRequestedShopId; - } - if (activeShopIds.size() == 1) { - return activeShopIds.get(0); - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择登录店铺"); - } - - /** - * Run business method `hasAnyShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean hasAnyShop() { - return !listEnabledShopOptionsForAdmin().isEmpty(); - } - - /** - * Run business method `normalizeShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long normalizeShopId(Long shopId) { - return shopId != null && shopId > 0 ? shopId : null; - } - - @Override - /** - * Run the registration flow. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean register(RegisterRequestDTO registerRequestDTO) { - String validatedAccount = AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()); - if (!verificationCodeService.verifyCode(registerRequestDTO.getPhone(), registerRequestDTO.getVerificationCode())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("验证码错误或已过期"); - } - - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) - ); - - if (existingUser != null) { - if (existingUser.getIsDelete() == 0) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("账号已存在"); - } else { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号已被注销,请使用手机号验证码登录"); - } - } - - UserDO existingPhoneUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, registerRequestDTO.getPhone()) - .eq(UserDO::getIsDelete, 0) - ); - - if (existingPhoneUser != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该手机号已被注册"); - } - - Long validatedShopId = resolveRegisterShopId(registerRequestDTO.getShopId(), registerRequestDTO.getInviteCode()); - if (validatedShopId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择店铺"); - } - - UserDO userDO = new UserDO(); - userDO.setShopId(validatedShopId); - userDO.setAccount(validatedAccount); - validatePasswordStrength(registerRequestDTO.getPassword()); - userDO.setPassword(passwordEncoder.encode(registerRequestDTO.getPassword())); - userDO.setNickname(registerRequestDTO.getNickname()); - userDO.setPhone(registerRequestDTO.getPhone()); - userDO.setPhoneVerified(1); - userDO.setType(Integer.valueOf(0)); - userDO.setLevel(VIP_LEVEL_NORMAL); - userDO.setVipId(0L); - userDO.setIsDelete(Integer.valueOf(0)); - userDO.setCreateTime(LocalDateTime.now()); - userDO.setUpdateTime(LocalDateTime.now()); - - userMapper.insert(userDO); - assignDefaultPermissions(userDO.getId(), userDO.getType()); - userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); - createRelationForRegister(userDO.getId(), validatedShopId, registerRequestDTO.getInviteCode()); - return true; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public LoginResponseVO registerPlanningManager(PlanningManagerRegisterDTO registerDTO) { - if (registerDTO == null) { - throw new RuntimeException("注册信息不能为空"); - } - String phone = validateUserPhone(registerDTO.getPhone(), null, true); - if (!verificationCodeService.verifyCode(phone, registerDTO.getCode())) { - throw new RuntimeException("验证码错误或已过期"); - } - String password = registerDTO.getPassword(); - if (!StringUtils.hasText(password)) { - throw new RuntimeException("密码不能为空"); - } - if (!Objects.equals(password, registerDTO.getConfirmPassword())) { - throw new RuntimeException("两次密码不一致"); - } - validatePasswordStrength(password); - String shopName = registerDTO.getShopName() == null ? null : registerDTO.getShopName().trim(); - if (!StringUtils.hasText(shopName)) { - throw new RuntimeException("店铺名称不能为空"); - } - - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); - if (existingUser != null) { - throw new RuntimeException("该手机号已注册"); - } - - ShopDO shop = new ShopDO(); - shop.setShopName(shopName); - shop.setDescription(brandProperties.getManagerRegisterShopDescription()); - shop.setBusinessHours("10:00-22:00"); - shop.setStatus(1); - shop.setAuthorizationStartDate(LocalDateTime.now().minusDays(1).toLocalDate()); - shop.setAuthorizationDays(0); - shop.setAuthorizationExpireTime(LocalDateTime.now().minusSeconds(1)); - shop.setIsDelete(0); - shopMapper.insert(shop); - - UserDO manager = new UserDO(); - manager.setShopId(shop.getId()); - manager.setNickname(shopName + "店长"); - manager.setAccount(phone); - manager.setPassword(passwordEncoder.encode(password)); - manager.setPhone(phone); - manager.setContactPhone(phone); - manager.setPhoneVerified(1); - manager.setEmailVerified(0); - manager.setType(2); - manager.setStatus(1); - manager.setIsDelete(0); - manager.setAvatar(DEFAULT_AVATAR_URL); - userMapper.insert(manager); - - syncDefaultPermissions(manager.getId(), manager.getType()); - userShopBindingSupport.syncUserShopBindings(manager.getId(), List.of(shop.getId())); - createRelationForRegister(manager.getId(), shop.getId(), null); - clearLoginFailureCount(manager.getAccount()); - return buildLoginResponse(manager, shop.getId(), false); - } - - @Override - /** - * Run business method `refreshToken`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param refreshToken parameter `refreshToken` supplied by the caller - * @return LoginResponseVO result consumed by the caller or returned to the frontend - */ - public LoginResponseVO refreshToken(String refreshToken) { - if (!jwtUtil.validateToken(refreshToken)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param Token parameter `Token` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("刷新Token无效或已过期"); - } - - if (!jwtUtil.isRefreshToken(refreshToken)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param Token parameter `Token` supplied by the caller - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("Token类型错误"); - } - - Long userId = jwtUtil.getUserIdFromToken(refreshToken); - String account = jwtUtil.getAccountFromToken(refreshToken); - Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); - String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); - String refreshJti = jwtUtil.getJtiFromToken(refreshToken); - if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("登录态已失效,请重新登录"); - } - - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; - if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前登录店铺已失效,请重新登录"); - } - - return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), sessionId); - } - - @Override - /** - * Run business method `logout`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sessionId parameter `sessionId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean logout(String sessionId) { - userSessionService.revokeSession(sessionId); - return true; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return UserVO result consumed by the caller or returned to the frontend - */ - public UserVO getCurrentUserInfo() { - org.springframework.web.context.request.ServletRequestAttributes attributes = - (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes(); - Long userId = attributes == null ? null : (Long) attributes.getRequest().getAttribute("userId"); - return userId == null ? null : getUserById(userId); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param userDTO parameter `userDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateCurrentUserInfo(Long userId, UserDTO userDTO) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - - if (userDTO.getNickname() != null) { - userDO.setNickname(userDTO.getNickname()); - } - if (userDTO.getAvatar() != null) { - if (userDTO.getAvatar().isEmpty()) { - userDO.setAvatar(null); - } else { - userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); - } - } - if (userDTO.getSignature() != null) { - userDO.setSignature(userDTO.getSignature()); - } - if (userDTO.getContactPhone() != null) { - userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); - } - if (userDTO.getBirthday() != null) { - userDO.setBirthday(userDTO.getBirthday()); - } - if (userDTO.getWechatId() != null) { - userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); - } - if (userDTO.getWechatQrCode() != null) { - userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); - } - UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); - - userDO.setUpdateTime(LocalDateTime.now()); - boolean updated = userMapper.updateById(userDO) > 0; - if (updated) { - syncDefaultPermissions(userDO.getId(), userDO.getType()); - } - return updated; - } - - @Override - /** - * Run business method `bindPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - validateVerificationCode(bindPhoneRequestDTO.getPhone(), bindPhoneRequestDTO.getVerificationCode()); - ensurePhoneNotUsed(bindPhoneRequestDTO.getPhone(), userId); - - userDO.setPhone(bindPhoneRequestDTO.getPhone()); - userDO.setPhoneVerified(1); - userDO.setUpdateTime(LocalDateTime.now()); - - return userMapper.updateById(userDO) > 0; - } - - @Override - /** - * Run business method `bindEmail`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO) { - UserDO userDO = userMapper.selectById(userId); - if (userDO == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户不存在"); - } - - userDO.setEmail(bindEmailRequestDTO.getEmail()); - userDO.setEmailVerified(1); - userDO.setUpdateTime(LocalDateTime.now()); - - return userMapper.updateById(userDO) > 0; - } - - @Override - /** - * Run business method `resetPassword`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param targetUserId parameter `targetUserId` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean resetPassword(Long targetUserId, Long currentUserId) { - UserDO targetUser = userMapper.selectById(targetUserId); - if (targetUser == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("目标用户不存在"); - } - - UserDO currentUser = userMapper.selectById(currentUserId); - if (currentUser == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前用户不存在"); - } - - Integer currentUserType = currentUser.getType(); - Integer targetUserType = targetUser.getType(); - - if (currentUserType == null || targetUserType == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户类型错误"); - } - - if (currentUserType <= targetUserType) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("权限不足,只能重置比自己级别低的用户密码"); - } - - targetUser.setPassword(passwordEncoder.encode(resolveAdminDefaultPassword())); - targetUser.setUpdateTime(LocalDateTime.now()); - boolean updated = userMapper.updateById(targetUser) > 0; - if (updated) { - userSessionService.revokeAllUserSessions(targetUserId); - } - return updated; - } - - @Override - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type) { - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return pageUsers(page, size, keyword, shopId, type, null, null, null, null, null, null, null, null, null); - } - - @Override - /** - * Query paged records. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param page parameter `page` supplied by the caller - * @param size parameter `size` supplied by the caller - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @param roleId parameter `roleId` supplied by the caller - * @param parentUserId parameter `parentUserId` supplied by the caller - * @param sourceType parameter `sourceType` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param vipLevel parameter `vipLevel` supplied by the caller - * @param createdFrom parameter `createdFrom` supplied by the caller - * @param createdTo parameter `createdTo` supplied by the caller - * @param hasPhone parameter `hasPhone` supplied by the caller - * @param hasOrder parameter `hasOrder` supplied by the caller - * @return PageResultVO result consumed by the caller or returned to the frontend - */ - public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { - Page pageParam = new Page<>(page, size); - - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); - wrapper.eq(UserDO::getIsDelete, 0); - // 不再过滤普通用户,由前端根据用户角色进行过滤 - if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(UserDO::getAccount, keyword) - .or().like(UserDO::getNickname, keyword) - .or().like(UserDO::getPhone, keyword) - .or().like(UserDO::getContactPhone, keyword)); - } - if (shopId != null && shopId > 0) { - List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); - if (userIds.isEmpty()) { - PageResultVO emptyResult = new PageResultVO<>(); - emptyResult.setList(List.of()); - emptyResult.setTotal(0L); - emptyResult.setPage(page); - emptyResult.setSize(size); - return emptyResult; - } - wrapper.in(UserDO::getId, userIds); - } - Set relationFilteredIds = resolveRelationFilteredUserIds(roleId, parentUserId, sourceType); - if (relationFilteredIds != null) { - if (relationFilteredIds.isEmpty()) { - PageResultVO emptyResult = new PageResultVO<>(); - emptyResult.setList(List.of()); - emptyResult.setTotal(0L); - emptyResult.setPage(page); - emptyResult.setSize(size); - return emptyResult; - } - wrapper.in(UserDO::getId, relationFilteredIds); - } - if (type != null) { - wrapper.eq(UserDO::getType, type); - } - if (status != null) { - wrapper.eq(UserDO::getStatus, status); - } - if (StringUtils.hasText(vipLevel)) { - wrapper.eq(UserDO::getLevel, vipLevel); - } - if (StringUtils.hasText(createdFrom)) { - wrapper.ge(UserDO::getCreateTime, LocalDateTime.parse(createdFrom)); - } - if (StringUtils.hasText(createdTo)) { - wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo)); - } - if (Boolean.TRUE.equals(hasPhone)) { - wrapper.isNotNull(UserDO::getPhone); - } - if (Boolean.FALSE.equals(hasPhone)) { - wrapper.isNull(UserDO::getPhone); - } - wrapper.orderByDesc(UserDO::getCreateTime); - - Page userPage = userMapper.selectPage(pageParam, wrapper); - - PageResultVO result = new PageResultVO<>(); - result.setList(userPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); - result.setTotal(userPage.getTotal()); - result.setPage(page); - result.setSize(size); - - return result; - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateUserStatus(Long id, Integer status) { - UserDO userDO = userMapper.selectById(id); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return false; - } - Integer normalizedStatus = Integer.valueOf(1).equals(status) ? 1 : 0; - boolean updated = userMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserDO::getId, id) - .eq(UserDO::getIsDelete, 0) - .set(UserDO::getStatus, normalizedStatus) - .set(UserDO::getUpdateTime, LocalDateTime.now()) - ) > 0; - if (updated && normalizedStatus == 1) { - UserDO latestUser = userMapper.selectById(id); - if (latestUser != null) { - clearLoginFailureCount(latestUser.getAccount()); - } - } else if (updated) { - userSessionService.revokeAllUserSessions(id); - } - return updated; - } - - @Override - /** - * Run business method `statisticsUsers`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param keyword parameter `keyword` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param type parameter `type` supplied by the caller - * @param roleId parameter `roleId` supplied by the caller - * @param parentUserId parameter `parentUserId` supplied by the caller - * @param sourceType parameter `sourceType` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param vipLevel parameter `vipLevel` supplied by the caller - * @param createdFrom parameter `createdFrom` supplied by the caller - * @param createdTo parameter `createdTo` supplied by the caller - * @param hasPhone parameter `hasPhone` supplied by the caller - * @param hasOrder parameter `hasOrder` supplied by the caller - * @return UserStatisticsVO result consumed by the caller or returned to the frontend - */ - public UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { - List users = pageUsers(1, Integer.MAX_VALUE, keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder).getList(); - UserStatisticsVO vo = new UserStatisticsVO(); - vo.setTotalUserCount(users.size()); - vo.setNormalUserCount(users.stream().filter(u -> Integer.valueOf(0).equals(u.getType())).count()); - vo.setEmployeeCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType()) || Integer.valueOf(3).equals(u.getType())).count()); - vo.setManagerCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType())).count()); - vo.setArtistCount(users.stream().filter(u -> Integer.valueOf(3).equals(u.getType())).count()); - vo.setVipUserCount(users.stream().filter(u -> StringUtils.hasText(u.getLevel()) && !"普通".equals(u.getLevel())).count()); - vo.setNewUserCount(users.stream().filter(u -> u.getCreateTime() != null && u.getCreateTime().isAfter(LocalDateTime.now().minusDays(7))).count()); - vo.setByShop(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopId()), Collectors.counting()))); - vo.setByRole(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopRoleName()), Collectors.counting()))); - vo.setByParent(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getParentUserName()), Collectors.counting()))); - return vo; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return UserRelationVO result consumed by the caller or returned to the frontend - */ - public UserRelationVO getCurrentUserRelation(Long userId) { - /** - * Run business method `buildRelationVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildRelationVO(userId); - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateUserStatusInShop(Long id, Integer status, Long shopId) { - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return updateUserStatus(id, status); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean deleteUserInShop(Long id, Long shopId) { - /** - * Run business method `unbindUserInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return unbindUserInShop(id, shopId); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `unbindUserInShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean unbindUserInShop(Long id, Long shopId) { - /** - * Run business method `unbindUserInShopWithOperator`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return unbindUserInShopWithOperator(id, shopId, null); - } - - @Override - @Transactional(rollbackFor = Exception.class) - /** - * Run business method `unbindUserInShopWithOperator`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param id parameter `id` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param operatorType parameter `operatorType` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType) { - Long normalizedShopId = normalizeShopId(shopId); - if (normalizedShopId == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前操作缺少店铺上下文"); - } - UserDO userDO = userMapper.selectById(id); - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - return false; - } - - boolean success = userShopBindingSupport.updateBindingStatus(id, normalizedShopId, 0); - if (!success) { - return false; - } - - if (Integer.valueOf(2).equals(operatorType) && Integer.valueOf(3).equals(userDO.getType())) { - userDO.setType(0); - userDO.setUpdateTime(LocalDateTime.now()); - userMapper.updateById(userDO); - syncDefaultPermissions(userDO.getId(), userDO.getType()); - } - return true; - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param avatarUrl parameter `avatarUrl` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updateUserAvatar(Long userId, String avatarUrl) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - userDO.setAvatar(avatarUrl); - userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param password parameter `password` supplied by the caller - * @param verificationCode parameter `verificationCode` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updatePassword(Long userId, String password, String verificationCode) { - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - if (!StringUtils.hasText(userDO.getPhone())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请先绑定手机号"); - } - validateVerificationCode(userDO.getPhone(), verificationCode); - validatePasswordStrength(password); - userDO.setPassword(passwordEncoder.encode(password)); - userDO.setUpdateTime(LocalDateTime.now()); - boolean updated = userMapper.updateById(userDO) > 0; - if (updated) { - userSessionService.revokeAllUserSessions(userId); - } - return updated; - } - - @Override - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { - String oldPhone = updatePhoneDTO.getOldPhone(); - String newPhone = updatePhoneDTO.getNewPhone(); - String verificationCode = updatePhoneDTO.getVerificationCode(); - - UserDO userDO = userMapper.selectById(userId); - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - assertUserAvailable(userDO); - if (!StringUtils.hasText(userDO.getPhone())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号未绑定手机号"); - } - if (!userDO.getPhone().equals(oldPhone)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("原手机号不匹配"); - } - - /** - * Run business method `validateVerificationCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param newPhone parameter `newPhone` supplied by the caller - * @param verificationCode parameter `verificationCode` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateVerificationCode(newPhone, verificationCode); - /** - * Run business method `ensurePhoneNotUsed`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param newPhone parameter `newPhone` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePhoneNotUsed(newPhone, userId); - - userDO.setPhone(newPhone); - userDO.setPhoneVerified(1); - userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; - } - - @Override - /** - * Run business method `resetPasswordByPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO) { - String phone = resetPasswordRequestDTO.getPhone(); - String verificationCode = resetPasswordRequestDTO.getVerificationCode(); - String newPassword = resetPasswordRequestDTO.getNewPassword(); - - /** - * Run business method `validateVerificationCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param verificationCode parameter `verificationCode` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - validateVerificationCode(phone, verificationCode); - - // 根据手机号查找用户 - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); - wrapper.eq(UserDO::getPhone, phone); - wrapper.eq(UserDO::getIsDelete, 0); - UserDO userDO = userMapper.selectOne(wrapper); - - if (userDO == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("未绑定手机号,请联系店员"); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("账号已被禁用"); - } - - // 更新密码 - validatePasswordStrength(newPassword); - userDO.setPassword(passwordEncoder.encode(newPassword)); - userDO.setUpdateTime(LocalDateTime.now()); - boolean updated = userMapper.updateById(userDO) > 0; - if (updated) { - userSessionService.revokeAllUserSessions(userDO.getId()); - } - return updated; - } - - /** - * Run business method `buildDeletedAccount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildDeletedAccount(UserDO userDO) { - String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); - String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted"; - /** - * Run business method `trimDeletedPlaceholder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param suffix parameter `suffix` supplied by the caller - * @param 50 parameter `50` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); - } - - /** - * Run business method `buildDeletedPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildDeletedPhone(UserDO userDO) { - String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); - String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone"; - /** - * Run business method `trimDeletedPlaceholder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param suffix parameter `suffix` supplied by the caller - * @param 50 parameter `50` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); - } - - /** - * Run business method `trimDeletedPlaceholder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param value parameter `value` supplied by the caller - * @param maxLength parameter `maxLength` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String trimDeletedPlaceholder(String value, int maxLength) { - if (!StringUtils.hasText(value) || value.length() <= maxLength) { - return value; - } - return value.substring(value.length() - maxLength); - } - - /** - * Run business method `assertUserAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertUserAvailable(UserDO userDO) { - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("用户不存在"); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("账号已被禁用"); - } - } - - /** - * Run business method `assertLoginAccountAvailable`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void assertLoginAccountAvailable(UserDO userDO) { - if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号不存在"); - } - if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号已被禁用"); - } - } - - /** - * Run business method `handleLoginPasswordFailure`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void handleLoginPasswordFailure(UserDO userDO) { - if (userDO == null || !StringUtils.hasText(userDO.getAccount())) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("密码错误"); - } - String failKey = buildLoginFailKey(userDO.getAccount()); - Long failCount = redisTemplate.opsForValue().increment(failKey); - redisTemplate.expire(failKey, LOGIN_FAIL_EXPIRE); - long safeFailCount = failCount == null ? 1L : failCount; - if (safeFailCount >= MAX_LOGIN_FAILURES) { - disableUserByFailedPassword(userDO.getId()); - redisTemplate.delete(failKey); - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("密码错误次数过多,账号已被禁用"); - } - long remainingAttempts = MAX_LOGIN_FAILURES - safeFailCount; - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("密码错误,还可尝试" + remainingAttempts + "次"); - } - - /** - * Run business method `disableUserByFailedPassword`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void disableUserByFailedPassword(Long userId) { - if (userId == null) { - return; - } - userMapper.update( - null, - new LambdaUpdateWrapper() - .eq(UserDO::getId, userId) - .eq(UserDO::getIsDelete, 0) - .set(UserDO::getStatus, 0) - .set(UserDO::getUpdateTime, LocalDateTime.now()) - ); - userSessionService.revokeAllUserSessions(userId); - } - - /** - * Run business method `clearLoginFailureCount`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void clearLoginFailureCount(String account) { - if (!StringUtils.hasText(account)) { - return; - } - redisTemplate.delete(buildLoginFailKey(account)); - } - - /** - * Run business method `buildLoginFailKey`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildLoginFailKey(String account) { - return LOGIN_FAIL_KEY_PREFIX + account.trim(); - } - - /** - * Run business method `validateVerificationCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param verificationCode parameter `verificationCode` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void validateVerificationCode(String phone, String verificationCode) { - if (!StringUtils.hasText(phone) || !StringUtils.hasText(verificationCode)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("验证码不能为空"); - } - if (!verificationCodeService.verifyCode(phone, verificationCode)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("验证码错误或已过期"); - } - } - - /** - * Purpose: validatePasswordStrength supports UserServiceImpl.java by holding or executing the validate password strength business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void validatePasswordStrength(String password) { - if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { - throw new RuntimeException("密码长度需为 8-32 位"); - } - int count = 0; - if (password.matches(".*\\d.*")) { - count++; - } - if (password.matches(".*[a-z].*")) { - count++; - } - if (password.matches(".*[A-Z].*")) { - count++; - } - if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { - count++; - } - if (count < 3) { - throw new RuntimeException("密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); - } - } - - private String resolveAdminDefaultPassword() { - return AdminDefaultPasswordSupport.resolveDefaultPassword(getConfiguredAdminDefaultPassword()); - } - - private String getConfiguredAdminDefaultPassword() { - return systemParameterConfigService.getEnabledValue( - AdminDefaultPasswordSupport.CONFIG_GROUP, - AdminDefaultPasswordSupport.CONFIG_KEY - ); - } - - /** - * Run business method `resolveValidatedShopIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @param fallbackShopId parameter `fallbackShopId` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List resolveValidatedShopIds(List shopIds, Long fallbackShopId) { - LinkedHashSet resolvedShopIds = new LinkedHashSet<>(); - if (shopIds != null) { - for (Long shopId : shopIds) { - Long validatedShopId = validateAndNormalizeShopId(shopId); - if (validatedShopId != null) { - resolvedShopIds.add(validatedShopId); - } - } - } - Long validatedFallbackShopId = validateAndNormalizeShopId(fallbackShopId); - if (validatedFallbackShopId != null) { - resolvedShopIds.add(validatedFallbackShopId); - } - return new ArrayList<>(resolvedShopIds); - } - - /** - * Run business method `pickPrimaryShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopIds parameter `shopIds` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long pickPrimaryShopId(List shopIds) { - return shopIds == null || shopIds.isEmpty() ? null : shopIds.get(0); - } - - /** - * Run business method `ensureShopBindingRequirement`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userType parameter `userType` supplied by the caller - * @param shopIds parameter `shopIds` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensureShopBindingRequirement(Integer userType, List shopIds) { - if (Integer.valueOf(4).equals(userType)) { - return; - } - if (shopIds == null || shopIds.isEmpty()) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请至少选择一个所属店铺"); - } - } - - /** - * Run business method `buildLoginShopSelection`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shops parameter `shops` supplied by the caller - * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller - * @param message parameter `message` supplied by the caller - * @return private LoginShopSelectionVO result consumed by the caller or returned to the frontend - */ - private LoginShopSelectionVO buildLoginShopSelection(List shops, boolean allowShoplessLogin, String message) { - LoginShopSelectionVO selectionVO = new LoginShopSelectionVO(); - selectionVO.setAllowShoplessLogin(allowShoplessLogin); - selectionVO.setMessage(message); - selectionVO.setShops(shops == null ? new ArrayList<>() : new ArrayList<>(shops)); - return selectionVO; - } - - /** - * Run business method `buildLoginShopMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shops parameter `shops` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildLoginShopMessage(List shops) { - if (shops == null || shops.isEmpty()) { - return "当前暂无可登录店铺"; - } - if (shops.size() == 1) { - return "已匹配到 1 家可登录店铺,已为您默认选中"; - } - return "该账号已绑定多家店铺,请选择本次登录店铺"; - } - - /** - * Run business method `buildAdminLoginShopMessage`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shops parameter `shops` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildAdminLoginShopMessage(List shops) { - if (shops == null || shops.isEmpty()) { - return "当前暂无启用店铺,可直接进入平台总览模式"; - } - if (shops.size() == 1) { - return "平台管理员将进入平台总览模式,店铺业务默认仅可查看"; - } - return "当前已有 " + shops.size() + " 家启用店铺;平台管理员将进入平台总览模式"; - } - - /** - * Run business method `resolveUserLoginShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param requestedShopId parameter `requestedShopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) { - if (Integer.valueOf(4).equals(userDO.getType())) { - return resolveAdminLoginShopId(userDO, requestedShopId); - } - Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId); - List activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()); - if (!activeShopIds.isEmpty()) { - if (normalizedRequestedShopId != null) { - if (!activeShopIds.contains(normalizedRequestedShopId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号无权登录所选店铺"); - } - return normalizedRequestedShopId; - } - if (activeShopIds.size() == 1) { - return activeShopIds.get(0); - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择登录店铺"); - } - - if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { - if (normalizedRequestedShopId != null) { - userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), normalizedRequestedShopId); - return normalizedRequestedShopId; - } - - Long legacyShopId = normalizeShopId(userDO.getShopId()); - if (legacyShopId != null && userShopBindingSupport.isShopActive(legacyShopId)) { - userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), legacyShopId); - return legacyShopId; - } - - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择店铺"); - } - - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("当前账号没有可登录的店铺,请联系门店处理"); - } - - /** - * Run business method `buildLoginResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param currentShopId parameter `currentShopId` supplied by the caller - * @param needSetPassword parameter `needSetPassword` supplied by the caller - * @return private LoginResponseVO result consumed by the caller or returned to the frontend - */ - private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) { - /** - * Run business method `buildLoginResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param currentShopId parameter `currentShopId` supplied by the caller - * @param needSetPassword parameter `needSetPassword` supplied by the caller - * @param null parameter `null` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return buildLoginResponse(userDO, currentShopId, needSetPassword, null); - } - - private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, boolean rememberMe) { - return buildLoginResponse(userDO, currentShopId, needSetPassword, null, rememberMe); - } - - /** - * Run business method `buildLoginResponse`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param currentShopId parameter `currentShopId` supplied by the caller - * @param needSetPassword parameter `needSetPassword` supplied by the caller - * @param previousSessionId parameter `previousSessionId` supplied by the caller - * @return private LoginResponseVO result consumed by the caller or returned to the frontend - */ - private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId) { - return buildLoginResponse(userDO, currentShopId, needSetPassword, previousSessionId, false); - } - - private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId, boolean rememberMe) { - UserSessionService.SessionIssueResult sessionIssueResult = StringUtils.hasText(previousSessionId) - ? userSessionService.rotateSession(previousSessionId, userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()) - : userSessionService.issueSession(userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()); - String accessToken = jwtUtil.generateAccessToken( - userDO.getId(), - userDO.getAccount(), - currentShopId, - sessionIssueResult.sessionId(), - sessionIssueResult.accessJti(), - jwtUtil.resolveAccessTokenExpirationSeconds(rememberMe) - ); - String refreshToken = jwtUtil.generateRefreshToken( - userDO.getId(), - userDO.getAccount(), - currentShopId, - sessionIssueResult.sessionId(), - sessionIssueResult.refreshJti() - ); - - LoginResponseVO responseVO = new LoginResponseVO(); - responseVO.setAccessToken(accessToken); - responseVO.setRefreshToken(refreshToken); - responseVO.setNeedSetPassword(needSetPassword); - responseVO.setUserInfo(buildLoginUserInfo(userDO, currentShopId)); - return responseVO; - } - - /** - * Run business method `buildLoginUserInfo`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param currentShopId parameter `currentShopId` supplied by the caller - * @return private LoginResponseVO.UserInfo result consumed by the caller or returned to the frontend - */ - private LoginResponseVO.UserInfo buildLoginUserInfo(UserDO userDO, Long currentShopId) { - boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; - List activeShopOptions = resolveShopOptions(userDO, true, !adminLogin); - Long normalizedCurrentShopId = normalizeShopId(currentShopId); - String currentShopName = activeShopOptions.stream() - .filter(shop -> Objects.equals(shop.getId(), normalizedCurrentShopId)) - .map(ShopSimpleVO::getShopName) - .findFirst() - .orElseGet(() -> { - if (normalizedCurrentShopId == null) { - return null; - } - ShopVO shopVO = shopService.getShopById(normalizedCurrentShopId); - return shopVO == null ? null : shopVO.getShopName(); - }); - - LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo(); - userInfo.setId(userDO.getId()); - userInfo.setAccount(userDO.getAccount()); - userInfo.setNickname(userDO.getNickname()); - userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); - userInfo.setType(userDO.getType()); - userInfo.setShopId(normalizedCurrentShopId); - userInfo.setShopName(currentShopName); - ShopVO currentShop = normalizedCurrentShopId == null ? null : shopService.getShopById(normalizedCurrentShopId); - userInfo.setShopAuthorizationExpireTime(currentShop == null ? null : currentShop.getAuthorizationExpireTime()); - userInfo.setShopAuthorizationExpired(currentShop != null && Boolean.TRUE.equals(currentShop.getAuthorizationExpired())); - userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); - userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); - userInfo.setCreateTime(userDO.getCreateTime()); - return userInfo; - } - - /** - * Run business method `resolveShopOptions`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @param onlyActiveBindings parameter `onlyActiveBindings` supplied by the caller - * @param onlyActiveShops parameter `onlyActiveShops` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List resolveShopOptions(UserDO userDO, boolean onlyActiveBindings, boolean onlyActiveShops) { - if (userDO == null) { - return new ArrayList<>(); - } - - List shopOptions; - if (Integer.valueOf(4).equals(userDO.getType())) { - shopOptions = new ArrayList<>(onlyActiveShops - ? userShopBindingSupport.listAllActiveShopOptions() - : listSelectableShopOptionsForPlatformAdmin()); - } else { - shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId( - userDO.getId(), - onlyActiveBindings, - onlyActiveShops - )); - } - - if (!shopOptions.isEmpty()) { - return shopOptions; - } - - if (userShopBindingSupport.hasBindingHistory(userDO.getId())) { - return shopOptions; - } - - Long legacyShopId = normalizeShopId(userDO.getShopId()); - if (legacyShopId != null) { - ShopVO legacyShop = shopService.getShopById(legacyShopId); - if (legacyShop != null && (!onlyActiveShops || Integer.valueOf(1).equals(legacyShop.getStatus()))) { - shopOptions.add(new ShopSimpleVO(legacyShop.getId(), legacyShop.getShopName())); - } - } - return shopOptions; - } - - /** - * Run business method `validateAndNormalizeShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param shopId parameter `shopId` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long validateAndNormalizeShopId(Long shopId) { - Long normalizedShopId = normalizeShopId(shopId); - if (normalizedShopId == null) { - return null; - } - if (!userShopBindingSupport.isShopActive(normalizedShopId)) { - if (userShopBindingSupport.isShopEnabledIgnoringAuthorization(normalizedShopId) - && userShopBindingSupport.isShopAuthorizationExpired(normalizedShopId)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("店铺已被冻结"); - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("所属店铺不存在或已失效"); - } - return normalizedShopId; - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return private List result consumed by the caller or returned to the frontend - */ - private List listEnabledShopOptionsForAdmin() { - return shopService.listAllShopsForAdmin().stream() - .filter(shop -> Integer.valueOf(1).equals(shop.getStatus())) - .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) - .collect(Collectors.toList()); - } - - /** - * Purpose: listSelectableShopOptionsForPlatformAdmin supports UserServiceImpl.java by holding or executing the list selectable shop options for platform admin business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private List listSelectableShopOptionsForPlatformAdmin() { - return shopService.listAllShopsForAdmin().stream() - .filter(shop -> !Boolean.TRUE.equals(shop.getAuthorizationExpired())) - .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) - .collect(Collectors.toList()); - } - - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private List result consumed by the caller or returned to the frontend - */ - private List listEnabledShopOptionsForUser(Long userId) { - return userShopBindingSupport.listShopOptionsByUserId(userId, true, false).stream() - .filter(shop -> userShopBindingSupport.isShopEnabledIgnoringAuthorization(shop.getId())) - .collect(Collectors.toList()); - } - - /** - * Run business method `validateUserPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @param required parameter `required` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String validateUserPhone(String phone, Long currentUserId, boolean required) { - String normalizedPhone = phone == null ? null : phone.trim(); - if (!StringUtils.hasText(normalizedPhone)) { - if (required) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("手机号不能为空"); - } - return null; - } - if (isDeletedPlaceholderPhone(normalizedPhone)) { - return normalizedPhone; - } - if (!normalizedPhone.matches(PHONE_REGEX)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("手机号格式不正确"); - } - /** - * Run business method `ensurePhoneNotUsed`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param normalizedPhone parameter `normalizedPhone` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePhoneNotUsed(normalizedPhone, currentUserId); - return normalizedPhone; - } - - /** - * Run business method `isDeletedPlaceholderPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isDeletedPlaceholderPhone(String phone) { - return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER); - } - - /** - * Run business method `ensurePhoneNotUsed`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param currentUserId parameter `currentUserId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void ensurePhoneNotUsed(String phone, Long currentUserId) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0); - if (currentUserId != null) { - wrapper.ne(UserDO::getId, currentUserId); - } - if (userMapper.selectOne(wrapper) != null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("手机号已被使用"); - } - } - /** - * Run business method `buildRelationVO`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @return private UserRelationVO result consumed by the caller or returned to the frontend - */ - private UserRelationVO buildRelationVO(Long userId) { - if (userId == null) { - return null; - } - UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() - .eq(UserRelationDO::getUserId, userId) - .eq(UserRelationDO::getIsDelete, 0) - .last("limit 1")); - if (relation == null) { - return null; - } - UserRelationVO vo = new UserRelationVO(); - vo.setUserId(userId); - vo.setShopId(relation.getShopId()); - vo.setShopName(relation.getShopId() == null ? null : Optional.ofNullable(shopService.getShopById(relation.getShopId())).map(ShopVO::getShopName).orElse(null)); - vo.setParentUserId(relation.getParentUserId()); - vo.setParentUserName(relation.getParentUserId() == null ? null : Optional.ofNullable(userMapper.selectById(relation.getParentUserId())).map(UserDO::getNickname).orElse(null)); - vo.setParentRoleType(relation.getParentRoleType()); - vo.setParentRoleTypeName(resolveUserTypeName(relation.getParentRoleType())); - vo.setSourceType(relation.getSourceType()); - vo.setSourceTypeName(resolveSourceTypeName(relation.getSourceType())); - return vo; - } - - /** - * Run business method `applyRelationInfo`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userVO parameter `userVO` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void applyRelationInfo(UserVO userVO, Long userId) { - UserRelationVO relation = buildRelationVO(userId); - if (relation != null) { - userVO.setParentUserId(relation.getParentUserId()); - userVO.setParentUserName(relation.getParentUserName()); - userVO.setParentUserTypeName(relation.getParentRoleTypeName()); - userVO.setRelationSourceType(relation.getSourceTypeName()); - } - UserShopRoleDO roleBinding = userShopRoleMapper.selectOne(new LambdaQueryWrapper() - .eq(UserShopRoleDO::getUserId, userId) - .eq(UserShopRoleDO::getIsDelete, 0) - .eq(UserShopRoleDO::getStatus, 1) - .last("limit 1")); - if (roleBinding != null) { - userVO.setShopRoleId(roleBinding.getRoleId()); - } - } - - /** - * Run business method `resolveUserTypeName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param type parameter `type` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveUserTypeName(Integer type) { - return switch (type == null ? -1 : type) { - case 0 -> "普通用户"; - case 2 -> "店长"; - case 3 -> "美甲师"; - case 4 -> "管理员"; - default -> "未知"; - }; - } - - /** - * Run business method `resolveSourceTypeName`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sourceType parameter `sourceType` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String resolveSourceTypeName(String sourceType) { - if (!StringUtils.hasText(sourceType)) { - return "-"; - } - return switch (sourceType) { - case "INVITE" -> "邀请码"; - case "DEFAULT_MANAGER" -> "默认店长"; - case "MANUAL" -> "手动"; - default -> sourceType; - }; - } - - /** - * Run business method `maskPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String maskPhone(String phone) { - if (!StringUtils.hasText(phone) || phone.length() < 7) { - return phone; - } - return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); - } - - /** - * Run business method `maskEmail`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param email parameter `email` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String maskEmail(String email) { - if (!StringUtils.hasText(email) || !email.contains("@")) { - return email; - } - int at = email.indexOf('@'); - return (at <= 1 ? "***" : email.substring(0, 1) + "***") + email.substring(at); - } - - /** - * Run business method `resolveRegisterShopId`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param requestedShopId parameter `requestedShopId` supplied by the caller - * @param inviteCode parameter `inviteCode` supplied by the caller - * @return private Long result consumed by the caller or returned to the frontend - */ - private Long resolveRegisterShopId(Long requestedShopId, String inviteCode) { - if (StringUtils.hasText(inviteCode)) { - UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() - .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) - .eq(UserInviteCodeDO::getIsDelete, 0) - .eq(UserInviteCodeDO::getStatus, 1) - .last("limit 1")); - if (code != null) { - return code.getShopId(); - } - } - Long normalized = validateAndNormalizeShopId(requestedShopId); - if (normalized != null) { - return normalized; - } - Long currentShopId = RequestShopContext.getCurrentShopId(); - if (currentShopId != null) { - return currentShopId; - } - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("请选择店铺"); - } - - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param shopId parameter `shopId` supplied by the caller - * @param inviteCode parameter `inviteCode` supplied by the caller - * @return private void result consumed by the caller or returned to the frontend - */ - private void createRelationForRegister(Long userId, Long shopId, String inviteCode) { - UserRelationDO relation = new UserRelationDO(); - relation.setUserId(userId); - relation.setShopId(shopId); - relation.setCreatorId(userId); - relation.setSourceType(StringUtils.hasText(inviteCode) ? "INVITE" : "DEFAULT_MANAGER"); - relation.setIsDelete(0); - if (StringUtils.hasText(inviteCode)) { - UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() - .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) - .eq(UserInviteCodeDO::getIsDelete, 0) - .last("limit 1")); - if (code != null) { - relation.setParentUserId(code.getOwnerUserId()); - UserDO parent = userMapper.selectById(code.getOwnerUserId()); - relation.setParentRoleType(parent == null ? null : parent.getType()); - code.setUseCount((code.getUseCount() == null ? 0 : code.getUseCount()) + 1); - code.setUpdateTime(LocalDateTime.now()); - userInviteCodeMapper.updateById(code); - } - } else if (shopId != null) { - UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() - .eq(UserDO::getShopId, shopId) - .eq(UserDO::getType, 2) - .eq(UserDO::getIsDelete, 0) - .eq(UserDO::getStatus, 1) - .last("limit 1")); - relation.setParentUserId(manager == null ? null : manager.getId()); - relation.setParentRoleType(manager == null ? null : manager.getType()); - } - userRelationMapper.insert(relation); - } - - /** - * Run business method `resolveRelationFilteredUserIds`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param roleId parameter `roleId` supplied by the caller - * @param parentUserId parameter `parentUserId` supplied by the caller - * @param sourceType parameter `sourceType` supplied by the caller - * @return private Set result consumed by the caller or returned to the frontend - */ - private Set resolveRelationFilteredUserIds(Long roleId, Long parentUserId, String sourceType) { - if (roleId == null && parentUserId == null && !StringUtils.hasText(sourceType)) { - return null; - } - List relations = userRelationMapper.selectList(new LambdaQueryWrapper() - .eq(UserRelationDO::getIsDelete, 0)); - if (roleId != null) { - Set roleUserIds = userShopRoleMapper.selectList(new LambdaQueryWrapper() - .eq(UserShopRoleDO::getRoleId, roleId) - .eq(UserShopRoleDO::getIsDelete, 0) - .eq(UserShopRoleDO::getStatus, 1)) - .stream().map(UserShopRoleDO::getUserId).filter(Objects::nonNull).collect(Collectors.toSet()); - relations = relations.stream() - .filter(r -> roleUserIds.contains(r.getParentUserId())) - .collect(Collectors.toList()); - } - if (parentUserId != null) { - relations = relations.stream() - .filter(r -> Objects.equals(parentUserId, r.getParentUserId())) - .collect(Collectors.toList()); - } - if (StringUtils.hasText(sourceType)) { - relations = relations.stream() - .filter(r -> sourceType.equals(r.getSourceType())) - .collect(Collectors.toList()); - } - return relations.stream() - .map(UserRelationDO::getUserId) - .filter(Objects::nonNull) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/support/UserProfileFieldSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/support/UserProfileFieldSupport.java deleted file mode 100644 index 7704e484..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/support/UserProfileFieldSupport.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.support; - -import org.springframework.util.StringUtils; - -public final class UserProfileFieldSupport { - - private UserProfileFieldSupport() { - } - - public static String normalizeOptionalText(String value) { - if (!StringUtils.hasText(value)) { - return null; - } - return value.trim(); - } - - public static void requireWechatIdForServiceUser(Integer userType, String wechatId) { - if ((Integer.valueOf(2).equals(userType) || Integer.valueOf(3).equals(userType)) - && !StringUtils.hasText(wechatId)) { - throw new IllegalArgumentException("店长和美甲师的微信号不能为空"); - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/InviteCodeVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/InviteCodeVO.java deleted file mode 100644 index 77ad72e9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/InviteCodeVO.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -/** - * InviteCodeVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class InviteCodeVO { - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long id; - /** - * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String inviteCode; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long ownerUserId; - /** - * Field `ownerUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String ownerUserName; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - /** - * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer status; - /** - * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer useCount; - /** - * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime expireTime; - /** - * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserAgreementConsentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserAgreementConsentVO.java deleted file mode 100644 index a8814a15..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserAgreementConsentVO.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.vo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.Map; - -@Data -@NoArgsConstructor -@AllArgsConstructor -/** - * Purpose: UserAgreementConsentVO supports UserAgreementConsentVO.java by holding or executing the user agreement consent vo business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class UserAgreementConsentVO { - - /** - * Purpose: consentVersions supports UserAgreementConsentVO.java by holding or executing the consent versions business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Map consentVersions; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserAssetVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserAssetVO.java deleted file mode 100644 index f4028bd7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserAssetVO.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.vo; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -@Data -/** - * UserAssetVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserAssetVO { - - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - - /** - * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String nickname; - - /** - * Field `balance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal balance; - - /** - * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private BigDecimal totalRechargeAmount; - - /** - * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime lastRechargeTime; - - /** - * Field `vipInfoId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long vipInfoId; - - /** - * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String vipLevel; - - /** - * Field `benefitId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long benefitId; - - /** - * Field `benefitInfo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String benefitInfo; - - /** - * Field `manualOverride` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Boolean manualOverride; - - /** - * Field `vipStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime vipStartTime; - - /** - * Field `vipExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private LocalDateTime vipExpireTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserRelationVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserRelationVO.java deleted file mode 100644 index 27383197..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserRelationVO.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -@Data -/** - * UserRelationVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserRelationVO { - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long userId; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopId; - /** - * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopName; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long parentUserId; - /** - * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String parentUserName; - /** - * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Integer parentRoleType; - /** - * Field `parentRoleTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String parentRoleTypeName; - /** - * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceType; - /** - * Field `sourceTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String sourceTypeName; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserStatisticsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserStatisticsVO.java deleted file mode 100644 index 35040a9f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserStatisticsVO.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.vo; - -import lombok.Data; - -import java.util.Map; - -@Data -/** - * UserStatisticsVO is a response VO. Services build it and controllers return it to the frontend. - * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. - */ -public class UserStatisticsVO { - /** - * Field `totalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long totalUserCount; - /** - * Field `normalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long normalUserCount; - /** - * Field `employeeCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long employeeCount; - /** - * Field `managerCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long managerCount; - /** - * Field `artistCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long artistCount; - /** - * Field `vipUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long vipUserCount; - /** - * Field `newUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private long newUserCount; - /** - * Field `byShop` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Map byShop; - /** - * Field `byRole` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Map byRole; - /** - * Field `byParent` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Map byParent; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java deleted file mode 100644 index 45dcc647..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.modules.user.vo; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; - -/** - * 系统用户信息表 VO - * 用于前端展示用户信息 - * - * @author xiaowang - * @date 2026-02-13 - */ -@Data -public class UserVO { - - /** - * 用户唯一主键ID(雪花ID) - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long id; - - /** - * 所属店铺ID,关联店铺表主键(0表示无所属店铺) - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long shopId; - - /** - * 店铺名称 - */ - private String shopName; - - /** - * 绑定店铺ID列表 - */ - @JsonSerialize(contentUsing = ToStringSerializer.class) - private List shopIds; - - /** - * 绑定店铺名称列表 - */ - private List shopNames; - - /** - * 用户昵称 - */ - private String nickname; - - /** - * 用户账号(登录用) - */ - private String account; - - /** - * 用户头像URL - */ - private String avatar; - - /** - * 用户签名 - */ - private String signature; - - /** - * 用户等级 - */ - private String level; - - /** - * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) - */ - private Integer type; - - /** - * 用户类型名称 - */ - private String typeName; - - /** - * 关联VIP信息表主键(0表示非VIP) - */ - @JsonSerialize(using = ToStringSerializer.class) - private Long vipId; - - /** - * VIP等级 - */ - private String vipLevel; - - /** - * 创建时间 - */ - private LocalDateTime createTime; - - /** - * 更新时间 - */ - private LocalDateTime updateTime; - - /** - * 用户状态:1-正常,0-禁用 - */ - private Integer status; - - /** - * 手机号 - */ - private String phone; - /** - * 联系电话 - */ - private String contactPhone; - /** - * 生日 - */ - private LocalDate birthday; - /** - * 微信号 - */ - private String wechatId; - /** - * 微信二维码 - */ - private String wechatQrCode; - /** - * Field `email` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String email; - /** - * Field `maskedPhone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String maskedPhone; - /** - * Field `maskedEmail` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String maskedEmail; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `shopRoleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long shopRoleId; - /** - * Field `shopRoleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String shopRoleName; - @JsonSerialize(using = ToStringSerializer.class) - /** - * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private Long parentUserId; - /** - * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String parentUserName; - /** - * Field `parentUserTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String parentUserTypeName; - /** - * Field `relationSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private String relationSourceType; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/RequestShopContext.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/RequestShopContext.java deleted file mode 100644 index f85c7f04..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/RequestShopContext.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support; - -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; - -/** - * 当前请求中的店铺上下文。 - */ -public final class RequestShopContext { - - /** - * Purpose: CURRENT_SHOP_ID_ATTRIBUTE supports RequestShopContext.java by holding or executing the current shop id attribute business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String CURRENT_SHOP_ID_ATTRIBUTE = "currentShopId"; - - private RequestShopContext() { - } - - /** - * Purpose: getCurrentShopId supports RequestShopContext.java by holding or executing the get current shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Long getCurrentShopId() { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - if (attributes == null) { - return null; - } - return parseShopId(attributes.getRequest().getAttribute(CURRENT_SHOP_ID_ATTRIBUTE)); - } - - /** - * Purpose: getCurrentShopId supports RequestShopContext.java by holding or executing the get current shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static Long getCurrentShopId(HttpServletRequest request) { - if (request == null) { - return null; - } - return parseShopId(request.getAttribute(CURRENT_SHOP_ID_ATTRIBUTE)); - } - - /** - * Purpose: parseShopId supports RequestShopContext.java by holding or executing the parse shop id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private static Long parseShopId(Object value) { - if (value == null) { - return null; - } - if (value instanceof Number number) { - long shopId = number.longValue(); - return shopId > 0 ? shopId : null; - } - if (value instanceof String text) { - try { - long shopId = Long.parseLong(text.trim()); - return shopId > 0 ? shopId : null; - } catch (NumberFormatException ignored) { - return null; - } - } - return null; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/cache/MultiLevelCacheService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/cache/MultiLevelCacheService.java deleted file mode 100644 index 9a87617e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/cache/MultiLevelCacheService.java +++ /dev/null @@ -1,324 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.cache; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.core.Cursor; -import org.springframework.data.redis.core.ScanOptions; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import java.time.Duration; -import java.nio.charset.StandardCharsets; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; - -/** - * 本地 + Redis 多级缓存。 - */ -@Component -@RequiredArgsConstructor -@Slf4j -public class MultiLevelCacheService { - - /** - * Purpose: NULL_SENTINEL supports MultiLevelCacheService.java by holding or executing the null sentinel business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String NULL_SENTINEL = "__CACHE_NULL__"; - - /** - * Purpose: stringRedisTemplate supports MultiLevelCacheService.java by holding or executing the string redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final StringRedisTemplate stringRedisTemplate; - /** - * Purpose: objectMapper supports MultiLevelCacheService.java by holding or executing the object mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final ObjectMapper objectMapper; - /** - * Purpose: cacheProperties supports MultiLevelCacheService.java by holding or executing the cache properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final AppCacheProperties cacheProperties; - - /** - * Purpose: localCache supports MultiLevelCacheService.java by holding or executing the local cache business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Cache localCache; - - /** - * Purpose: getLocalCache supports MultiLevelCacheService.java by holding or executing the get local cache business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Cache getLocalCache() { - if (localCache == null) { - localCache = Caffeine.newBuilder() - .maximumSize(Math.max(128, cacheProperties.getLocalMaxSize())) - .build(); - } - return localCache; - } - - public T getOrLoad(String key, - Duration localTtl, - Duration redisTtl, - TypeReference typeReference, - Supplier loader) { - CacheLookup lookup = get(key, localTtl, typeReference); - if (lookup.isHit()) { - return lookup.getValue(); - } - - T loaded = loader.get(); - put(key, loaded, localTtl, redisTtl); - return loaded; - } - - /** - * Purpose: get supports MultiLevelCacheService.java by holding or executing the get business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public CacheLookup get(String key, Duration localTtl, TypeReference typeReference) { - if (!StringUtils.hasText(key)) { - return CacheLookup.miss(); - } - - LocalCacheEntry localEntry = getLocalCache().getIfPresent(key); - if (localEntry != null) { - if (!localEntry.isExpired()) { - return CacheLookup.hit(readValue(localEntry.getJson(), typeReference)); - } - getLocalCache().invalidate(key); - } - - String json = readRedisValue(key); - if (!StringUtils.hasText(json)) { - return CacheLookup.miss(); - } - - putLocal(key, json, localTtl); - return CacheLookup.hit(readValue(json, typeReference)); - } - - /** - * Purpose: put supports MultiLevelCacheService.java by holding or executing the put business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void put(String key, Object value, Duration localTtl, Duration redisTtl) { - if (!StringUtils.hasText(key)) { - return; - } - String json = writeValue(value); - putLocal(key, json, localTtl); - writeRedisValue(key, json, redisTtl); - } - - /** - * Purpose: evict supports MultiLevelCacheService.java by holding or executing the evict business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void evict(String... keys) { - if (keys == null || keys.length == 0) { - return; - } - for (String key : keys) { - getLocalCache().invalidate(key); - } - deleteRedisKeys(Set.of(keys)); - } - - /** - * Purpose: evictByPrefix supports MultiLevelCacheService.java by holding or executing the evict by prefix business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void evictByPrefix(String prefix) { - if (!StringUtils.hasText(prefix)) { - return; - } - getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix)); - Set redisKeys = scanRedisKeys(prefix + "*"); - if (!CollectionUtils.isEmpty(redisKeys)) { - deleteRedisKeys(redisKeys); - } - } - - /** - * Purpose: readRedisValue supports MultiLevelCacheService.java by holding or executing the read redis value business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String readRedisValue(String key) { - try { - return stringRedisTemplate.opsForValue().get(key); - } catch (Exception exception) { - log.warn("Redis cache read failed, key={}", key, exception); - return null; - } - } - - /** - * Purpose: writeRedisValue supports MultiLevelCacheService.java by holding or executing the write redis value business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void writeRedisValue(String key, String json, Duration redisTtl) { - try { - stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS); - } catch (Exception exception) { - log.warn("Redis cache write failed, key={}", key, exception); - } - } - - /** - * Purpose: deleteRedisKeys supports MultiLevelCacheService.java by holding or executing the delete redis keys business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void deleteRedisKeys(Set keys) { - if (CollectionUtils.isEmpty(keys)) { - return; - } - try { - stringRedisTemplate.delete(keys); - } catch (Exception exception) { - log.warn("Redis cache delete failed, size={}", keys.size(), exception); - } - } - - /** - * Purpose: scanRedisKeys supports MultiLevelCacheService.java by holding or executing the scan redis keys business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Set scanRedisKeys(String pattern) { - Set keys = new LinkedHashSet<>(); - try { - return stringRedisTemplate.execute((RedisConnection connection) -> { - Set matchedKeys = new LinkedHashSet<>(); - try (Cursor cursor = connection.scan(ScanOptions.scanOptions() - .match(pattern) - .count(500) - .build())) { - while (cursor.hasNext()) { - matchedKeys.add(new String(cursor.next(), StandardCharsets.UTF_8)); - } - } - return matchedKeys; - }); - } catch (Exception exception) { - log.warn("Redis cache scan failed, pattern={}", pattern, exception); - return keys; - } - } - - /** - * Purpose: putLocal supports MultiLevelCacheService.java by holding or executing the put local business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void putLocal(String key, String json, Duration localTtl) { - getLocalCache().put(key, new LocalCacheEntry(json, System.currentTimeMillis() + Math.max(1L, localTtl.toMillis()))); - } - - /** - * Purpose: writeValue supports MultiLevelCacheService.java by holding or executing the write value business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String writeValue(Object value) { - try { - return value == null ? NULL_SENTINEL : objectMapper.writeValueAsString(value); - } catch (JsonProcessingException exception) { - throw new RuntimeException("缓存序列化失败", exception); - } - } - - /** - * Purpose: readValue supports MultiLevelCacheService.java by holding or executing the read value business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private T readValue(String json, TypeReference typeReference) { - if (NULL_SENTINEL.equals(json)) { - return null; - } - try { - return objectMapper.readValue(json, typeReference); - } catch (JsonProcessingException exception) { - throw new RuntimeException("缓存反序列化失败", exception); - } - } - - @Getter - /** - * Purpose: CacheLookup supports MultiLevelCacheService.java by holding or executing the cache lookup business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final class CacheLookup { - /** - * Purpose: hit supports MultiLevelCacheService.java by holding or executing the hit business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final boolean hit; - /** - * Purpose: value supports MultiLevelCacheService.java by holding or executing the value business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final T value; - - private CacheLookup(boolean hit, T value) { - this.hit = hit; - this.value = value; - } - - /** - * Purpose: hit supports MultiLevelCacheService.java by holding or executing the hit business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static CacheLookup hit(T value) { - return new CacheLookup<>(true, value); - } - - /** - * Purpose: miss supports MultiLevelCacheService.java by holding or executing the miss business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static CacheLookup miss() { - return new CacheLookup<>(false, null); - } - } - - @Getter - @RequiredArgsConstructor - /** - * Purpose: LocalCacheEntry supports MultiLevelCacheService.java by holding or executing the local cache entry business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final class LocalCacheEntry { - /** - * Purpose: json supports MultiLevelCacheService.java by holding or executing the json business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final String json; - /** - * Purpose: expireAt supports MultiLevelCacheService.java by holding or executing the expire at business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final long expireAt; - - /** - * Purpose: isExpired supports MultiLevelCacheService.java by holding or executing the is expired business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isExpired() { - return System.currentTimeMillis() >= expireAt; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/id/TimeOrderedSnowflakeIdGenerator.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/id/TimeOrderedSnowflakeIdGenerator.java deleted file mode 100644 index ca4f9839..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/id/TimeOrderedSnowflakeIdGenerator.java +++ /dev/null @@ -1,275 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.id; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.lang.management.ManagementFactory; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.nio.charset.StandardCharsets; -import java.util.Enumeration; -import java.util.Locale; - -/** - * 时间高位雪花 ID 生成器。 - * 统一为数据库主键和业务有序标识提供趋势递增的唯一 ID。 - */ -@Slf4j -@Component -public class TimeOrderedSnowflakeIdGenerator { - - /** - * Purpose: DEFAULT_EPOCH supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the default epoch business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long DEFAULT_EPOCH = 1704067200000L; - /** - * Purpose: WORKER_ID_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id bits business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long WORKER_ID_BITS = 5L; - /** - * Purpose: DATACENTER_ID_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id bits business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long DATACENTER_ID_BITS = 5L; - /** - * Purpose: SEQUENCE_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the sequence bits business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long SEQUENCE_BITS = 12L; - private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); - private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); - private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); - /** - * Purpose: WORKER_ID_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id shift business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; - /** - * Purpose: DATACENTER_ID_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id shift business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; - /** - * Purpose: TIMESTAMP_LEFT_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the timestamp left shift business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; - - /** - * Purpose: epoch supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the epoch business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final long epoch; - /** - * Purpose: workerId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final long workerId; - /** - * Purpose: datacenterId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final long datacenterId; - - /** - * Purpose: sequence supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the sequence business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long sequence = 0L; - /** - * Purpose: lastTimestamp supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the last timestamp business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private long lastTimestamp = -1L; - - public TimeOrderedSnowflakeIdGenerator( - @Value("${snowflake.epoch:" + DEFAULT_EPOCH + "}") long configuredEpoch, - @Value("${snowflake.worker-id:-1}") long configuredWorkerId, - @Value("${snowflake.datacenter-id:-1}") long configuredDatacenterId, - @Value("${spring.application.name:jc-artlist-core}") String applicationName - ) { - this.epoch = configuredEpoch > 0 ? configuredEpoch : DEFAULT_EPOCH; - this.datacenterId = resolveNodeId(configuredDatacenterId, MAX_DATACENTER_ID, resolveDatacenterId()); - this.workerId = resolveNodeId(configuredWorkerId, MAX_WORKER_ID, resolveWorkerId(applicationName)); - log.info("Snowflake generator ready: app={}, epoch={}, datacenterId={}, workerId={}", - applicationName, this.epoch, this.datacenterId, this.workerId); - } - - /** - * Purpose: nextId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public synchronized long nextId() { - long timestamp = currentTimeMillis(); - if (timestamp < lastTimestamp) { - timestamp = waitUntil(lastTimestamp); - } - - if (timestamp == lastTimestamp) { - sequence = (sequence + 1) & SEQUENCE_MASK; - if (sequence == 0L) { - timestamp = waitUntilNextMillis(lastTimestamp); - } - } else { - sequence = 0L; - } - - lastTimestamp = timestamp; - return ((timestamp - epoch) << TIMESTAMP_LEFT_SHIFT) - | (datacenterId << DATACENTER_ID_SHIFT) - | (workerId << WORKER_ID_SHIFT) - | sequence; - } - - /** - * Purpose: nextIdString supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next id string business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String nextIdString() { - return Long.toUnsignedString(nextId()); - } - - /** - * Purpose: nextBase36String supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next base36 string business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String nextBase36String(int width) { - String raw = Long.toUnsignedString(nextId(), 36).toUpperCase(Locale.ROOT); - if (raw.length() >= width) { - return raw.substring(raw.length() - width); - } - return "0".repeat(width - raw.length()) + raw; - } - - /** - * Purpose: currentTimeMillis supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the current time millis business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long currentTimeMillis() { - return System.currentTimeMillis(); - } - - /** - * Purpose: waitUntil supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the wait until business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long waitUntil(long targetTimestamp) { - long timestamp = currentTimeMillis(); - while (timestamp < targetTimestamp) { - Thread.yield(); - timestamp = currentTimeMillis(); - } - return timestamp; - } - - /** - * Purpose: waitUntilNextMillis supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the wait until next millis business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long waitUntilNextMillis(long currentTimestamp) { - long timestamp = currentTimeMillis(); - while (timestamp <= currentTimestamp) { - Thread.yield(); - timestamp = currentTimeMillis(); - } - return timestamp; - } - - /** - * Purpose: resolveNodeId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve node id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long resolveNodeId(long configuredValue, long maxValue, long fallbackValue) { - long candidate = configuredValue >= 0 ? configuredValue : fallbackValue; - return Math.floorMod(candidate, maxValue + 1); - } - - /** - * Purpose: resolveDatacenterId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve datacenter id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long resolveDatacenterId() { - return stableHash(resolveMachineFingerprint()); - } - - /** - * Purpose: resolveWorkerId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve worker id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long resolveWorkerId(String applicationName) { - return stableHash(applicationName + ":" + resolveProcessFingerprint()); - } - - /** - * Purpose: resolveMachineFingerprint supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve machine fingerprint business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveMachineFingerprint() { - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - while (interfaces != null && interfaces.hasMoreElements()) { - NetworkInterface networkInterface = interfaces.nextElement(); - if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual()) { - continue; - } - byte[] hardwareAddress = networkInterface.getHardwareAddress(); - if (hardwareAddress != null && hardwareAddress.length > 0) { - return bytesToHex(hardwareAddress); - } - } - } catch (Exception exception) { - log.warn("Unable to resolve hardware address for snowflake datacenter id", exception); - } - - try { - return InetAddress.getLocalHost().getHostAddress(); - } catch (Exception exception) { - log.warn("Unable to resolve host address for snowflake datacenter id", exception); - return "fallback-host"; - } - } - - /** - * Purpose: resolveProcessFingerprint supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve process fingerprint business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveProcessFingerprint() { - try { - return ManagementFactory.getRuntimeMXBean().getName(); - } catch (Exception exception) { - return "pid-unknown"; - } - } - - /** - * Purpose: stableHash supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the stable hash business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private long stableHash(String value) { - if (value == null || value.isEmpty()) { - return 0L; - } - long hash = 1469598103934665603L; - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - for (byte currentByte : bytes) { - hash ^= currentByte; - hash *= 1099511628211L; - } - return hash & Long.MAX_VALUE; - } - - /** - * Purpose: bytesToHex supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the bytes to hex business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String bytesToHex(byte[] source) { - StringBuilder builder = new StringBuilder(source.length * 2); - for (byte currentByte : source) { - builder.append(String.format("%02X", currentByte)); - } - return builder.toString(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/CachedBodyHttpServletRequest.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/CachedBodyHttpServletRequest.java deleted file mode 100644 index 4f81f6d1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/CachedBodyHttpServletRequest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -/** - * 可重复读取 body 的请求包装。 - */ -public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper { - - /** - * Purpose: cachedBody supports CachedBodyHttpServletRequest.java by holding or executing the cached body business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final byte[] cachedBody; - - public CachedBodyHttpServletRequest(HttpServletRequest request, byte[] cachedBody) { - super(request); - this.cachedBody = cachedBody == null ? new byte[0] : cachedBody; - } - - @Override - /** - * Purpose: getInputStream supports CachedBodyHttpServletRequest.java by holding or executing the get input stream business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public ServletInputStream getInputStream() { - ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody); - return new ServletInputStream() { - @Override - /** - * Purpose: isFinished supports CachedBodyHttpServletRequest.java by holding or executing the is finished business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isFinished() { - return inputStream.available() == 0; - } - - @Override - /** - * Purpose: isReady supports CachedBodyHttpServletRequest.java by holding or executing the is ready business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isReady() { - return true; - } - - @Override - /** - * Purpose: setReadListener supports CachedBodyHttpServletRequest.java by holding or executing the set read listener business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void setReadListener(ReadListener readListener) { - // no-op - } - - @Override - /** - * Purpose: read supports CachedBodyHttpServletRequest.java by holding or executing the read business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public int read() { - return inputStream.read(); - } - }; - } - - @Override - /** - * Purpose: getReader supports CachedBodyHttpServletRequest.java by holding or executing the get reader business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public BufferedReader getReader() throws IOException { - Charset charset = getCharacterEncoding() == null - ? StandardCharsets.UTF_8 - : Charset.forName(getCharacterEncoding()); - return new BufferedReader(new InputStreamReader(getInputStream(), charset)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/OperationGuardService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/OperationGuardService.java deleted file mode 100644 index 4fde7878..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/OperationGuardService.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jacyucloudsalon.core.support.RequestShopContext; -import lombok.RequiredArgsConstructor; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.script.DefaultRedisScript; -import org.springframework.stereotype.Component; -import org.springframework.util.DigestUtils; -import org.springframework.util.StringUtils; - -import javax.servlet.http.HttpServletRequest; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import static com.xiaowang.jacyucloudsalon.core.support.security.RequestSignatureService.REQUEST_BODY_ATTRIBUTE; - -@Component -@RequiredArgsConstructor -/** - * Purpose: OperationGuardService supports OperationGuardService.java by holding or executing the operation guard service business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class OperationGuardService { - - private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); - - static { - RELEASE_LOCK_SCRIPT.setScriptText( - "if redis.call('get', KEYS[1]) == ARGV[1] then " - + "return redis.call('del', KEYS[1]) " - + "else return 0 end" - ); - RELEASE_LOCK_SCRIPT.setResultType(Long.class); - } - - private static final TypeReference> MAP_TYPE = new TypeReference<>() { - }; - - /** - * Purpose: stringRedisTemplate supports OperationGuardService.java by holding or executing the string redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final StringRedisTemplate stringRedisTemplate; - /** - * Purpose: objectMapper supports OperationGuardService.java by holding or executing the object mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final ObjectMapper objectMapper; - - /** - * Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public GuardHandle tryAcquire(HttpServletRequest request, String action, Duration ttl) { - String key = buildKey(request, action); - String token = UUID.randomUUID().toString(); - Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( - key, - token, - Math.max(1L, ttl == null ? 10L : ttl.getSeconds()), - TimeUnit.SECONDS - ); - return new GuardHandle(key, token, Boolean.TRUE.equals(success)); - } - - /** - * Purpose: release supports OperationGuardService.java by holding or executing the release business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void release(GuardHandle handle) { - if (handle == null || !handle.acquired()) { - return; - } - stringRedisTemplate.execute( - RELEASE_LOCK_SCRIPT, - Collections.singletonList(handle.key()), - handle.token() - ); - } - - /** - * Purpose: buildKey supports OperationGuardService.java by holding or executing the build key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String buildKey(HttpServletRequest request, String action) { - String safeAction = sanitize(action); - String path = request == null ? "-" : sanitize(request.getRequestURI()); - Long userId = request == null ? null : parseLong(request.getAttribute("userId")); - Integer userType = request == null ? null : parseInteger(request.getAttribute("userType")); - Long shopId = request == null ? null : RequestShopContext.getCurrentShopId(request); - - if (isUploadPath(path)) { - return buildUploadKey(request, safeAction, userId); - } - - String fingerprint = buildRequestFingerprint(request, path); - if (userId != null) { - if (isAdminRequest(path, userType)) { - return String.join(":", - "op", - "admin", - String.valueOf(userId), - safeAction, - sanitize(shopId), - fingerprint - ); - } - return String.join(":", - "op", - "user", - String.valueOf(userId), - safeAction, - fingerprint - ); - } - - String subject = resolvePublicSubject(request); - return String.join(":", - "op", - "public", - safeAction, - subject, - sanitize(resolveClientIp(request)), - sanitize(resolveDeviceId(request)) - ); - } - - /** - * Purpose: buildUploadKey supports OperationGuardService.java by holding or executing the build upload key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildUploadKey(HttpServletRequest request, String action, Long userId) { - String uploadId = firstNonBlank( - request == null ? null : request.getParameter("uploadId"), - readBodyField(request, "uploadId") - ); - String chunkIndex = firstNonBlank( - request == null ? null : request.getParameter("chunkIndex"), - readBodyField(request, "chunkIndex") - ); - String suffix = StringUtils.hasText(chunkIndex) - ? sanitize(chunkIndex) - : buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); - return String.join(":", - "op", - "upload", - sanitize(userId), - action, - sanitize(uploadId), - suffix - ); - } - - /** - * Purpose: buildRequestFingerprint supports OperationGuardService.java by holding or executing the build request fingerprint business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildRequestFingerprint(HttpServletRequest request, String path) { - String canonicalParams = buildCanonicalParams(request == null ? null : request.getParameterMap()); - String bodyHash = buildBodyHash(request); - String raw = String.join("|", - sanitize(path), - sanitize(canonicalParams), - sanitize(bodyHash) - ); - return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); - } - - /** - * Purpose: resolvePublicSubject supports OperationGuardService.java by holding or executing the resolve public subject business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolvePublicSubject(HttpServletRequest request) { - for (String key : new String[]{"account", "phone", "shopId", "productId", "couponId", "userId", "uploadId", "ticket"}) { - String value = firstNonBlank( - request == null ? null : request.getParameter(key), - readBodyField(request, key) - ); - if (StringUtils.hasText(value)) { - return sanitize(value); - } - } - return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); - } - - /** - * Purpose: buildBodyHash supports OperationGuardService.java by holding or executing the build body hash business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildBodyHash(HttpServletRequest request) { - if (request == null) { - return "-"; - } - Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); - if (cachedBody instanceof byte[] bytes && bytes.length > 0) { - return DigestUtils.md5DigestAsHex(bytes); - } - return DigestUtils.md5DigestAsHex( - buildCanonicalParams(request.getParameterMap()).getBytes(StandardCharsets.UTF_8) - ); - } - - /** - * Purpose: readBodyField supports OperationGuardService.java by holding or executing the read body field business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String readBodyField(HttpServletRequest request, String fieldName) { - if (request == null || !StringUtils.hasText(fieldName)) { - return null; - } - Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); - if (!(cachedBody instanceof byte[] bytes) || bytes.length == 0) { - return null; - } - try { - Map payload = objectMapper.readValue(bytes, MAP_TYPE); - Object value = payload.get(fieldName); - return value == null ? null : String.valueOf(value); - } catch (Exception ignored) { - return null; - } - } - - /** - * Purpose: buildCanonicalParams supports OperationGuardService.java by holding or executing the build canonical params business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildCanonicalParams(Map parameterMap) { - if (parameterMap == null || parameterMap.isEmpty()) { - return ""; - } - Map sorted = new LinkedHashMap<>(); - parameterMap.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEach(entry -> sorted.put(entry.getKey(), entry.getValue())); - StringBuilder builder = new StringBuilder(); - sorted.forEach((key, values) -> { - if (builder.length() > 0) { - builder.append('&'); - } - builder.append(key) - .append('=') - .append(String.join(",", sortValues(values))); - }); - return builder.toString(); - } - - /** - * Purpose: sortValues supports OperationGuardService.java by holding or executing the sort values business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String[] sortValues(String[] values) { - String[] copy = values == null ? new String[0] : values.clone(); - Arrays.sort(copy, Comparator.nullsLast(String::compareTo)); - return copy; - } - - /** - * Purpose: isUploadPath supports OperationGuardService.java by holding or executing the is upload path business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isUploadPath(String path) { - return StringUtils.hasText(path) && path.contains("/upload/"); - } - - /** - * Purpose: isAdminRequest supports OperationGuardService.java by holding or executing the is admin request business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isAdminRequest(String path, Integer userType) { - return (StringUtils.hasText(path) && (path.startsWith("/admin/") || path.startsWith("/order/admin/"))) - || (userType != null && userType >= 2); - } - - /** - * Purpose: resolveClientIp supports OperationGuardService.java by holding or executing the resolve client ip business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveClientIp(HttpServletRequest request) { - if (request == null) { - return "-"; - } - String forwarded = request.getHeader("X-Forwarded-For"); - if (StringUtils.hasText(forwarded)) { - return forwarded.split(",")[0].trim(); - } - String realIp = request.getHeader("X-Real-IP"); - if (StringUtils.hasText(realIp)) { - return realIp.trim(); - } - return request.getRemoteAddr(); - } - - /** - * Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveDeviceId(HttpServletRequest request) { - if (request == null) { - return "-"; - } - return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER); - } - - /** - * Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sanitize(Object value) { - if (value == null) { - return "-"; - } - String text = String.valueOf(value).trim(); - return text.isEmpty() ? "-" : text.replace(":", "_"); - } - - /** - * Purpose: firstNonBlank supports OperationGuardService.java by holding or executing the first non blank business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String firstNonBlank(String... values) { - if (values == null) { - return null; - } - for (String value : values) { - if (StringUtils.hasText(value)) { - return value.trim(); - } - } - return null; - } - - /** - * Purpose: parseLong supports OperationGuardService.java by holding or executing the parse long business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long parseLong(Object value) { - if (value instanceof Number number) { - return number.longValue(); - } - if (value instanceof String text && StringUtils.hasText(text)) { - try { - return Long.parseLong(text.trim()); - } catch (NumberFormatException ignored) { - return null; - } - } - return null; - } - - /** - * Purpose: parseInteger supports OperationGuardService.java by holding or executing the parse integer business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer parseInteger(Object value) { - if (value instanceof Number number) { - return number.intValue(); - } - if (value instanceof String text && StringUtils.hasText(text)) { - try { - return Integer.parseInt(text.trim()); - } catch (NumberFormatException ignored) { - return null; - } - } - return null; - } - - /** - * Purpose: GuardHandle supports OperationGuardService.java by holding or executing the guard handle business role. - * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. - */ - public record GuardHandle(String key, String token, boolean acquired) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/OperationGuardStrategy.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/OperationGuardStrategy.java deleted file mode 100644 index 1174867d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/OperationGuardStrategy.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -/** - * Purpose: OperationGuardStrategy supports OperationGuardStrategy.java by holding or executing the operation guard strategy business role. - * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. - */ -public enum OperationGuardStrategy { - REJECT_IF_RUNNING, - NOOP_IF_DUPLICATE -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/RequestSignatureService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/RequestSignatureService.java deleted file mode 100644 index dae0a859..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/RequestSignatureService.java +++ /dev/null @@ -1,238 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -import com.xiaowang.jacyucloudsalon.core.config.RequestSignatureProperties; -import lombok.RequiredArgsConstructor; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import javax.servlet.http.HttpServletRequest; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.time.Instant; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - * 已登录写接口签名校验。 - */ -@Component -@RequiredArgsConstructor -public class RequestSignatureService { - - /** - * Purpose: REQUEST_BODY_ATTRIBUTE supports RequestSignatureService.java by holding or executing the request body attribute business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String REQUEST_BODY_ATTRIBUTE = "cachedRequestBody"; - /** - * Purpose: HEADER_TIMESTAMP supports RequestSignatureService.java by holding or executing the header timestamp business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String HEADER_TIMESTAMP = "X-Timestamp"; - /** - * Purpose: HEADER_NONCE supports RequestSignatureService.java by holding or executing the header nonce business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String HEADER_NONCE = "X-Nonce"; - /** - * Purpose: HEADER_SIGNATURE supports RequestSignatureService.java by holding or executing the header signature business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String HEADER_SIGNATURE = "X-Signature"; - /** - * Purpose: HEADER_SIGNATURE_VERSION supports RequestSignatureService.java by holding or executing the header signature version business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String HEADER_SIGNATURE_VERSION = "X-Sign-Version"; - - /** - * Purpose: SIGNATURE_VERSION supports RequestSignatureService.java by holding or executing the signature version business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SIGNATURE_VERSION = "v1"; - /** - * Purpose: HMAC_ALGORITHM supports RequestSignatureService.java by holding or executing the hmac algorithm business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String HMAC_ALGORITHM = "HmacSHA256"; - - /** - * Purpose: properties supports RequestSignatureService.java by holding or executing the properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final RequestSignatureProperties properties; - /** - * Purpose: stringRedisTemplate supports RequestSignatureService.java by holding or executing the string redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final StringRedisTemplate stringRedisTemplate; - - /** - * Purpose: validateRequest supports RequestSignatureService.java by holding or executing the validate request business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void validateRequest(HttpServletRequest request, String accessToken, Long userId) { - if (!properties.isEnabled() || isSafeMethod(request.getMethod())) { - return; - } - if (!StringUtils.hasText(accessToken)) { - throw new RuntimeException("请求签名缺少登录态"); - } - - String version = request.getHeader(HEADER_SIGNATURE_VERSION); - String timestamp = request.getHeader(HEADER_TIMESTAMP); - String nonce = request.getHeader(HEADER_NONCE); - String signature = request.getHeader(HEADER_SIGNATURE); - - if (!SIGNATURE_VERSION.equals(version)) { - throw new RuntimeException("请求签名版本不正确"); - } - if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) { - throw new RuntimeException("请求签名缺失"); - } - - validateTimestamp(timestamp); - registerNonce(userId, nonce); - - String bodyHash = sha256Hex(resolvePayloadBytes(request)); - String canonical = request.getMethod().toUpperCase() - + "\n" + request.getRequestURI() - + "\n" + timestamp - + "\n" + nonce - + "\n" + bodyHash; - String expected = hmacSha256Hex(accessToken, canonical); - if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) { - throw new RuntimeException("请求签名无效"); - } - } - - /** - * Purpose: validateTimestamp supports RequestSignatureService.java by holding or executing the validate timestamp business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void validateTimestamp(String timestamp) { - long requestTimestamp; - try { - requestTimestamp = Long.parseLong(timestamp); - } catch (NumberFormatException exception) { - throw new RuntimeException("请求时间戳不合法"); - } - long now = Instant.now().toEpochMilli(); - long delta = Math.abs(now - requestTimestamp); - if (delta > properties.getWindowSeconds() * 1000L) { - throw new RuntimeException("请求已过期,请重试"); - } - } - - /** - * Purpose: registerNonce supports RequestSignatureService.java by holding or executing the register nonce business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void registerNonce(Long userId, String nonce) { - String nonceKey = "request:nonce:" + (userId == null ? "anon" : userId) + ":" + nonce; - Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( - nonceKey, - "1", - properties.getNonceRetentionSeconds(), - TimeUnit.SECONDS - ); - if (Boolean.FALSE.equals(success)) { - throw new RuntimeException("请求已失效,请勿重复提交"); - } - } - - /** - * Purpose: isSafeMethod supports RequestSignatureService.java by holding or executing the is safe method business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isSafeMethod(String method) { - if (!StringUtils.hasText(method)) { - return true; - } - String normalized = method.toUpperCase(); - return "GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized); - } - - /** - * Purpose: resolvePayloadBytes supports RequestSignatureService.java by holding or executing the resolve payload bytes business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private byte[] resolvePayloadBytes(HttpServletRequest request) { - Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); - if (cachedBody instanceof byte[] bytes && bytes.length > 0) { - return bytes; - } - String canonicalParams = buildCanonicalParams(request.getParameterMap()); - return canonicalParams.getBytes(StandardCharsets.UTF_8); - } - - /** - * Purpose: buildCanonicalParams supports RequestSignatureService.java by holding or executing the build canonical params business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildCanonicalParams(Map parameterMap) { - if (parameterMap == null || parameterMap.isEmpty()) { - return ""; - } - return parameterMap.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .map(entry -> entry.getKey() + "=" + String.join(",", sorted(entry.getValue()))) - .reduce((left, right) -> left + "&" + right) - .orElse(""); - } - - /** - * Purpose: sorted supports RequestSignatureService.java by holding or executing the sorted business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String[] sorted(String[] values) { - String[] result = values == null ? new String[0] : values.clone(); - Arrays.sort(result, Comparator.nullsLast(String::compareTo)); - return result; - } - - /** - * Purpose: sha256Hex supports RequestSignatureService.java by holding or executing the sha256 hex business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sha256Hex(byte[] payload) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(payload == null ? new byte[0] : payload); - return toHex(bytes); - } catch (Exception exception) { - throw new RuntimeException("计算请求摘要失败", exception); - } - } - - /** - * Purpose: hmacSha256Hex supports RequestSignatureService.java by holding or executing the hmac sha256 hex business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String hmacSha256Hex(String secret, String text) { - try { - Mac mac = Mac.getInstance(HMAC_ALGORITHM); - mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM)); - return toHex(mac.doFinal(text.getBytes(StandardCharsets.UTF_8))); - } catch (Exception exception) { - throw new RuntimeException("计算请求签名失败", exception); - } - } - - /** - * Purpose: toHex supports RequestSignatureService.java by holding or executing the to hex business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String toHex(byte[] bytes) { - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte value : bytes) { - builder.append(String.format("%02x", value)); - } - return builder.toString(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/RequestThrottleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/RequestThrottleService.java deleted file mode 100644 index 1717e33b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/RequestThrottleService.java +++ /dev/null @@ -1,230 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -import com.xiaowang.jacyucloudsalon.core.config.LoginLockProperties; -import com.xiaowang.jacyucloudsalon.core.config.RateLimitProperties; -import lombok.RequiredArgsConstructor; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Component; -import org.springframework.util.DigestUtils; -import org.springframework.util.StringUtils; - -import javax.servlet.http.HttpServletRequest; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; - -@Component -@RequiredArgsConstructor -/** - * Purpose: RequestThrottleService supports RequestThrottleService.java by holding or executing the request throttle service business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class RequestThrottleService { - - /** - * Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String DEVICE_ID_HEADER = "X-Device-Id"; - - /** - * Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final StringRedisTemplate stringRedisTemplate; - /** - * Purpose: rateLimitProperties supports RequestThrottleService.java by holding or executing the rate limit properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final RateLimitProperties rateLimitProperties; - /** - * Purpose: loginLockProperties supports RequestThrottleService.java by holding or executing the login lock properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final LoginLockProperties loginLockProperties; - - /** - * Purpose: checkLogin supports RequestThrottleService.java by holding or executing the check login business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkLogin(HttpServletRequest request, String account) { - assertLoginNotLocked(request, account); - assertAllowed("login", request, sanitize(account), rateLimitProperties.getLogin(), "登录过于频繁,请稍后再试"); - } - - /** - * Purpose: checkRegister supports RequestThrottleService.java by holding or executing the check register business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkRegister(HttpServletRequest request, String account) { - assertAllowed("register", request, sanitize(account), rateLimitProperties.getRegister(), "注册过于频繁,请稍后再试"); - } - - /** - * Purpose: checkSendCode supports RequestThrottleService.java by holding or executing the check send code business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkSendCode(HttpServletRequest request, String phone) { - assertAllowed("send-code", request, sanitize(phone), rateLimitProperties.getSendCode(), "验证码发送过于频繁,请稍后再试"); - } - - /** - * Purpose: checkResetPassword supports RequestThrottleService.java by holding or executing the check reset password business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkResetPassword(HttpServletRequest request, String phone) { - assertAllowed("reset-password", request, sanitize(phone), rateLimitProperties.getResetPassword(), "密码重置请求过于频繁,请稍后再试"); - } - - /** - * Purpose: checkWechatMiniLogin supports RequestThrottleService.java by holding or executing the check wechat mini login business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkWechatMiniLogin(HttpServletRequest request, String subject) { - assertAllowed("wechat-mini-login", request, sanitize(subject), rateLimitProperties.getWechatMiniLogin(), "微信登录过于频繁,请稍后再试"); - } - - /** - * Purpose: checkAgreementRead supports RequestThrottleService.java by holding or executing the check agreement read business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkAgreementRead(HttpServletRequest request, String agreementType) { - assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试"); - } - - /** - * Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void checkAuthenticatedWrite(HttpServletRequest request, Long userId) { - String path = request.getRequestURI(); - RateLimitProperties.LimitRule rule = rateLimitProperties.getAuthenticatedWrite(); - String message = "操作过于频繁,请稍后再试"; - String category = "write:" + path; - if ("/order/create".equals(path)) { - rule = rateLimitProperties.getOrderCreate(); - message = "下单过于频繁,请稍后再试"; - } - assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); - } - - /** - * Purpose: recordLoginFailure supports RequestThrottleService.java by holding or executing the record login failure business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void recordLoginFailure(HttpServletRequest request, String account) { - if (loginLockProperties.getMaxFailures() <= 0 || loginLockProperties.getWindowSeconds() <= 0) { - return; - } - String key = buildLoginFailureKey(request, account); - Long count = stringRedisTemplate.opsForValue().increment(key); - if (count != null && count == 1L) { - stringRedisTemplate.expire(key, loginLockProperties.getWindowSeconds(), TimeUnit.SECONDS); - } - if (count != null && count >= loginLockProperties.getMaxFailures()) { - stringRedisTemplate.opsForValue().set(buildLoginLockKey(request, account), "1", loginLockProperties.getLockSeconds(), TimeUnit.SECONDS); - } - } - - /** - * Purpose: clearLoginFailure supports RequestThrottleService.java by holding or executing the clear login failure business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void clearLoginFailure(HttpServletRequest request, String account) { - stringRedisTemplate.delete(buildLoginFailureKey(request, account)); - stringRedisTemplate.delete(buildLoginLockKey(request, account)); - } - - private void assertAllowed(String category, - HttpServletRequest request, - String subject, - RateLimitProperties.LimitRule rule, - String message) { - if (rule == null || rule.getLimit() <= 0 || rule.getWindowSeconds() <= 0) { - return; - } - String raw = String.join("|", - category, - sanitize(resolveClientIp(request)), - sanitize(resolveDeviceId(request)), - sanitize(subject) - ); - String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); - Long count = stringRedisTemplate.opsForValue().increment(key); - if (count != null && count == 1L) { - stringRedisTemplate.expire(key, rule.getWindowSeconds(), TimeUnit.SECONDS); - } - if (count != null && count > rule.getLimit()) { - throw new RuntimeException(message); - } - } - - /** - * Purpose: assertLoginNotLocked supports RequestThrottleService.java by holding or executing the assert login not locked business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void assertLoginNotLocked(HttpServletRequest request, String account) { - Boolean locked = stringRedisTemplate.hasKey(buildLoginLockKey(request, account)); - if (Boolean.TRUE.equals(locked)) { - throw new RuntimeException("登录失败次数过多,请稍后再试"); - } - } - - /** - * Purpose: buildLoginFailureKey supports RequestThrottleService.java by holding or executing the build login failure key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildLoginFailureKey(HttpServletRequest request, String account) { - return "login:fail:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); - } - - /** - * Purpose: buildLoginLockKey supports RequestThrottleService.java by holding or executing the build login lock key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildLoginLockKey(HttpServletRequest request, String account) { - return "login:lock:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); - } - - /** - * Purpose: buildLoginLockRaw supports RequestThrottleService.java by holding or executing the build login lock raw business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildLoginLockRaw(HttpServletRequest request, String account) { - return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account)); - } - - /** - * Purpose: resolveClientIp supports RequestThrottleService.java by holding or executing the resolve client ip business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveClientIp(HttpServletRequest request) { - if (request == null) { - return "-"; - } - String forwarded = request.getHeader("X-Forwarded-For"); - if (StringUtils.hasText(forwarded)) { - return forwarded.split(",")[0].trim(); - } - String realIp = request.getHeader("X-Real-IP"); - if (StringUtils.hasText(realIp)) { - return realIp.trim(); - } - return request.getRemoteAddr(); - } - - /** - * Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveDeviceId(HttpServletRequest request) { - return request == null ? null : request.getHeader(DEVICE_ID_HEADER); - } - - /** - * Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sanitize(String value) { - return StringUtils.hasText(value) ? value.trim() : "-"; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/UploadSecurityValidator.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/UploadSecurityValidator.java deleted file mode 100644 index c3e1e55b..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/UploadSecurityValidator.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -import com.xiaowang.jacyucloudsalon.core.config.UploadSecurityProperties; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import java.util.Locale; -import java.util.Set; - -@Component -@RequiredArgsConstructor -/** - * Purpose: UploadSecurityValidator supports UploadSecurityValidator.java by holding or executing the upload security validator business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class UploadSecurityValidator { - - private static final Set BLOCKED_EXTENSIONS = Set.of( - ".jsp", ".jspx", ".php", ".asp", ".aspx", ".js", ".html", ".htm", ".exe", ".bat", ".cmd", ".sh", ".jar" - ); - - private static final Set IMAGE_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".webp", ".gif"); - - private static final Set COMPATIBLE_IMAGE_MIME_TYPES = Set.of( - "image/jpeg", - "image/jpg", - "image/pjpeg", - "image/png", - "image/webp", - "image/gif" - ); - - /** - * Purpose: properties supports UploadSecurityValidator.java by holding or executing the properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final UploadSecurityProperties properties; - - /** - * Purpose: validate supports UploadSecurityValidator.java by holding or executing the validate business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void validate(MultipartFile file) { - if (file == null || file.isEmpty()) { - throw new RuntimeException("上传文件不能为空"); - } - if (file.getSize() > properties.getMaxSize()) { - throw new RuntimeException("上传文件过大"); - } - String filename = file.getOriginalFilename(); - String extension = resolveExtension(filename); - if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { - throw new RuntimeException("不支持的文件类型"); - } - String contentType = normalizeContentType(file.getContentType()); - if (!contentType.isEmpty() && !isAllowedMimeType(contentType)) { - throw new RuntimeException("文件 MIME 类型不允许"); - } - if (isLikelyImage(extension, contentType) && !IMAGE_EXTENSIONS.contains(extension)) { - throw new RuntimeException("图片文件扩展名不匹配"); - } - } - - /** - * Purpose: validateMetadata supports UploadSecurityValidator.java by holding or executing the validate metadata business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void validateMetadata(String filename, String contentType, Long fileSize) { - if (fileSize == null || fileSize <= 0 || fileSize > properties.getMaxTotalSize()) { - throw new RuntimeException("上传文件大小不合法"); - } - String extension = resolveExtension(filename); - if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { - throw new RuntimeException("不支持的文件类型"); - } - String normalizedContentType = normalizeContentType(contentType); - if (!normalizedContentType.isEmpty() && !isAllowedMimeType(normalizedContentType)) { - throw new RuntimeException("文件 MIME 类型不允许"); - } - } - - /** - * Purpose: validateChunk supports UploadSecurityValidator.java by holding or executing the validate chunk business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void validateChunk(MultipartFile chunkFile) { - if (chunkFile == null || chunkFile.isEmpty()) { - throw new RuntimeException("上传分片不能为空"); - } - if (chunkFile.getSize() > properties.getMaxSize()) { - throw new RuntimeException("上传文件过大"); - } - String filename = chunkFile.getOriginalFilename(); - String extension = resolveExtension(filename); - if (StringUtils.hasText(extension) && BLOCKED_EXTENSIONS.contains(extension)) { - throw new RuntimeException("不支持的文件类型"); - } - } - - /** - * Purpose: isAllowedMimeType supports UploadSecurityValidator.java by holding or executing the is allowed mime type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isAllowedMimeType(String contentType) { - return properties.getAllowedMimeTypes().contains(contentType) || COMPATIBLE_IMAGE_MIME_TYPES.contains(contentType); - } - - /** - * Purpose: isLikelyImage supports UploadSecurityValidator.java by holding or executing the is likely image business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isLikelyImage(String extension, String contentType) { - return IMAGE_EXTENSIONS.contains(extension) || contentType.startsWith("image/"); - } - - /** - * Purpose: normalizeContentType supports UploadSecurityValidator.java by holding or executing the normalize content type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String normalizeContentType(String contentType) { - return StringUtils.hasText(contentType) ? contentType.toLowerCase(Locale.ROOT).trim() : ""; - } - - /** - * Purpose: resolveExtension supports UploadSecurityValidator.java by holding or executing the resolve extension business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String resolveExtension(String filename) { - if (!StringUtils.hasText(filename) || !filename.contains(".")) { - return ""; - } - String normalized = filename.trim(); - int queryIndex = normalized.indexOf('?'); - if (queryIndex >= 0) { - normalized = normalized.substring(0, queryIndex); - } - int fragmentIndex = normalized.indexOf('#'); - if (fragmentIndex >= 0) { - normalized = normalized.substring(0, fragmentIndex); - } - int dotIndex = normalized.lastIndexOf("."); - return dotIndex >= 0 ? normalized.substring(dotIndex).toLowerCase(Locale.ROOT) : ""; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/UserSessionService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/UserSessionService.java deleted file mode 100644 index 1fb1cb48..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/support/security/UserSessionService.java +++ /dev/null @@ -1,254 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.support.security; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jacyucloudsalon.core.config.JwtProperties; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.RequiredArgsConstructor; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import java.time.Duration; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -/** - * 基于 Redis 的登录会话状态。 - */ -@Component -@RequiredArgsConstructor -public class UserSessionService { - - /** - * Purpose: SESSION_KEY_PREFIX supports UserSessionService.java by holding or executing the session key prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String SESSION_KEY_PREFIX = "auth:session:"; - /** - * Purpose: USER_SESSION_SET_PREFIX supports UserSessionService.java by holding or executing the user session set prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:"; - - /** - * Purpose: stringRedisTemplate supports UserSessionService.java by holding or executing the string redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final StringRedisTemplate stringRedisTemplate; - /** - * Purpose: objectMapper supports UserSessionService.java by holding or executing the object mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final ObjectMapper objectMapper; - /** - * Purpose: jwtProperties supports UserSessionService.java by holding or executing the jwt properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final JwtProperties jwtProperties; - /** - * Purpose: idGenerator supports UserSessionService.java by holding or executing the id generator business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final TimeOrderedSnowflakeIdGenerator idGenerator; - - /** - * Purpose: issueSession supports UserSessionService.java by holding or executing the issue session business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public SessionIssueResult issueSession(Long userId, String account, Long shopId, Integer userType) { - String sessionId = idGenerator.nextIdString(); - String accessJti = idGenerator.nextIdString(); - String refreshJti = idGenerator.nextIdString(); - SessionState state = SessionState.builder() - .sessionId(sessionId) - .userId(userId) - .account(account) - .shopId(shopId) - .userType(userType) - .accessJti(accessJti) - .refreshJti(refreshJti) - .build(); - save(state); - return new SessionIssueResult(sessionId, accessJti, refreshJti); - } - - /** - * Purpose: rotateSession supports UserSessionService.java by holding or executing the rotate session business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public SessionIssueResult rotateSession(String previousSessionId, Long userId, String account, Long shopId, Integer userType) { - revokeSession(previousSessionId); - return issueSession(userId, account, shopId, userType); - } - - /** - * Purpose: isAccessSessionActive supports UserSessionService.java by holding or executing the is access session active business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isAccessSessionActive(Long userId, String sessionId, String accessJti) { - SessionState state = getSessionState(sessionId); - return matches(state, userId) && StringUtils.hasText(accessJti) && accessJti.equals(state.getAccessJti()); - } - - /** - * Purpose: isRefreshSessionActive supports UserSessionService.java by holding or executing the is refresh session active business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isRefreshSessionActive(Long userId, String sessionId, String refreshJti) { - SessionState state = getSessionState(sessionId); - return matches(state, userId) && StringUtils.hasText(refreshJti) && refreshJti.equals(state.getRefreshJti()); - } - - /** - * Purpose: revokeSession supports UserSessionService.java by holding or executing the revoke session business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void revokeSession(String sessionId) { - if (!StringUtils.hasText(sessionId)) { - return; - } - SessionState state = getSessionState(sessionId); - stringRedisTemplate.delete(buildSessionKey(sessionId)); - if (state != null && state.getUserId() != null) { - stringRedisTemplate.opsForSet().remove(buildUserSessionSetKey(state.getUserId()), sessionId); - } - } - - /** - * Purpose: revokeAllUserSessions supports UserSessionService.java by holding or executing the revoke all user sessions business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public void revokeAllUserSessions(Long userId) { - if (userId == null) { - return; - } - String setKey = buildUserSessionSetKey(userId); - Set sessionIds = stringRedisTemplate.opsForSet().members(setKey); - if (sessionIds != null) { - for (String sessionId : sessionIds) { - stringRedisTemplate.delete(buildSessionKey(sessionId)); - } - } - stringRedisTemplate.delete(setKey); - } - - /** - * Purpose: matches supports UserSessionService.java by holding or executing the matches business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean matches(SessionState state, Long userId) { - return state != null && state.getUserId() != null && state.getUserId().equals(userId); - } - - /** - * Purpose: save supports UserSessionService.java by holding or executing the save business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private void save(SessionState state) { - try { - String sessionKey = buildSessionKey(state.getSessionId()); - String setKey = buildUserSessionSetKey(state.getUserId()); - Duration ttl = Duration.ofSeconds(jwtProperties.getRefreshTokenExpirationSeconds()); - String json = objectMapper.writeValueAsString(state); - stringRedisTemplate.opsForValue().set(sessionKey, json, ttl.getSeconds(), TimeUnit.SECONDS); - stringRedisTemplate.opsForSet().add(setKey, state.getSessionId()); - stringRedisTemplate.expire(setKey, ttl.getSeconds(), TimeUnit.SECONDS); - } catch (JsonProcessingException exception) { - throw new RuntimeException("写入登录会话失败", exception); - } - } - - /** - * Purpose: getSessionState supports UserSessionService.java by holding or executing the get session state business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private SessionState getSessionState(String sessionId) { - if (!StringUtils.hasText(sessionId)) { - return null; - } - String json = stringRedisTemplate.opsForValue().get(buildSessionKey(sessionId)); - if (!StringUtils.hasText(json)) { - return null; - } - try { - return objectMapper.readValue(json, SessionState.class); - } catch (JsonProcessingException exception) { - stringRedisTemplate.delete(buildSessionKey(sessionId)); - return null; - } - } - - /** - * Purpose: buildSessionKey supports UserSessionService.java by holding or executing the build session key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildSessionKey(String sessionId) { - return SESSION_KEY_PREFIX + sessionId; - } - - /** - * Purpose: buildUserSessionSetKey supports UserSessionService.java by holding or executing the build user session set key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String buildUserSessionSetKey(Long userId) { - return USER_SESSION_SET_PREFIX + userId; - } - - @Data - @Builder - @NoArgsConstructor - @AllArgsConstructor - /** - * Purpose: SessionState supports UserSessionService.java by holding or executing the session state business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ - public static class SessionState { - /** - * Purpose: sessionId supports UserSessionService.java by holding or executing the session id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String sessionId; - /** - * Purpose: userId supports UserSessionService.java by holding or executing the user id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long userId; - /** - * Purpose: account supports UserSessionService.java by holding or executing the account business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String account; - /** - * Purpose: shopId supports UserSessionService.java by holding or executing the shop id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Long shopId; - /** - * Purpose: userType supports UserSessionService.java by holding or executing the user type business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private Integer userType; - /** - * Purpose: accessJti supports UserSessionService.java by holding or executing the access jti business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String accessJti; - /** - * Purpose: refreshJti supports UserSessionService.java by holding or executing the refresh jti business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String refreshJti; - } - - /** - * Purpose: SessionIssueResult supports UserSessionService.java by holding or executing the session issue result business role. - * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. - */ - public record SessionIssueResult(String sessionId, String accessJti, String refreshJti) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/AccountValidationUtils.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/AccountValidationUtils.java deleted file mode 100644 index 21180288..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/AccountValidationUtils.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.utils; - -import org.springframework.util.StringUtils; - -import java.util.regex.Pattern; - -/** - * Purpose: AccountValidationUtils supports AccountValidationUtils.java by holding or executing the account validation utils business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public final class AccountValidationUtils { - - /** - * Purpose: ACCOUNT_REGEX supports AccountValidationUtils.java by holding or executing the account regex business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String ACCOUNT_REGEX = "^[A-Za-z0-9]+$"; - private static final Pattern ACCOUNT_PATTERN = Pattern.compile(ACCOUNT_REGEX); - - private AccountValidationUtils() { - } - - /** - * Purpose: normalizeAccount supports AccountValidationUtils.java by holding or executing the normalize account business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static String normalizeAccount(String account) { - return account == null ? "" : account.trim(); - } - - /** - * Purpose: ensureValidAccountFormat supports AccountValidationUtils.java by holding or executing the ensure valid account format business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static void ensureValidAccountFormat(String account) { - if (!StringUtils.hasText(account)) { - throw new RuntimeException("账号不能为空"); - } - if (!ACCOUNT_PATTERN.matcher(account).matches()) { - throw new RuntimeException("账号只能包含字母和数字"); - } - } - - /** - * Purpose: requireValidAccount supports AccountValidationUtils.java by holding or executing the require valid account business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static String requireValidAccount(String account) { - String normalized = normalizeAccount(account); - ensureValidAccountFormat(normalized); - return normalized; - } - - /** - * Purpose: validateOptionalAccount supports AccountValidationUtils.java by holding or executing the validate optional account business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public static String validateOptionalAccount(String account) { - if (account == null) { - return null; - } - String normalized = normalizeAccount(account); - ensureValidAccountFormat(normalized); - return normalized; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/JwtUtil.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/JwtUtil.java deleted file mode 100644 index 1b3b3065..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/JwtUtil.java +++ /dev/null @@ -1,236 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.utils; - -import com.xiaowang.jacyucloudsalon.core.config.JwtProperties; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.security.Keys; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.crypto.SecretKey; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -@Component -@RequiredArgsConstructor -/** - * Purpose: JwtUtil supports JwtUtil.java by holding or executing the jwt util business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class JwtUtil { - - /** - * Purpose: jwtProperties supports JwtUtil.java by holding or executing the jwt properties business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private final JwtProperties jwtProperties; - - /** - * Purpose: getKey supports JwtUtil.java by holding or executing the get key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private SecretKey getKey() { - return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); - } - - /** - * Purpose: generateAccessToken supports JwtUtil.java by holding or executing the generate access token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { - return generateAccessToken(userId, account, currentShopId, sessionId, jti, jwtProperties.getAccessTokenExpirationSeconds()); - } - - public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti, long expirationSeconds) { - Map claims = new HashMap<>(); - claims.put("userId", userId); - claims.put("account", account); - claims.put("type", "access"); - claims.put("sessionId", sessionId); - claims.put("jti", jti); - if (currentShopId != null && currentShopId > 0) { - claims.put("shopId", currentShopId); - } - return createToken(claims, userId.toString(), expirationSeconds * 1000); - } - - public long resolveAccessTokenExpirationSeconds(boolean rememberMe) { - return rememberMe - ? jwtProperties.getRememberMeAccessTokenExpirationSeconds() - : jwtProperties.getAccessTokenExpirationSeconds(); - } - - /** - * Purpose: generateRefreshToken supports JwtUtil.java by holding or executing the generate refresh token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String generateRefreshToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { - Map claims = new HashMap<>(); - claims.put("userId", userId); - claims.put("account", account); - claims.put("type", "refresh"); - claims.put("sessionId", sessionId); - claims.put("jti", jti); - if (currentShopId != null && currentShopId > 0) { - claims.put("shopId", currentShopId); - } - return createToken(claims, userId.toString(), jwtProperties.getRefreshTokenExpirationSeconds() * 1000); - } - - /** - * Purpose: createToken supports JwtUtil.java by holding or executing the create token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private String createToken(Map claims, String subject, long expiration) { - Date now = new Date(); - Date expiryDate = new Date(now.getTime() + expiration); - - return Jwts.builder() - .setClaims(claims) - .setSubject(subject) - .setIssuer(jwtProperties.getIssuer()) - .setIssuedAt(now) - .setExpiration(expiryDate) - .signWith(getKey(), SignatureAlgorithm.HS512) - .compact(); - } - - /** - * Purpose: parseToken supports JwtUtil.java by holding or executing the parse token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Claims parseToken(String token) { - return Jwts.parserBuilder() - .setSigningKey(getKey()) - .setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds()) - .requireIssuer(jwtProperties.getIssuer()) - .build() - .parseClaimsJws(token) - .getBody(); - } - - /** - * Purpose: getUserIdFromToken supports JwtUtil.java by holding or executing the get user id from token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Long getUserIdFromToken(String token) { - Claims claims = parseToken(token); - return claims.get("userId", Long.class); - } - - /** - * Purpose: getAccountFromToken supports JwtUtil.java by holding or executing the get account from token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String getAccountFromToken(String token) { - Claims claims = parseToken(token); - return claims.get("account", String.class); - } - - /** - * Purpose: getTokenType supports JwtUtil.java by holding or executing the get token type business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String getTokenType(String token) { - Claims claims = parseToken(token); - return claims.get("type", String.class); - } - - /** - * Purpose: getSessionIdFromToken supports JwtUtil.java by holding or executing the get session id from token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String getSessionIdFromToken(String token) { - Claims claims = parseToken(token); - return claims.get("sessionId", String.class); - } - - /** - * Purpose: getJtiFromToken supports JwtUtil.java by holding or executing the get jti from token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String getJtiFromToken(String token) { - Claims claims = parseToken(token); - return claims.get("jti", String.class); - } - - /** - * Purpose: getIssuerFromToken supports JwtUtil.java by holding or executing the get issuer from token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public String getIssuerFromToken(String token) { - Claims claims = parseToken(token); - return claims.getIssuer(); - } - - /** - * Purpose: getShopIdFromToken supports JwtUtil.java by holding or executing the get shop id from token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Long getShopIdFromToken(String token) { - Claims claims = parseToken(token); - Object value = claims.get("shopId"); - if (value == null) { - return null; - } - if (value instanceof Integer integer) { - return integer.longValue(); - } - if (value instanceof Long longValue) { - return longValue; - } - if (value instanceof String text) { - try { - return Long.parseLong(text); - } catch (NumberFormatException ignored) { - return null; - } - } - return null; - } - - /** - * Purpose: isTokenExpired supports JwtUtil.java by holding or executing the is token expired business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isTokenExpired(String token) { - try { - Claims claims = parseToken(token); - return claims.getExpiration().before(new Date()); - } catch (Exception e) { - return true; - } - } - - /** - * Purpose: validateToken supports JwtUtil.java by holding or executing the validate token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean validateToken(String token) { - try { - parseToken(token); - return !isTokenExpired(token); - } catch (Exception e) { - return false; - } - } - - /** - * Purpose: isAccessToken supports JwtUtil.java by holding or executing the is access token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isAccessToken(String token) { - return "access".equals(getTokenType(token)); - } - - /** - * Purpose: isRefreshToken supports JwtUtil.java by holding or executing the is refresh token business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public boolean isRefreshToken(String token) { - return "refresh".equals(getTokenType(token)); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/RedisUtils.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/RedisUtils.java deleted file mode 100644 index 596cda54..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/utils/RedisUtils.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.xiaowang.jacyucloudsalon.core.utils; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -/** - * Redis工具类 - * - * @author xiaowang - * @date 2026-02-12 - */ -@Component -public class RedisUtils { - - @Autowired - /** - * Purpose: redisTemplate supports RedisUtils.java by holding or executing the redis template business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private RedisTemplate redisTemplate; - - /** - * 指定缓存失效时间 - * @param key 键 - * @param time 时间(秒) - * @return - */ - public boolean expire(String key, long time) { - try { - if (time > 0) { - redisTemplate.expire(key, time, TimeUnit.SECONDS); - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * 根据key 获取过期时间 - * @param key 键 不能为null - * @return 时间(秒) 返回0代表为永久有效 - */ - public long getExpire(String key) { - return redisTemplate.getExpire(key, TimeUnit.SECONDS); - } - - /** - * 判断key是否存在 - * @param key 键 - * @return true 存在 false不存在 - */ - public boolean hasKey(String key) { - try { - return redisTemplate.hasKey(key); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * 删除缓存 - * @param key 可以传一个值 或多个 - */ - @SuppressWarnings("unchecked") - public void del(String... key) { - if (key != null && key.length > 0) { - if (key.length == 1) { - redisTemplate.delete(key[0]); - } else { - redisTemplate.delete((Collection) CollectionUtils.arrayToList(key)); - } - } - } - - // ============================String============================= - /** - * 普通缓存获取 - * @param key 键 - * @return 值 - */ - public Object get(String key) { - return key == null ? null : redisTemplate.opsForValue().get(key); - } - - /** - * 普通缓存放入 - * @param key 键 - * @param value 值 - * @return true成功 false失败 - */ - public boolean set(String key, Object value) { - try { - redisTemplate.opsForValue().set(key, value); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * 普通缓存放入并设置时间 - * @param key 键 - * @param value 值 - * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 - * @return true成功 false 失败 - */ - public boolean set(String key, Object value, long time) { - try { - if (time > 0) { - redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); - } else { - set(key, value); - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - // ================================Hash================================= - /** - * HashGet - * @param key 键 不能为null - * @param item 项 不能为null - * @return 值 - */ - public Object hget(String key, String item) { - return redisTemplate.opsForHash().get(key, item); - } - - /** - * 向一张hash表中放入数据,如果不存在将创建 - * @param key 键 - * @param item 项 - * @param value 值 - * @return true 成功 false失败 - */ - public boolean hset(String key, String item, Object value) { - try { - redisTemplate.opsForHash().put(key, item, value); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * 向一张hash表中放入数据,如果不存在将创建 - * @param key 键 - * @param item 项 - * @param value 值 - * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 - * @return true 成功 false失败 - */ - public boolean hset(String key, String item, Object value, long time) { - try { - redisTemplate.opsForHash().put(key, item, value); - if (time > 0) { - expire(key, time); - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * 获取hashKey对应的所有键值 - * @param key 键 - * @return 对应的多个键值 - */ - public Map hmget(String key) { - return redisTemplate.opsForHash().entries(key); - } - - // ============================set============================= - /** - * 根据key获取Set中的所有值 - * @param key 键 - * @return - */ - public Set sGet(String key) { - try { - return redisTemplate.opsForSet().members(key); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * 将数据放入set缓存 - * @param key 键 - * @param values 值 可以是多个 - * @return 成功个数 - */ - public long sSet(String key, Object... values) { - try { - return redisTemplate.opsForSet().add(key, values); - } catch (Exception e) { - e.printStackTrace(); - return 0; - } - } - - // ===============================list================================= - /** - * 获取list缓存的内容 - * @param key 键 - * @param start 开始 - * @param end 结束 0 到 -1代表所有值 - * @return - */ - public List lGet(String key, long start, long end) { - try { - return redisTemplate.opsForList().range(key, start, end); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * 将list放入缓存 - * @param key 键 - * @param value 值 - * @return - */ - public boolean lSet(String key, Object value) { - try { - redisTemplate.opsForList().rightPush(key, value); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/JayuCloudArtListCoreApplication.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/JayuCloudArtListCoreApplication.java new file mode 100644 index 00000000..bc56135e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/JayuCloudArtListCoreApplication.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.scheduling.annotation.EnableScheduling; + +@EnableDiscoveryClient +@EnableScheduling +@SpringBootApplication +/** + * Purpose: JayuCloudArtListCoreApplication supports JayuCloudArtListCoreApplication.java by holding or executing the JayuCloud business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class JayuCloudArtListCoreApplication { + + /** + * Purpose: main supports JayuCloudArtListCoreApplication.java by holding or executing the main business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static void main(String[] args) { + SpringApplication.run(JayuCloudArtListCoreApplication.class, args); + } + +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/annotation/OperationGuard.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/annotation/OperationGuard.java new file mode 100644 index 00000000..d890bdfa --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/annotation/OperationGuard.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.annotation; + +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +/** + * Purpose: OperationGuard supports OperationGuard.java by holding or executing the operation guard business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public @interface OperationGuard { + + String action(); + + OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING; + + int ttlSeconds() default 10; + + String message() default "操作进行中,请勿重复点击"; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/annotation/RequirePermission.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/annotation/RequirePermission.java new file mode 100644 index 00000000..8cc9cd9e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/annotation/RequirePermission.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +/** + * Purpose: RequirePermission supports RequirePermission.java by holding or executing the require permission business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public @interface RequirePermission { + + String value() default ""; + + int requireUserType() default -1; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/aspect/OperationGuardAspect.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/aspect/OperationGuardAspect.java new file mode 100644 index 00000000..35307c97 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/aspect/OperationGuardAspect.java @@ -0,0 +1,65 @@ +package com.xiaowang.jayucloud.artlist.core.aspect; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardService; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.time.Duration; + +@Aspect +@Component +@Order(100) +@RequiredArgsConstructor +/** + * Purpose: OperationGuardAspect supports OperationGuardAspect.java by holding or executing the operation guard aspect business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OperationGuardAspect { + + /** + * Purpose: operationGuardService supports OperationGuardAspect.java by holding or executing the operation guard service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final OperationGuardService operationGuardService; + + @Around("@annotation(operationGuard)") + /** + * Purpose: guardOperation supports OperationGuardAspect.java by holding or executing the guard operation business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return Result.error(500, "无法获取请求信息"); + } + + HttpServletRequest request = attributes.getRequest(); + OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire( + request, + operationGuard.action(), + Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds())) + ); + if (!handle.acquired()) { + if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) { + return Result.success(); + } + return Result.error(409, operationGuard.message()); + } + + try { + return joinPoint.proceed(); + } finally { + operationGuardService.release(handle); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/aspect/PermissionAspect.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/aspect/PermissionAspect.java new file mode 100644 index 00000000..3a9baa66 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/aspect/PermissionAspect.java @@ -0,0 +1,147 @@ +package com.xiaowang.jayucloud.artlist.core.aspect; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.PermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.PermissionService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; + +@Aspect +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +@RequiredArgsConstructor +/** + * Purpose: PermissionAspect supports PermissionAspect.java by holding or executing the permission aspect business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class PermissionAspect { + + /** + * Purpose: permissionService supports PermissionAspect.java by holding or executing the permission service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final PermissionService permissionService; + /** + * Purpose: permissionMapper supports PermissionAspect.java by holding or executing the permission mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final PermissionMapper permissionMapper; + /** + * Purpose: userMapper supports PermissionAspect.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + + @Around("@annotation(com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission)") + /** + * Purpose: checkPermission supports PermissionAspect.java by holding or executing the check permission business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return Result.error(403, "无法获取请求信息"); + } + + HttpServletRequest request = attributes.getRequest(); + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error(401, "未登录"); + } + + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + RequirePermission requirePermission = method.getAnnotation(RequirePermission.class); + if (requirePermission == null) { + return joinPoint.proceed(); + } + + UserDO userDO = userMapper.selectById(userId); + if (userDO == null) { + return Result.error(404, "用户不存在"); + } + + String permissionCode = requirePermission.value(); + Long currentShopId = parseShopId(request.getAttribute("currentShopId")); + if (Integer.valueOf(4).equals(userDO.getType()) + && currentShopId == null + && StringUtils.hasText(permissionCode) + && !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) { + return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作"); + } + + if (Integer.valueOf(4).equals(userDO.getType()) + && currentShopId == null + && StringUtils.hasText(permissionCode) + && PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) { + return joinPoint.proceed(); + } + + boolean hasPermission = !StringUtils.hasText(permissionCode) + || permissionService.hasPermission(userId, permissionCode); + if (!hasPermission) { + return Result.error(403, buildPermissionDeniedMessage(permissionCode)); + } + + return joinPoint.proceed(); + } + + /** + * Purpose: buildPermissionDeniedMessage supports PermissionAspect.java by holding or executing the build permission denied message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildPermissionDeniedMessage(String permissionCode) { + if (!StringUtils.hasText(permissionCode)) { + return "权限不足"; + } + + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + .last("limit 1") + ); + if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) { + return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")"; + } + return "权限不足:缺少权限代码 " + permissionCode; + } + + /** + * Purpose: parseShopId supports PermissionAspect.java by holding or executing the parse shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long parseShopId(Object value) { + if (value instanceof Number number) { + long shopId = number.longValue(); + return shopId > 0 ? shopId : null; + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + long shopId = Long.parseLong(text.trim()); + return shopId > 0 ? shopId : null; + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/BusinessException.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/BusinessException.java new file mode 100644 index 00000000..df552bae --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/BusinessException.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.artlist.core.common; + +/** + * 业务异常。 + */ +public class BusinessException extends RuntimeException { + + /** + * Purpose: code supports BusinessException.java by holding or executing the code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final Integer code; + + public BusinessException(String message) { + this(500, message); + } + + public BusinessException(Integer code, String message) { + super(message); + this.code = code; + } + + public BusinessException(String message, Throwable cause) { + this(500, message, cause); + } + + public BusinessException(Integer code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + /** + * Purpose: getCode supports BusinessException.java by holding or executing the get code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Integer getCode() { + return code; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/GlobalExceptionHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/GlobalExceptionHandler.java new file mode 100644 index 00000000..d5de8d73 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/GlobalExceptionHandler.java @@ -0,0 +1,155 @@ +package com.xiaowang.jayucloud.artlist.core.common; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.support.DefaultMessageSourceResolvable; +import org.springframework.validation.BindException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.multipart.MultipartException; + +import javax.validation.ConstraintViolationException; + +/** + * 全局异常处理器。 + */ +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + /** + * Purpose: MAX_UPLOAD_SIZE_BYTES supports GlobalExceptionHandler.java by holding or executing the max upload size bytes business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024; + + @ExceptionHandler(MethodArgumentNotValidException.class) + /** + * Purpose: handleMethodArgumentNotValidException supports GlobalExceptionHandler.java by holding or executing the handle method argument not valid exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + String message = e.getBindingResult().getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .findFirst() + .orElse("请求参数不合法"); + return Result.error(message); + } + + @ExceptionHandler(BindException.class) + /** + * Purpose: handleBindException supports GlobalExceptionHandler.java by holding or executing the handle bind exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleBindException(BindException e) { + String message = e.getBindingResult().getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .findFirst() + .orElse("请求参数不合法"); + return Result.error(message); + } + + @ExceptionHandler(ConstraintViolationException.class) + /** + * Purpose: handleConstraintViolationException supports GlobalExceptionHandler.java by holding or executing the handle constraint violation exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleConstraintViolationException(ConstraintViolationException e) { + String message = e.getConstraintViolations().stream() + .map(violation -> violation.getMessage()) + .findFirst() + .orElse("请求参数不合法"); + return Result.error(message); + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + /** + * Purpose: handleMaxUploadSizeExceededException supports GlobalExceptionHandler.java by holding or executing the handle max upload size exceeded exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) { + log.warn("上传文件超过限制: {}", e.getMessage()); + return Result.error(buildUploadLimitMessage()); + } + + @ExceptionHandler(MultipartException.class) + /** + * Purpose: handleMultipartException supports GlobalExceptionHandler.java by holding or executing the handle multipart exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleMultipartException(MultipartException e) { + log.warn("文件上传请求异常: {}", e.getMessage()); + return Result.error(buildUploadLimitMessage()); + } + + @ExceptionHandler(IllegalStateException.class) + /** + * Purpose: handleIllegalStateException supports GlobalExceptionHandler.java by holding or executing the handle illegal state exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleIllegalStateException(IllegalStateException e) { + if (isUploadLimitException(e)) { + log.warn("上传文件超过限制: {}", e.getMessage()); + return Result.error(buildUploadLimitMessage()); + } + log.error("非法状态异常", e); + return Result.error(e.getMessage()); + } + + @ExceptionHandler(BusinessException.class) + /** + * Purpose: handleBusinessException supports GlobalExceptionHandler.java by holding or executing the handle business exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleBusinessException(BusinessException e) { + log.warn("业务异常: {}", e.getMessage()); + return Result.error(e.getCode(), e.getMessage()); + } + + @ExceptionHandler(RuntimeException.class) + /** + * Purpose: handleRuntimeException supports GlobalExceptionHandler.java by holding or executing the handle runtime exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleRuntimeException(RuntimeException e) { + log.error("运行时异常", e); + return Result.error(e.getMessage()); + } + + @ExceptionHandler(Exception.class) + /** + * Purpose: handleException supports GlobalExceptionHandler.java by holding or executing the handle exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleException(Exception e) { + log.error("系统异常", e); + return Result.error("系统繁忙,请稍后再试"); + } + + /** + * Purpose: buildUploadLimitMessage supports GlobalExceptionHandler.java by holding or executing the build upload limit message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildUploadLimitMessage() { + return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB"; + } + + /** + * Purpose: isUploadLimitException supports GlobalExceptionHandler.java by holding or executing the is upload limit exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isUploadLimitException(Throwable throwable) { + Throwable current = throwable; + while (current != null) { + String message = current.getMessage(); + if (message != null && (message.contains("maximum permitted size") + || message.contains("FileSizeLimitExceededException") + || message.contains("exceeds its maximum permitted size"))) { + return true; + } + current = current.getCause(); + } + return false; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/Result.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/Result.java new file mode 100644 index 00000000..23fb071c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/Result.java @@ -0,0 +1,68 @@ +package com.xiaowang.jayucloud.artlist.core.common; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * 统一响应结果类 + * + * @param 数据类型 + * @author xiaowang + * @date 2026-02-12 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Result implements Serializable { + + /** + * Purpose: code supports Result.java by holding or executing the code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer code; + /** + * Purpose: message supports Result.java by holding or executing the message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String message; + /** + * Purpose: data supports Result.java by holding or executing the data business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private T data; + + /** + * Purpose: success supports Result.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result success() { + return new Result<>(200, "操作成功", null); + } + + /** + * Purpose: success supports Result.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result success(T data) { + return new Result<>(200, "操作成功", data); + } + + /** + * Purpose: error supports Result.java by holding or executing the error business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result error(String message) { + return new Result<>(500, message, null); + } + + /** + * Purpose: error supports Result.java by holding or executing the error business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result error(Integer code, String message) { + return new Result<>(code, message, null); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/dto/AgreementAwareRequest.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/dto/AgreementAwareRequest.java new file mode 100644 index 00000000..fdffd346 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/dto/AgreementAwareRequest.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.common.dto; + +import java.util.Map; + +/** + * Purpose: AgreementAwareRequest supports AgreementAwareRequest.java by holding or executing the agreement aware request business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface AgreementAwareRequest { + + Boolean getAgreementAccepted(); + + Map getAgreementVersions(); + + String getClientType(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/entity/BaseEntity.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/entity/BaseEntity.java new file mode 100644 index 00000000..8aa93a0d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/entity/BaseEntity.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.common.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 实体类基类 + * 提取公共字段,方便后续实体类扩展 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Data +public abstract class BaseEntity { + + /** + * 主键ID + */ + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/vo/PageResultVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/vo/PageResultVO.java new file mode 100644 index 00000000..43808b02 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/common/vo/PageResultVO.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.common.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * PageResultVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class PageResultVO { + /** + * Field `list` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List list; + /** + * Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long total; + /** + * Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer page; + /** + * Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer size; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/AppCacheProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/AppCacheProperties.java new file mode 100644 index 00000000..314c2a83 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/AppCacheProperties.java @@ -0,0 +1,60 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 多级缓存配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.cache") +public class AppCacheProperties { + + /** + * Purpose: localMaxSize supports AppCacheProperties.java by holding or executing the local max size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long localMaxSize = 2048; + + private CacheSpec productDetail = new CacheSpec(120, 900); + + private CacheSpec productList = new CacheSpec(60, 300); + + private CacheSpec productSearch = new CacheSpec(60, 300); + + private CacheSpec shop = new CacheSpec(180, 900); + + private CacheSpec tag = new CacheSpec(300, 1200); + + private CacheSpec objectStorageFile = new CacheSpec(300, 1800); + + private CacheSpec dashboard = new CacheSpec(30, 90); + + @Data + /** + * Purpose: CacheSpec supports AppCacheProperties.java by holding or executing the cache spec business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class CacheSpec { + /** + * Purpose: localTtlSeconds supports AppCacheProperties.java by holding or executing the local ttl seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long localTtlSeconds; + /** + * Purpose: redisTtlSeconds supports AppCacheProperties.java by holding or executing the redis ttl seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long redisTtlSeconds; + + public CacheSpec() { + } + + public CacheSpec(long localTtlSeconds, long redisTtlSeconds) { + this.localTtlSeconds = localTtlSeconds; + this.redisTtlSeconds = redisTtlSeconds; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/AuthInterceptor.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/AuthInterceptor.java new file mode 100644 index 00000000..39a40bcb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/AuthInterceptor.java @@ -0,0 +1,230 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestSignatureService; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService; +import com.xiaowang.jayucloud.artlist.core.utils.JwtUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Component +@RequiredArgsConstructor +/** + * Purpose: AuthInterceptor supports AuthInterceptor.java by holding or executing the auth interceptor business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class AuthInterceptor implements HandlerInterceptor { + + /** + * Purpose: jwtUtil supports AuthInterceptor.java by holding or executing the jwt util business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtUtil jwtUtil; + /** + * Purpose: userMapper supports AuthInterceptor.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + /** + * Purpose: userShopBindingSupport supports AuthInterceptor.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Purpose: userSessionService supports AuthInterceptor.java by holding or executing the user session service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserSessionService userSessionService; + /** + * Purpose: requestSignatureService supports AuthInterceptor.java by holding or executing the request signature service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestSignatureService requestSignatureService; + /** + * Purpose: requestThrottleService supports AuthInterceptor.java by holding or executing the request throttle service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestThrottleService requestThrottleService; + + /** + * Purpose: AUTHORIZATION_HEADER supports AuthInterceptor.java by holding or executing the authorization header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String AUTHORIZATION_HEADER = "Authorization"; + /** + * Purpose: BEARER_PREFIX supports AuthInterceptor.java by holding or executing the bearer prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String BEARER_PREFIX = "Bearer "; + + @Override + /** + * Purpose: preHandle supports AuthInterceptor.java by holding or executing the pre handle business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String path = request.getRequestURI(); + + String authHeader = request.getHeader(AUTHORIZATION_HEADER); + + if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType("application/json;charset=UTF-8"); + response.getWriter().write("{\"code\":401,\"message\":\"未提供认证Token\"}"); + return false; + } + + String token = authHeader.substring(BEARER_PREFIX.length()); + + if (!jwtUtil.validateToken(token)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期"); + return false; + } + + if (!jwtUtil.isAccessToken(token)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误"); + return false; + } + + Long userId = jwtUtil.getUserIdFromToken(token); + String account = jwtUtil.getAccountFromToken(token); + Long currentShopId = jwtUtil.getShopIdFromToken(token); + String sessionId = jwtUtil.getSessionIdFromToken(token); + String jti = jwtUtil.getJtiFromToken(token); + if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录"); + return false; + } + + UserDO currentUser = userMapper.selectById(userId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效"); + return false; + } + + if (currentUser.getStatus() != null && !Integer.valueOf(1).equals(currentUser.getStatus())) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "账号已被禁用"); + return false; + } + + boolean adminPath = isAdminPath(path); + if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限"); + return false; + } + + boolean canAccessShop = userShopBindingSupport.canUserAccessShop( + userId, + currentShopId, + adminPath, + currentUser.getType() + ); + if (!canAccessShop) { + String message = currentShopId == null || currentShopId <= 0 + ? "当前登录未选择可用店铺,请重新登录" + : (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId) + && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) + ? "店铺已被冻结" + : "当前登录店铺已停用或账号已失去该店铺访问权限"); + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message); + return false; + } + + if (adminPath + && !Integer.valueOf(4).equals(currentUser.getType()) + && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) + && !isExpiredAdminAllowedPath(path)) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员"); + return false; + } + + if (requiresSignature(request)) { + try { + requestSignatureService.validateRequest(request, token, userId); + } catch (RuntimeException exception) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); + return false; + } + } + + if (requiresWriteRateLimit(request)) { + try { + requestThrottleService.checkAuthenticatedWrite(request, userId); + } catch (RuntimeException exception) { + writeJsonResponse(response, 429, exception.getMessage()); + return false; + } + } + + request.setAttribute("userId", userId); + request.setAttribute("account", account); + request.setAttribute("userType", currentUser.getType()); + request.setAttribute("accessToken", token); + request.setAttribute("sessionId", sessionId); + request.setAttribute("tokenJti", jti); + request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId); + + return true; + } + + /** + * Purpose: requiresSignature supports AuthInterceptor.java by holding or executing the requires signature business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean requiresSignature(HttpServletRequest request) { + return requiresWriteRateLimit(request); + } + + /** + * Purpose: requiresWriteRateLimit supports AuthInterceptor.java by holding or executing the requires write rate limit business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean requiresWriteRateLimit(HttpServletRequest request) { + String method = request.getMethod(); + if (!StringUtils.hasText(method)) { + return false; + } + String normalized = method.toUpperCase(); + return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized)); + } + + /** + * Purpose: isAdminPath supports AuthInterceptor.java by holding or executing the is admin path business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isAdminPath(String path) { + return path.startsWith("/admin/") || path.startsWith("/order/admin/"); + } + + /** + * Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isExpiredAdminAllowedPath(String path) { + return path.startsWith("/admin/auth/") + || path.equals("/admin/user/info") + || path.equals("/permission/list/user/current") + || path.equals("/api/permission/list/user/current") + || path.startsWith("/admin/planning/") + || path.startsWith("/admin/shops/"); + } + + /** + * Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception { + response.setStatus(status); + response.setContentType("application/json;charset=UTF-8"); + response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}"); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/BrandProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/BrandProperties.java new file mode 100644 index 00000000..150a37ad --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/BrandProperties.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 平台品牌文案配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.brand") +public class BrandProperties { + + /** + * 短信模板中的平台名称。 + */ + private String messageTemplateName = "JayuCloudArtList"; + + /** + * 管理师注册店铺的默认描述。 + */ + private String managerRegisterShopDescription = "甲屿店务注册店铺"; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/HttpClientConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/HttpClientConfig.java new file mode 100644 index 00000000..bb28e030 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/HttpClientConfig.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import java.util.concurrent.TimeUnit; + +@Configuration +/** + * Purpose: HttpClientConfig supports HttpClientConfig.java by holding or executing the http client config business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class HttpClientConfig { + + @Bean + /** + * Purpose: poolingHttpClientConnectionManager supports HttpClientConfig.java by holding or executing the pooling http client connection manager business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(HttpClientProperties properties) { + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setMaxTotal(properties.getMaxTotalConnections()); + connectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute()); + return connectionManager; + } + + @Bean + public RestTemplate restTemplate(HttpClientProperties properties, + PoolingHttpClientConnectionManager connectionManager) { + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(properties.getConnectTimeoutMs()) + .setSocketTimeout(properties.getReadTimeoutMs()) + .setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs()) + .build(); + CloseableHttpClient httpClient = HttpClients.custom() + .setConnectionManager(connectionManager) + .setDefaultRequestConfig(requestConfig) + .disableCookieManagement() + .evictIdleConnections(30, TimeUnit.SECONDS) + .build(); + + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + requestFactory.setConnectTimeout(properties.getConnectTimeoutMs()); + requestFactory.setReadTimeout(properties.getReadTimeoutMs()); + requestFactory.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs()); + return new RestTemplate(requestFactory); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/HttpClientProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/HttpClientProperties.java new file mode 100644 index 00000000..2fa82af4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/HttpClientProperties.java @@ -0,0 +1,45 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.http-client") +/** + * Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class HttpClientProperties { + + /** + * Purpose: connectTimeoutMs supports HttpClientProperties.java by holding or executing the connect timeout ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int connectTimeoutMs = 3000; + + /** + * Purpose: readTimeoutMs supports HttpClientProperties.java by holding or executing the read timeout ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int readTimeoutMs = 5000; + + /** + * Purpose: connectionRequestTimeoutMs supports HttpClientProperties.java by holding or executing the connection request timeout ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int connectionRequestTimeoutMs = 1000; + + /** + * Purpose: maxTotalConnections supports HttpClientProperties.java by holding or executing the max total connections business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int maxTotalConnections = 200; + + /** + * Purpose: maxConnectionsPerRoute supports HttpClientProperties.java by holding or executing the max connections per route business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int maxConnectionsPerRoute = 50; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/JacksonConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/JacksonConfig.java new file mode 100644 index 00000000..234a4ab2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/JacksonConfig.java @@ -0,0 +1,64 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.LocalDateTime; +import java.io.IOException; +import java.time.format.DateTimeFormatter; + +@Configuration +/** + * Purpose: JacksonConfig supports JacksonConfig.java by holding or executing the jackson config business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class JacksonConfig { + + @Bean + /** + * Purpose: longToStringJacksonCustomizer supports JacksonConfig.java by holding or executing the long to string jackson customizer business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() { + return builder -> { + // Snowflake IDs are serialized as strings so the web and mini program do not lose precision. + builder.serializerByType(Long.class, ToStringSerializer.instance); + builder.serializerByType(Long.TYPE, ToStringSerializer.instance); + + JavaTimeModule javaTimeModule = new JavaTimeModule(); + javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer()); + builder.modules(javaTimeModule); + }; + } + + /** + * Purpose: FlexibleLocalDateTimeDeserializer supports JacksonConfig.java by holding or executing the flexible local date time deserializer business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer { + private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + @Override + /** + * Purpose: deserialize supports JacksonConfig.java by holding or executing the deserialize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String value = parser.getValueAsString(); + if (value == null || value.trim().isEmpty()) { + return null; + } + String normalized = value.trim(); + if (normalized.contains("T")) { + return LocalDateTime.parse(normalized); + } + return LocalDateTime.parse(normalized, SPACE_FORMATTER); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/JwtProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/JwtProperties.java new file mode 100644 index 00000000..33cfa771 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/JwtProperties.java @@ -0,0 +1,44 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * JWT 配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.security.jwt") +public class JwtProperties { + + /** + * HS512 密钥,生产环境请通过 Nacos 覆盖。 + */ + private String secret = "jayucloud-artlist-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + + /** + * Token 发行者。 + */ + private String issuer = "jayucloud-artlist"; + + /** + * AccessToken 有效期,单位秒。 + */ + private long accessTokenExpirationSeconds = 2 * 60 * 60; + + /** + * 记住登录 AccessToken 有效期,单位秒。 + */ + private long rememberMeAccessTokenExpirationSeconds = 7 * 24 * 60 * 60; + + /** + * RefreshToken 有效期,单位秒。 + */ + private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60; + + /** + * 时钟偏移容忍,单位秒。 + */ + private long clockSkewSeconds = 30; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/LoginLockProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/LoginLockProperties.java new file mode 100644 index 00000000..4f933c3b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/LoginLockProperties.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.security.login-lock") +/** + * Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LoginLockProperties { + + /** + * Purpose: maxFailures supports LoginLockProperties.java by holding or executing the max failures business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int maxFailures = 5; + + /** + * Purpose: windowSeconds supports LoginLockProperties.java by holding or executing the window seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long windowSeconds = 600; + + /** + * Purpose: lockSeconds supports LoginLockProperties.java by holding or executing the lock seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long lockSeconds = 900; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java new file mode 100644 index 00000000..59e35b0f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java @@ -0,0 +1,87 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * MyBatis-Plus配置类 + * 配置分页、乐观锁和防止全表更新等插件 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Configuration +@MapperScan({ + "com.xiaowang.jayucloud.artlist.core.modules.artist.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.auth.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.content.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.file.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.integration.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.message.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.order.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.payment.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.planning.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.product.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.security.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.shop.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.system.mapper", + "com.xiaowang.jayucloud.artlist.core.modules.user.mapper" +}) +public class MyBatisPlusConfig { + + /** + * 配置MyBatis-Plus插件 + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + + // 1. 分页插件 + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + + // 2. 乐观锁插件 + interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + + // 3. 防止全表更新与删除插件 + interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); + + return interceptor; + } + + @Bean + /** + * Purpose: identifierGenerator supports MyBatisPlusConfig.java by holding or executing the identifier generator business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) { + return new IdentifierGenerator() { + @Override + /** + * Purpose: nextId supports MyBatisPlusConfig.java by holding or executing the next id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Number nextId(Object entity) { + return snowflakeIdGenerator.nextId(); + } + + @Override + /** + * Purpose: nextUUID supports MyBatisPlusConfig.java by holding or executing the next uuid business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String nextUUID(Object entity) { + return snowflakeIdGenerator.nextIdString(); + } + }; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java new file mode 100644 index 00000000..b0745ddf --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java @@ -0,0 +1,41 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +/** + * MyBatis-Plus 自动填充配置 + * 用于自动填充实体类中的创建时间、更新时间等字段 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Slf4j +@Component +public class MyMetaObjectHandler implements MetaObjectHandler { + + @Override + /** + * Purpose: insertFill supports MyMetaObjectHandler.java by holding or executing the insert fill business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void insertFill(MetaObject metaObject) { + log.info("start insert fill ...."); + this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); + this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + } + + @Override + /** + * Purpose: updateFill supports MyMetaObjectHandler.java by holding or executing the update fill business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void updateFill(MetaObject metaObject) { + log.info("start update fill ...."); + this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/ObjectStorageProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/ObjectStorageProperties.java new file mode 100644 index 00000000..c1f3368e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/ObjectStorageProperties.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.util.Arrays; +import java.util.List; + +@Data +@Component +@Validated +@ConfigurationProperties(prefix = "object-storage") +public class ObjectStorageProperties { + + @NotEmpty + private List providerOrder = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS"); + + @NotEmpty + private List replicaRequiredProviders = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS"); + + private String primaryProvider; + + private String backupProvider; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @NotBlank + private String backupQueueName; + + @NotBlank + private String backupExchangeName; + + @NotBlank + private String backupRoutingKey; + + @NotNull + @Min(1) + private Integer backupRetryBatchLimit; + + @NotBlank + private String backupRetryCron; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RabbitMQConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RabbitMQConfig.java new file mode 100644 index 00000000..c9150a75 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RabbitMQConfig.java @@ -0,0 +1,59 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; +import org.springframework.amqp.support.converter.MessageConverter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RequiredArgsConstructor +public class RabbitMQConfig { + + public static final String EXAMPLE_QUEUE = "jayucloud-artlist.example.queue"; + public static final String EXAMPLE_EXCHANGE = "jayucloud-artlist.example.exchange"; + public static final String EXAMPLE_ROUTING_KEY = "jayucloud-artlist.example.routing.key"; + + private final ObjectStorageProperties objectStorageProperties; + + @Bean + public MessageConverter jsonMessageConverter() { + return new Jackson2JsonMessageConverter(); + } + + @Bean + public Queue exampleQueue() { + return new Queue(EXAMPLE_QUEUE, true); + } + + @Bean + public DirectExchange exampleExchange() { + return new DirectExchange(EXAMPLE_EXCHANGE); + } + + @Bean + public Binding exampleBinding() { + return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY); + } + + @Bean + public Queue objectStorageBackupQueue() { + return new Queue(objectStorageProperties.getBackupQueueName(), true); + } + + @Bean + public DirectExchange objectStorageBackupExchange() { + return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false); + } + + @Bean + public Binding objectStorageBackupBinding() { + return BindingBuilder.bind(objectStorageBackupQueue()) + .to(objectStorageBackupExchange()) + .with(objectStorageProperties.getBackupRoutingKey()); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java new file mode 100644 index 00000000..1eaaef16 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 限流配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.security.rate-limit") +public class RateLimitProperties { + + private LimitRule login = new LimitRule(10, 60); + + private LimitRule register = new LimitRule(5, 300); + + private LimitRule sendCode = new LimitRule(5, 60); + + private LimitRule resetPassword = new LimitRule(5, 600); + + private LimitRule wechatMiniLogin = new LimitRule(10, 60); + + private LimitRule agreementRead = new LimitRule(60, 60); + + private LimitRule authenticatedWrite = new LimitRule(80, 60); + + private LimitRule orderCreate = new LimitRule(10, 60); + + @Data + /** + * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class LimitRule { + /** + * Purpose: limit supports RateLimitProperties.java by holding or executing the limit business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int limit; + /** + * Purpose: windowSeconds supports RateLimitProperties.java by holding or executing the window seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long windowSeconds; + + public LimitRule() { + } + + public LimitRule(int limit, long windowSeconds) { + this.limit = limit; + this.windowSeconds = windowSeconds; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RedisConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RedisConfig.java new file mode 100644 index 00000000..61372cae --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RedisConfig.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * Redis配置类 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Configuration +@EnableCaching +public class RedisConfig extends CachingConfigurerSupport { + + @Bean + /** + * Purpose: redisTemplate supports RedisConfig.java by holding or executing the redis template business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + + // key采用String的序列化方式 + template.setKeySerializer(stringRedisSerializer); + // hash的key也采用String的序列化方式 + template.setHashKeySerializer(stringRedisSerializer); + // value序列化方式采用jackson + template.setValueSerializer(jackson2JsonRedisSerializer); + // hash的value序列化方式采用jackson + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + + return template; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RequestSignatureProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RequestSignatureProperties.java new file mode 100644 index 00000000..35cd4537 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RequestSignatureProperties.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 请求签名配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.security.signature") +public class RequestSignatureProperties { + + /** + * 是否启用签名校验。 + */ + private boolean enabled = true; + + /** + * 时间窗口,单位秒。 + */ + private long windowSeconds = 300; + + /** + * nonce 额外保留时间,单位秒。 + */ + private long nonceRetentionSeconds = 600; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SecurityHeadersFilter.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SecurityHeadersFilter.java new file mode 100644 index 00000000..ff65ec4a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SecurityHeadersFilter.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import org.springframework.stereotype.Component; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +/** + * Purpose: SecurityHeadersFilter supports SecurityHeadersFilter.java by holding or executing the security headers filter business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityHeadersFilter implements Filter { + + @Override + /** + * Purpose: doFilter supports SecurityHeadersFilter.java by holding or executing the do filter business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (response instanceof HttpServletResponse httpResponse) { + httpResponse.setHeader("X-Content-Type-Options", "nosniff"); + httpResponse.setHeader("X-Frame-Options", "DENY"); + httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin"); + httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:"); + } + chain.doFilter(request, response); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SlowRequestLogProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SlowRequestLogProperties.java new file mode 100644 index 00000000..daef859a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SlowRequestLogProperties.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.slow-request") +/** + * Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SlowRequestLogProperties { + + /** + * Purpose: enabled supports SlowRequestLogProperties.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean enabled = true; + + /** + * Purpose: thresholdMs supports SlowRequestLogProperties.java by holding or executing the threshold ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long thresholdMs = 300; + + /** + * Purpose: logResponseHeaderRequestId supports SlowRequestLogProperties.java by holding or executing the log response header request id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean logResponseHeaderRequestId = true; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SlowRequestLoggingInterceptor.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SlowRequestLoggingInterceptor.java new file mode 100644 index 00000000..d4f67dce --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/SlowRequestLoggingInterceptor.java @@ -0,0 +1,172 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.HandlerMapping; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.UUID; + +@Component +/** + * Purpose: SlowRequestLoggingInterceptor supports SlowRequestLoggingInterceptor.java by holding or executing the slow request logging interceptor business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SlowRequestLoggingInterceptor implements HandlerInterceptor { + + /** + * Purpose: REQUEST_ID_HEADER supports SlowRequestLoggingInterceptor.java by holding or executing the request id header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String REQUEST_ID_HEADER = "X-Request-Id"; + + private static final String START_TIME_ATTRIBUTE = SlowRequestLoggingInterceptor.class.getName() + ".startTime"; + private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("core-slow"); + + /** + * Purpose: properties supports SlowRequestLoggingInterceptor.java by holding or executing the properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SlowRequestLogProperties properties; + + public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) { + this.properties = properties; + } + + @Override + /** + * Purpose: preHandle supports SlowRequestLoggingInterceptor.java by holding or executing the pre handle business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + String requestId = resolveRequestId(request); + request.setAttribute(REQUEST_ID_HEADER, requestId); + if (properties.isLogResponseHeaderRequestId()) { + response.setHeader(REQUEST_ID_HEADER, requestId); + } + if (properties.isEnabled()) { + request.setAttribute(START_TIME_ATTRIBUTE, System.nanoTime()); + } + return true; + } + + @Override + /** + * Purpose: afterCompletion supports SlowRequestLoggingInterceptor.java by holding or executing the after completion business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) { + if (!properties.isEnabled()) { + return; + } + Object startTimeValue = request.getAttribute(START_TIME_ATTRIBUTE); + if (!(startTimeValue instanceof Long)) { + return; + } + + long durationMs = Math.max(0L, (System.nanoTime() - (Long) startTimeValue) / 1_000_000L); + if (durationMs < properties.getThresholdMs()) { + return; + } + + String requestId = (String) request.getAttribute(REQUEST_ID_HEADER); + String bestMatchingPattern = toStringValue(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); + String controllerMethod = resolveControllerMethod(handler); + String exceptionClass = ex == null ? "" : ex.getClass().getSimpleName(); + + SLOW_REQUEST_LOGGER.warn( + "requestId={} method={} uri={} query={} bestMatchingPattern={} controllerMethod={} status={} durationMs={} userId={} userType={} shopId={} clientIp={} contentLength={} exceptionClass={}", + sanitize(requestId), + request.getMethod(), + request.getRequestURI(), + sanitize(request.getQueryString()), + sanitize(bestMatchingPattern), + sanitize(controllerMethod), + response.getStatus(), + durationMs, + castLong(request.getAttribute("userId")), + castInteger(request.getAttribute("userType")), + castLong(request.getAttribute("currentShopId")), + resolveClientIp(request), + request.getContentLengthLong(), + sanitize(exceptionClass) + ); + } + + /** + * Purpose: resolveRequestId supports SlowRequestLoggingInterceptor.java by holding or executing the resolve request id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveRequestId(HttpServletRequest request) { + String requestId = request.getHeader(REQUEST_ID_HEADER); + return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", ""); + } + + /** + * Purpose: resolveControllerMethod supports SlowRequestLoggingInterceptor.java by holding or executing the resolve controller method business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveControllerMethod(Object handler) { + if (handler instanceof HandlerMethod handlerMethod) { + return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName(); + } + return ""; + } + + /** + * Purpose: resolveClientIp supports SlowRequestLoggingInterceptor.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + if (StringUtils.hasText(realIp)) { + return realIp.trim(); + } + return request.getRemoteAddr(); + } + + /** + * Purpose: sanitize supports SlowRequestLoggingInterceptor.java by holding or executing the sanitize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sanitize(String value) { + if (!StringUtils.hasText(value)) { + return ""; + } + return value.replace('\n', '_').replace('\r', '_'); + } + + /** + * Purpose: toStringValue supports SlowRequestLoggingInterceptor.java by holding or executing the to string value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String toStringValue(Object value) { + return value == null ? "" : value.toString(); + } + + /** + * Purpose: castLong supports SlowRequestLoggingInterceptor.java by holding or executing the cast long business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long castLong(Object value) { + return value instanceof Long ? (Long) value : null; + } + + /** + * Purpose: castInteger supports SlowRequestLoggingInterceptor.java by holding or executing the cast integer business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer castInteger(Object value) { + return value instanceof Integer ? (Integer) value : null; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/UploadSecurityProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/UploadSecurityProperties.java new file mode 100644 index 00000000..600fa710 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/UploadSecurityProperties.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.security.upload") +/** + * Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UploadSecurityProperties { + + /** + * Purpose: maxSize supports UploadSecurityProperties.java by holding or executing the max size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long maxSize = 10 * 1024 * 1024; + + private long maxTotalSize = 500L * 1024 * 1024; + + private List allowedMimeTypes = new ArrayList<>(List.of( + "image/jpeg", + "image/png", + "image/webp", + "image/gif" + )); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/WebMvcConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/WebMvcConfig.java new file mode 100644 index 00000000..1a53f42a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/WebMvcConfig.java @@ -0,0 +1,75 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@RequiredArgsConstructor +/** + * Purpose: WebMvcConfig supports WebMvcConfig.java by holding or executing the web mvc config business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class WebMvcConfig implements WebMvcConfigurer { + + /** + * Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AuthInterceptor authInterceptor; + /** + * Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor; + + @Override + /** + * Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(slowRequestLoggingInterceptor) + .addPathPatterns("/**") + .order(-100); + + registry.addInterceptor(authInterceptor) + .addPathPatterns("/**") + .order(0) + .excludePathPatterns( + "/user/login", + "/user/register", + "/user/check/**", + "/user/refresh-token", + "/user/send-verification-code", + "/user/phone-login", + "/user/wechat-mini/**", + "/user/reset-password-by-phone", + "/legal-agreement/current", + "/legal-agreement/current/**", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", + "/product/get/**", + "/product/list/**", + "/comment/list/product/**", + "/api/comment/list/product/**", + "/nail-artist/profile/**", + "/nail-artist/*/availability", + "/nail-artist/*/reviews", + "/shop/get/**", + "/shop/trust-profile/**", + "/shop/list", + "/shop/list/public", + "/shop/list/simple", + "/tag/list/all", + "/tag/list/filter-options", + "/file/get-signed-url/**", + "/admin/auth/login", + "/admin/auth/login-shops/**", + "/admin/auth/refresh", + "/error", + "/health/**" + ); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/WechatMiniProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/WechatMiniProperties.java new file mode 100644 index 00000000..ca14f33f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/WechatMiniProperties.java @@ -0,0 +1,40 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 微信小程序登录配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.wechat.mini") +public class WechatMiniProperties { + + /** + * Purpose: appId supports WechatMiniProperties.java by holding or executing the app id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String appId; + /** + * Purpose: appSecret supports WechatMiniProperties.java by holding or executing the app secret business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String appSecret; + /** + * Purpose: code2sessionUrl supports WechatMiniProperties.java by holding or executing the code2session url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session"; + /** + * Purpose: phoneNumberUrl supports WechatMiniProperties.java by holding or executing the phone number url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"; + /** + * Purpose: accessTokenBufferSeconds supports WechatMiniProperties.java by holding or executing the access token buffer seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer accessTokenBufferSeconds = 60; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/filter/RequestBodyCacheFilter.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/filter/RequestBodyCacheFilter.java new file mode 100644 index 00000000..823c0fb1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/filter/RequestBodyCacheFilter.java @@ -0,0 +1,60 @@ +package com.xiaowang.jayucloud.artlist.core.filter; + +import com.xiaowang.jayucloud.artlist.core.support.security.CachedBodyHttpServletRequest; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestSignatureService; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * 缓存 JSON 请求体,供签名校验复用。 + */ +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RequestBodyCacheFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + if (!shouldWrap(request)) { + filterChain.doFilter(request, response); + return; + } + + byte[] body = StreamUtils.copyToByteArray(request.getInputStream()); + CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body); + wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body); + filterChain.doFilter(wrappedRequest, response); + } + + /** + * Purpose: shouldWrap supports RequestBodyCacheFilter.java by holding or executing the should wrap business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean shouldWrap(HttpServletRequest request) { + String method = request.getMethod(); + if (!StringUtils.hasText(method)) { + return false; + } + String normalizedMethod = method.toUpperCase(); + if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) { + return false; + } + String contentType = request.getContentType(); + if (!StringUtils.hasText(contentType)) { + return false; + } + String normalizedType = contentType.toLowerCase(); + return normalizedType.contains("application/json"); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java new file mode 100644 index 00000000..e6884f79 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java @@ -0,0 +1,450 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.controller.front; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.artlist.core.modules.content.entity.CommentDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.OperationsAnalyticsService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.DashboardStatsVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.HotProductVO; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.RecentActivityVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/admin/dashboard") +@RequiredArgsConstructor +/** + * DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class DashboardController { + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentMapper commentMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + /** + * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderItemMapper orderItemMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + private final OperationsAnalyticsService operationsAnalyticsService; + + @GetMapping("/stats") + @RequirePermission("dashboard:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getDashboardStats(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopIdScope = resolveShopScope(currentUser); + String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope); + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard(); + DashboardStatsVO stats = multiLevelCacheService.getOrLoad( + "cache:dashboard:stats:" + cacheScope, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> buildDashboardStats(currentUser, shopIdScope) + ); + return Result.success(stats); + } + + @GetMapping("/analytics") + @RequirePermission("analytics:view") + public Result getAnalytics(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopIdScope = resolveShopScope(currentUser); + Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; + return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope)); + } + + /** + * Run business method `buildDashboardStats`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopIdScope parameter `shopIdScope` supplied by the caller + * @return private DashboardStatsVO result consumed by the caller or returned to the frontend + */ + private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) { + DashboardStatsVO stats = new DashboardStatsVO(); + Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; + + if (currentUser != null) { + // 根据用户类型显示不同的数据 + if (currentUser.getType() == 4) { // 管理员 + stats.setTotalUsers(userMapper.selectCount(null)); + stats.setTotalProducts(productMapper.selectCount(null)); + stats.setTotalShops(shopMapper.selectCount(null)); + stats.setTodayOrders(getTodayOrders(null)); + stats.setTotalCustomers(countUsers(null, 0, null, null)); + stats.setTotalArtists(countUsers(null, 3, null, null)); + } else { // 店长或美甲师 + Long shopId = currentUser.getShopId(); + if (shopId != null) { + shopIdScope = shopId; + // 只显示当前店铺的数据 + stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false)); + stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper().eq(ProductDO::getShopId, shopId))); + stats.setTotalShops(0L); // 非管理员不显示店铺数量 + stats.setTodayOrders(getTodayOrders(shopId)); + stats.setTotalCustomers(countUsers(shopId, 0, null, null)); + stats.setTotalArtists(countUsers(shopId, 3, null, null)); + } else { + // 没有店铺ID的情况 + stats.setTotalUsers(0L); + stats.setTotalProducts(0L); + stats.setTotalShops(0L); + stats.setTodayOrders(0L); + stats.setTotalCustomers(0L); + stats.setTotalArtists(0L); + } + } + } else { + // 无法获取用户信息的情况 + stats.setTotalUsers(0L); + stats.setTotalProducts(0L); + stats.setTotalShops(0L); + stats.setTodayOrders(0L); + stats.setTotalCustomers(0L); + stats.setTotalArtists(0L); + } + + LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); + LocalDateTime weekStart = todayStart.minusDays(6); + stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null)); + stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null)); + stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null)); + stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null)); + stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null)); + stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null)); + long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null); + long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null); + stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders); + stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null)); + + stats.setHotProducts(getHotProducts(shopIdScope)); + stats.setRecentActivities(getRecentActivities(shopIdScope)); + + return stats; + } + + /** + * Run business method `resolveShopScope`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveShopScope(UserDO currentUser) { + if (currentUser == null || currentUser.getType() == 4) { + return null; + } + return currentUser.getShopId(); + } + + /** + * Purpose: countUsers supports DashboardController.java by holding or executing the count users business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (type != null) { + wrapper.eq(UserDO::getType, type); + } + if (from != null) { + wrapper.ge(UserDO::getCreateTime, from); + } + if (to != null) { + wrapper.le(UserDO::getCreateTime, to); + } + if (shopId != null) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false); + if (userIds.isEmpty()) { + return 0L; + } + wrapper.in(UserDO::getId, userIds); + } + return userMapper.selectCount(wrapper); + } + + /** + * Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { + return (long) listScopedOrders(shopId, artistId, status, from, to).size(); + } + + /** + * Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) { + return listScopedOrders(shopId, artistId, null, from, to).stream() + .map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount()) + .filter(amount -> amount != null) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + /** + * Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + wrapper.eq(OrderDO::getShopId, shopId); + } + if (status != null) { + wrapper.eq(OrderDO::getStatus, status); + } + if (from != null) { + wrapper.ge(OrderDO::getCreateTime, from); + } + if (to != null) { + wrapper.le(OrderDO::getCreateTime, to); + } + if (artistId != null) { + Set orderIds = listOrderIdsByArtist(artistId); + if (orderIds.isEmpty()) { + return Collections.emptyList(); + } + wrapper.in(OrderDO::getId, orderIds); + } + return orderMapper.selectList(wrapper); + } + + /** + * Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set listOrderIdsByArtist(Long artistId) { + List items = orderItemMapper.selectList(new LambdaQueryWrapper() + .select(OrderItemDO::getOrderId) + .eq(OrderItemDO::getArtistId, artistId)); + return items.stream() + .map(OrderItemDO::getOrderId) + .filter(id -> id != null) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long getTodayOrders(Long shopId) { + // 获取今天的开始时间 + LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); + String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + if (shopId != null) { + // 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺 + java.util.Map result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr); + return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; + } else { + // 管理员查询所有订单 + java.util.Map result = orderItemMapper.countTodayOrders(todayStartStr); + return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; + } + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getHotProducts(Long shopId) { + // 通过订单商品表统计每个商品的订单数量,按订单数量排序 + // 使用SQL查询获取商品及其订单数量 + List> productOrderCounts = orderItemMapper.selectMaps( + new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper() + .select("product_id, COUNT(*) as order_count") + .groupBy("product_id") + .orderByDesc("order_count") + .last("LIMIT 5") + ); + + List hotProducts = new ArrayList<>(); + + // 遍历查询结果,获取商品详情 + for (Map map : productOrderCounts) { + Long productId = Long.valueOf(map.get("product_id").toString()); + ProductDO product = productMapper.selectById(productId); + + if (product != null && (shopId == null || shopId.equals(product.getShopId()))) { + HotProductVO vo = new HotProductVO(); + BeanUtils.copyProperties(product, vo); + vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0); + hotProducts.add(vo); + } + } + + // 如果按订单数量查询没有结果,使用点赞数作为备选 + if (hotProducts.isEmpty()) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + wrapper.eq(ProductDO::getShopId, shopId); + } + wrapper.orderByDesc(ProductDO::getLikeCount) + .last("LIMIT 5"); + List products = productMapper.selectList(wrapper); + + hotProducts = products.stream().map(product -> { + HotProductVO vo = new HotProductVO(); + BeanUtils.copyProperties(product, vo); + vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0); + return vo; + }).collect(Collectors.toList()); + } + + return hotProducts; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getRecentActivities(Long shopId) { + List activities = new ArrayList<>(); + + LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false); + if (userIds.isEmpty()) { + userWrapper.eq(UserDO::getId, -1L); + } else { + userWrapper.in(UserDO::getId, userIds); + } + } + userWrapper.orderByDesc(UserDO::getCreateTime) + .last("LIMIT 3"); + List recentUsers = userMapper.selectList(userWrapper); + + for (UserDO user : recentUsers) { + RecentActivityVO vo = new RecentActivityVO(); + vo.setId(user.getId()); + vo.setType("user"); + vo.setTitle("新用户注册"); + vo.setDescription("用户\"" + user.getNickname() + "\"注册成功"); + vo.setTime(user.getCreateTime()); + vo.setColor(""); + activities.add(vo); + } + + LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + productWrapper.eq(ProductDO::getShopId, shopId); + } + productWrapper.orderByDesc(ProductDO::getCreateTime) + .last("LIMIT 2"); + List recentProducts = productMapper.selectList(productWrapper); + + for (ProductDO product : recentProducts) { + RecentActivityVO vo = new RecentActivityVO(); + vo.setId(product.getId()); + vo.setType("product"); + vo.setTitle("新品上架"); + vo.setDescription("新品\"" + product.getTitle() + "\"已上架"); + vo.setTime(product.getCreateTime()); + vo.setColor("blue"); + activities.add(vo); + } + + LambdaQueryWrapper commentWrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + commentWrapper.eq(CommentDO::getShopId, shopId); + } + commentWrapper.orderByDesc(CommentDO::getCreateTime) + .last("LIMIT 2"); + List recentComments = commentMapper.selectList(commentWrapper); + + for (CommentDO comment : recentComments) { + RecentActivityVO vo = new RecentActivityVO(); + vo.setId(comment.getId()); + vo.setType("comment"); + vo.setTitle("用户评论"); + String content = comment.getCommentContent(); + if (content != null && content.length() > 20) { + content = content.substring(0, 20) + "..."; + } + vo.setDescription(content != null ? content : "用户发表了评论"); + vo.setTime(comment.getCreateTime()); + vo.setColor("green"); + activities.add(vo); + } + + activities.sort((a, b) -> b.getTime().compareTo(a.getTime())); + + return activities.stream().limit(5).collect(Collectors.toList()); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java new file mode 100644 index 00000000..2927c955 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.service; + +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO; + +public interface OperationsAnalyticsService { + OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java new file mode 100644 index 00000000..2be03c97 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.service; + +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.StoreWorkbenchVO; + +public interface WorkbenchService { + StoreWorkbenchVO getWorkbench(Long shopId, Long artistId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java new file mode 100644 index 00000000..72a022a6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserGrowthRecordDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserGrowthRecordMapper; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.OperationsAnalyticsService; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Service +@RequiredArgsConstructor +public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService { + + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final ProductMapper productMapper; + private final UserGrowthRecordMapper userGrowthRecordMapper; + + @Override + public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) { + List orders = orderMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, OrderDO::getShopId, shopId) + .eq(OrderDO::getIsDelete, 0)); + if (artistId != null) { + Set orderIds = new HashSet<>(); + orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getArtistId, artistId) + .eq(OrderItemDO::getIsDelete, 0)) + .forEach(item -> orderIds.add(item.getOrderId())); + orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList(); + } + OperationsAnalyticsVO vo = new OperationsAnalyticsVO(); + vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)) + .stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum()); + vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)) + .stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum()); + vo.setCartCount(0L); + vo.setOrderCount((long) orders.size()); + vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count()); + vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); + vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() + .eq(UserGrowthRecordDO::getSourceType, "REVIEW"))); + vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() + .eq(UserGrowthRecordDO::getSourceType, "REBOOK"))); + vo.setTotalAmount(orders.stream() + .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java new file mode 100644 index 00000000..7641e43d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java @@ -0,0 +1,145 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistChangeRequestDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.AfterSaleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistChangeRequestMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.WorkbenchService; +import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.StoreWorkbenchVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Service +@RequiredArgsConstructor +public class WorkbenchServiceImpl implements WorkbenchService { + + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final AfterSaleMapper afterSaleMapper; + private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + private final InventoryItemMapper inventoryItemMapper; + private final ArtistScheduleMapper artistScheduleMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; + + @Override + public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) { + LocalDateTime todayStart = LocalDate.now().atStartOfDay(); + LocalDateTime tomorrowStart = todayStart.plusDays(1); + List orders = scopedOrders(shopId, artistId); + StoreWorkbenchVO vo = new StoreWorkbenchVO(); + vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count()); + vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count()); + vo.setPendingAfterSaleCount(countAfterSales(shopId)); + vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId)); + vo.setLowStockItemCount(countLowStock(shopId)); + vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate())); + vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart)); + vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); + vo.setServiceAmount(orders.stream() + .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + vo.setAverageRating(resolveRating(artistId)); + return vo; + } + + private boolean isActionableOrder(OrderDO order) { + if (order == null || order.getStatus() == null) { + return false; + } + return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); + } + + private List scopedOrders(Long shopId, Long artistId) { + List orders = orderMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, OrderDO::getShopId, shopId) + .eq(OrderDO::getIsDelete, 0)); + if (artistId == null) { + return orders; + } + Set orderIds = new HashSet<>(); + orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getArtistId, artistId) + .eq(OrderItemDO::getIsDelete, 0)) + .forEach(item -> orderIds.add(item.getOrderId())); + return orders.stream().filter(order -> orderIds.contains(order.getId())).toList(); + } + + private long countAfterSales(Long shopId) { + return afterSaleMapper.selectCount(new LambdaQueryWrapper() + .eq(shopId != null, AfterSaleDO::getShopId, shopId) + .eq(AfterSaleDO::getStatus, "PENDING") + .eq(AfterSaleDO::getIsDelete, 0)); + } + + private long countArtistChanges(Long shopId, Long artistId) { + return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper() + .eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId) + .eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId) + .eq(OrderArtistChangeRequestDO::getStatus, "PENDING") + .eq(OrderArtistChangeRequestDO::getIsDelete, 0)); + } + + private long countLowStock(Long shopId) { + return inventoryItemMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, InventoryItemDO::getShopId, shopId) + .eq(InventoryItemDO::getIsDelete, 0)) + .stream() + .filter(item -> item.getStockQuantity() != null + && item.getWarningThreshold() != null + && item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0) + .count(); + } + + private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) { + return artistScheduleMapper.selectCount(new LambdaQueryWrapper() + .eq(shopId != null, ArtistScheduleDO::getShopId, shopId) + .eq(artistId != null, ArtistScheduleDO::getArtistId, artistId) + .ge(ArtistScheduleDO::getWorkDate, today) + .lt(ArtistScheduleDO::getWorkDate, today.plusDays(3)) + .eq(ArtistScheduleDO::getIsDelete, 0)); + } + + private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) { + if (artistId == null) { + return 0L; + } + return orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getArtistId, artistId) + .ge(OrderItemDO::getAppointmentTime, todayStart) + .lt(OrderItemDO::getAppointmentTime, tomorrowStart) + .eq(OrderItemDO::getIsDelete, 0)) + .size(); + } + + private BigDecimal resolveRating(Long artistId) { + if (artistId == null) { + return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); + } + BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); + return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP); + } + + private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) { + return value != null && !value.isBefore(start) && value.isBefore(end); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java new file mode 100644 index 00000000..edc5acc4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java @@ -0,0 +1,89 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.HotProductVO; +@Data +/** + * DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class DashboardStatsVO { + /** + * Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long totalUsers; + /** + * Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long totalProducts; + /** + * Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long totalShops; + /** + * Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long todayOrders; + /** + * Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal totalOrderAmount; + /** + * Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal todayOrderAmount; + /** + * Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal weekOrderAmount; + /** + * Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long totalCustomers; + /** + * Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long totalArtists; + /** + * Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long newCustomersToday; + /** + * Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long newCustomers7Days; + /** + * Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long newOrders7Days; + /** + * Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long pendingOrders; + /** + * Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long completedOrders; + /** + * Field `hotProducts` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List hotProducts; + /** + * Field `recentActivities` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List recentActivities; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java new file mode 100644 index 00000000..e794124c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OperationsAnalyticsVO { + private Long viewCount; + private Long favoriteCount; + private Long cartCount; + private Long orderCount; + private Long paidOrderCount; + private Long completedOrderCount; + private Long reviewCount; + private Long rebookCount; + private BigDecimal totalAmount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java new file mode 100644 index 00000000..bebca37f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java @@ -0,0 +1,37 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * RecentActivityVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class RecentActivityVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String type; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + /** + * Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime time; + /** + * Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String color; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java new file mode 100644 index 00000000..8839fc77 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class StoreWorkbenchVO { + private Long todayOrderCount; + private Long pendingOrderCount; + private Long pendingAfterSaleCount; + private Long pendingArtistChangeCount; + private Long lowStockItemCount; + private Long scheduleReminderCount; + private Long todayServiceCount; + private Long completedServiceCount; + private BigDecimal serviceAmount; + private BigDecimal averageRating; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/controller/front/NailArtistController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/controller/front/NailArtistController.java new file mode 100644 index 00000000..ac1072c6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/controller/front/NailArtistController.java @@ -0,0 +1,68 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistAvailabilityVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistProfileVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistReviewVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 美甲师信息Controller(前台) + */ +@RestController +@RequestMapping("/nail-artist") +public class NailArtistController { + + @Autowired + /** + * Purpose: nailArtistInfoService supports NailArtistController.java by holding or executing the nail artist info service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private NailArtistInfoService nailArtistInfoService; + + /** + * 获取所有可用的美甲师信息(前台使用) + */ + @GetMapping("/list") + public Result> getAllAvailableNailArtists() { + List nailArtistInfoDTOList = nailArtistInfoService.getAllAvailableNailArtists(); + return Result.success(nailArtistInfoDTOList); + } + + @GetMapping("/list/shop/{shopId}") + public Result> listByShopId(@PathVariable Long shopId) { + return Result.success(nailArtistInfoService.getByShopId(shopId)); + } + + /** + * 根据用户ID获取美甲师信息(前台使用) + */ + @GetMapping("/get/{userId}") + public Result getNailArtistInfo(@PathVariable Long userId) { + NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); + return Result.success(nailArtistInfoDTO); + } + + @GetMapping("/profile/{artistId}") + public Result getPublicProfile(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.getPublicProfile(artistId)); + } + + @GetMapping("/{artistId}/availability") + public Result> getAvailability(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.getAvailability(artistId)); + } + + @GetMapping("/{artistId}/reviews") + public Result> listPublicReviews(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.listPublicReviews(artistId)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java new file mode 100644 index 00000000..28da0150 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.dto; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Data +public class ArtistScheduleDTO { + private Long shopId; + private Long artistId; + private LocalDate workDate; + private LocalTime startTime; + private LocalTime endTime; + private Integer slotMinutes; + private Integer capacity; + private Integer status; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java new file mode 100644 index 00000000..7f43bf77 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.dto; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Data +public class ArtistScheduleExceptionDTO { + private Long shopId; + private Long artistId; + private LocalDate workDate; + private String exceptionType; + private LocalTime startTime; + private LocalTime endTime; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java new file mode 100644 index 00000000..b4d1f4ce --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.dto; + +import lombok.Data; + +import java.time.LocalTime; +import java.util.List; + +@Data +public class ArtistScheduleRuleDTO { + private Long shopId; + private Long artistId; + private String presetType; + private List workDays; + private LocalTime startTime; + private LocalTime endTime; + private Integer status; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/NailArtistInfoDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/NailArtistInfoDTO.java new file mode 100644 index 00000000..b91c194c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/NailArtistInfoDTO.java @@ -0,0 +1,117 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.dto; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalTime; + +/** + * 美甲师信息DTO + */ +@Data +public class NailArtistInfoDTO { + /** + * 主键ID + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 关联用户表主键(美甲师用户) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long userId; + + /** + * 身份 + */ + private String identity; + + /** + * 从业年限 + */ + private Integer experience; + + /** + * 技能标签ID集合,多个ID以逗号分隔 + */ + private String skills; + + /** + * 评分 + */ + private BigDecimal rating; + + /** + * 状态:1-营业中,0-休息中 + */ + private Integer status; + + /** + * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer participateProduction; + + /** + * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workStartTime; + + /** + * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workEndTime; + + /** + * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer userType; + + /** + * Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String userTypeName; + + /** + * 作品集商品ID集合,多个ID以逗号分隔 + */ + private String portfolio; + + /** + * 美甲师姓名(从用户表获取) + */ + private String nickname; + + /** + * 所属店铺ID + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 用户签名 + */ + private String signature; + + /** + * 头像访问地址 + */ + private String avatar; + + /** + * 排班模式摘要 + */ + private String scheduleModeSummary; + + /** + * 排班时间摘要 + */ + private String scheduleTimeSummary; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleDO.java new file mode 100644 index 00000000..7bf2919c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDate; +import java.time.LocalTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_artist_schedule") +public class ArtistScheduleDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("work_date") + private LocalDate workDate; + @TableField("start_time") + private LocalTime startTime; + @TableField("end_time") + private LocalTime endTime; + @TableField("slot_minutes") + private Integer slotMinutes; + @TableField("capacity") + private Integer capacity; + @TableField("status") + private Integer status; + @TableField("remark") + private String remark; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleExceptionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleExceptionDO.java new file mode 100644 index 00000000..23daaad6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleExceptionDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_artist_schedule_exception") +public class ArtistScheduleExceptionDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("work_date") + private LocalDate workDate; + @TableField("exception_type") + private String exceptionType; + @TableField("start_time") + private LocalTime startTime; + @TableField("end_time") + private LocalTime endTime; + @TableField("slot_minutes") + private Integer slotMinutes; + @TableField("capacity") + private Integer capacity; + @TableField("remark") + private String remark; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleRuleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleRuleDO.java new file mode 100644 index 00000000..caa03178 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/ArtistScheduleRuleDO.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_artist_schedule_rule") +public class ArtistScheduleRuleDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("preset_type") + private String presetType; + @TableField("work_days") + private String workDays; + @TableField("start_time") + private LocalTime startTime; + @TableField("end_time") + private LocalTime endTime; + @TableField("slot_minutes") + private Integer slotMinutes; + @TableField("capacity") + private Integer capacity; + @TableField("status") + private Integer status; + @TableField("remark") + private String remark; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/NailArtistInfoDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/NailArtistInfoDO.java new file mode 100644 index 00000000..8377ee78 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/entity/NailArtistInfoDO.java @@ -0,0 +1,79 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 美甲师信息实体类 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_nail_artist_info") +public class NailArtistInfoDO extends BaseEntity { + /** + * 关联用户表主键(美甲师用户) + */ + private Long userId; + + /** + * 身份 + */ + private String identity; + + /** + * 从业年限 + */ + private Integer experience; + + /** + * 技能标签ID集合,多个ID以逗号分隔 + */ + private String skills; + + /** + * 评分 + */ + private BigDecimal rating; + + /** + * 状态:1-营业中,0-休息中 + */ + private Integer status; + + @TableField("participate_production") + /** + * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer participateProduction; + + @TableField("work_start_time") + /** + * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workStartTime; + + @TableField("work_end_time") + /** + * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workEndTime; + + /** + * 作品集商品ID集合,多个ID以逗号分隔 + */ + private String portfolio; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java new file mode 100644 index 00000000..a13c912d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleExceptionDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ArtistScheduleExceptionMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleMapper.java new file mode 100644 index 00000000..90a10d42 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleMapper.java @@ -0,0 +1,47 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Mapper +public interface ArtistScheduleMapper extends BaseMapper { + @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " + + "AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE") + ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") LocalTime startTime, + @Param("endTime") LocalTime endTime); + + @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND work_date = #{workDate} AND is_delete = 0 ORDER BY start_time ASC LIMIT 1 FOR UPDATE") + ArtistScheduleDO selectDayScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate); + + @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND work_date = #{workDate} AND start_time = #{startTime} AND is_delete = 0 LIMIT 1 FOR UPDATE") + ArtistScheduleDO selectSlotScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") LocalTime startTime); + + @Update("UPDATE t_artist_schedule SET start_time = #{startTime}, end_time = #{endTime}, " + + "slot_minutes = #{slotMinutes}, capacity = #{capacity}, status = #{status}, remark = #{remark}, " + + "update_time = NOW() WHERE id = #{id} AND is_delete = 0") + int updateGeneratedSchedule(@Param("id") Long id, + @Param("startTime") LocalTime startTime, + @Param("endTime") LocalTime endTime, + @Param("slotMinutes") Integer slotMinutes, + @Param("capacity") Integer capacity, + @Param("status") Integer status, + @Param("remark") String remark); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleRuleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleRuleMapper.java new file mode 100644 index 00000000..49427817 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/ArtistScheduleRuleMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleRuleDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ArtistScheduleRuleMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/NailArtistInfoMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/NailArtistInfoMapper.java new file mode 100644 index 00000000..aaef238c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/mapper/NailArtistInfoMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 美甲师信息Mapper + */ +@Mapper +public interface NailArtistInfoMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java new file mode 100644 index 00000000..5ad05a63 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.service; + +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleExceptionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleRuleDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleExceptionVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleSettingVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleVO; + +import java.time.LocalDate; +import java.util.List; + +public interface ArtistScheduleService { + ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto); + + List listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate); + + ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId); + + ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto); + + ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/NailArtistInfoService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/NailArtistInfoService.java new file mode 100644 index 00000000..fa2d2d32 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/NailArtistInfoService.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistAvailabilityVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistProfileVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistReviewVO; + +import java.util.List; + +/** + * 美甲师信息服务 + */ +public interface NailArtistInfoService extends IService { + /** + * 根据用户ID获取美甲师信息 + * @param userId 用户ID + * @return 美甲师信息 + */ + NailArtistInfoDTO getByUserId(Long userId); + + /** + * 获取所有美甲师信息 + * @return 美甲师信息列表 + */ + List getAllNailArtists(); + + /** + * 根据店铺ID获取美甲师信息 + * @param shopId 店铺ID + * @return 美甲师信息列表 + */ + List getByShopId(Long shopId); + + /** + * 保存或更新美甲师信息 + * @param nailArtistInfoDTO 美甲师信息DTO + * @return 保存后的美甲师信息 + */ + NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO); + + /** + * 获取所有可用的美甲师信息(前台使用) + * @return 美甲师信息列表 + */ + List getAllAvailableNailArtists(); + + NailArtistProfileVO getPublicProfile(Long artistId); + + List getAvailability(Long artistId); + + List listPublicReviews(Long artistId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java new file mode 100644 index 00000000..d68ee7d1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java @@ -0,0 +1,423 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleExceptionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleRuleDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleExceptionDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleRuleDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleRuleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.service.ArtistScheduleService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleExceptionVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleSettingVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class ArtistScheduleServiceImpl implements ArtistScheduleService { + + private static final int GENERATED_DAYS = 60; + private static final int DEFAULT_SLOT_MINUTES = 60; + private static final int DEFAULT_CAPACITY = 1; + private static final String PRESET_SINGLE_REST = "SINGLE_REST"; + private static final String PRESET_DOUBLE_REST = "DOUBLE_REST"; + private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE"; + private static final String PRESET_LATE_SHIFT = "LATE_SHIFT"; + private static final String PRESET_CUSTOM = "CUSTOM"; + private static final String EXCEPTION_REST = "REST"; + private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK"; + private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT"; + + private final ArtistScheduleMapper artistScheduleMapper; + private final ArtistScheduleRuleMapper ruleMapper; + private final ArtistScheduleExceptionMapper exceptionMapper; + private final AppointmentReservationMapper reservationMapper; + + @Override + @Transactional + public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null + || dto.getStartTime() == null || dto.getEndTime() == null) { + throw new RuntimeException("排班信息不完整"); + } + ArtistScheduleDO schedule = new ArtistScheduleDO(); + BeanUtils.copyProperties(dto, schedule); + schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes()); + schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity()); + schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + schedule.setIsDelete(0); + ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime()); + if (existing == null) { + artistScheduleMapper.insert(schedule); + } else { + schedule.setId(existing.getId()); + artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(), + schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark()); + } + return toVO(schedule); + } + + @Override + public List listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(ArtistScheduleDO::getIsDelete, 0) + .orderByAsc(ArtistScheduleDO::getWorkDate) + .orderByAsc(ArtistScheduleDO::getStartTime); + if (shopId != null) { + wrapper.eq(ArtistScheduleDO::getShopId, shopId); + } + if (artistId != null) { + wrapper.eq(ArtistScheduleDO::getArtistId, artistId); + } + if (startDate != null) { + wrapper.ge(ArtistScheduleDO::getWorkDate, startDate); + } + if (endDate != null) { + wrapper.le(ArtistScheduleDO::getWorkDate, endDate); + } + return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList(); + } + + private ArtistScheduleVO toVO(ArtistScheduleDO schedule) { + ArtistScheduleVO vo = new ArtistScheduleVO(); + BeanUtils.copyProperties(schedule, vo); + return vo; + } + + @Override + public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) { + if (shopId == null || artistId == null) { + throw new RuntimeException("排班规则查询参数不完整"); + } + ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO(); + ArtistScheduleRuleDO rule = selectRule(shopId, artistId); + setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule)); + setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L)) + .stream() + .map(this::toExceptionVO) + .toList()); + return setting; + } + + @Override + @Transactional + public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) { + ArtistScheduleRuleDO normalized = normalizeRule(dto); + ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId()); + if (existing == null) { + ruleMapper.insert(normalized); + } else { + normalized.setId(existing.getId()); + ruleMapper.updateById(normalized); + } + refreshGeneratedSchedules(normalized); + return toRuleVO(normalized); + } + + @Override + @Transactional + public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) { + ArtistScheduleExceptionDO normalized = normalizeException(dto); + ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId()); + if (rule == null) { + rule = defaultRule(normalized.getShopId(), normalized.getArtistId()); + } + ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate()); + if (existing == null) { + exceptionMapper.insert(normalized); + } else { + normalized.setId(existing.getId()); + exceptionMapper.updateById(normalized); + } + refreshScheduleForDate(rule, normalized, normalized.getWorkDate()); + return toExceptionVO(normalized); + } + + private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) { + throw new RuntimeException("排班规则信息不完整"); + } + String presetType = normalizePresetType(dto.getPresetType()); + LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime(); + LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime(); + validateTimeRange(startTime, endTime); + ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO(); + rule.setShopId(dto.getShopId()); + rule.setArtistId(dto.getArtistId()); + rule.setPresetType(presetType); + rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType))); + rule.setStartTime(startTime); + rule.setEndTime(endTime); + rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); + rule.setCapacity(DEFAULT_CAPACITY); + rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + rule.setRemark(trimText(dto.getRemark())); + rule.setIsDelete(0); + return rule; + } + + private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) { + throw new RuntimeException("排班例外信息不完整"); + } + String exceptionType = normalizeExceptionType(dto.getExceptionType()); + LocalTime startTime = dto.getStartTime(); + LocalTime endTime = dto.getEndTime(); + if (!EXCEPTION_REST.equals(exceptionType)) { + if (startTime == null || endTime == null) { + throw new RuntimeException("临时上班或改班必须填写开始和结束时间"); + } + validateTimeRange(startTime, endTime); + } + ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO(); + exception.setShopId(dto.getShopId()); + exception.setArtistId(dto.getArtistId()); + exception.setWorkDate(dto.getWorkDate()); + exception.setExceptionType(exceptionType); + exception.setStartTime(startTime); + exception.setEndTime(endTime); + exception.setSlotMinutes(DEFAULT_SLOT_MINUTES); + exception.setCapacity(DEFAULT_CAPACITY); + exception.setRemark(trimText(dto.getRemark())); + exception.setIsDelete(0); + return exception; + } + + private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) { + return ruleMapper.selectOne(new LambdaQueryWrapper() + .eq(ArtistScheduleRuleDO::getShopId, shopId) + .eq(ArtistScheduleRuleDO::getArtistId, artistId) + .eq(ArtistScheduleRuleDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) { + return exceptionMapper.selectOne(new LambdaQueryWrapper() + .eq(ArtistScheduleExceptionDO::getShopId, shopId) + .eq(ArtistScheduleExceptionDO::getArtistId, artistId) + .eq(ArtistScheduleExceptionDO::getWorkDate, workDate) + .eq(ArtistScheduleExceptionDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + private List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { + return exceptionMapper.selectList(new LambdaQueryWrapper() + .eq(ArtistScheduleExceptionDO::getShopId, shopId) + .eq(ArtistScheduleExceptionDO::getArtistId, artistId) + .eq(ArtistScheduleExceptionDO::getIsDelete, 0) + .between(ArtistScheduleExceptionDO::getWorkDate, start, end) + .orderByAsc(ArtistScheduleExceptionDO::getWorkDate)); + } + + private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) { + LocalDate start = LocalDate.now(); + LocalDate end = start.plusDays(GENERATED_DAYS - 1L); + Map exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end) + .stream() + .collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a)); + LocalDate cursor = start; + while (!cursor.isAfter(end)) { + refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor); + cursor = cursor.plusDays(1L); + } + } + + private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) { + GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate); + if (!generated.working()) { + assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate); + upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark()); + return; + } + assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime()); + upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark()); + } + + private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) { + if (exception != null) { + if (EXCEPTION_REST.equals(exception.getExceptionType())) { + return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception)); + } + if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) { + return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception)); + } + } + boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue()); + return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班"); + } + + private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime, + Integer slotMinutes, Integer capacity, Integer status, String remark) { + ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate); + if (schedule == null) { + schedule = new ArtistScheduleDO(); + schedule.setShopId(rule.getShopId()); + schedule.setArtistId(rule.getArtistId()); + schedule.setWorkDate(workDate); + schedule.setStartTime(startTime); + schedule.setEndTime(endTime); + schedule.setSlotMinutes(slotMinutes); + schedule.setCapacity(capacity); + schedule.setStatus(status); + schedule.setRemark(remark); + schedule.setIsDelete(0); + artistScheduleMapper.insert(schedule); + return; + } + artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark); + } + + private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) { + int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate); + if (count > 0) { + throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count); + } + } + + private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) { + int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime); + if (count > 0) { + throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count); + } + } + + private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) { + return toRuleVO(defaultRule(shopId, artistId)); + } + + private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) { + ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO(); + rule.setShopId(shopId); + rule.setArtistId(artistId); + rule.setPresetType(PRESET_DOUBLE_REST); + rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5))); + rule.setStartTime(LocalTime.of(9, 0)); + rule.setEndTime(LocalTime.of(17, 0)); + rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); + rule.setCapacity(DEFAULT_CAPACITY); + rule.setStatus(1); + rule.setIsDelete(0); + return rule; + } + + private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) { + ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO(); + BeanUtils.copyProperties(rule, vo); + vo.setWorkDays(decodeWorkDays(rule.getWorkDays())); + return vo; + } + + private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) { + ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO(); + BeanUtils.copyProperties(exception, vo); + return vo; + } + + private String normalizePresetType(String presetType) { + String value = trimText(presetType); + if (value == null || value.isBlank()) { + return PRESET_CUSTOM; + } + return value; + } + + private String normalizeExceptionType(String exceptionType) { + String value = trimText(exceptionType); + if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) { + return value; + } + throw new RuntimeException("不支持的排班例外类型:" + value); + } + + private List resolveWorkDays(List inputWorkDays, String presetType) { + List presetDays = switch (presetType) { + case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5); + case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6); + default -> inputWorkDays; + }; + Set normalized = new LinkedHashSet<>(); + for (Integer day : presetDays == null ? List.of() : presetDays) { + if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) { + normalized.add(day); + } + } + if (normalized.isEmpty()) { + throw new RuntimeException("请至少选择一个工作日"); + } + return normalized.stream().sorted().toList(); + } + + private String encodeWorkDays(List workDays) { + return workDays.stream() + .sorted() + .map(String::valueOf) + .collect(Collectors.joining(",")); + } + + private List decodeWorkDays(String workDays) { + if (workDays == null || workDays.isBlank()) { + return new ArrayList<>(); + } + return List.of(workDays.split(",")).stream() + .map(String::trim) + .filter(value -> !value.isBlank()) + .map(Integer::valueOf) + .sorted() + .toList(); + } + + private LocalTime presetStartTime(String presetType) { + if (PRESET_NINE_TO_FIVE.equals(presetType)) { + return LocalTime.of(9, 0); + } + return LocalTime.of(10, 0); + } + + private LocalTime presetEndTime(String presetType) { + if (PRESET_NINE_TO_FIVE.equals(presetType)) { + return LocalTime.of(17, 0); + } + return LocalTime.of(22, 0); + } + + private void validateTimeRange(LocalTime startTime, LocalTime endTime) { + if (startTime == null || endTime == null || !startTime.isBefore(endTime)) { + throw new RuntimeException("排班开始时间必须早于结束时间"); + } + } + + private String trimText(String value) { + return value == null ? null : value.trim(); + } + + private String exceptionRemark(ArtistScheduleExceptionDO exception) { + if (exception.getRemark() != null && !exception.getRemark().isBlank()) { + return exception.getRemark(); + } + return "例外排班:" + exception.getExceptionType(); + } + + private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes, + Integer capacity, String remark) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java new file mode 100644 index 00000000..e1ce5c19 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -0,0 +1,831 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleRuleDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleRuleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistAvailabilityVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistProfileVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistReviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.NailArtistWorkVO; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +/** + * NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class NailArtistInfoServiceImpl extends ServiceImpl implements NailArtistInfoService { + + private static final int REVIEW_STATUS_SUBMITTED = 1; + private static final int ORDER_STATUS_COMPLETED = 2; + private static final int AVAILABILITY_DAYS = 7; + private static final int SLOT_MINUTES = 60; + private static final int MAX_AVAILABILITY_SLOTS = 16; + private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; + private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm"); + private static final String PRESET_DOUBLE_REST = "DOUBLE_REST"; + private static final String PRESET_SINGLE_REST = "SINGLE_REST"; + + @Autowired + /** + * Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserMapper userMapper; + + @Autowired + /** + * Purpose: shopMapper supports NailArtistInfoServiceImpl.java by holding or executing the shop mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ShopMapper shopMapper; + + @Autowired + /** + * Purpose: userShopBindingSupport supports NailArtistInfoServiceImpl.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserShopBindingSupport userShopBindingSupport; + + @Autowired + private ProductMapper productMapper; + + @Autowired + private OrderMapper orderMapper; + + @Autowired + private OrderItemMapper orderItemMapper; + + @Autowired + private OrderArtistReviewMapper orderArtistReviewMapper; + + @Autowired + private ObjectStorageFileService objectStorageFileService; + + @Autowired + private ObjectStorageUrlSupport objectStorageUrlSupport; + + @Autowired(required = false) + private ArtistScheduleMapper artistScheduleMapper; + + @Autowired(required = false) + private ArtistScheduleRuleMapper artistScheduleRuleMapper; + + @Autowired(required = false) + private AppointmentReservationMapper appointmentReservationMapper; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + public NailArtistInfoDTO getByUserId(Long userId) { + NailArtistInfoDO info = getOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + return info == null ? null : convertToDTO(info); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllNailArtists() { + List result = new ArrayList<>(); + List records = list(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getIsDelete, 0)); + for (NailArtistInfoDO record : records) { + NailArtistInfoDTO dto = convertToDTO(record); + if (isVisibleServiceUser(dto)) { + result.add(dto); + } + } + enrichScheduleSummaries(result, null); + return result; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getByShopId(Long shopId) { + List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (serviceUserIds.isEmpty()) { + return new ArrayList<>(); + } + + List users = userMapper.selectList(new LambdaQueryWrapper() + .in(UserDO::getId, serviceUserIds) + .eq(UserDO::getType, 3) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .orderByAsc(UserDO::getCreateTime) + .orderByAsc(UserDO::getId)); + List result = new ArrayList<>(); + ShopDO shop = shopMapper.selectById(shopId); + for (UserDO user : users) { + NailArtistInfoDTO dto = getByUserId(user.getId()); + if (dto == null) { + dto = buildFallbackArtistInfo(user); + } + dto.setShopId(shopId); + dto.setShopName(shop == null ? null : shop.getShopName()); + result.add(dto); + } + enrichScheduleSummaries(result, shopId); + return result; + } + + @Override + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) { + NailArtistInfoDO entity = new NailArtistInfoDO(); + BeanUtils.copyProperties(dto, entity); + + NailArtistInfoDO existing = getOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, dto.getUserId()) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existing != null) { + entity.setId(existing.getId()); + } + if (entity.getStatus() == null) { + entity.setStatus(1); + } + if (entity.getParticipateProduction() == null) { + UserDO user = userMapper.selectById(dto.getUserId()); + entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + } + + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + saveOrUpdate(entity); + /** + * Run business method `convertToDTO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToDTO(entity); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllAvailableNailArtists() { + List result = new ArrayList<>(); + List records = list(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getStatus, 1) + .eq(NailArtistInfoDO::getIsDelete, 0)); + for (NailArtistInfoDO record : records) { + NailArtistInfoDTO dto = convertToDTO(record); + if (isBookableServiceUser(dto)) { + result.add(dto); + } + } + return result; + } + + @Override + public NailArtistProfileVO getPublicProfile(Long artistId) { + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + UserDO artist = userMapper.selectById(artistId); + if (artist == null || isDeleted(artist.getIsDelete())) { + throw new RuntimeException("美甲师信息不存在"); + } + + List servedItems = loadArtistOrderItems(artistId, true); + List reviews = listPublicReviews(artistId); + NailArtistProfileVO profile = new NailArtistProfileVO(); + profile.setArtistId(artistId); + profile.setArtistName(resolveArtistName(artistInfo, artist)); + profile.setAvatar(artist.getAvatar()); + profile.setIdentity(artistInfo.getIdentity()); + profile.setSignature(artistInfo.getSignature()); + profile.setExperience(artistInfo.getExperience()); + profile.setStatus(artistInfo.getStatus()); + profile.setShopId(artistInfo.getShopId()); + profile.setShopName(artistInfo.getShopName()); + profile.setRating(resolvePublicRating(artistId, artistInfo)); + profile.setServiceCount(countServiceQuantity(servedItems)); + profile.setWorkStartTime(artistInfo.getWorkStartTime()); + profile.setWorkEndTime(artistInfo.getWorkEndTime()); + profile.setStyleTags(parseTextTokens(artistInfo.getSkills())); + profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 24)); + profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList())); + profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList())); + return profile; + } + + @Override + public List getAvailability(Long artistId) { + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + if (!Integer.valueOf(1).equals(artistInfo.getStatus())) { + return new ArrayList<>(); + } + + List scheduleSlots = buildScheduleAvailabilitySlots(artistId, artistInfo); + if (!scheduleSlots.isEmpty()) { + return scheduleSlots; + } + + LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime(); + LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime(); + if (!workEnd.isAfter(workStart)) { + workStart = LocalTime.of(10, 0); + workEnd = LocalTime.of(20, 0); + } + + LocalDate today = LocalDate.now(); + LocalDateTime rangeStart = today.atStartOfDay(); + LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay(); + Set bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd); + LocalDateTime now = LocalDateTime.now(); + List slots = new ArrayList<>(); + + for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) { + LocalDate date = today.plusDays(dayOffset); + LocalTime cursor = workStart; + while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) { + LocalDateTime slotStart = date.atTime(cursor); + LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES); + if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) { + slots.add(buildAvailabilitySlot(slotStart, slotEnd)); + } + cursor = cursor.plusMinutes(SLOT_MINUTES); + } + } + return slots; + } + + private List buildScheduleAvailabilitySlots(Long artistId, NailArtistInfoDTO artistInfo) { + if (artistScheduleMapper == null || artistInfo.getShopId() == null) { + return new ArrayList<>(); + } + LocalDate today = LocalDate.now(); + List schedules = artistScheduleMapper.selectList(new LambdaQueryWrapper() + .eq(ArtistScheduleDO::getShopId, artistInfo.getShopId()) + .eq(ArtistScheduleDO::getArtistId, artistId) + .eq(ArtistScheduleDO::getStatus, 1) + .eq(ArtistScheduleDO::getIsDelete, 0) + .ge(ArtistScheduleDO::getWorkDate, today) + .lt(ArtistScheduleDO::getWorkDate, today.plusDays(AVAILABILITY_DAYS)) + .orderByAsc(ArtistScheduleDO::getWorkDate) + .orderByAsc(ArtistScheduleDO::getStartTime)); + if (schedules == null || schedules.isEmpty()) { + return new ArrayList<>(); + } + LocalDateTime minStart = LocalDateTime.now().plusMinutes(30); + List slots = new ArrayList<>(); + for (ArtistScheduleDO schedule : schedules) { + int slotMinutes = schedule.getSlotMinutes() == null || schedule.getSlotMinutes() < 15 ? SLOT_MINUTES : schedule.getSlotMinutes(); + int capacity = schedule.getCapacity() == null || schedule.getCapacity() < 1 ? 1 : schedule.getCapacity(); + LocalTime cursor = schedule.getStartTime(); + while (cursor != null && schedule.getEndTime() != null + && !cursor.plusMinutes(slotMinutes).isAfter(schedule.getEndTime()) + && slots.size() < MAX_AVAILABILITY_SLOTS) { + LocalDateTime slotStart = schedule.getWorkDate().atTime(cursor); + LocalDateTime slotEnd = slotStart.plusMinutes(slotMinutes); + int used = appointmentReservationMapper == null ? 0 + : appointmentReservationMapper.countOverlappingActive(artistId, slotStart, slotEnd); + if (slotStart.isAfter(minStart) && used < capacity) { + slots.add(buildAvailabilitySlot(slotStart, slotEnd)); + } + cursor = cursor.plusMinutes(slotMinutes); + } + if (slots.size() >= MAX_AVAILABILITY_SLOTS) { + break; + } + } + return slots; + } + + @Override + public List listPublicReviews(Long artistId) { + if (artistId == null) { + return new ArrayList<>(); + } + List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() + .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .orderByDesc(OrderArtistReviewDO::getSubmittedAt) + .orderByDesc(OrderArtistReviewDO::getId)); + if (reviews == null || reviews.isEmpty()) { + return new ArrayList<>(); + } + + List limitedReviews = reviews.stream().limit(20).collect(Collectors.toList()); + Map customerMap = loadUsers(limitedReviews.stream() + .map(OrderArtistReviewDO::getCustomerId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + Map productMap = loadProducts(limitedReviews.stream() + .map(OrderArtistReviewDO::getProductId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + Set imageIds = new LinkedHashSet<>(); + for (OrderArtistReviewDO review : limitedReviews) { + imageIds.addAll(parseLongTokens(review.getImageFileIds())); + } + Map fileMap = loadFiles(imageIds); + + List result = new ArrayList<>(); + for (OrderArtistReviewDO review : limitedReviews) { + result.add(buildReviewVO(review, customerMap, productMap, fileMap)); + } + return result; + } + + /** + * Run business method `convertToDTO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) { + NailArtistInfoDTO dto = new NailArtistInfoDTO(); + BeanUtils.copyProperties(entity, dto); + + UserDO user = userMapper.selectById(entity.getUserId()); + if (user != null) { + dto.setNickname(user.getNickname()); + dto.setSignature(user.getSignature()); + dto.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + dto.setUserType(user.getType()); + dto.setUserTypeName(resolveUserTypeName(user.getType())); + if (dto.getParticipateProduction() == null) { + dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + } + + List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); + if (!shopOptions.isEmpty()) { + ShopSimpleVO primaryShop = shopOptions.get(0); + dto.setShopId(primaryShop.getId()); + dto.setShopName(primaryShop.getShopName()); + } else if (user.getShopId() != null && user.getShopId() > 0) { + ShopDO shop = shopMapper.selectById(user.getShopId()); + if (shop != null) { + dto.setShopId(shop.getId()); + dto.setShopName(shop.getShopName()); + } + } + } + return dto; + } + + private NailArtistInfoDTO buildFallbackArtistInfo(UserDO user) { + NailArtistInfoDTO dto = new NailArtistInfoDTO(); + dto.setUserId(user.getId()); + dto.setNickname(user.getNickname()); + dto.setSignature(user.getSignature()); + dto.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + dto.setUserType(user.getType()); + dto.setUserTypeName(resolveUserTypeName(user.getType())); + dto.setIdentity("美甲师"); + dto.setStatus(1); + dto.setParticipateProduction(1); + dto.setShopId(user.getShopId()); + List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); + if (!shopOptions.isEmpty()) { + ShopSimpleVO primaryShop = shopOptions.get(0); + dto.setShopId(primaryShop.getId()); + dto.setShopName(primaryShop.getShopName()); + } else if (user.getShopId() != null && user.getShopId() > 0) { + ShopDO shop = shopMapper.selectById(user.getShopId()); + if (shop != null) { + dto.setShopId(shop.getId()); + dto.setShopName(shop.getShopName()); + } + } + return dto; + } + + private void enrichScheduleSummaries(List artists, Long shopId) { + if (artistScheduleRuleMapper == null || artists == null || artists.isEmpty()) { + return; + } + Set artistIds = artists.stream() + .map(NailArtistInfoDTO::getUserId) + .filter(userId -> userId != null && userId > 0) + .collect(Collectors.toCollection(LinkedHashSet::new)); + if (artistIds.isEmpty()) { + return; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .in(ArtistScheduleRuleDO::getArtistId, artistIds) + .eq(ArtistScheduleRuleDO::getIsDelete, 0); + if (shopId != null && shopId > 0) { + wrapper.eq(ArtistScheduleRuleDO::getShopId, shopId); + } + Map ruleByArtistId = artistScheduleRuleMapper.selectList(wrapper).stream() + .collect(Collectors.toMap(ArtistScheduleRuleDO::getArtistId, rule -> rule, (left, right) -> left)); + artists.forEach(artist -> applyScheduleSummary(artist, ruleByArtistId.get(artist.getUserId()))); + } + + private void applyScheduleSummary(NailArtistInfoDTO artist, ArtistScheduleRuleDO rule) { + if (artist == null) { + return; + } + if (rule == null || !Integer.valueOf(1).equals(rule.getStatus())) { + artist.setScheduleModeSummary("未设置"); + artist.setScheduleTimeSummary(""); + return; + } + artist.setScheduleModeSummary(resolveScheduleModeSummary(rule.getPresetType())); + artist.setScheduleTimeSummary(formatScheduleTimeSummary(rule.getStartTime(), rule.getEndTime())); + } + + private String resolveScheduleModeSummary(String presetType) { + if (PRESET_DOUBLE_REST.equals(presetType)) { + return "双休"; + } + if (PRESET_SINGLE_REST.equals(presetType)) { + return "单休"; + } + return "自定义"; + } + + private String formatScheduleTimeSummary(LocalTime startTime, LocalTime endTime) { + if (startTime == null || endTime == null) { + return ""; + } + return TIME_TEXT_FORMATTER.format(startTime) + "-" + TIME_TEXT_FORMATTER.format(endTime); + } + + private String resolveAccessibleAvatar(String avatar) { + if (!StringUtils.hasText(avatar)) { + return null; + } + String accessibleUrl = objectStorageUrlSupport.toAccessibleUrl(avatar); + return StringUtils.hasText(accessibleUrl) ? accessibleUrl : avatar; + } + + /** + * Run business method `isVisibleServiceUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVisibleServiceUser(NailArtistInfoDTO dto) { + if (dto == null || dto.getUserType() == null) { + return false; + } + return Integer.valueOf(3).equals(dto.getUserType()) + || Integer.valueOf(2).equals(dto.getUserType()); + } + + /** + * Run business method `isBookableServiceUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isBookableServiceUser(NailArtistInfoDTO dto) { + return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus()); + } + + /** + * Run business method `resolveUserTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveUserTypeName(Integer type) { + if (Integer.valueOf(2).equals(type)) { + return "店长"; + } + if (Integer.valueOf(3).equals(type)) { + return "美甲师"; + } + return "用户"; + } + + private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) { + if (artistId == null) { + throw new RuntimeException("美甲师信息不存在"); + } + NailArtistInfoDTO artistInfo = getByUserId(artistId); + if (artistInfo != null && isVisibleServiceUser(artistInfo)) { + return artistInfo; + } + UserDO artist = userMapper.selectById(artistId); + if (artist == null + || isDeleted(artist.getIsDelete()) + || !Integer.valueOf(3).equals(artist.getType()) + || !Integer.valueOf(1).equals(artist.getStatus())) { + throw new RuntimeException("美甲师信息不存在"); + } + return buildFallbackArtistInfo(artist); + } + + private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) { + BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); + BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating; + if (rating == null) { + return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); + } + return rating.setScale(1, RoundingMode.HALF_UP); + } + + private List loadArtistOrderItems(Long artistId, boolean completedOnly) { + List orders = orderMapper.selectByArtistId(artistId); + if (orders == null || orders.isEmpty()) { + return new ArrayList<>(); + } + + Set allowedOrderIds = orders.stream() + .filter(order -> !isDeleted(order.getIsDelete())) + .filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus())) + .map(OrderDO::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + if (allowedOrderIds.isEmpty()) { + return new ArrayList<>(); + } + + List items = new ArrayList<>(); + for (Long orderId : allowedOrderIds) { + List orderItems = orderItemMapper.selectByOrderId(orderId); + if (orderItems == null) { + continue; + } + for (OrderItemDO item : orderItems) { + if (item != null + && artistId.equals(item.getArtistId()) + && !isDeleted(item.getIsDelete())) { + items.add(item); + } + } + } + return items; + } + + private long countServiceQuantity(List items) { + if (items == null || items.isEmpty()) { + return 0L; + } + long count = 0L; + for (OrderItemDO item : items) { + if (item == null) { + continue; + } + count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity(); + } + return count; + } + + private List buildWorks(String portfolio, List servedItems, int limit) { + LinkedHashSet productIds = new LinkedHashSet<>(parseLongTokens(portfolio)); + if (servedItems != null) { + servedItems.stream() + .sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .map(OrderItemDO::getProductId) + .filter(productId -> productId != null && productId > 0) + .forEach(productIds::add); + } + if (productIds.isEmpty()) { + return new ArrayList<>(); + } + + List limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList()); + Map productMap = loadProducts(new LinkedHashSet<>(limitedIds)); + Set fileIds = new LinkedHashSet<>(); + for (ProductDO product : productMap.values()) { + fileIds.addAll(parseLongTokens(product.getImageFileIds())); + } + Map fileMap = loadFiles(fileIds); + + List works = new ArrayList<>(); + for (Long productId : limitedIds) { + ProductDO product = productMap.get(productId); + if (product == null || isDeleted(product.getIsDelete()) || !isFrontVisible(product)) { + continue; + } + works.add(buildWorkVO(product, fileMap)); + } + return works; + } + + private NailArtistWorkVO buildWorkVO(ProductDO product, Map fileMap) { + NailArtistWorkVO work = new NailArtistWorkVO(); + work.setId(product.getId()); + work.setTitle(product.getTitle()); + work.setDescription(product.getDescription()); + work.setPrice(product.getPrice()); + work.setTags(parseTextTokens(product.getTags())); + work.setLikeCount(product.getLikeCount()); + work.setCollectCount(product.getCollectCount()); + List imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap); + work.setImageUrls(imageUrls); + work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0)); + return work; + } + + private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review, + Map customerMap, + Map productMap, + Map fileMap) { + NailArtistReviewVO vo = new NailArtistReviewVO(); + vo.setId(review.getId()); + vo.setArtistId(review.getArtistId()); + vo.setCustomerId(review.getCustomerId()); + UserDO customer = customerMap.get(review.getCustomerId()); + vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname()); + vo.setCustomerAvatar(customer == null ? null : customer.getAvatar()); + vo.setProductId(review.getProductId()); + ProductDO product = productMap.get(review.getProductId()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setRating(review.getRatingScore()); + vo.setContent(review.getContent()); + List imageFileIds = parseLongTokens(review.getImageFileIds()); + vo.setImageFileIds(imageFileIds); + vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap)); + vo.setSubmittedAt(review.getSubmittedAt()); + return vo; + } + + private Set loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) { + List bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd); + if (bookedItems == null || bookedItems.isEmpty()) { + return new HashSet<>(); + } + return bookedItems.stream() + .map(OrderItemDO::getAppointmentTime) + .filter(appointmentTime -> appointmentTime != null) + .map(this::truncateToMinute) + .collect(Collectors.toSet()); + } + + private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) { + NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO(); + slot.setStartTime(startTime); + slot.setEndTime(endTime); + slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate())); + slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime())); + slot.setAvailable(true); + return slot; + } + + private Map loadProducts(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return new HashMap<>(); + } + List products = productMapper.selectBatchIds(productIds); + if (products == null || products.isEmpty()) { + return new HashMap<>(); + } + return products.stream() + .filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete()) && isFrontVisible(product)) + .collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new)); + } + + private Map loadUsers(Set userIds) { + if (userIds == null || userIds.isEmpty()) { + return new HashMap<>(); + } + List users = userMapper.selectBatchIds(new ArrayList<>(userIds)); + if (users == null || users.isEmpty()) { + return new HashMap<>(); + } + return users.stream() + .filter(user -> user != null && user.getId() != null) + .collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new)); + } + + private Map loadFiles(Set fileIds) { + if (fileIds == null || fileIds.isEmpty()) { + return new HashMap<>(); + } + Map files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + return files == null ? new HashMap<>() : files; + } + + private List resolveImageUrls(List fileIds, Map fileMap) { + if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { + return new ArrayList<>(); + } + List urls = new ArrayList<>(); + for (Long fileId : fileIds) { + ObjectStorageFileVO file = fileMap.get(fileId); + if (file != null && StringUtils.hasText(file.getFileUrl())) { + urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); + } + } + return urls; + } + + private List parseLongTokens(String raw) { + if (!StringUtils.hasText(raw)) { + return new ArrayList<>(); + } + LinkedHashSet ids = new LinkedHashSet<>(); + for (String token : raw.split("[,;,;\\s]+")) { + if (!StringUtils.hasText(token)) { + continue; + } + try { + ids.add(Long.parseLong(token.trim())); + } catch (NumberFormatException ignored) { + // Some legacy fields store tag names instead of ids. + } + } + return new ArrayList<>(ids); + } + + private List parseTextTokens(String raw) { + if (!StringUtils.hasText(raw)) { + return new ArrayList<>(); + } + LinkedHashSet tokens = new LinkedHashSet<>(); + for (String token : raw.split("[,;,;、\\s]+")) { + if (StringUtils.hasText(token)) { + tokens.add(token.trim()); + } + } + return new ArrayList<>(tokens); + } + + private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) { + if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) { + return artistInfo.getNickname(); + } + if (artist != null && StringUtils.hasText(artist.getNickname())) { + return artist.getNickname(); + } + return "美甲师"; + } + + private boolean isDeleted(Integer isDelete) { + return Integer.valueOf(1).equals(isDelete); + } + + private boolean isFrontVisible(ProductDO product) { + return product != null && Integer.valueOf(1).equals(product.getFrontVisible()); + } + + private LocalDateTime truncateToMinute(LocalDateTime value) { + return value == null ? null : value.withSecond(0).withNano(0); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/support/BookableArtistSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/support/BookableArtistSupport.java new file mode 100644 index 00000000..4f6e8d69 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/support/BookableArtistSupport.java @@ -0,0 +1,116 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.support; + +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; + +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +@Component +@RequiredArgsConstructor +/** + * Purpose: BookableArtistSupport supports BookableArtistSupport.java by holding or executing the bookable artist support business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BookableArtistSupport { + + /** + * Purpose: userMapper supports BookableArtistSupport.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + /** + * Purpose: nailArtistInfoMapper supports BookableArtistSupport.java by holding or executing the nail artist info mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final NailArtistInfoMapper nailArtistInfoMapper; + /** + * Purpose: userShopBindingSupport supports BookableArtistSupport.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + + /** + * Purpose: isValidBookableArtist supports BookableArtistSupport.java by holding or executing the is valid bookable artist business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isValidBookableArtist(Long shopId, Long artistId) { + if (artistId == null || artistId <= 0) { + return false; + } + + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { + return false; + } + if (!isBookableServiceUser(artist)) { + return false; + } + if (!Integer.valueOf(1).equals(artist.getStatus())) { + return false; + } + return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId); + } + + /** + * Purpose: isBookableServiceUser supports BookableArtistSupport.java by holding or executing the is bookable service user business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isBookableServiceUser(UserDO user) { + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { + return false; + } + if (Integer.valueOf(3).equals(user.getType())) { + return true; + } + if (!Integer.valueOf(2).equals(user.getType())) { + return false; + } + NailArtistInfoDO info = nailArtistInfoMapper.selectOne( + new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, user.getId()) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1") + ); + return info != null + && Integer.valueOf(1).equals(info.getStatus()) + && Integer.valueOf(1).equals(info.getParticipateProduction()); + } + + /** + * Purpose: filterValidBookableArtists supports BookableArtistSupport.java by holding or executing the filter valid bookable artists business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String filterValidBookableArtists(Long shopId, String rawBookableArtists) { + if (!StringUtils.hasText(rawBookableArtists)) { + return ""; + } + + Set validArtistIds = new LinkedHashSet<>(); + for (String artistIdText : rawBookableArtists.split(",")) { + if (!StringUtils.hasText(artistIdText)) { + continue; + } + try { + Long artistId = Long.parseLong(artistIdText.trim()); + if (isValidBookableArtist(shopId, artistId)) { + validArtistIds.add(artistId); + } + } catch (NumberFormatException ignored) { + // Ignore invalid configured IDs and only expose currently valid artists. + } + } + + return validArtistIds.stream() + .map(String::valueOf) + .collect(Collectors.joining(",")); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistCalendarAppointmentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistCalendarAppointmentVO.java new file mode 100644 index 00000000..c4692f9a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistCalendarAppointmentVO.java @@ -0,0 +1,90 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ArtistCalendarAppointmentVO { + /** + * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderId; + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer orderStatus; + /** + * Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderStatusText; + /** + * Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderItemId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + /** + * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistName; + /** + * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerNickname; + /** + * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerPhoneMasked; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentStartTime; + /** + * Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentEndTime; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long durationMinutes; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java new file mode 100644 index 00000000..2833e5e7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +@Data +public class ArtistScheduleExceptionVO { + private Long id; + private Long shopId; + private Long artistId; + private LocalDate workDate; + private String exceptionType; + private LocalTime startTime; + private LocalTime endTime; + private String remark; + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java new file mode 100644 index 00000000..fdf82f63 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class ArtistScheduleRuleSettingVO { + private ArtistScheduleRuleVO rule; + private List exceptions; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java new file mode 100644 index 00000000..89096f7c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; + +@Data +public class ArtistScheduleRuleVO { + private Long id; + private Long shopId; + private Long artistId; + private String presetType; + private List workDays; + private LocalTime startTime; + private LocalTime endTime; + private Integer status; + private String remark; + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java new file mode 100644 index 00000000..2e2a9091 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java @@ -0,0 +1,22 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +@Data +public class ArtistScheduleVO { + private Long id; + private Long shopId; + private Long artistId; + private LocalDate workDate; + private LocalTime startTime; + private LocalTime endTime; + private Integer slotMinutes; + private Integer capacity; + private Integer status; + private String remark; + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistAvailabilityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistAvailabilityVO.java new file mode 100644 index 00000000..5c15c5cd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistAvailabilityVO.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class NailArtistAvailabilityVO { + private LocalDateTime startTime; + private LocalDateTime endTime; + private String dateText; + private String timeText; + private Boolean available; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistProfileVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistProfileVO.java new file mode 100644 index 00000000..4f954216 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistProfileVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistProfileVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long artistId; + private String artistName; + private String avatar; + private String identity; + private String signature; + private Integer experience; + private Integer status; + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + private String shopName; + private BigDecimal rating; + private Long serviceCount; + private LocalTime workStartTime; + private LocalTime workEndTime; + private List styleTags = new ArrayList<>(); + private List works = new ArrayList<>(); + private List reviews = new ArrayList<>(); + private List availability = new ArrayList<>(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistReviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistReviewVO.java new file mode 100644 index 00000000..d84b6b3e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistReviewVO.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistReviewVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + @JsonSerialize(using = ToStringSerializer.class) + private Long artistId; + @JsonSerialize(using = ToStringSerializer.class) + private Long customerId; + private String customerName; + private String customerAvatar; + @JsonSerialize(using = ToStringSerializer.class) + private Long productId; + private String productTitle; + private BigDecimal rating; + private String content; + private List imageFileIds = new ArrayList<>(); + private List imageUrls = new ArrayList<>(); + private LocalDateTime submittedAt; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistWorkVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistWorkVO.java new file mode 100644 index 00000000..ddfde171 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/NailArtistWorkVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.artist.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistWorkVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + private String title; + private String description; + private BigDecimal price; + private String coverImageUrl; + private List imageUrls = new ArrayList<>(); + private List tags = new ArrayList<>(); + private Integer likeCount; + private Integer collectCount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/controller/front/LoginIdentityController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/controller/front/LoginIdentityController.java new file mode 100644 index 00000000..87c0c276 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/controller/front/LoginIdentityController.java @@ -0,0 +1,111 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.LoginIdentityDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginIdentityVO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.service.LoginIdentityService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户登录标识信息表 Controller + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/login-identity", "/api/login-identity"}) +@RequiredArgsConstructor +public class LoginIdentityController { + /** + * Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LoginIdentityService loginIdentityService; + + /** + * 创建登录标识 + * + * @param loginIdentityDTO 登录标识DTO + * @return 登录标识ID + */ + @PostMapping("/create") + public Result createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) { + Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO); + return Result.success(id); + } + + /** + * 更新登录标识 + * + * @param id 登录标识ID + * @param loginIdentityDTO 登录标识DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) { + boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO); + return Result.success(success); + } + + /** + * 删除登录标识 + * + * @param id 登录标识ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteLoginIdentity(@PathVariable Long id) { + boolean success = loginIdentityService.deleteLoginIdentity(id); + return Result.success(success); + } + + /** + * 根据ID查询登录标识 + * + * @param id 登录标识ID + * @return 登录标识VO + */ + @GetMapping("/get/{id}") + public Result getLoginIdentityById(@PathVariable Long id) { + LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id); + return Result.success(loginIdentityVO); + } + + /** + * 查询所有登录标识 + * + * @return 登录标识VO列表 + */ + @GetMapping("/list/all") + public Result> listAllLoginIdentities() { + List loginIdentityVOs = loginIdentityService.listAllLoginIdentities(); + return Result.success(loginIdentityVOs); + } + + /** + * 根据用户ID查询登录标识 + * + * @param userId 用户ID + * @return 登录标识VO列表 + */ + @GetMapping("/list/user/{userId}") + public Result> listLoginIdentitiesByUserId(@PathVariable Long userId) { + List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId); + return Result.success(loginIdentityVOs); + } + + /** + * 根据登录方式查询登录标识 + * + * @param loginMethod 登录方式 + * @return 登录标识VO列表 + */ + @GetMapping("/list/loginMethod/{loginMethod}") + public Result> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) { + List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod); + return Result.success(loginIdentityVOs); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/BindEmailRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/BindEmailRequestDTO.java new file mode 100644 index 00000000..8237d19b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/BindEmailRequestDTO.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +/** + * 绑定邮箱请求 DTO + * 用于用户绑定邮箱账号 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class BindEmailRequestDTO { + + /** + * 邮箱地址 + */ + private String email; + + /** + * 验证码 + */ + private String code; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/BindPhoneRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/BindPhoneRequestDTO.java new file mode 100644 index 00000000..f01925ca --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/BindPhoneRequestDTO.java @@ -0,0 +1,26 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import com.fasterxml.jackson.annotation.JsonAlias; +import lombok.Data; + +/** + * 绑定手机号请求 DTO + * 用于用户绑定手机号 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class BindPhoneRequestDTO { + + /** + * 手机号 + */ + private String phone; + + /** + * 验证码 + */ + @JsonAlias("code") + private String verificationCode; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/LoginIdentityDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/LoginIdentityDTO.java new file mode 100644 index 00000000..6d19d168 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/LoginIdentityDTO.java @@ -0,0 +1,41 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户登录标识信息表 DTO + * 用于登录标识信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class LoginIdentityDTO { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 登录方式(0-手机号、1-账号、2-邮箱) + */ + private String loginMethod; + + /** + * 前端输入的具体值(如手机号、账号、邮箱) + */ + private String inputValue; + + /** + * 输入时间 + */ + private LocalDateTime inputTime; + + /** + * 状态:1-有效,0-无效 + */ + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/LoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/LoginRequestDTO.java new file mode 100644 index 00000000..4bc4d2a2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/LoginRequestDTO.java @@ -0,0 +1,62 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import com.xiaowang.jayucloud.artlist.core.utils.AccountValidationUtils; +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.Map; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +/** + * 登录请求 DTO + * 用于用户账号密码登录 + * + * @author xiaowang + * @date 2026-02-14 + */ +@Getter +@Setter +public class LoginRequestDTO implements AgreementAwareRequest { + + /** + * 账号 + */ + @NotBlank(message = "账号不能为空") + @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + private String account; + + /** + * 密码 + */ + private String password; + + /** + * 记住我标志 + */ + private Boolean rememberMe; + + /** + * 店铺ID + */ + private Long shopId; + + /** + * Purpose: agreementAccepted supports LoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports LoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports LoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/PhoneLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/PhoneLoginRequestDTO.java new file mode 100644 index 00000000..00d9a807 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/PhoneLoginRequestDTO.java @@ -0,0 +1,59 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.Map; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +/** + * 手机号验证码登录请求 DTO + * + * @author xiaowang + * @date 2026-03-03 + */ +@Data +public class PhoneLoginRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + + @NotBlank(message = "验证码不能为空") + @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") + /** + * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String verificationCode; + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * 记住登录标志 + */ + private Boolean rememberMe; + + /** + * Purpose: agreementAccepted supports PhoneLoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports PhoneLoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports PhoneLoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/RefreshTokenRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/RefreshTokenRequestDTO.java new file mode 100644 index 00000000..71191466 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/RefreshTokenRequestDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +/** + * 刷新Token请求 DTO + * 用于刷新访问令牌 + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class RefreshTokenRequestDTO { + + /** + * 刷新令牌 + */ + private String refreshToken; +} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/RegisterRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/RegisterRequestDTO.java new file mode 100644 index 00000000..2296b6ab --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/RegisterRequestDTO.java @@ -0,0 +1,78 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import com.xiaowang.jayucloud.artlist.core.utils.AccountValidationUtils; +import lombok.Data; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.Map; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +/** + * 注册请求 DTO + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class RegisterRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "账号不能为空") + @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + + @NotBlank(message = "密码不能为空") + /** + * Field `password` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String password; + + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + + @NotBlank(message = "验证码不能为空") + @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") + /** + * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String verificationCode; + + /** + * Purpose: agreementAccepted supports RegisterRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports RegisterRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports RegisterRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/ResetPasswordRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/ResetPasswordRequestDTO.java new file mode 100644 index 00000000..92438ba6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/ResetPasswordRequestDTO.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +/** + * 重置密码请求 DTO + * 用于用户重置密码 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class ResetPasswordRequestDTO { + + /** + * 手机号 + */ + private String phone; + + /** + * 验证码 + */ + private String verificationCode; + + /** + * 新密码 + */ + private String newPassword; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/SendVerificationCodeRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/SendVerificationCodeRequestDTO.java new file mode 100644 index 00000000..aacc8c4d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/SendVerificationCodeRequestDTO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +/** + * 发送验证码请求 DTO。 + */ +@Data +public class SendVerificationCodeRequestDTO { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + + /** + * 业务场景编码,用来选择 JayuCloudArtList 投递 MessageHub 时的配置。 + */ + private String sceneCode; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/SwitchShopRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/SwitchShopRequestDTO.java new file mode 100644 index 00000000..a88ff658 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/SwitchShopRequestDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +@Data +/** + * SwitchShopRequestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SwitchShopRequestDTO { + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/UpdatePhoneRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/UpdatePhoneRequestDTO.java new file mode 100644 index 00000000..5f08fede --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/dto/UpdatePhoneRequestDTO.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.dto; + +import lombok.Data; + +/** + * 更换手机号请求 DTO + * 用于用户更换绑定的手机号 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class UpdatePhoneRequestDTO { + + /** + * 原手机号 + */ + private String oldPhone; + + /** + * 新手机号 + */ + private String newPhone; + + /** + * 验证码 + */ + private String verificationCode; +} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/entity/LoginIdentityDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/entity/LoginIdentityDO.java new file mode 100644 index 00000000..89d6aad9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/entity/LoginIdentityDO.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 用户登录标识信息表 DO + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_login_identity") +public class LoginIdentityDO extends BaseEntity { + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 登录方式(0-手机号、1-账号、2-邮箱) + */ + @TableField("login_method") + private String loginMethod; + + /** + * 前端输入的具体值(如手机号、账号、邮箱) + */ + @TableField("input_value") + private String inputValue; + + /** + * 输入时间 + */ + @TableField("input_time") + private LocalDateTime inputTime; + + /** + * 状态:1-有效,0-无效 + */ + @TableField("status") + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/mapper/LoginIdentityMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/mapper/LoginIdentityMapper.java new file mode 100644 index 00000000..28f7b938 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/mapper/LoginIdentityMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.auth.entity.LoginIdentityDO; + +/** + * 用户登录标识信息表 Mapper + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface LoginIdentityMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/LoginIdentityService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/LoginIdentityService.java new file mode 100644 index 00000000..687bc55d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/LoginIdentityService.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.auth.entity.LoginIdentityDO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.LoginIdentityDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginIdentityVO; + +import java.util.List; + +/** + * 用户登录标识信息表 Service + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface LoginIdentityService extends IService { + + /** + * 创建登录标识 + * + * @param loginIdentityDTO 登录标识DTO + * @return 登录标识ID + */ + Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO); + + /** + * 更新登录标识 + * + * @param id 登录标识ID + * @param loginIdentityDTO 登录标识DTO + * @return 是否更新成功 + */ + boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO); + + /** + * 删除登录标识 + * + * @param id 登录标识ID + * @return 是否删除成功 + */ + boolean deleteLoginIdentity(Long id); + + /** + * 根据ID查询登录标识 + * + * @param id 登录标识ID + * @return 登录标识VO + */ + LoginIdentityVO getLoginIdentityById(Long id); + + /** + * 查询所有登录标识 + * + * @return 登录标识VO列表 + */ + List listAllLoginIdentities(); + + /** + * 根据用户ID查询登录标识 + * + * @param userId 用户ID + * @return 登录标识VO列表 + */ + List listLoginIdentitiesByUserId(Long userId); + + /** + * 根据登录方式查询登录标识 + * + * @param loginMethod 登录方式 + * @return 登录标识VO列表 + */ + List listLoginIdentitiesByLoginMethod(String loginMethod); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/VerificationCodeService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/VerificationCodeService.java new file mode 100644 index 00000000..5eccc5a0 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/VerificationCodeService.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.service; + + +/** + * 验证码服务接口 + * + * @author xiaowang + * @date 2026-03-03 + */ +public interface VerificationCodeService { + + /** + * Run business method `generateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String generateVerificationCode(); + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + */ + void sendVerificationCode(String phone); + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + */ + void sendVerificationCode(String phone, String sceneCode); + + /** + * Run business method `verifyCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean verifyCode(String phone, String code); + + /** + * Run business method `canResend`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean canResend(String phone); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/LoginIdentityServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/LoginIdentityServiceImpl.java new file mode 100644 index 00000000..5bfd91b5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/LoginIdentityServiceImpl.java @@ -0,0 +1,166 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.LoginIdentityDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.entity.LoginIdentityDO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.mapper.LoginIdentityMapper; +import com.xiaowang.jayucloud.artlist.core.modules.auth.service.LoginIdentityService; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginIdentityVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户登录标识信息表 Service 实现 + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class LoginIdentityServiceImpl extends ServiceImpl implements LoginIdentityService { + /** + * Variable `loginIdentityMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LoginIdentityMapper loginIdentityMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO) { + LoginIdentityDO loginIdentityDO = new LoginIdentityDO(); + loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); + loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod()); + loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue()); + loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime()); + loginIdentityDO.setStatus(loginIdentityDTO.getStatus()); + loginIdentityMapper.insert(loginIdentityDO); + return loginIdentityDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO) { + LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); + if (loginIdentityDO == null) { + return false; + } + loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); + loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod()); + loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue()); + loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime()); + loginIdentityDO.setStatus(loginIdentityDTO.getStatus()); + return loginIdentityMapper.updateById(loginIdentityDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteLoginIdentity(Long id) { + return loginIdentityMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return LoginIdentityVO result consumed by the caller or returned to the frontend + */ + public LoginIdentityVO getLoginIdentityById(Long id) { + LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); + if (loginIdentityDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginIdentityDO parameter `loginIdentityDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(loginIdentityDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllLoginIdentities() { + List loginIdentityDOs = loginIdentityMapper.selectList(null); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listLoginIdentitiesByUserId(Long userId) { + List loginIdentityDOs = loginIdentityMapper.selectList( + Wrappers.lambdaQuery(LoginIdentityDO.class) + .eq(LoginIdentityDO::getUserId, userId) + ); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginMethod parameter `loginMethod` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listLoginIdentitiesByLoginMethod(String loginMethod) { + List loginIdentityDOs = loginIdentityMapper.selectList( + Wrappers.lambdaQuery(LoginIdentityDO.class) + .eq(LoginIdentityDO::getLoginMethod, loginMethod) + ); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param loginIdentityDO 登录标识DO + * @return 登录标识VO + */ + private LoginIdentityVO convertToVO(LoginIdentityDO loginIdentityDO) { + LoginIdentityVO loginIdentityVO = new LoginIdentityVO(); + loginIdentityVO.setId(loginIdentityDO.getId()); + loginIdentityVO.setUserId(loginIdentityDO.getUserId()); + loginIdentityVO.setLoginMethod(loginIdentityDO.getLoginMethod()); + loginIdentityVO.setInputValue(loginIdentityDO.getInputValue()); + loginIdentityVO.setInputTime(loginIdentityDO.getInputTime()); + loginIdentityVO.setUpdateTime(loginIdentityDO.getUpdateTime()); + loginIdentityVO.setStatus(loginIdentityDO.getStatus()); + return loginIdentityVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java new file mode 100644 index 00000000..9a95ec9f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -0,0 +1,147 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.security.SecureRandom; +import java.time.Duration; + +/** + * 验证码服务实现。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class VerificationCodeServiceImpl implements VerificationCodeService { + + /** + * Purpose: CODE_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the code prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CODE_PREFIX = "verification:code:"; + /** + * Purpose: SEND_TIME_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the send time prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SEND_TIME_PREFIX = "verification:send_time:"; + /** + * Purpose: CODE_LENGTH supports VerificationCodeServiceImpl.java by holding or executing the code length business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int CODE_LENGTH = 6; + /** + * Purpose: CODE_EXPIRE_MINUTES supports VerificationCodeServiceImpl.java by holding or executing the code expire minutes business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int CODE_EXPIRE_MINUTES = 5; + /** + * Purpose: RESEND_INTERVAL_SECONDS supports VerificationCodeServiceImpl.java by holding or executing the resend interval seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int RESEND_INTERVAL_SECONDS = 60; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubClientService messageHubClientService; + + @Override + /** + * Run business method `generateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String generateVerificationCode() { + SecureRandom random = new SecureRandom(); + StringBuilder code = new StringBuilder(); + for (int i = 0; i < CODE_LENGTH; i++) { + code.append(random.nextInt(10)); + } + return code.toString(); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + */ + public void sendVerificationCode(String phone) { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + sendVerificationCode(phone, "USER_LOGIN_SMS_CODE"); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + */ + public void sendVerificationCode(String phone, String sceneCode) { + String code = generateVerificationCode(); + + String codeKey = CODE_PREFIX + phone; + String sendTimeKey = SEND_TIME_PREFIX + phone; + + redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); + redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), + Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); + + messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); + log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); + } + + @Override + /** + * Run business method `verifyCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean verifyCode(String phone, String code) { + String codeKey = CODE_PREFIX + phone; + String storedCode = redisTemplate.opsForValue().get(codeKey); + + if (storedCode == null) { + log.warn("验证码不存在或已过期,手机号: {}", phone); + return false; + } + + if (!storedCode.equals(code)) { + log.warn("验证码错误,手机号: {}", phone); + return false; + } + + redisTemplate.delete(codeKey); + log.info("验证码验证成功,手机号: {}", phone); + return true; + } + + @Override + /** + * Run business method `canResend`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean canResend(String phone) { + String sendTimeKey = SEND_TIME_PREFIX + phone; + String sendTime = redisTemplate.opsForValue().get(sendTimeKey); + return sendTime == null; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginIdentityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginIdentityVO.java new file mode 100644 index 00000000..7192c270 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginIdentityVO.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户登录标识信息表 VO + * 用于前端展示登录标识信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class LoginIdentityVO { + + /** + * 登录标识唯一主键ID(雪花id) + */ + private Long id; + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 登录方式(0-手机号、1-账号、2-邮箱) + */ + private String loginMethod; + + /** + * 登录方式名称 + */ + private String loginMethodName; + + /** + * 前端输入的具体值(如手机号、账号、邮箱) + */ + private String inputValue; + + /** + * 输入时间 + */ + private LocalDateTime inputTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; + + /** + * 状态:1-有效,0-无效 + */ + private Integer status; + + /** + * 状态名称 + */ + private String statusName; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginResponseVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginResponseVO.java new file mode 100644 index 00000000..842ef76e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginResponseVO.java @@ -0,0 +1,97 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 登录响应 VO + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class LoginResponseVO { + + /** + * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String accessToken; + + /** + * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String refreshToken; + + /** + * Field `userInfo` (UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private UserInfo userInfo; + + /** + * Field `needSetPassword` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private boolean needSetPassword; // 是否需要设置密码 + + @Data + /** + * Purpose: UserInfo supports LoginResponseVO.java by holding or executing the user info business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class UserInfo { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + /** + * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String avatar; + /** + * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer type; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `shopAuthorizationExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime shopAuthorizationExpireTime; + /** + * Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean shopAuthorizationExpired; + @JsonSerialize(contentUsing = ToStringSerializer.class) + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + /** + * Field `shopNames` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopNames; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginShopSelectionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginShopSelectionVO.java new file mode 100644 index 00000000..9cd7f32a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/vo/LoginShopSelectionVO.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.modules.auth.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +/** + * 登录页可选店铺结果。 + */ +@Data +public class LoginShopSelectionVO { + + /** + * Field `allowShoplessLogin` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private boolean allowShoplessLogin; + + /** + * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String message; + + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops = new ArrayList<>(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/controller/front/CommentController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/controller/front/CommentController.java new file mode 100644 index 00000000..44fbd80d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/controller/front/CommentController.java @@ -0,0 +1,215 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.modules.content.dto.CommentDTO; +import com.xiaowang.jayucloud.artlist.core.modules.content.service.CommentService; +import com.xiaowang.jayucloud.artlist.core.modules.content.vo.CommentVO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadCompleteRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ChunkUploadService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.support.security.UploadSecurityValidator; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.io.FileInputStream; +import java.util.List; + +@RestController +@RequestMapping({"/comment", "/api/comment"}) +@RequiredArgsConstructor +public class CommentController { + + private final CommentService commentService; + private final ObjectStorageFileService objectStorageFileService; + private final PrimaryObjectStorageService primaryObjectStorageService; + private final ChunkUploadService chunkUploadService; + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final UploadSecurityValidator uploadSecurityValidator; + private final ObjectStorageProperties objectStorageProperties; + + @PostMapping("/create") + public Result createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) { + Long userId = (Long) request.getAttribute("userId"); + Long id = commentService.createComment(userId, commentDTO); + return Result.success(id); + } + + @PostMapping("/upload-image") + @OperationGuard(action = "comment-image-upload", ttlSeconds = 15, message = "图片正在上传中,请勿重复操作") + public Result uploadCommentImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + try { + uploadSecurityValidator.validate(file); + String originalFilename = normalizeOriginalFilename(file.getOriginalFilename()); + String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); + String fileUrl = primaryObjectStorageService.uploadFile(file, objectName); + return Result.success(createCommentImageRecord(originalFilename, fileUrl, objectName, file.getContentType(), file.getSize())); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("评价图片上传失败: " + e.getMessage()); + } + } + + @PostMapping("/upload-image/init") + @OperationGuard(action = "comment-image-upload-init", ttlSeconds = 10, message = "图片正在上传中,请勿重复操作") + public Result initCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); + return Result.success(chunkUploadService.initCommentImageUpload(userId, requestDTO)); + } + + @PostMapping("/upload-image/chunk") + @OperationGuard(action = "comment-image-upload-chunk", ttlSeconds = 20) + public Result uploadCommentImageChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + uploadSecurityValidator.validateChunk(chunkFile); + chunkUploadService.uploadCommentImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-image/complete") + @OperationGuard(action = "comment-image-upload-complete", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") + public Result completeCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareCommentImageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = normalizeOriginalFilename(preparedUploadFile.getFileName()); + String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); + String fileUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + ObjectStorageFileVO fileVO = createCommentImageRecord(originalFilename, fileUrl, objectName, preparedUploadFile.getContentType(), preparedUploadFile.getFileSize()); + chunkUploadService.clearCommentImageUpload(userId, requestDTO.getUploadId()); + return Result.success(fileVO); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("评价图片上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-image/{uploadId}") + @OperationGuard(action = "comment-image-upload-cancel", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") + public Result cancelCommentImageUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再取消上传"); + } + chunkUploadService.clearCommentImageUpload(userId, uploadId); + return Result.success(true); + } + + @PutMapping("/update/{id}") + public Result updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = commentService.updateComment(id, userId, commentDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = commentService.deleteComment(id, userId); + return Result.success(success); + } + + @GetMapping("/get/{id}") + public Result getCommentById(@PathVariable Long id) { + CommentVO commentVO = commentService.getCommentById(id); + return Result.success(commentVO); + } + + @GetMapping("/list/all") + public Result> listAllComments() { + List commentVOs = commentService.listAllComments(); + return Result.success(commentVOs); + } + + @GetMapping("/list/user/{userId}") + public Result> listCommentsByUserId(@PathVariable Long userId) { + List commentVOs = commentService.listCommentsByUserId(userId); + return Result.success(commentVOs); + } + + @GetMapping("/list/shop/{shopId}") + public Result> listCommentsByShopId(@PathVariable Long shopId) { + List commentVOs = commentService.listCommentsByShopId(shopId); + return Result.success(commentVOs); + } + + @GetMapping("/list/product/{productId}") + public Result> listCommentsByProductId(@PathVariable Long productId) { + List commentVOs = commentService.listCommentsByProductId(productId); + return Result.success(commentVOs); + } + + @GetMapping("/list/parent/{parentCommentId}") + public Result> listCommentsByParentCommentId(@PathVariable Long parentCommentId) { + List commentVOs = commentService.listCommentsByParentCommentId(parentCommentId); + return Result.success(commentVOs); + } + + private ObjectStorageFileVO createCommentImageRecord(String originalFilename, String fileUrl, String objectName, String contentType, Long fileSize) { + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(fileUrl); + dto.setObjectName(objectName); + dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider()); + dto.setPrimaryUrl(fileUrl); + dto.setBackupProvider(objectStorageProperties.getBackupProvider()); + dto.setContentType(contentType); + dto.setFileSize(fileSize); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setStatus(1); + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + return objectStorageFileService.getObjectStorageFileById(fileId); + } + + private String normalizeOriginalFilename(String originalFilename) { + if (originalFilename == null || originalFilename.isBlank()) { + return "comment-image"; + } + return originalFilename; + } + + private String resolveFileExtension(String originalFilename) { + if (originalFilename == null || !originalFilename.contains(".")) { + return ""; + } + return originalFilename.substring(originalFilename.lastIndexOf(".")); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/dto/CommentDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/dto/CommentDTO.java new file mode 100644 index 00000000..77725d90 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/dto/CommentDTO.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 用户评论信息表 DTO + * 用于评论信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class CommentDTO { + + /** + * 评论用户ID,关联用户表主键 + */ + private Long userId; + + /** + * 关联店铺表主键(0表示非店铺评论) + */ + private Long shopId; + + /** + * 关联商品表主键(0表示非商品评论) + */ + private Long productId; + + /** + * 评论内容 + */ + private String commentContent; + + /** + * 父级评论ID(0表示为根评论) + */ + private Long parentCommentId; + + /** + * 评论评分:1-5星,根评论使用 + */ + private Integer ratingScore; + + /** + * 评论图片文件ID集合,根评论使用 + */ + private List imageFileIds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/entity/CommentDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/entity/CommentDO.java new file mode 100644 index 00000000..7757b7ed --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/entity/CommentDO.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 用户评论信息表 DO + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_comment") +public class CommentDO extends BaseEntity { + + /** + * 评论用户ID,关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 关联店铺表主键(0表示非店铺评论) + */ + @TableField("shop_id") + private Long shopId; + + /** + * 关联商品表主键(0表示非商品评论) + */ + @TableField("product_id") + private Long productId; + + /** + * 评论内容 + */ + @TableField("comment_content") + private String commentContent; + + /** + * 父级评论ID(0表示为根评论) + */ + @TableField("parent_comment_id") + private Long parentCommentId; + + /** + * 评论评分:1-5星 + */ + @TableField("rating_score") + private Integer ratingScore; + + /** + * 评论图片文件ID集合,多个ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + /** + * 评论点赞数 + */ + @TableField("like_count") + private Integer likeCount; + + /** + * 逻辑删除标识:0-未删除,1-已删除 + */ + @TableField("is_delete") + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/mapper/CommentMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/mapper/CommentMapper.java new file mode 100644 index 00000000..8cf382bc --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/mapper/CommentMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.content.entity.CommentDO; + +/** + * 用户评论信息表 Mapper + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface CommentMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/CommentService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/CommentService.java new file mode 100644 index 00000000..e2f6111e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/CommentService.java @@ -0,0 +1,138 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.content.entity.CommentDO; +import com.xiaowang.jayucloud.artlist.core.modules.content.dto.CommentDTO; +import com.xiaowang.jayucloud.artlist.core.modules.content.vo.CommentVO; + +import java.util.List; + +/** + * 用户评论信息表 Service + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface CommentService extends IService { + + /** + * 创建评论 + * + * @param commentDTO 评论DTO + * @return 评论ID + */ + Long createComment(CommentDTO commentDTO); + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createComment(Long currentUserId, CommentDTO commentDTO); + + /** + * 更新评论 + * + * @param id 评论ID + * @param commentDTO 评论DTO + * @return 是否更新成功 + */ + boolean updateComment(Long id, CommentDTO commentDTO); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO); + + /** + * 删除评论 + * + * @param id 评论ID + * @return 是否删除成功 + */ + boolean deleteComment(Long id); + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean deleteComment(Long id, Long currentUserId); + + /** + * Run business method `adminDeleteComment`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param managedShopId parameter `managedShopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean adminDeleteComment(Long id, Long managedShopId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminComments(Long productId, Long userId, Long shopId, String keyword); + + /** + * 根据ID查询评论 + * + * @param id 评论ID + * @return 评论VO + */ + CommentVO getCommentById(Long id); + + /** + * 查询所有评论 + * + * @return 评论VO列表 + */ + List listAllComments(); + + /** + * 根据用户ID查询评论 + * + * @param userId 用户ID + * @return 评论VO列表 + */ + List listCommentsByUserId(Long userId); + + /** + * 根据店铺ID查询评论 + * + * @param shopId 店铺ID + * @return 评论VO列表 + */ + List listCommentsByShopId(Long shopId); + + /** + * 根据商品ID查询评论 + * + * @param productId 商品ID + * @return 评论VO列表 + */ + List listCommentsByProductId(Long productId); + + /** + * 根据父级评论ID查询回复 + * + * @param parentCommentId 父级评论ID + * @return 评论VO列表 + */ + List listCommentsByParentCommentId(Long parentCommentId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java new file mode 100644 index 00000000..ed42aed6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java @@ -0,0 +1,620 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.content.dto.CommentDTO; +import com.xiaowang.jayucloud.artlist.core.modules.content.entity.CommentDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.content.service.CommentService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.content.vo.CommentVO; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 用户评论信息表 Service 实现 + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class CommentServiceImpl extends ServiceImpl implements CommentService { + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentMapper commentMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createComment(CommentDTO commentDTO) { + if (commentDTO == null || commentDTO.getUserId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录后再评论"); + } + return createComment(commentDTO.getUserId(), commentDTO); + } + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createComment(Long currentUserId, CommentDTO commentDTO) { + if (currentUserId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录后再评论"); + } + if (commentDTO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论内容不能为空"); + } + String content = sanitizeContent(commentDTO.getCommentContent()); + Long productId = normalizeId(commentDTO.getProductId()); + Long parentCommentId = normalizeId(commentDTO.getParentCommentId()); + if (productId == null && parentCommentId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择要评论的作品"); + } + CommentDO parentComment = null; + if (parentCommentId != null) { + parentComment = commentMapper.selectById(parentCommentId); + if (parentComment == null || Integer.valueOf(1).equals(parentComment.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("回复的评论不存在"); + } + if (productId == null) { + productId = parentComment.getProductId(); + } else if (parentComment.getProductId() != null && !productId.equals(parentComment.getProductId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("回复内容与作品不匹配"); + } + } + Long shopId = normalizeId(commentDTO.getShopId()); + if (shopId == null && productId != null) { + ProductDO product = productMapper.selectById(productId); + if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) { + shopId = product.getShopId(); + } + } + CommentDO commentDO = new CommentDO(); + boolean rootComment = parentCommentId == null; + commentDO.setUserId(currentUserId); + commentDO.setShopId(shopId); + commentDO.setProductId(productId); + commentDO.setCommentContent(content); + commentDO.setParentCommentId(parentCommentId); + if (rootComment) { + commentDO.setRatingScore(normalizeRatingScore(commentDTO.getRatingScore())); + commentDO.setImageFileIds(joinImageFileIds(commentDTO.getImageFileIds())); + } + commentDO.setLikeCount(0); + commentDO.setIsDelete(0); + commentMapper.insert(commentDO); + return commentDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateComment(Long id, CommentDTO commentDTO) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null) { + return false; + } + commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteComment(Long id) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null) { + return false; + } + commentDO.setIsDelete(1); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return false; + } + if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能修改自己的评论"); + } + commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteComment(Long id, Long currentUserId) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return false; + } + if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能删除自己的评论"); + } + commentDO.setIsDelete(1); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Run business method `adminDeleteComment`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param managedShopId parameter `managedShopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean adminDeleteComment(Long id, Long managedShopId) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return false; + } + if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权删除其他门店评论"); + } + commentDO.setIsDelete(1); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return CommentVO result consumed by the caller or returned to the frontend + */ + public CommentVO getCommentById(Long id) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDO parameter `commentDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(commentDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllComments() { + return toCommentVOList(activeQuery().orderByDesc(CommentDO::getCreateTime)); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByUserId(Long userId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getUserId, userId) + .eq(CommentDO::getIsDelete, 0) + .orderByDesc(CommentDO::getCreateTime) + ); + return commentDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByShopId(Long shopId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getShopId, shopId) + .eq(CommentDO::getIsDelete, 0) + .orderByDesc(CommentDO::getCreateTime) + ); + return commentDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByProductId(Long productId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getProductId, productId) + .eq(CommentDO::getIsDelete, 0) + .orderByDesc(CommentDO::getCreateTime) + ); + /** + * Run business method `buildTree`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDOs parameter `commentDOs` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildTree(commentDOs); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param parentCommentId parameter `parentCommentId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByParentCommentId(Long parentCommentId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getParentCommentId, parentCommentId) + .eq(CommentDO::getIsDelete, 0) + .orderByAsc(CommentDO::getCreateTime) + ); + return commentDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminComments(Long productId, Long userId, Long shopId, String keyword) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getIsDelete, 0) + .eq(productId != null && productId > 0, CommentDO::getProductId, productId) + .eq(userId != null && userId > 0, CommentDO::getUserId, userId) + .eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId) + .like(StringUtils.hasText(keyword), CommentDO::getCommentContent, keyword) + .orderByDesc(CommentDO::getCreateTime) + ); + return commentDOs.stream().map(this::convertToVO).collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param commentDO 评论DO + * @return 评论VO + */ + private CommentVO convertToVO(CommentDO commentDO) { + CommentVO commentVO = new CommentVO(); + commentVO.setId(commentDO.getId()); + commentVO.setUserId(commentDO.getUserId()); + commentVO.setShopId(commentDO.getShopId()); + commentVO.setProductId(commentDO.getProductId()); + commentVO.setCommentContent(commentDO.getCommentContent()); + commentVO.setParentCommentId(commentDO.getParentCommentId()); + commentVO.setLikeCount(commentDO.getLikeCount()); + commentVO.setRatingScore(commentDO.getRatingScore()); + List imageFileIds = parseImageFileIds(commentDO.getImageFileIds()); + commentVO.setImageFileIds(imageFileIds); + commentVO.setImageUrls(resolveImageUrls(imageFileIds)); + commentVO.setCreateTime(commentDO.getCreateTime()); + commentVO.setUpdateTime(commentDO.getUpdateTime()); + /** + * Run business method `fillDisplayFields`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentVO parameter `commentVO` supplied by the caller + * @param commentDO parameter `commentDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + fillDisplayFields(commentVO, commentDO); + return commentVO; + } + + /** + * Run business method `toCommentVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper) { + return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList()); + } + + /** + * Run business method `buildTree`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDOs parameter `commentDOs` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List buildTree(List commentDOs) { + Map rootMap = new HashMap<>(); + List roots = new ArrayList<>(); + List replies = new ArrayList<>(); + for (CommentDO commentDO : commentDOs) { + CommentVO vo = convertToVO(commentDO); + if (commentDO.getParentCommentId() == null || commentDO.getParentCommentId() <= 0) { + vo.setReplies(new ArrayList<>()); + rootMap.put(commentDO.getId(), vo); + roots.add(vo); + } else { + replies.add(vo); + } + } + replies.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder()))); + for (CommentVO reply : replies) { + CommentVO root = rootMap.get(reply.getParentCommentId()); + if (root != null) { + root.getReplies().add(reply); + } + } + roots.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed()); + return roots; + } + + /** + * Run business method `fillDisplayFields`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentVO parameter `commentVO` supplied by the caller + * @param commentDO parameter `commentDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { + UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); + if (user != null) { + commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + } + ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId()); + if (shop != null) { + commentVO.setShopName(shop.getShopName()); + } + ProductDO product = commentDO.getProductId() == null ? null : productMapper.selectById(commentDO.getProductId()); + if (product != null) { + commentVO.setProductTitle(product.getTitle()); + } + if (commentDO.getParentCommentId() != null && commentDO.getParentCommentId() > 0) { + CommentDO parent = commentMapper.selectById(commentDO.getParentCommentId()); + if (parent != null && !Integer.valueOf(1).equals(parent.getIsDelete())) { + commentVO.setParentCommentContent(parent.getCommentContent()); + } + } + } + + private Integer normalizeRatingScore(Integer ratingScore) { + if (ratingScore == null) { + return 5; + } + return Math.max(1, Math.min(5, ratingScore)); + } + + private String joinImageFileIds(List imageFileIds) { + if (imageFileIds == null || imageFileIds.isEmpty()) { + return null; + } + return imageFileIds.stream() + .filter(id -> id != null && id > 0) + .distinct() + .limit(6) + .map(String::valueOf) + .collect(Collectors.joining(",")); + } + + private List parseImageFileIds(String imageFileIds) { + List result = new ArrayList<>(); + if (!StringUtils.hasText(imageFileIds)) { + return result; + } + for (String token : imageFileIds.split(",")) { + if (!StringUtils.hasText(token)) { + continue; + } + try { + Long id = Long.valueOf(token.trim()); + if (id > 0) { + result.add(id); + } + } catch (NumberFormatException ignored) { + // Ignore malformed legacy tokens. + } + } + return new ArrayList<>(new LinkedHashSet<>(result)); + } + + private List resolveImageUrls(List imageFileIds) { + if (imageFileIds == null || imageFileIds.isEmpty()) { + return new ArrayList<>(); + } + Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(new LinkedHashSet<>(imageFileIds)); + List urls = new ArrayList<>(); + for (Long imageFileId : imageFileIds) { + ObjectStorageFileVO fileVO = fileMap.get(imageFileId); + if (fileVO == null || !StringUtils.hasText(fileVO.getFileUrl())) { + continue; + } + urls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); + } + return urls; + } + + /** + * Run business method `activeQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ + private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { + return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0); + } + + /** + * Run business method `normalizeId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long normalizeId(Long id) { + return id == null || id <= 0 ? null : id; + } + + /** + * Run business method `sanitizeContent`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param content parameter `content` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String sanitizeContent(String content) { + if (!StringUtils.hasText(content)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论内容不能为空"); + } + String sanitized = content.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim(); + sanitized = sanitized.replaceAll("<[^>]*>", ""); + if (!StringUtils.hasText(sanitized)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论内容不能为空"); + } + if (sanitized.length() > 300) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论最多输入 300 个字"); + } + return sanitized; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/vo/CommentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/vo/CommentVO.java new file mode 100644 index 00000000..c5cda1a4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/vo/CommentVO.java @@ -0,0 +1,102 @@ +package com.xiaowang.jayucloud.artlist.core.modules.content.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 用户评论信息表 VO + * 用于前端展示评论信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class CommentVO { + + /** + * 评论唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 评论用户ID,关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 关联店铺表主键(0表示非店铺评论) + */ + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 关联商品表主键(0表示非商品评论) + */ + private Long productId; + + /** + * 商品标题 + */ + private String productTitle; + + /** + * 评论内容 + */ + private String commentContent; + + /** + * 父级评论ID(0表示为根评论) + */ + private Long parentCommentId; + + /** + * 父级评论内容 + */ + private String parentCommentContent; + + /** + * 评论点赞数 + */ + private Integer likeCount; + + /** + * 评论评分:1-5星 + */ + private Integer ratingScore; + + /** + * 评论图片文件ID集合 + */ + private List imageFileIds; + + /** + * 评论图片展示链接 + */ + private List imageUrls; + + /** + * 评论创建时间 + */ + private LocalDateTime createTime; + + /** + * 评论更新时间 + */ + private LocalDateTime updateTime; + + /** + * 回复列表 + */ + private List replies; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/AliyunOssConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/AliyunOssConfig.java new file mode 100644 index 00000000..631225be --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/AliyunOssConfig.java @@ -0,0 +1,49 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.config; + +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import lombok.Data; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "aliyun.oss") +public class AliyunOssConfig { + + @NotNull + private Boolean enabled; + @NotBlank + private String endpoint; + @NotBlank + private String region; + @NotBlank + private String bucketName; + @NotBlank + private String accessKeyId; + @NotBlank + private String accessKeySecret; + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean(destroyMethod = "shutdown") + @ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true") + public OSS aliyunOssClient() { + if (!StringUtils.hasText(endpoint) + || !StringUtils.hasText(accessKeyId) + || !StringUtils.hasText(accessKeySecret)) { + throw new IllegalStateException("Aliyun OSS is enabled but endpoint/accessKeyId/accessKeySecret is incomplete"); + } + return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/MinioStorageConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/MinioStorageConfig.java new file mode 100644 index 00000000..fc63faca --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/MinioStorageConfig.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.config; + +import io.minio.MinioClient; +import lombok.Data; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "minio") +public class MinioStorageConfig { + + @NotNull + private Boolean enabled; + + private String endpoint; + + private String bucketName; + + private String accessKey; + + private String secretKey; + + @NotNull + private Boolean privateBucket; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean + @ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true") + public MinioClient minioClient() { + if (!StringUtils.hasText(endpoint) + || !StringUtils.hasText(accessKey) + || !StringUtils.hasText(secretKey)) { + throw new IllegalStateException("MinIO is enabled but endpoint/accessKey/secretKey is incomplete"); + } + return MinioClient.builder() + .endpoint(endpoint) + .credentials(accessKey, secretKey) + .build(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/QiniuKodoConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/QiniuKodoConfig.java new file mode 100644 index 00000000..81764aab --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/config/QiniuKodoConfig.java @@ -0,0 +1,82 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.config; + +import com.qiniu.common.Zone; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.UploadManager; +import com.qiniu.util.Auth; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "qiniu.kodo") +public class QiniuKodoConfig { + + @NotBlank + private String accessKey; + + @NotBlank + private String secretKey; + + @NotBlank + private String bucketName; + + @NotBlank + private String domain; + + @NotBlank + private String zone; + + @NotNull + private Boolean privateBucket; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean + public Auth qiniuAuth() { + return Auth.create(accessKey, secretKey); + } + + @Bean + public com.qiniu.storage.Configuration qiniuConfiguration() { + return new com.qiniu.storage.Configuration(resolveZone()); + } + + @Bean + public UploadManager qiniuUploadManager(com.qiniu.storage.Configuration qiniuConfiguration) { + return new UploadManager(qiniuConfiguration); + } + + @Bean + public BucketManager qiniuBucketManager(com.qiniu.storage.Configuration qiniuConfiguration, Auth qiniuAuth) { + return new BucketManager(qiniuAuth, qiniuConfiguration); + } + + private Zone resolveZone() { + String normalizedZone = zone.trim().toLowerCase(); + switch (normalizedZone) { + case "z0": + return Zone.zone0(); + case "z1": + return Zone.zone1(); + case "z2": + return Zone.zone2(); + case "na0": + return Zone.zoneNa0(); + case "as0": + return Zone.zoneAs0(); + default: + throw new IllegalStateException("Unsupported Qiniu zone: " + zone); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/controller/front/FrontendFileController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/controller/front/FrontendFileController.java new file mode 100644 index 00000000..d268d5e6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/controller/front/FrontendFileController.java @@ -0,0 +1,84 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * Purpose: FrontendFileController exposes signed-file access only for public frontend references. + * Usage: anonymous clients call /file/get-signed-url/{fileId}; the controller verifies the file is referenced by public content before returning a URL. + */ +@RestController +@RequestMapping("/file") +@RequiredArgsConstructor +public class FrontendFileController { + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ProductMapper productMapper; + private final ShopMapper shopMapper; + private final EffectDiagramMapper effectDiagramMapper; + + /** + * Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public. + * Usage: pass a public file id and optional expiry minutes; private or unreferenced files are rejected. + */ + @GetMapping("/get-signed-url/{fileId}") + public Result getSignedUrl(@PathVariable Long fileId, + @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { + try { + ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); + if (fileVO == null) { + return Result.error("文件不存在"); + } + if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) { + return Result.error("文件不可公开访问"); + } + + String signedUrl = hasObjectStorageReference(fileVO) + ? objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes) + : fileVO.getFileUrl(); + return Result.success(signedUrl); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("获取签名链接失败: " + e.getMessage()); + } + } + + private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) { + return StringUtils.hasText(fileVO.getObjectName()) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getPrimaryUrl())) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl())); + } + + /** + * Purpose: isPublicFileReference prevents arbitrary uploaded files from being exposed through the public signing endpoint. + * Usage: call with a file id and keep mapper checks in sync with public content tables. + */ + private boolean isPublicFileReference(Long fileId) { + if (fileId == null) { + return false; + } + return positive(productMapper.countPublicImageReference(fileId)) + || positive(shopMapper.countPublicImageReference(fileId)) + || positive(effectDiagramMapper.countPublicImageReference(fileId)); + } + + /** + * Purpose: positive normalizes nullable mapper counts. + * Usage: use for COUNT(*) results where null should behave like zero. + */ + private boolean positive(Long count) { + return count != null && count > 0; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/controller/front/ObjectStorageFileController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/controller/front/ObjectStorageFileController.java new file mode 100644 index 00000000..087f01a2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/controller/front/ObjectStorageFileController.java @@ -0,0 +1,282 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadCompleteRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ChunkUploadService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; +import com.xiaowang.jayucloud.artlist.core.support.security.UploadSecurityValidator; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ChunkUploadSessionVO; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.io.FileInputStream; +import java.util.List; + +/** + * 对象存储文件控制器,对应表 t_object_storage_file。 + */ +@RestController +@RequestMapping("/admin/object-storage-file") +@RequiredArgsConstructor +@Validated +public class ObjectStorageFileController { + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageOrchestrationService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + /** + * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ChunkUploadService chunkUploadService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Purpose: uploadSecurityValidator supports ObjectStorageFileController.java by holding or executing the upload security validator business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UploadSecurityValidator uploadSecurityValidator; + private final ObjectStorageProperties objectStorageProperties; + + @PostMapping("/upload/init") + @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initChunkUpload(HttpServletRequest request, + @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); + return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO)); + } + + @PostMapping("/upload/chunk") + @OperationGuard(action = "admin-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + uploadSecurityValidator.validateChunk(chunkFile); + chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload/complete") + @OperationGuard(action = "admin-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result completeChunkUpload(HttpServletRequest request, + @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; + + ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( + inputStream, + preparedUploadFile.getFileSize(), + preparedUploadFile.getContentType(), + objectName + ); + + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(uploadOutcome.getPrimaryUrl()); + dto.setObjectName(objectName); + dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); + dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); + dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); + dto.setContentType(preparedUploadFile.getContentType()); + dto.setFileSize(preparedUploadFile.getFileSize()); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setUploadAttempts(uploadOutcome.getAttempts()); + dto.setStatus(1); + + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("文件上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload/{uploadId}") + @OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Run business method `cancelChunkUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId); + return Result.success(true); + } + + /** + * 上传文件。 + */ + @PostMapping("/upload") + @OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result uploadFile(@RequestParam("file") MultipartFile file) { + try { + uploadSecurityValidator.validate(file); + String originalFilename = file.getOriginalFilename(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; + + ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( + file.getInputStream(), + file.getSize(), + file.getContentType(), + objectName + ); + + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(uploadOutcome.getPrimaryUrl()); + dto.setObjectName(objectName); + dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); + dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); + dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); + dto.setContentType(file.getContentType()); + dto.setFileSize(file.getSize()); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setUploadAttempts(uploadOutcome.getAttempts()); + dto.setStatus(1); + + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("文件上传失败: " + e.getMessage()); + } + } + + /** + * 获取带签名的图片链接。 + */ + @GetMapping("/get-signed-url/{fileId}") + public Result getSignedUrl(@PathVariable Long fileId, + @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { + try { + ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); + if (fileVO == null) { + return Result.error("文件不存在"); + } + + String signedUrl = objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes); + return Result.success(signedUrl); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("获取签名链接失败: " + e.getMessage()); + } + } + + @PostMapping("/create") + @OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) { + Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @OperationGuard(action = "admin-file-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateObjectStorageFile(@PathVariable Long id, + @RequestBody ObjectStorageFileDTO objectStorageFileDTO) { + boolean success = objectStorageFileService.updateObjectStorageFile(id, objectStorageFileDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteObjectStorageFile(@PathVariable Long id) { + boolean success = objectStorageFileService.deleteObjectStorageFile(id); + return Result.success(success); + } + + @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getObjectStorageFileById(@PathVariable Long id) { + ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id); + return Result.success(objectStorageFileVO); + } + + @GetMapping("/list/all") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllObjectStorageFiles() { + List objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles(); + return Result.success(objectStorageFileVOs); + } + + @GetMapping("/list/status/{status}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listObjectStorageFilesByStatus(@PathVariable Integer status) { + List objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status); + return Result.success(objectStorageFileVOs); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java new file mode 100644 index 00000000..5a2b29ca --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 分片上传完成请求 + */ +@Data +public class ChunkUploadCompleteRequestDTO { + + @NotBlank(message = "上传标识不能为空") + /** + * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String uploadId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ChunkUploadInitRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ChunkUploadInitRequestDTO.java new file mode 100644 index 00000000..ce21a48a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ChunkUploadInitRequestDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.Data; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * 分片上传初始化请求 + */ +@Data +public class ChunkUploadInitRequestDTO { + + @NotBlank(message = "文件名不能为空") + /** + * Field `fileName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String fileName; + + @NotNull(message = "文件大小不能为空") + @Min(value = 1, message = "文件大小不合法") + /** + * Field `fileSize` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long fileSize; + + @NotBlank(message = "文件类型不能为空") + /** + * Field `contentType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String contentType; + + @NotBlank(message = "文件指纹不能为空") + /** + * Field `fileFingerprint` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String fileFingerprint; + + @NotBlank(message = "上传场景不能为空") + /** + * Field `scene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String scene; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageBackupMessage.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageBackupMessage.java new file mode 100644 index 00000000..f558117c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageBackupMessage.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ObjectStorageBackupMessage { + + private Long fileId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageFileDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageFileDTO.java new file mode 100644 index 00000000..7bc02e21 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageFileDTO.java @@ -0,0 +1,70 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 对象存储文件信息表 DTO + * 用于文件信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ObjectStorageFileDTO { + + /** + * 文件名称 + */ + private String fileName; + + /** + * 文件访问链接 + */ + private String fileUrl; + + private String objectName; + + private String primaryProvider; + + private String primaryUrl; + + private String backupProvider; + + private String backupUrl; + + private String contentType; + + private Long fileSize; + + private Integer primaryUploadStatus; + + private Integer backupUploadStatus; + + private Integer backupRetryCount; + + private String backupLastError; + + private LocalDateTime backupUploadedAt; + + private LocalDateTime backupLastRetryTime; + + private List uploadAttempts; + + /** + * 文件状态:1-可用,0-不可用,2-回收站 + */ + private Integer status; + + /** + * 文件删除时间(NULL表示未删除) + */ + private LocalDateTime deleteTime; + + /** + * 文件移入回收站时间(NULL表示未移入) + */ + private LocalDateTime recycleTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageReplicaDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageReplicaDTO.java new file mode 100644 index 00000000..764941eb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageReplicaDTO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class ObjectStorageReplicaDTO { + + private String provider; + + private String objectName; + + private String objectUrl; + + private Integer uploadStatus; + + private Integer retryCount; + + private String lastError; + + private LocalDateTime uploadedAt; + + private LocalDateTime lastRetryTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageUploadAttempt.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageUploadAttempt.java new file mode 100644 index 00000000..84655c8b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageUploadAttempt.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ObjectStorageUploadAttempt { + + private String provider; + + private String objectName; + + private String objectUrl; + + private Integer uploadStatus; + + private Integer retryCount; + + private String lastError; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageUploadOutcome.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageUploadOutcome.java new file mode 100644 index 00000000..40701041 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/dto/ObjectStorageUploadOutcome.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.List; + +@Data +@AllArgsConstructor +public class ObjectStorageUploadOutcome { + + private String primaryProvider; + + private String primaryUrl; + + private List attempts; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/entity/ObjectStorageFileDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/entity/ObjectStorageFileDO.java new file mode 100644 index 00000000..6c2d1ed7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/entity/ObjectStorageFileDO.java @@ -0,0 +1,91 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 对象存储文件信息表 DO + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_object_storage_file") +public class ObjectStorageFileDO extends BaseEntity { + + /** + * 文件名称 + */ + @TableField("file_name") + private String fileName; + + /** + * 文件访问链接 + */ + @TableField("file_url") + private String fileUrl; + + @TableField("object_name") + private String objectName; + + @TableField("primary_provider") + private String primaryProvider; + + @TableField("primary_url") + private String primaryUrl; + + @TableField("backup_provider") + private String backupProvider; + + @TableField("backup_url") + private String backupUrl; + + @TableField("content_type") + private String contentType; + + @TableField("file_size") + private Long fileSize; + + @TableField("primary_upload_status") + private Integer primaryUploadStatus; + + @TableField("backup_upload_status") + private Integer backupUploadStatus; + + @TableField("backup_retry_count") + private Integer backupRetryCount; + + @TableField("backup_last_error") + private String backupLastError; + + @TableField("backup_uploaded_at") + private LocalDateTime backupUploadedAt; + + @TableField("backup_last_retry_time") + private LocalDateTime backupLastRetryTime; + + /** + * 文件状态:1-可用,0-不可用,2-回收站 + */ + @TableField("status") + private Integer status; + + /** + * 文件删除时间(NULL表示未删除) + */ + @TableField("delete_time") + private LocalDateTime deleteTime; + + /** + * 文件移入回收站时间(NULL表示未移入) + */ + @TableField("recycle_time") + private LocalDateTime recycleTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/entity/ObjectStorageReplicaDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/entity/ObjectStorageReplicaDO.java new file mode 100644 index 00000000..d71d978b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/entity/ObjectStorageReplicaDO.java @@ -0,0 +1,42 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_object_storage_file_replica") +public class ObjectStorageReplicaDO extends BaseEntity { + + @TableField("file_id") + private Long fileId; + + @TableField("provider") + private String provider; + + @TableField("object_name") + private String objectName; + + @TableField("object_url") + private String objectUrl; + + @TableField("upload_status") + private Integer uploadStatus; + + @TableField("retry_count") + private Integer retryCount; + + @TableField("last_error") + private String lastError; + + @TableField("uploaded_at") + private LocalDateTime uploadedAt; + + @TableField("last_retry_time") + private LocalDateTime lastRetryTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mapper/ObjectStorageFileMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mapper/ObjectStorageFileMapper.java new file mode 100644 index 00000000..48fc9fb8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mapper/ObjectStorageFileMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageFileDO; + +/** + * 对象存储文件信息表 Mapper + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ObjectStorageFileMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mapper/ObjectStorageReplicaMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mapper/ObjectStorageReplicaMapper.java new file mode 100644 index 00000000..87fdde04 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mapper/ObjectStorageReplicaMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageReplicaDO; + +public interface ObjectStorageReplicaMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mq/ObjectStorageBackupMessageListener.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mq/ObjectStorageBackupMessageListener.java new file mode 100644 index 00000000..7358e337 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mq/ObjectStorageBackupMessageListener.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.mq; + +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageBackupMessage; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageBackupService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupMessageListener { + + private final ObjectStorageBackupService objectStorageBackupService; + + @RabbitListener(queues = "#{objectStorageProperties.backupQueueName}") + public void handle(ObjectStorageBackupMessage message) { + if (message == null || message.getFileId() == null) { + return; + } + try { + objectStorageBackupService.backupFile(message.getFileId()); + } catch (Exception e) { + log.warn("Handle object storage backup message failed, fileId={}", message.getFileId(), e); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java new file mode 100644 index 00000000..bd5524ff --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java @@ -0,0 +1,32 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.mq; + +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageBackupMessage; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupMessagePublisher { + + private final RabbitTemplate rabbitTemplate; + private final ObjectStorageProperties objectStorageProperties; + + public void publish(Long fileId) { + if (fileId == null || fileId <= 0) { + return; + } + try { + rabbitTemplate.convertAndSend( + objectStorageProperties.getBackupExchangeName(), + objectStorageProperties.getBackupRoutingKey(), + new ObjectStorageBackupMessage(fileId) + ); + } catch (Exception e) { + log.warn("Publish object storage backup message failed, fileId={}", fileId, e); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java new file mode 100644 index 00000000..4a56ff2a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java @@ -0,0 +1,43 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.scheduler; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.mapper.ObjectStorageReplicaMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageBackupService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.impl.ObjectStorageBackupServiceImpl; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupRetryScheduler { + + private final ObjectStorageReplicaMapper objectStorageReplicaMapper; + private final ObjectStorageBackupService objectStorageBackupService; + private final ObjectStorageProperties objectStorageProperties; + + @Scheduled(cron = "${object-storage.backup-retry-cron}", zone = "Asia/Shanghai") + public void retryPendingOrFailedBackups() { + List replicas = objectStorageReplicaMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .in(ObjectStorageReplicaDO::getProvider, objectStorageProperties.getReplicaRequiredProviders()) + .in(ObjectStorageReplicaDO::getUploadStatus, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_PENDING, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED) + .last("LIMIT " + objectStorageProperties.getBackupRetryBatchLimit()) + ); + for (ObjectStorageReplicaDO replica : replicas) { + try { + objectStorageBackupService.backupFile(replica.getFileId()); + } catch (Exception e) { + log.warn("Retry object storage replica failed, fileId={}, provider={}", replica.getFileId(), replica.getProvider(), e); + } + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/AliyunOssService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/AliyunOssService.java new file mode 100644 index 00000000..47f90227 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/AliyunOssService.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import java.io.InputStream; + +public interface AliyunOssService { + + String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType); + + String getPresignedUrl(String objectName); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ChunkUploadService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ChunkUploadService.java new file mode 100644 index 00000000..511a3f45 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ChunkUploadService.java @@ -0,0 +1,145 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ChunkUploadSessionVO; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; + +/** + * ChunkUploadService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ChunkUploadService { + + /** + * Run business method `initAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + /** + * Run business method `initUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + /** + * Run business method `uploadAdminObjectStorageChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + /** + * Run business method `uploadUserAvatarChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + /** + * Run business method `prepareAdminObjectStorageFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId); + + /** + * Run business method `prepareUserAvatarFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId); + + PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId); + + PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId); + + /** + * Run business method `clearAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + void clearAdminObjectStorageUpload(Long ownerId, String uploadId); + + /** + * Run business method `clearUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + void clearUserAvatarUpload(Long ownerId, String uploadId); + + void clearUserProfileImageUpload(Long ownerId, String uploadId); + + void clearCommentImageUpload(Long ownerId, String uploadId); +/** + * PreparedUploadFile declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ + interface PreparedUploadFile extends AutoCloseable { + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return File result consumed by the caller or returned to the frontend + */ + File getFile(); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String getFileName(); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String getContentType(); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return long result consumed by the caller or returned to the frontend + */ + long getFileSize(); + + @Override + /** + * Run business method `close`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ + void close(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageBackupService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageBackupService.java new file mode 100644 index 00000000..7e035925 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageBackupService.java @@ -0,0 +1,6 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +public interface ObjectStorageBackupService { + + void backupFile(Long fileId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageFileService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageFileService.java new file mode 100644 index 00000000..c179dd4b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageFileService.java @@ -0,0 +1,78 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * 对象存储文件信息表 Service + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ObjectStorageFileService extends IService { + + /** + * 创建文件 + * + * @param objectStorageFileDTO 文件DTO + * @return 文件ID + */ + Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO); + + /** + * 更新文件 + * + * @param id 文件ID + * @param objectStorageFileDTO 文件DTO + * @return 是否更新成功 + */ + boolean updateObjectStorageFile(Long id, ObjectStorageFileDTO objectStorageFileDTO); + + /** + * 删除文件 + * + * @param id 文件ID + * @return 是否删除成功 + */ + boolean deleteObjectStorageFile(Long id); + + /** + * 根据ID查询文件 + * + * @param id 文件ID + * @return 文件VO + */ + ObjectStorageFileVO getObjectStorageFileById(Long id); + + /** + * 鎵归噺鏌ヨ鏂囦欢锛岃繑鍥瀒D -> 鏂囦欢淇℃伅鏄犲皠 + * + * @param ids 鏂囦欢ID闆嗗悎 + * @return 鏂囦欢鏄犲皠 + */ + Map getObjectStorageFileMapByIds(Collection ids); + + /** + * 查询所有文件 + * + * @return 文件VO列表 + */ + List listAllObjectStorageFiles(); + + /** + * 根据状态查询文件 + * + * @param status 文件状态 + * @return 文件VO列表 + */ + List listObjectStorageFilesByStatus(Integer status); + + void evictObjectStorageFileCache(Long id); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageOrchestrationService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageOrchestrationService.java new file mode 100644 index 00000000..5c78f2e5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageOrchestrationService.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageFileDO; + +import java.io.InputStream; + +public interface ObjectStorageOrchestrationService { + + ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + void completeReplicas(ObjectStorageFileDO file); + + String getPresignedUrl(Long fileId, String objectName, Integer expiryTimeInMinutes); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageProvider.java new file mode 100644 index 00000000..adedb177 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageProvider.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import java.io.InputStream; + +public interface ObjectStorageProvider { + + String providerCode(); + + boolean isEnabled(); + + String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + InputStream downloadFile(String objectName) throws Exception; + + void deleteFile(String objectName) throws Exception; + + String getFileUrl(String objectName); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageReplicaService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageReplicaService.java new file mode 100644 index 00000000..03d02254 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/ObjectStorageReplicaService.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageReplicaDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageUploadAttempt; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageReplicaDO; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public interface ObjectStorageReplicaService { + + List listByFileId(Long fileId); + + Map> listMapByFileIds(Collection fileIds); + + void saveInitialReplicas(Long fileId, List attempts); + + void saveOrUpdateReplica(Long fileId, ObjectStorageReplicaDTO replicaDTO); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/PrimaryObjectStorageService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/PrimaryObjectStorageService.java new file mode 100644 index 00000000..6d36f92f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/PrimaryObjectStorageService.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service; + +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; + +public interface PrimaryObjectStorageService { + + String uploadFile(MultipartFile file, String objectName) throws Exception; + + String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + InputStream downloadFile(String objectName) throws Exception; + + void deleteFile(String objectName) throws Exception; + + String getFileUrl(String objectName); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/AliyunOssServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/AliyunOssServiceImpl.java new file mode 100644 index 00000000..8ae54d3d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/AliyunOssServiceImpl.java @@ -0,0 +1,112 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.aliyun.oss.HttpMethod; +import com.aliyun.oss.OSS; +import com.aliyun.oss.model.GeneratePresignedUrlRequest; +import com.aliyun.oss.model.ObjectMetadata; +import com.aliyun.oss.model.PutObjectRequest; +import com.xiaowang.jayucloud.artlist.core.modules.file.config.AliyunOssConfig; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.AliyunOssService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageProvider; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.io.InputStream; +import java.net.URL; +import java.util.Date; + +@Slf4j +@Service +@RequiredArgsConstructor +public class AliyunOssServiceImpl implements AliyunOssService, ObjectStorageProvider { + + private final ObjectProvider ossClientProvider; + private final AliyunOssConfig aliyunOssConfig; + + @Override + public String providerCode() { + return "ALIYUN_OSS"; + } + + @Override + public boolean isEnabled() { + return Boolean.TRUE.equals(aliyunOssConfig.getEnabled()) + && ossClientProvider.getIfAvailable() != null + && StringUtils.hasText(aliyunOssConfig.getBucketName()); + } + + @Override + public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) { + return uploadStream(objectName, inputStream, fileSize, contentType); + } + + @Override + public String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType) { + OSS ossClient = requireClient(); + ObjectMetadata metadata = new ObjectMetadata(); + if (fileSize >= 0) { + metadata.setContentLength(fileSize); + } + if (StringUtils.hasText(contentType)) { + metadata.setContentType(contentType); + } + ossClient.putObject(new PutObjectRequest(aliyunOssConfig.getBucketName(), objectName, inputStream, metadata)); + log.info("Aliyun OSS backup uploaded: {}", objectName); + return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; + } + + @Override + public InputStream downloadFile(String objectName) { + OSS ossClient = requireClient(); + return ossClient.getObject(aliyunOssConfig.getBucketName(), objectName).getObjectContent(); + } + + @Override + public void deleteFile(String objectName) { + OSS ossClient = requireClient(); + ossClient.deleteObject(aliyunOssConfig.getBucketName(), objectName); + } + + @Override + public String getFileUrl(String objectName) { + return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName) { + return getPresignedUrl(objectName, aliyunOssConfig.getSignedUrlExpireMinutes()); + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { + OSS ossClient = requireClient(); + Date expiration = new Date(System.currentTimeMillis() + + resolveExpireMinutes(expiryTimeInMinutes) * 60L * 1000L); + GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest( + aliyunOssConfig.getBucketName(), + objectName, + HttpMethod.GET + ); + request.setExpiration(expiration); + URL url = ossClient.generatePresignedUrl(request); + return url.toString(); + } + + private int resolveExpireMinutes(Integer expiryTimeInMinutes) { + if (expiryTimeInMinutes != null && expiryTimeInMinutes > 0) { + return expiryTimeInMinutes; + } + return aliyunOssConfig.getSignedUrlExpireMinutes(); + } + + private OSS requireClient() { + OSS ossClient = ossClientProvider.getIfAvailable(); + if (ossClient == null) { + throw new IllegalStateException("Aliyun OSS is not enabled or not configured"); + } + return ossClient; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ChunkUploadServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ChunkUploadServiceImpl.java new file mode 100644 index 00000000..b8aa9bb5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ChunkUploadServiceImpl.java @@ -0,0 +1,995 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ChunkUploadService; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ChunkUploadSessionVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +@Slf4j +@Service +@RequiredArgsConstructor +/** + * ChunkUploadServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ChunkUploadServiceImpl implements ChunkUploadService { + + // Keep each chunk comfortably below the common 1 MB gateway/body limit. + private static final int CHUNK_SIZE = 512 * 1024; + /** + * Purpose: SESSION_EXPIRE_HOURS supports ChunkUploadServiceImpl.java by holding or executing the session expire hours business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long SESSION_EXPIRE_HOURS = 24; + /** + * Purpose: METADATA_FILE_NAME supports ChunkUploadServiceImpl.java by holding or executing the metadata file name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String METADATA_FILE_NAME = "metadata.json"; + /** + * Purpose: CHUNK_FILE_PREFIX supports ChunkUploadServiceImpl.java by holding or executing the chunk file prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHUNK_FILE_PREFIX = "chunk-"; + /** + * Purpose: CHUNK_FILE_SUFFIX supports ChunkUploadServiceImpl.java by holding or executing the chunk file suffix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHUNK_FILE_SUFFIX = ".part"; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + + @Override + /** + * Run business method `initAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + public ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return initUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, requestDTO); + } + + @Override + /** + * Run business method `initUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + public ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO); + } + + @Override + public ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + return initUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, requestDTO); + } + + @Override + public ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + return initUpload(UploadTargetType.COMMENT_IMAGE, ownerId, requestDTO); + } + + @Override + /** + * Run business method `uploadAdminObjectStorageChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + public void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + uploadChunk(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + /** + * Run business method `uploadUserAvatarChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + public void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + public void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + uploadChunk(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + public void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + uploadChunk(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + /** + * Run business method `prepareAdminObjectStorageFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + public PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId) { + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return prepareMergedFile(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); + } + + @Override + /** + * Run business method `prepareUserAvatarFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + public PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId) { + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId); + } + + @Override + public PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId) { + return prepareMergedFile(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); + } + + @Override + public PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId) { + return prepareMergedFile(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); + } + + @Override + /** + * Run business method `clearAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + public void clearAdminObjectStorageUpload(Long ownerId, String uploadId) { + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + clearUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); + } + + @Override + /** + * Run business method `clearUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + public void clearUserAvatarUpload(Long ownerId, String uploadId) { + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId); + } + + @Override + public void clearUserProfileImageUpload(Long ownerId, String uploadId) { + clearUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); + } + + @Override + public void clearCommentImageUpload(Long ownerId, String uploadId) { + clearUpload(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); + } + + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + private ChunkUploadSessionVO initUpload(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `validateInitRequest`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateInitRequest(ownerId, requestDTO); + /** + * Run business method `cleanupExpiredSessionsQuietly`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + cleanupExpiredSessionsQuietly(); + + String uploadId = buildUploadId(targetType, ownerId, requestDTO); + Path sessionDir = getSessionDir(uploadId); + int totalChunks = (int) Math.ceil((double) requestDTO.getFileSize() / CHUNK_SIZE); + + try { + Files.createDirectories(sessionDir); + + UploadMetadata metadata = readMetadataIfExists(sessionDir); + if (metadata != null && !isCompatible(metadata, targetType, ownerId, requestDTO, totalChunks)) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + Files.createDirectories(sessionDir); + metadata = null; + } + + if (metadata == null) { + metadata = new UploadMetadata(); + metadata.setUploadId(uploadId); + metadata.setTargetType(targetType.name()); + metadata.setOwnerId(ownerId); + metadata.setFileName(requestDTO.getFileName()); + metadata.setContentType(requestDTO.getContentType()); + metadata.setFileSize(requestDTO.getFileSize()); + metadata.setFileFingerprint(requestDTO.getFileFingerprint()); + metadata.setScene(requestDTO.getScene()); + metadata.setChunkSize(CHUNK_SIZE); + metadata.setTotalChunks(totalChunks); + metadata.setCreatedAt(Instant.now().toEpochMilli()); + } + metadata.setUpdatedAt(Instant.now().toEpochMilli()); + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + writeMetadata(sessionDir, metadata); + + ChunkUploadSessionVO sessionVO = new ChunkUploadSessionVO(); + sessionVO.setUploadId(uploadId); + sessionVO.setChunkSize(metadata.getChunkSize()); + sessionVO.setTotalChunks(metadata.getTotalChunks()); + sessionVO.setUploadedChunks(getUploadedChunks(sessionDir, metadata.getTotalChunks())); + return sessionVO; + } catch (IOException e) { + log.error("初始化分片上传失败, uploadId={}", uploadId, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("初始化上传失败"); + } + } + + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void uploadChunk(UploadTargetType targetType, Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + if (ownerId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("未获取到上传用户信息"); + } + if (!StringUtils.hasText(uploadId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传标识不能为空"); + } + if (chunkIndex == null || chunkIndex < 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片序号不合法"); + } + if (totalChunks == null || totalChunks <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片总数不合法"); + } + if (chunkFile == null || chunkFile.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传分片不能为空"); + } + + Path sessionDir = getSessionDir(uploadId); + UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + if (!Objects.equals(metadata.getTotalChunks(), totalChunks)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片总数不匹配,请重新上传"); + } + if (chunkIndex >= metadata.getTotalChunks()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片序号超出范围"); + } + + try { + Path chunkPath = getChunkPath(sessionDir, chunkIndex); + Path tempChunkPath = sessionDir.resolve(chunkPath.getFileName().toString() + ".tmp"); + try (InputStream inputStream = chunkFile.getInputStream()) { + Files.copy(inputStream, tempChunkPath, StandardCopyOption.REPLACE_EXISTING); + } + Files.move(tempChunkPath, chunkPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + metadata.setUpdatedAt(Instant.now().toEpochMilli()); + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + writeMetadata(sessionDir, metadata); + } catch (IOException e) { + log.error("保存分片失败, uploadId={}, chunkIndex={}", uploadId, chunkIndex, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传分片失败"); + } + } + + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private PreparedUploadFile result consumed by the caller or returned to the frontend + */ + private PreparedUploadFile prepareMergedFile(UploadTargetType targetType, Long ownerId, String uploadId) { + Path sessionDir = getSessionDir(uploadId); + UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + List uploadedChunks = getUploadedChunks(sessionDir, metadata.getTotalChunks()); + if (uploadedChunks.size() != metadata.getTotalChunks()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件尚未上传完成,请稍后再试"); + } + + try { + Path mergedFilePath = Files.createTempFile("jayucloud-artlist-upload-", ".tmp"); + try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergedFilePath))) { + for (int chunkIndex = 0; chunkIndex < metadata.getTotalChunks(); chunkIndex++) { + Path chunkPath = getChunkPath(sessionDir, chunkIndex); + if (!Files.exists(chunkPath)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("缺少上传分片,请重新上传"); + } + Files.copy(chunkPath, outputStream); + } + } + return new LocalPreparedUploadFile(mergedFilePath.toFile(), metadata.getFileName(), metadata.getContentType(), metadata.getFileSize()); + } catch (IOException e) { + log.error("合并上传文件失败, uploadId={}", uploadId, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("合并上传文件失败"); + } + } + + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void clearUpload(UploadTargetType targetType, Long ownerId, String uploadId) { + Path sessionDir = getSessionDir(uploadId); + /** + * Run business method `readAndValidateMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + } + + /** + * Run business method `readAndValidateMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private UploadMetadata result consumed by the caller or returned to the frontend + */ + private UploadMetadata readAndValidateMetadata(Path sessionDir, UploadTargetType targetType, Long ownerId, String uploadId) { + UploadMetadata metadata = readMetadataIfExists(sessionDir); + if (metadata == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传会话不存在,请重新上传"); + } + if (!targetType.name().equals(metadata.getTargetType()) || !Objects.equals(ownerId, metadata.getOwnerId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权操作该上传会话"); + } + if (!uploadId.equals(metadata.getUploadId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传会话不匹配"); + } + return metadata; + } + + /** + * Run business method `validateInitRequest`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateInitRequest(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + if (ownerId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("未获取到上传用户信息"); + } + if (requestDTO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传参数不能为空"); + } + if (!StringUtils.hasText(requestDTO.getFileName())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件名不能为空"); + } + if (!StringUtils.hasText(requestDTO.getContentType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件类型不能为空"); + } + if (!StringUtils.hasText(requestDTO.getFileFingerprint())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件指纹不能为空"); + } + if (!StringUtils.hasText(requestDTO.getScene())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传场景不能为空"); + } + if (requestDTO.getFileSize() == null || requestDTO.getFileSize() <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件大小不合法"); + } + } + + /** + * Run business method `isCompatible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param metadata parameter `metadata` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isCompatible(UploadMetadata metadata, UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO, int totalChunks) { + return targetType.name().equals(metadata.getTargetType()) + && Objects.equals(ownerId, metadata.getOwnerId()) + && Objects.equals(metadata.getFileSize(), requestDTO.getFileSize()) + && Objects.equals(metadata.getTotalChunks(), totalChunks) + && Objects.equals(metadata.getFileFingerprint(), requestDTO.getFileFingerprint()) + && Objects.equals(metadata.getScene(), requestDTO.getScene()); + } + + /** + * Run business method `buildUploadId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildUploadId(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + String raw = targetType.name() + "|" + ownerId + "|" + requestDTO.getScene() + "|" + requestDTO.getFileFingerprint(); + return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param uploadId parameter `uploadId` supplied by the caller + * @return private Path result consumed by the caller or returned to the frontend + */ + private Path getSessionDir(String uploadId) { + return getUploadRoot().resolve(uploadId); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Path result consumed by the caller or returned to the frontend + */ + private Path getUploadRoot() { + return Path.of(System.getProperty("java.io.tmpdir"), "jayucloud-artlist", "chunk-upload"); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @return private Path result consumed by the caller or returned to the frontend + */ + private Path getChunkPath(Path sessionDir, int chunkIndex) { + return sessionDir.resolve(CHUNK_FILE_PREFIX + String.format("%05d", chunkIndex) + CHUNK_FILE_SUFFIX); + } + + /** + * Run business method `readMetadataIfExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return private UploadMetadata result consumed by the caller or returned to the frontend + */ + private UploadMetadata readMetadataIfExists(Path sessionDir) { + Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); + if (!Files.exists(metadataPath)) { + return null; + } + try { + return objectMapper.readValue(metadataPath.toFile(), UploadMetadata.class); + } catch (IOException e) { + log.warn("读取上传元数据失败: {}", metadataPath, e); + return null; + } + } + + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void writeMetadata(Path sessionDir, UploadMetadata metadata) throws IOException { + Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); + objectMapper.writeValue(metadataPath.toFile(), metadata); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getUploadedChunks(Path sessionDir, int totalChunks) { + List uploadedChunks = new ArrayList<>(); + for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + if (Files.exists(getChunkPath(sessionDir, chunkIndex))) { + uploadedChunks.add(chunkIndex); + } + } + return uploadedChunks; + } + + /** + * Run business method `cleanupExpiredSessionsQuietly`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void cleanupExpiredSessionsQuietly() { + try { + Path uploadRoot = getUploadRoot(); + if (!Files.exists(uploadRoot)) { + return; + } + Instant expireAt = Instant.now().minus(SESSION_EXPIRE_HOURS, ChronoUnit.HOURS); + try (var stream = Files.list(uploadRoot)) { + stream.filter(Files::isDirectory) + .sorted(Comparator.comparing(Path::toString)) + .forEach(sessionDir -> cleanupExpiredSession(sessionDir, expireAt)); + } + } catch (IOException e) { + log.warn("清理过期上传会话失败", e); + } + } + + /** + * Run business method `cleanupExpiredSession`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param expireAt parameter `expireAt` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void cleanupExpiredSession(Path sessionDir, Instant expireAt) { + UploadMetadata metadata = readMetadataIfExists(sessionDir); + if (metadata == null) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + return; + } + Instant updatedAt = Instant.ofEpochMilli(metadata.getUpdatedAt() == null ? 0L : metadata.getUpdatedAt()); + if (updatedAt.isBefore(expireAt)) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + } + } + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param directory parameter `directory` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deleteDirectory(Path directory) { + if (directory == null || !Files.exists(directory)) { + return; + } + try (var walk = Files.walk(directory)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + log.warn("删除上传临时文件失败: {}", path, e); + } + }); + } catch (IOException e) { + log.warn("删除上传目录失败: {}", directory, e); + } + } + + /** + * Purpose: UploadTargetType supports ChunkUploadServiceImpl.java by holding or executing the upload target type business role. + * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. + */ + private enum UploadTargetType { + ADMIN_OBJECT_STORAGE, + USER_AVATAR, + USER_PROFILE_IMAGE, + COMMENT_IMAGE + } + + @Data + /** + * Purpose: UploadMetadata supports ChunkUploadServiceImpl.java by holding or executing the upload metadata business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class UploadMetadata { + /** + * Purpose: uploadId supports ChunkUploadServiceImpl.java by holding or executing the upload id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String uploadId; + /** + * Purpose: targetType supports ChunkUploadServiceImpl.java by holding or executing the target type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String targetType; + /** + * Purpose: ownerId supports ChunkUploadServiceImpl.java by holding or executing the owner id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long ownerId; + /** + * Purpose: fileName supports ChunkUploadServiceImpl.java by holding or executing the file name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String fileName; + /** + * Purpose: contentType supports ChunkUploadServiceImpl.java by holding or executing the content type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String contentType; + /** + * Purpose: fileSize supports ChunkUploadServiceImpl.java by holding or executing the file size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long fileSize; + /** + * Purpose: fileFingerprint supports ChunkUploadServiceImpl.java by holding or executing the file fingerprint business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String fileFingerprint; + /** + * Purpose: scene supports ChunkUploadServiceImpl.java by holding or executing the scene business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String scene; + /** + * Purpose: chunkSize supports ChunkUploadServiceImpl.java by holding or executing the chunk size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer chunkSize; + /** + * Purpose: totalChunks supports ChunkUploadServiceImpl.java by holding or executing the total chunks business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer totalChunks; + /** + * Purpose: createdAt supports ChunkUploadServiceImpl.java by holding or executing the created at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long createdAt; + /** + * Purpose: updatedAt supports ChunkUploadServiceImpl.java by holding or executing the updated at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long updatedAt; + } + + /** + * Purpose: LocalPreparedUploadFile supports ChunkUploadServiceImpl.java by holding or executing the local prepared upload file business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class LocalPreparedUploadFile implements PreparedUploadFile { + /** + * Variable `file`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final File file; + /** + * Variable `fileName`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String fileName; + /** + * Variable `contentType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String contentType; + /** + * Variable `fileSize`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final long fileSize; + + /** + * Run business method `LocalPreparedUploadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param file parameter `file` supplied by the caller + * @param fileName parameter `fileName` supplied by the caller + * @param contentType parameter `contentType` supplied by the caller + * @param fileSize parameter `fileSize` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private LocalPreparedUploadFile(File file, String fileName, String contentType, long fileSize) { + this.file = file; + this.fileName = fileName; + this.contentType = contentType; + this.fileSize = fileSize; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return File result consumed by the caller or returned to the frontend + */ + public File getFile() { + return file; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String getFileName() { + return fileName; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String getContentType() { + return contentType; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return long result consumed by the caller or returned to the frontend + */ + public long getFileSize() { + return fileSize; + } + + @Override + /** + * Run business method `close`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ + public void close() { + if (file != null && file.exists() && !file.delete()) { + log.warn("删除合并后的临时文件失败: {}", file.getAbsolutePath()); + } + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/MinioObjectStorageProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/MinioObjectStorageProvider.java new file mode 100644 index 00000000..eaf1bb37 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/MinioObjectStorageProvider.java @@ -0,0 +1,119 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.file.config.MinioStorageConfig; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageProvider; +import io.minio.GetObjectArgs; +import io.minio.GetPresignedObjectUrlArgs; +import io.minio.MinioClient; +import io.minio.PutObjectArgs; +import io.minio.RemoveObjectArgs; +import io.minio.http.Method; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.io.InputStream; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class MinioObjectStorageProvider implements ObjectStorageProvider { + + private static final long UNKNOWN_SIZE_PART_SIZE = 10 * 1024 * 1024L; + + private final ObjectProvider minioClientProvider; + private final MinioStorageConfig minioStorageConfig; + + @Override + public String providerCode() { + return "MINIO"; + } + + @Override + public boolean isEnabled() { + return Boolean.TRUE.equals(minioStorageConfig.getEnabled()) + && minioClientProvider.getIfAvailable() != null + && StringUtils.hasText(minioStorageConfig.getBucketName()); + } + + @Override + public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { + MinioClient minioClient = requireClient(); + PutObjectArgs.Builder builder = PutObjectArgs.builder() + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .stream(inputStream, fileSize, fileSize < 0 ? UNKNOWN_SIZE_PART_SIZE : -1L); + if (StringUtils.hasText(contentType)) { + builder.contentType(contentType); + } + minioClient.putObject(builder.build()); + log.info("MinIO object uploaded, objectName={}", objectName); + return getFileUrl(objectName); + } + + @Override + public InputStream downloadFile(String objectName) throws Exception { + return requireClient().getObject( + GetObjectArgs.builder() + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .build() + ); + } + + @Override + public void deleteFile(String objectName) throws Exception { + requireClient().removeObject( + RemoveObjectArgs.builder() + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .build() + ); + } + + @Override + public String getFileUrl(String objectName) { + return normalizeEndpoint(minioStorageConfig.getEndpoint()) + "/" + minioStorageConfig.getBucketName() + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception { + if (!Boolean.TRUE.equals(minioStorageConfig.getPrivateBucket())) { + return getFileUrl(objectName); + } + return requireClient().getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder() + .method(Method.GET) + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .expiry(resolveExpireMinutes(expiryTimeInMinutes), TimeUnit.MINUTES) + .build() + ); + } + + private MinioClient requireClient() { + MinioClient minioClient = minioClientProvider.getIfAvailable(); + if (minioClient == null) { + throw new IllegalStateException("MinIO is not enabled or not configured"); + } + return minioClient; + } + + private int resolveExpireMinutes(Integer expiryTimeInMinutes) { + if (expiryTimeInMinutes != null && expiryTimeInMinutes > 0) { + return expiryTimeInMinutes; + } + return minioStorageConfig.getSignedUrlExpireMinutes(); + } + + private String normalizeEndpoint(String endpoint) { + String normalized = endpoint.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + return normalized; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java new file mode 100644 index 00000000..7f2f6ce8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java @@ -0,0 +1,78 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageBackupService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageOrchestrationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ObjectStorageBackupServiceImpl implements ObjectStorageBackupService { + + public static final int UPLOAD_STATUS_PENDING = 0; + public static final int UPLOAD_STATUS_SUCCEEDED = 1; + public static final int UPLOAD_STATUS_FAILED = 2; + + private static final int ACTIVE_STATUS = 1; + private static final int MAX_ERROR_LENGTH = 500; + + private final ObjectStorageFileMapper objectStorageFileMapper; + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + private final ObjectStorageFileService objectStorageFileService; + + @Override + public void backupFile(Long fileId) { + if (fileId == null || fileId <= 0) { + return; + } + ObjectStorageFileDO file = objectStorageFileMapper.selectById(fileId); + if (!shouldBackup(file)) { + return; + } + + try { + objectStorageOrchestrationService.completeReplicas(file); + markSucceeded(file); + } catch (Exception e) { + log.warn("Complete object storage replicas failed, fileId={}", fileId, e); + markFailed(file, e); + } + } + + private boolean shouldBackup(ObjectStorageFileDO file) { + return file != null + && Integer.valueOf(ACTIVE_STATUS).equals(file.getStatus()) + && Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getPrimaryUploadStatus()) + && StringUtils.hasText(file.getObjectName()); + } + + private void markSucceeded(ObjectStorageFileDO file) { + file.setBackupUploadStatus(UPLOAD_STATUS_SUCCEEDED); + file.setBackupUploadedAt(LocalDateTime.now()); + file.setBackupLastError(null); + objectStorageFileMapper.updateById(file); + objectStorageFileService.evictObjectStorageFileCache(file.getId()); + } + + private void markFailed(ObjectStorageFileDO file, Exception e) { + file.setBackupUploadStatus(UPLOAD_STATUS_FAILED); + file.setBackupRetryCount((file.getBackupRetryCount() == null ? 0 : file.getBackupRetryCount()) + 1); + file.setBackupLastError(truncateError(e)); + file.setBackupLastRetryTime(LocalDateTime.now()); + objectStorageFileMapper.updateById(file); + objectStorageFileService.evictObjectStorageFileCache(file.getId()); + } + + private String truncateError(Exception e) { + String message = e.getClass().getSimpleName() + ": " + (e.getMessage() == null ? "" : e.getMessage()); + return message.length() <= MAX_ERROR_LENGTH ? message : message.substring(0, MAX_ERROR_LENGTH); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java new file mode 100644 index 00000000..1224bad9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -0,0 +1,308 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.mq.ObjectStorageBackupMessagePublisher; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageReplicaService; +import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 对象存储文件信息表 Service 实现 + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class ObjectStorageFileServiceImpl extends ServiceImpl implements ObjectStorageFileService { + + /** + * Purpose: FILE_DETAIL_CACHE_PREFIX supports ObjectStorageFileServiceImpl.java by holding or executing the file detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String FILE_DETAIL_CACHE_PREFIX = "cache:file:detail:"; + /** + * Variable `objectStorageFileMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileMapper objectStorageFileMapper; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + private final ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher; + private final ObjectStorageProperties objectStorageProperties; + private final ObjectStorageReplicaService objectStorageReplicaService; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO) { + ObjectStorageFileDO objectStorageFileDO = new ObjectStorageFileDO(); + applyDTO(objectStorageFileDO, objectStorageFileDTO); + objectStorageFileMapper.insert(objectStorageFileDO); + objectStorageReplicaService.saveInitialReplicas(objectStorageFileDO.getId(), objectStorageFileDTO.getUploadAttempts()); + evictFileCache(objectStorageFileDO.getId()); + publishBackupIfNeeded(objectStorageFileDO); + return objectStorageFileDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateObjectStorageFile(Long id, ObjectStorageFileDTO objectStorageFileDTO) { + ObjectStorageFileDO objectStorageFileDO = objectStorageFileMapper.selectById(id); + if (objectStorageFileDO == null) { + return false; + } + applyDTO(objectStorageFileDO, objectStorageFileDTO); + boolean updated = objectStorageFileMapper.updateById(objectStorageFileDO) > 0; + if (updated) { + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictFileCache(id); + } + return updated; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteObjectStorageFile(Long id) { + boolean deleted = objectStorageFileMapper.deleteById(id) > 0; + if (deleted) { + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictFileCache(id); + } + return deleted; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ObjectStorageFileVO result consumed by the caller or returned to the frontend + */ + public ObjectStorageFileVO getObjectStorageFileById(Long id) { + return getObjectStorageFileMapByIds(Collections.singleton(id)).get(id); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return Map result consumed by the caller or returned to the frontend + */ + public Map getObjectStorageFileMapByIds(Collection ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyMap(); + } + + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getObjectStorageFile(); + Duration localTtl = Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()); + Duration redisTtl = Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()); + Map result = new LinkedHashMap<>(); + Set missingIds = new LinkedHashSet<>(); + + for (Long id : ids) { + if (id == null || id <= 0) { + continue; + } + MultiLevelCacheService.CacheLookup lookup = multiLevelCacheService.get( + buildDetailCacheKey(id), + localTtl, + new TypeReference() { + } + ); + if (lookup.isHit()) { + if (lookup.getValue() != null) { + result.put(id, lookup.getValue()); + } + continue; + } + missingIds.add(id); + } + + if (!missingIds.isEmpty()) { + Map loadedMap = objectStorageFileMapper.selectBatchIds(missingIds).stream() + .collect(Collectors.toMap(ObjectStorageFileDO::getId, this::convertToVO, (left, right) -> left, LinkedHashMap::new)); + for (Long missingId : missingIds) { + ObjectStorageFileVO fileVO = loadedMap.get(missingId); + multiLevelCacheService.put(buildDetailCacheKey(missingId), fileVO, localTtl, redisTtl); + if (fileVO != null) { + result.put(missingId, fileVO); + } + } + } + + return result; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllObjectStorageFiles() { + List objectStorageFileDOs = objectStorageFileMapper.selectList(null); + return objectStorageFileDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listObjectStorageFilesByStatus(Integer status) { + List objectStorageFileDOs = objectStorageFileMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageFileDO.class) + .eq(ObjectStorageFileDO::getStatus, status) + ); + return objectStorageFileDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param objectStorageFileDO 文件DO + * @return 文件VO + */ + private ObjectStorageFileVO convertToVO(ObjectStorageFileDO objectStorageFileDO) { + ObjectStorageFileVO objectStorageFileVO = new ObjectStorageFileVO(); + objectStorageFileVO.setId(objectStorageFileDO.getId()); + objectStorageFileVO.setFileName(objectStorageFileDO.getFileName()); + objectStorageFileVO.setFileUrl(objectStorageFileDO.getFileUrl()); + objectStorageFileVO.setObjectName(objectStorageFileDO.getObjectName()); + objectStorageFileVO.setPrimaryProvider(objectStorageFileDO.getPrimaryProvider()); + objectStorageFileVO.setPrimaryUrl(objectStorageFileDO.getPrimaryUrl()); + objectStorageFileVO.setBackupProvider(objectStorageFileDO.getBackupProvider()); + objectStorageFileVO.setBackupUrl(objectStorageFileDO.getBackupUrl()); + objectStorageFileVO.setContentType(objectStorageFileDO.getContentType()); + objectStorageFileVO.setFileSize(objectStorageFileDO.getFileSize()); + objectStorageFileVO.setPrimaryUploadStatus(objectStorageFileDO.getPrimaryUploadStatus()); + objectStorageFileVO.setBackupUploadStatus(objectStorageFileDO.getBackupUploadStatus()); + objectStorageFileVO.setBackupRetryCount(objectStorageFileDO.getBackupRetryCount()); + objectStorageFileVO.setBackupLastError(objectStorageFileDO.getBackupLastError()); + objectStorageFileVO.setBackupUploadedAt(objectStorageFileDO.getBackupUploadedAt()); + objectStorageFileVO.setBackupLastRetryTime(objectStorageFileDO.getBackupLastRetryTime()); + objectStorageFileVO.setCreateTime(objectStorageFileDO.getCreateTime()); + objectStorageFileVO.setStatus(objectStorageFileDO.getStatus()); + objectStorageFileVO.setDeleteTime(objectStorageFileDO.getDeleteTime()); + objectStorageFileVO.setRecycleTime(objectStorageFileDO.getRecycleTime()); + return objectStorageFileVO; + } + + private void applyDTO(ObjectStorageFileDO objectStorageFileDO, ObjectStorageFileDTO objectStorageFileDTO) { + objectStorageFileDO.setFileName(objectStorageFileDTO.getFileName()); + objectStorageFileDO.setFileUrl(objectStorageFileDTO.getFileUrl()); + objectStorageFileDO.setObjectName(objectStorageFileDTO.getObjectName()); + objectStorageFileDO.setPrimaryProvider(objectStorageFileDTO.getPrimaryProvider()); + objectStorageFileDO.setPrimaryUrl(objectStorageFileDTO.getPrimaryUrl()); + objectStorageFileDO.setBackupProvider(objectStorageFileDTO.getBackupProvider()); + objectStorageFileDO.setBackupUrl(objectStorageFileDTO.getBackupUrl()); + objectStorageFileDO.setContentType(objectStorageFileDTO.getContentType()); + objectStorageFileDO.setFileSize(objectStorageFileDTO.getFileSize()); + objectStorageFileDO.setPrimaryUploadStatus(objectStorageFileDTO.getPrimaryUploadStatus()); + objectStorageFileDO.setBackupUploadStatus(objectStorageFileDTO.getBackupUploadStatus()); + objectStorageFileDO.setBackupRetryCount(objectStorageFileDTO.getBackupRetryCount()); + objectStorageFileDO.setBackupLastError(objectStorageFileDTO.getBackupLastError()); + objectStorageFileDO.setBackupUploadedAt(objectStorageFileDTO.getBackupUploadedAt()); + objectStorageFileDO.setBackupLastRetryTime(objectStorageFileDTO.getBackupLastRetryTime()); + objectStorageFileDO.setStatus(objectStorageFileDTO.getStatus()); + objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime()); + objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime()); + } + + private void publishBackupIfNeeded(ObjectStorageFileDO objectStorageFileDO) { + if (StringUtils.hasText(objectStorageFileDO.getObjectName()) + && objectStorageProperties.getProviderOrder().contains(objectStorageFileDO.getPrimaryProvider()) + && Integer.valueOf(1).equals(objectStorageFileDO.getPrimaryUploadStatus()) + && Integer.valueOf(0).equals(objectStorageFileDO.getBackupUploadStatus())) { + objectStorageBackupMessagePublisher.publish(objectStorageFileDO.getId()); + } + } + + @Override + public void evictObjectStorageFileCache(Long id) { + evictFileCache(id); + } + + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictFileCache(Long id) { + if (id != null && id > 0) { + multiLevelCacheService.evict(buildDetailCacheKey(id)); + } + } + + /** + * Run business method `buildDetailCacheKey`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildDetailCacheKey(Long id) { + return FILE_DETAIL_CACHE_PREFIX + id; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java new file mode 100644 index 00000000..48517479 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java @@ -0,0 +1,226 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageReplicaDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageUploadAttempt; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageReplicaService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrchestrationService { + + private static final int MAX_ERROR_LENGTH = 500; + + private final List providers; + private final ObjectStorageProperties objectStorageProperties; + private final ObjectStorageReplicaService objectStorageReplicaService; + + @Override + public ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { + byte[] bytes = toBytes(inputStream); + List attempts = new ArrayList<>(); + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + ObjectStorageProvider provider = requireProvider(providerCode); + try { + ensureEnabled(provider); + String objectUrl = provider.uploadStream( + new ByteArrayInputStream(bytes), + fileSize, + contentType, + objectName + ); + attempts.add(new ObjectStorageUploadAttempt( + provider.providerCode(), + objectName, + objectUrl, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED, + 0, + null + )); + return new ObjectStorageUploadOutcome(provider.providerCode(), objectUrl, attempts); + } catch (Exception e) { + lastFailure = e; + attempts.add(new ObjectStorageUploadAttempt( + provider.providerCode(), + objectName, + null, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED, + 1, + truncateError(e) + )); + log.warn("Upload object to provider failed, provider={}, objectName={}", provider.providerCode(), objectName, e); + } + } + throw new IllegalStateException("No available object storage provider for objectName=" + objectName, lastFailure); + } + + @Override + public void completeReplicas(ObjectStorageFileDO file) { + if (file == null || file.getId() == null || !StringUtils.hasText(file.getObjectName())) { + return; + } + List replicas = objectStorageReplicaService.listByFileId(file.getId()); + Map replicaMap = replicas.stream() + .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); + boolean completed = true; + for (String providerCode : objectStorageProperties.getReplicaRequiredProviders()) { + ObjectStorageReplicaDO existing = replicaMap.get(providerCode); + if (existing != null + && Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(existing.getUploadStatus())) { + continue; + } + completed = uploadReplica(file, providerCode, replicaMap) && completed; + } + if (!completed) { + throw new IllegalStateException("Object storage replicas are not fully completed for fileId=" + file.getId()); + } + } + + @Override + public String getPresignedUrl(Long fileId, String objectName, Integer expiryTimeInMinutes) { + if (fileId == null || fileId <= 0) { + return getPresignedUrl(objectName, expiryTimeInMinutes); + } + List replicas = objectStorageReplicaService.listByFileId(fileId); + if (CollectionUtils.isEmpty(replicas)) { + return getPresignedUrl(objectName, expiryTimeInMinutes); + } + Map replicaMap = replicas.stream() + .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + ObjectStorageReplicaDO replica = replicaMap.get(providerCode); + if (replica == null + || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { + continue; + } + try { + return requireProvider(providerCode).getPresignedUrl(replica.getObjectName(), expiryTimeInMinutes); + } catch (Exception e) { + lastFailure = e; + log.warn("Generate object storage signed URL failed, fileId={}, provider={}", fileId, providerCode, e); + } + } + throw new IllegalStateException("No available object storage signed URL for fileId=" + fileId, lastFailure); + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + try { + ObjectStorageProvider provider = requireProvider(providerCode); + ensureEnabled(provider); + return provider.getPresignedUrl(objectName, expiryTimeInMinutes); + } catch (Exception e) { + lastFailure = e; + log.warn("Generate object storage signed URL by objectName failed, provider={}, objectName={}", providerCode, objectName, e); + } + } + throw new IllegalStateException("No available object storage signed URL for objectName=" + objectName, lastFailure); + } + + private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map replicaMap) { + ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); + replicaDTO.setProvider(providerCode); + replicaDTO.setObjectName(file.getObjectName()); + boolean success = false; + try (InputStream inputStream = openReadableReplica(replicaMap, file.getObjectName())) { + ObjectStorageProvider targetProvider = requireProvider(providerCode); + ensureEnabled(targetProvider); + String objectUrl = targetProvider.uploadStream( + inputStream, + file.getFileSize() == null ? -1L : file.getFileSize(), + file.getContentType(), + file.getObjectName() + ); + replicaDTO.setObjectUrl(objectUrl); + replicaDTO.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED); + replicaDTO.setRetryCount(0); + replicaDTO.setUploadedAt(LocalDateTime.now()); + replicaDTO.setLastError(null); + success = true; + } catch (Exception e) { + ObjectStorageReplicaDO existing = replicaMap.get(providerCode); + replicaDTO.setObjectUrl(existing == null ? null : existing.getObjectUrl()); + replicaDTO.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED); + replicaDTO.setRetryCount((existing == null || existing.getRetryCount() == null ? 0 : existing.getRetryCount()) + 1); + replicaDTO.setLastRetryTime(LocalDateTime.now()); + replicaDTO.setLastError(truncateError(e)); + log.warn("Complete object storage replica failed, fileId={}, provider={}", file.getId(), providerCode, e); + } + objectStorageReplicaService.saveOrUpdateReplica(file.getId(), replicaDTO); + return success; + } + + private InputStream openReadableReplica(Map replicaMap, String objectName) throws Exception { + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + ObjectStorageReplicaDO replica = replicaMap.get(providerCode); + if (replica == null + || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { + continue; + } + try { + return requireProvider(providerCode).downloadFile(replica.getObjectName()); + } catch (Exception e) { + lastFailure = e; + log.warn("Download object storage readable replica failed, provider={}, objectName={}", providerCode, replica.getObjectName(), e); + } + } + throw new IllegalStateException("No readable object storage replica for objectName=" + objectName, lastFailure); + } + + private ObjectStorageProvider requireProvider(String providerCode) { + for (ObjectStorageProvider provider : providers) { + if (provider.providerCode().equals(providerCode)) { + return provider; + } + } + throw new IllegalStateException("Object storage provider is not registered: " + providerCode); + } + + private void ensureEnabled(ObjectStorageProvider provider) { + if (!provider.isEnabled()) { + throw new IllegalStateException("Object storage provider is disabled or incomplete: " + provider.providerCode()); + } + } + + private byte[] toBytes(InputStream inputStream) throws Exception { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, read); + } + return outputStream.toByteArray(); + } + } + + private String truncateError(Exception e) { + String message = e.getClass().getSimpleName() + ": " + (e.getMessage() == null ? "" : e.getMessage()); + return message.length() <= MAX_ERROR_LENGTH ? message : message.substring(0, MAX_ERROR_LENGTH); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java new file mode 100644 index 00000000..1749ee20 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java @@ -0,0 +1,104 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageReplicaDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ObjectStorageUploadAttempt; +import com.xiaowang.jayucloud.artlist.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.jayucloud.artlist.core.modules.file.mapper.ObjectStorageReplicaMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageReplicaService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class ObjectStorageReplicaServiceImpl implements ObjectStorageReplicaService { + + private final ObjectStorageReplicaMapper objectStorageReplicaMapper; + + @Override + public List listByFileId(Long fileId) { + if (fileId == null || fileId <= 0) { + return Collections.emptyList(); + } + return objectStorageReplicaMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .eq(ObjectStorageReplicaDO::getFileId, fileId) + ); + } + + @Override + public Map> listMapByFileIds(Collection fileIds) { + if (CollectionUtils.isEmpty(fileIds)) { + return Collections.emptyMap(); + } + List replicas = objectStorageReplicaMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .in(ObjectStorageReplicaDO::getFileId, fileIds) + ); + return replicas.stream() + .collect(Collectors.groupingBy( + ObjectStorageReplicaDO::getFileId, + LinkedHashMap::new, + Collectors.toList() + )); + } + + @Override + public void saveInitialReplicas(Long fileId, List attempts) { + if (fileId == null || fileId <= 0 || CollectionUtils.isEmpty(attempts)) { + return; + } + for (ObjectStorageUploadAttempt attempt : attempts) { + ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); + replicaDTO.setProvider(attempt.getProvider()); + replicaDTO.setObjectName(attempt.getObjectName()); + replicaDTO.setObjectUrl(attempt.getObjectUrl()); + replicaDTO.setUploadStatus(attempt.getUploadStatus()); + replicaDTO.setRetryCount(attempt.getRetryCount()); + replicaDTO.setLastError(attempt.getLastError()); + if (Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(attempt.getUploadStatus())) { + replicaDTO.setUploadedAt(LocalDateTime.now()); + } + saveOrUpdateReplica(fileId, replicaDTO); + } + } + + @Override + public void saveOrUpdateReplica(Long fileId, ObjectStorageReplicaDTO replicaDTO) { + if (fileId == null || fileId <= 0 || replicaDTO == null) { + return; + } + ObjectStorageReplicaDO replica = objectStorageReplicaMapper.selectOne( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .eq(ObjectStorageReplicaDO::getFileId, fileId) + .eq(ObjectStorageReplicaDO::getProvider, replicaDTO.getProvider()) + .last("LIMIT 1") + ); + if (replica == null) { + replica = new ObjectStorageReplicaDO(); + replica.setFileId(fileId); + replica.setProvider(replicaDTO.getProvider()); + } + replica.setObjectName(replicaDTO.getObjectName()); + replica.setObjectUrl(replicaDTO.getObjectUrl()); + replica.setUploadStatus(replicaDTO.getUploadStatus()); + replica.setRetryCount(replicaDTO.getRetryCount()); + replica.setLastError(replicaDTO.getLastError()); + replica.setUploadedAt(replicaDTO.getUploadedAt()); + replica.setLastRetryTime(replicaDTO.getLastRetryTime()); + if (replica.getId() == null) { + objectStorageReplicaMapper.insert(replica); + } else { + objectStorageReplicaMapper.updateById(replica); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java new file mode 100644 index 00000000..f223b7b2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java @@ -0,0 +1,136 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.service.impl; + +import com.qiniu.http.Response; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.UploadManager; +import com.qiniu.storage.model.DefaultPutRet; +import com.qiniu.util.Auth; +import com.qiniu.util.StringMap; +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.modules.file.config.QiniuKodoConfig; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.PrimaryObjectStorageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; +import java.io.ByteArrayOutputStream; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class QiniuObjectStorageServiceImpl implements PrimaryObjectStorageService, ObjectStorageProvider { + + private final QiniuKodoConfig qiniuKodoConfig; + private final ObjectStorageProperties objectStorageProperties; + private final Auth qiniuAuth; + private final UploadManager qiniuUploadManager; + private final BucketManager qiniuBucketManager; + + @Override + public String providerCode() { + return "QINIU_KODO"; + } + + @Override + public boolean isEnabled() { + return StringUtils.hasText(qiniuKodoConfig.getAccessKey()) + && StringUtils.hasText(qiniuKodoConfig.getSecretKey()) + && StringUtils.hasText(qiniuKodoConfig.getBucketName()) + && StringUtils.hasText(qiniuKodoConfig.getDomain()); + } + + @Override + public String uploadFile(MultipartFile file, String objectName) throws Exception { + try (InputStream inputStream = file.getInputStream()) { + return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName); + } + } + + @Override + public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { + byte[] bytes = toBytes(inputStream); + String uploadToken = qiniuAuth.uploadToken( + qiniuKodoConfig.getBucketName(), + objectName, + buildUploadPolicyExpirySeconds(), + new StringMap() + ); + Response response = qiniuUploadManager.put( + bytes, + objectName, + uploadToken, + null, + contentType, + false + ); + DefaultPutRet putRet = response.jsonToObject(DefaultPutRet.class); + log.info("七牛云文件上传成功, key={}", putRet.key); + return getFileUrl(objectName); + } + + @Override + public InputStream downloadFile(String objectName) throws Exception { + URL url = new URL(getPresignedUrl(objectName, objectStorageProperties.getSignedUrlExpireMinutes())); + return url.openStream(); + } + + @Override + public void deleteFile(String objectName) throws Exception { + qiniuBucketManager.delete(qiniuKodoConfig.getBucketName(), objectName); + log.info("七牛云文件删除成功, key={}", objectName); + } + + @Override + public String getFileUrl(String objectName) { + return normalizeDomain(qiniuKodoConfig.getDomain()) + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception { + if (!Boolean.TRUE.equals(qiniuKodoConfig.getPrivateBucket())) { + return getFileUrl(objectName); + } + int expireMinutes = expiryTimeInMinutes == null || expiryTimeInMinutes <= 0 + ? qiniuKodoConfig.getSignedUrlExpireMinutes() + : expiryTimeInMinutes; + return qiniuAuth.privateDownloadUrl( + getFileUrl(objectName), + TimeUnit.MINUTES.toSeconds(expireMinutes) + ); + } + + private long buildUploadPolicyExpirySeconds() { + return TimeUnit.MINUTES.toSeconds(qiniuKodoConfig.getSignedUrlExpireMinutes()); + } + + private byte[] toBytes(InputStream inputStream) throws Exception { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, read); + } + return outputStream.toByteArray(); + } + } + + private String normalizeDomain(String domain) { + String normalized = domain.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + if (!StringUtils.hasText(normalized)) { + throw new IllegalStateException("Qiniu domain is blank"); + } + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + return "http://" + normalized; + } + return normalized; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/support/ObjectStorageUrlSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/support/ObjectStorageUrlSupport.java new file mode 100644 index 00000000..cffb64ef --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/support/ObjectStorageUrlSupport.java @@ -0,0 +1,203 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.support; + +import com.xiaowang.jayucloud.artlist.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.artlist.core.modules.file.config.QiniuKodoConfig; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.AliyunOssService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.net.URI; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageUrlSupport { + + private static final int UPLOAD_STATUS_SUCCEEDED = 1; + + private final PrimaryObjectStorageService primaryObjectStorageService; + private final QiniuKodoConfig qiniuKodoConfig; + private final AliyunOssService aliyunOssService; + private final ObjectStorageProperties objectStorageProperties; + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + + public String toAccessibleUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return fileUrl; + } + String objectName = extractObjectName(fileUrl); + if (!StringUtils.hasText(objectName)) { + return fileUrl; + } + try { + return objectStorageOrchestrationService.getPresignedUrl( + objectName, + objectStorageProperties.getSignedUrlExpireMinutes() + ); + } catch (Exception e) { + log.warn("生成主对象存储访问链接失败, fileUrl={}", fileUrl, e); + return null; + } + } + + public String toAccessibleUrl(ObjectStorageFileVO file) { + return toAccessibleUrl(file, objectStorageProperties.getSignedUrlExpireMinutes()); + } + + public String toAccessibleUrl(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { + if (file == null) { + return null; + } + try { + return getSignedUrlOrThrow(file, expiryTimeInMinutes); + } catch (Exception e) { + String fallback = hasObjectStorageReference(file) ? null : firstText(file.getFileUrl(), file.getPrimaryUrl()); + log.warn("生成对象存储访问链接失败, fileId={}", file.getId(), e); + return fallback; + } + } + + public String getSignedUrlOrThrow(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { + if (file == null) { + throw new IllegalStateException("No available object storage signed URL: file is null"); + } + String objectName = resolveObjectName(file); + if (!StringUtils.hasText(objectName)) { + throw new IllegalStateException("No available object storage signed URL: objectName is empty"); + } + + Exception primaryFailure = null; + try { + return objectStorageOrchestrationService.getPresignedUrl(file.getId(), objectName, expiryTimeInMinutes); + } catch (Exception e) { + primaryFailure = e; + log.warn("生成主对象存储访问链接失败, fileId={}, objectName={}", file.getId(), objectName, e); + } + + if (Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getBackupUploadStatus())) { + try { + return aliyunOssService.getPresignedUrl(objectName); + } catch (Exception e) { + IllegalStateException failure = new IllegalStateException( + "No available object storage signed URL for fileId=" + file.getId(), + e + ); + failure.addSuppressed(primaryFailure); + throw failure; + } + } + + IllegalStateException failure = new IllegalStateException( + "No available object storage signed URL for fileId=" + file.getId() + ); + failure.addSuppressed(primaryFailure); + throw failure; + } + + public String toStoredUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return fileUrl; + } + String objectName = extractObjectName(fileUrl); + if (!StringUtils.hasText(objectName)) { + return fileUrl; + } + return primaryObjectStorageService.getFileUrl(objectName); + } + + public String extractObjectName(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return ""; + } + + String normalizedUrl = fileUrl.trim(); + if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) { + return stripQuery(stripLeadingSlash(normalizedUrl)); + } + + try { + URI fileUri = URI.create(normalizedUrl); + URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain())); + if (!sameAuthority(fileUri, domainUri)) { + return ""; + } + return stripQuery(stripLeadingSlash(fileUri.getPath())); + } catch (Exception e) { + log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e); + return ""; + } + } + + private String resolveObjectName(ObjectStorageFileVO file) { + if (StringUtils.hasText(file.getObjectName())) { + return file.getObjectName(); + } + String objectName = extractObjectName(file.getPrimaryUrl()); + if (StringUtils.hasText(objectName)) { + return objectName; + } + return extractObjectName(file.getFileUrl()); + } + + private boolean hasObjectStorageReference(ObjectStorageFileVO file) { + return StringUtils.hasText(file.getObjectName()) + || StringUtils.hasText(extractObjectName(file.getPrimaryUrl())) + || StringUtils.hasText(extractObjectName(file.getFileUrl())); + } + + private String firstText(String... values) { + if (values == null) { + return null; + } + for (String value : values) { + if (StringUtils.hasText(value)) { + return value; + } + } + return null; + } + + private String normalizeDomain(String domain) { + String normalized = domain.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + return "http://" + normalized; + } + return normalized; + } + + private boolean sameAuthority(URI left, URI right) { + return left.getScheme() != null + && left.getScheme().equalsIgnoreCase(right.getScheme()) + && left.getHost() != null + && left.getHost().equalsIgnoreCase(right.getHost()) + && normalizedPort(left) == normalizedPort(right); + } + + private int normalizedPort(URI uri) { + if (uri.getPort() >= 0) { + return uri.getPort(); + } + return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; + } + + private String stripLeadingSlash(String rawValue) { + String normalized = rawValue; + while (normalized.startsWith("/")) { + normalized = normalized.substring(1); + } + return normalized; + } + + private String stripQuery(String rawValue) { + int queryIndex = rawValue.indexOf('?'); + return queryIndex >= 0 ? rawValue.substring(0, queryIndex) : rawValue; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/vo/ChunkUploadSessionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/vo/ChunkUploadSessionVO.java new file mode 100644 index 00000000..71ec629a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/vo/ChunkUploadSessionVO.java @@ -0,0 +1,32 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.vo; + +import lombok.Data; + +import java.util.List; + +/** + * 分片上传会话信息 + */ +@Data +public class ChunkUploadSessionVO { + + /** + * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String uploadId; + + /** + * Field `chunkSize` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer chunkSize; + + /** + * Field `totalChunks` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer totalChunks; + + /** + * Field `uploadedChunks` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List uploadedChunks; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/vo/ObjectStorageFileVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/vo/ObjectStorageFileVO.java new file mode 100644 index 00000000..aaf89638 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/file/vo/ObjectStorageFileVO.java @@ -0,0 +1,82 @@ +package com.xiaowang.jayucloud.artlist.core.modules.file.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 对象存储文件信息表 VO + * 用于前端展示文件信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ObjectStorageFileVO { + + /** + * 文件记录唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 文件名称 + */ + private String fileName; + + /** + * 文件访问链接 + */ + private String fileUrl; + + private String objectName; + + private String primaryProvider; + + private String primaryUrl; + + private String backupProvider; + + private String backupUrl; + + private String contentType; + + private Long fileSize; + + private Integer primaryUploadStatus; + + private Integer backupUploadStatus; + + private Integer backupRetryCount; + + private String backupLastError; + + private LocalDateTime backupUploadedAt; + + private LocalDateTime backupLastRetryTime; + + /** + * 文件上传时间 + */ + private LocalDateTime createTime; + + /** + * 文件状态:1-可用,0-不可用,2-回收站 + */ + private Integer status; + + /** + * 文件状态名称 + */ + private String statusName; + + /** + * 文件删除时间(NULL表示未删除) + */ + private LocalDateTime deleteTime; + + /** + * 文件移入回收站时间(NULL表示未移入) + */ + private LocalDateTime recycleTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/controller/front/MessageHubPushConfigController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/controller/front/MessageHubPushConfigController.java new file mode 100644 index 00000000..ed7f9550 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/controller/front/MessageHubPushConfigController.java @@ -0,0 +1,110 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.MessageHubPushConfigDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.MessageHubPushTestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.MessageHubPushConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/messagehub-push-config", "/api/messagehub-push-config", "/admin/messagehub-push-config"}) +/** + * MessageHubPushConfigController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class MessageHubPushConfigController { + /** + * Variable `configService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigService configService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("messagehub:config:manage") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> list(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.listConfigs(currentUser)); + } + + @PostMapping("/admin/create") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-create", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody MessageHubPushConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.createConfig(currentUser, dto)); + } + + @PutMapping("/admin/{id}") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-update", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.updateConfig(currentUser, id, dto)); + } + + @PutMapping("/admin/{id}/status") + @RequirePermission("messagehub:config:manage") + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer enabled) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.updateStatus(currentUser, id, enabled)); + } + + @PostMapping("/admin/{id}/test") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-test", ttlSeconds = 8, message = "测试投递处理中,请勿重复提交") + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result test(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushTestDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.testConfig(currentUser, id, dto)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/MessageHubPushConfigDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/MessageHubPushConfigDTO.java new file mode 100644 index 00000000..741d437e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/MessageHubPushConfigDTO.java @@ -0,0 +1,85 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * MessageHubPushConfigDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushConfigDTO { + + @NotBlank(message = "场景编码不能为空") + @Size(max = 80, message = "场景编码不能超过80个字符") + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + + @NotBlank(message = "场景名称不能为空") + @Size(max = 100, message = "场景名称不能超过100个字符") + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + + @NotBlank(message = "消息平台不能为空") + @Size(max = 20, message = "消息平台不能超过20个字符") + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform = "SMS"; + + @NotBlank(message = "消息类型不能为空") + @Size(max = 30, message = "消息类型不能超过30个字符") + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType = "VERIFICATION"; + + @NotBlank(message = "队列名称不能为空") + @Size(max = 100, message = "队列名称不能超过100个字符") + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + + @NotBlank(message = "来源系统不能为空") + @Size(max = 80, message = "来源系统不能超过80个字符") + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + + @NotBlank(message = "模板编码不能为空") + @Size(max = 100, message = "模板编码不能超过100个字符") + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + + @Size(max = 30, message = "发送方式不能超过30个字符") + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled = 1; + + @Size(max = 255, message = "备注不能超过255个字符") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/MessageHubPushTestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/MessageHubPushTestDTO.java new file mode 100644 index 00000000..1fead6d6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/MessageHubPushTestDTO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@Data +/** + * MessageHubPushTestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushTestDTO { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java new file mode 100644 index 00000000..4293fee5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 微信小程序自动登录请求。 + */ +@Data +public class WechatMiniAutoLoginRequestDTO { + + @NotBlank(message = "微信登录凭证不能为空") + /** + * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String wxCode; + + /** + * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long preferredShopId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java new file mode 100644 index 00000000..bd6de7d9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.util.Map; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +/** + * 微信小程序补选店铺后确认登录请求。 + */ +@Data +public class WechatMiniConfirmLoginRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "登录票据不能为空") + /** + * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ticket; + + @NotNull(message = "店铺不能为空") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * Purpose: agreementAccepted supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java new file mode 100644 index 00000000..32d3fc9d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java @@ -0,0 +1,49 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.util.Map; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +/** + * 微信小程序手机号一键登录请求。 + */ +@Data +public class WechatMiniPhoneLoginRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "微信登录凭证不能为空") + /** + * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String wxCode; + + @NotBlank(message = "手机号授权凭证不能为空") + /** + * Field `phoneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phoneCode; + + /** + * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long preferredShopId; + + /** + * Purpose: agreementAccepted supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/BusinessEventOutboxDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/BusinessEventOutboxDO.java new file mode 100644 index 00000000..678883af --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/BusinessEventOutboxDO.java @@ -0,0 +1,103 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_business_event_outbox") +/** + * Purpose: BusinessEventOutboxDO supports BusinessEventOutboxDO.java by holding or executing the business event outbox do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BusinessEventOutboxDO extends BaseEntity { + + @TableField("event_key") + /** + * Purpose: eventKey supports BusinessEventOutboxDO.java by holding or executing the event key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String eventKey; + + @TableField("event_type") + /** + * Purpose: eventType supports BusinessEventOutboxDO.java by holding or executing the event type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String eventType; + + @TableField("business_type") + /** + * Purpose: businessType supports BusinessEventOutboxDO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + + @TableField("business_id") + /** + * Purpose: businessId supports BusinessEventOutboxDO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + + @TableField("payload_json") + /** + * Purpose: payloadJson supports BusinessEventOutboxDO.java by holding or executing the payload json business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String payloadJson; + + @TableField("status") + /** + * Purpose: status supports BusinessEventOutboxDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String status; + + @TableField("retry_count") + /** + * Purpose: retryCount supports BusinessEventOutboxDO.java by holding or executing the retry count business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer retryCount; + + @TableField("next_retry_time") + /** + * Purpose: nextRetryTime supports BusinessEventOutboxDO.java by holding or executing the next retry time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime nextRetryTime; + + @TableField("last_error") + /** + * Purpose: lastError supports BusinessEventOutboxDO.java by holding or executing the last error business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String lastError; + + @TableField("claimed_at") + /** + * Purpose: claimedAt supports BusinessEventOutboxDO.java by holding or executing the claimed at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime claimedAt; + + @TableField("processed_at") + /** + * Purpose: processedAt supports BusinessEventOutboxDO.java by holding or executing the processed at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime processedAt; + + @TableField("is_delete") + /** + * Purpose: isDelete supports BusinessEventOutboxDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/MessageHubPushConfigDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/MessageHubPushConfigDO.java new file mode 100644 index 00000000..41154071 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/MessageHubPushConfigDO.java @@ -0,0 +1,93 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * JayuCloudArtList 调用 MessageHub 的场景级配置。 + * + *

这里不保存 Spug、阿里云等供应商密钥;这些真实通道仍由 MessageHub 自己管理。 + * 本表只描述 JayuCloudArtList 在某个业务功能里投递 MessageHub 时要携带的参数。

+ */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_messagehub_push_config") +public class MessageHubPushConfigDO extends BaseEntity { + + @TableField("scene_code") + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + + @TableField("scene_name") + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + + @TableField("platform") + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform; + + @TableField("msg_type") + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType; + + @TableField("queue_name") + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + + @TableField("source_system") + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + + @TableField("template_code") + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + + @TableField("channel_id") + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + + @TableField("send_method") + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + + @TableField("enabled") + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/WechatMiniBindingDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/WechatMiniBindingDO.java new file mode 100644 index 00000000..3a9e294a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/entity/WechatMiniBindingDO.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 微信小程序用户绑定关系。 + */ +@Getter +@Setter +@TableName("t_wechat_mini_binding") +public class WechatMiniBindingDO extends BaseEntity { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("app_id") + /** + * Field `appId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String appId; + + @TableField("openid") + /** + * Field `openId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String openId; + + @TableField("unionid") + /** + * Field `unionId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String unionId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/BusinessEventOutboxMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/BusinessEventOutboxMapper.java new file mode 100644 index 00000000..2ba73953 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/BusinessEventOutboxMapper.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.BusinessEventOutboxDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDateTime; +import java.util.List; + +@Mapper +/** + * Purpose: BusinessEventOutboxMapper supports BusinessEventOutboxMapper.java by holding or executing the business event outbox mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface BusinessEventOutboxMapper extends BaseMapper { + + @Select("SELECT * FROM t_business_event_outbox WHERE status IN ('PENDING', 'FAILED') AND is_delete = 0 AND (next_retry_time IS NULL OR next_retry_time <= #{now}) ORDER BY create_time ASC, id ASC LIMIT #{limit}") + List selectDueEvents(@Param("now") LocalDateTime now, @Param("limit") int limit); + + @Update("UPDATE t_business_event_outbox SET status = 'PROCESSING', claimed_at = #{now} WHERE id = #{id} AND status IN ('PENDING', 'FAILED') AND is_delete = 0") + int claimDueEvent(@Param("id") Long id, @Param("now") LocalDateTime now); + + @Update("UPDATE t_business_event_outbox SET status = 'SUCCEEDED', processed_at = #{now}, last_error = NULL WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0") + int markSucceeded(@Param("id") Long id, @Param("now") LocalDateTime now); + + @Update("UPDATE t_business_event_outbox SET status = 'FAILED', retry_count = COALESCE(retry_count, 0) + 1, next_retry_time = #{nextRetryTime}, last_error = #{lastError} WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0") + int markFailed(@Param("id") Long id, @Param("nextRetryTime") LocalDateTime nextRetryTime, @Param("lastError") String lastError); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/MessageHubPushConfigMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/MessageHubPushConfigMapper.java new file mode 100644 index 00000000..f8f50829 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/MessageHubPushConfigMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHubPushConfigDO; + +/** + * MessageHubPushConfigMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface MessageHubPushConfigMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/WechatMiniBindingMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/WechatMiniBindingMapper.java new file mode 100644 index 00000000..7af46768 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/mapper/WechatMiniBindingMapper.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.WechatMiniBindingDO; + +/** + * 微信小程序绑定关系 Mapper。 + */ +public interface WechatMiniBindingMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/BusinessEventOutboxService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/BusinessEventOutboxService.java new file mode 100644 index 00000000..00f78304 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/BusinessEventOutboxService.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service; + +/** + * Purpose: BusinessEventOutboxService supports BusinessEventOutboxService.java by holding or executing the business event outbox service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface BusinessEventOutboxService { + + void enqueueOrderCompleted(Long orderId); + + void processDueEvents(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MapService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MapService.java new file mode 100644 index 00000000..2fef541a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MapService.java @@ -0,0 +1,15 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * Purpose: MapService supports MapService.java by holding or executing the map service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface MapService { + + String normalizeProvider(String provider); + + Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MessageHubClientService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MessageHubClientService.java new file mode 100644 index 00000000..d6717a99 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MessageHubClientService.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service; + + +/** + * MessageHub客户端服务接口 + * 用于调用MessageHub服务发送消息 + * + * @author xiaowang + * @date 2026-03-03 + */ +public interface MessageHubClientService { + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + void sendSmsVerificationCode(String phone, String code); + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + void sendSmsVerificationCode(String sceneCode, String phone, String code); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MessageHubPushConfigService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MessageHubPushConfigService.java new file mode 100644 index 00000000..da4ebec2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/MessageHubPushConfigService.java @@ -0,0 +1,71 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service; + +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.MessageHubPushConfigDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.MessageHubPushTestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHubPushConfigDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.MessageHubPushConfigVO; + +import java.util.List; + +/** + * MessageHubPushConfigService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface MessageHubPushConfigService { + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listConfigs(UserDO currentUser); + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto); + + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateStatus(UserDO currentUser, Long id, Integer enabled); + + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + MessageHubPushConfigDO getEnabledConfig(String sceneCode); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/WechatMiniAuthService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/WechatMiniAuthService.java new file mode 100644 index 00000000..fa8bcbfb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/WechatMiniAuthService.java @@ -0,0 +1,43 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service; + +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLoginResultVO; + +/** + * 微信小程序登录编排服务。 + */ +public interface WechatMiniAuthService { + + /** + * Run business method `autoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO); + + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO); + + /** + * Run business method `confirmLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO); + + /** + * Run business method `invalidateBindingsByUserId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + void invalidateBindingsByUserId(Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/WechatMiniClientService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/WechatMiniClientService.java new file mode 100644 index 00000000..1e0f5fe1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/WechatMiniClientService.java @@ -0,0 +1,42 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service; + + +/** + * 微信小程序开放接口客户端。 + */ +public interface WechatMiniClientService { + + /** + * Run business method `code2Session`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wxCode parameter `wxCode` supplied by the caller + * @return SessionInfo result consumed by the caller or returned to the frontend + */ + SessionInfo code2Session(String wxCode); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneCode parameter `phoneCode` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ + String getPhoneNumber(String phoneCode); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String getConfiguredAppId(); + + /** + * Run business method `SessionInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + * @param sessionKey parameter `sessionKey` supplied by the caller + * @return record result consumed by the caller or returned to the frontend + */ + record SessionInfo(String openId, String unionId, String sessionKey) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java new file mode 100644 index 00000000..1f56326e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java @@ -0,0 +1,92 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.BusinessEventOutboxDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.mapper.BusinessEventOutboxMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +import com.xiaowang.jayucloud.artlist.core.modules.order.service.impl.OrderServiceImpl; + +@Component +@RequiredArgsConstructor +/** + * Purpose: BusinessEventOutboxProcessor supports BusinessEventOutboxProcessor.java by holding or executing the business event outbox processor business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BusinessEventOutboxProcessor { + + /** + * Purpose: EVENT_ORDER_COMPLETED supports BusinessEventOutboxProcessor.java by holding or executing the event order completed business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED"; + /** + * Purpose: PROCESS_BATCH_SIZE supports BusinessEventOutboxProcessor.java by holding or executing the process batch size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int PROCESS_BATCH_SIZE = 20; + + /** + * Purpose: outboxMapper supports BusinessEventOutboxProcessor.java by holding or executing the outbox mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final BusinessEventOutboxMapper outboxMapper; + /** + * Purpose: orderMapper supports BusinessEventOutboxProcessor.java by holding or executing the order mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final OrderMapper orderMapper; + /** + * Purpose: orderService supports BusinessEventOutboxProcessor.java by holding or executing the order service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final OrderServiceImpl orderService; + + @Scheduled(fixedDelay = 2000L) + @Transactional + /** + * Purpose: processDueEvents supports BusinessEventOutboxProcessor.java by holding or executing the process due events business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void processDueEvents() { + LocalDateTime now = LocalDateTime.now(); + List events = outboxMapper.selectDueEvents(now, PROCESS_BATCH_SIZE); + for (BusinessEventOutboxDO event : events) { + processOne(event); + } + } + + @Transactional + /** + * Purpose: processOne supports BusinessEventOutboxProcessor.java by holding or executing the process one business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void processOne(BusinessEventOutboxDO event) { + if (event == null || event.getId() == null) { + return; + } + LocalDateTime now = LocalDateTime.now(); + if (outboxMapper.claimDueEvent(event.getId(), now) == 0) { + return; + } + try { + if (EVENT_ORDER_COMPLETED.equals(event.getEventType())) { + OrderDO order = orderMapper.selectById(event.getBusinessId()); + orderService.createPendingArtistReviewTasksAndNotifyFromOutbox(order); + } + outboxMapper.markSucceeded(event.getId(), LocalDateTime.now()); + } catch (Exception exception) { + int retryCount = event.getRetryCount() == null ? 0 : event.getRetryCount(); + LocalDateTime nextRetryTime = LocalDateTime.now().plusSeconds(Math.min(300L, (long) Math.pow(2, retryCount) * 10L)); + outboxMapper.markFailed(event.getId(), nextRetryTime, + BusinessEventOutboxServiceImpl.limit(exception.getMessage(), 500)); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java new file mode 100644 index 00000000..6eff89d7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java @@ -0,0 +1,85 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.BusinessEventOutboxDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.mapper.BusinessEventOutboxMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.BusinessEventOutboxService; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +/** + * Purpose: BusinessEventOutboxServiceImpl supports BusinessEventOutboxServiceImpl.java by holding or executing the business event outbox service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BusinessEventOutboxServiceImpl implements BusinessEventOutboxService { + + /** + * Purpose: EVENT_ORDER_COMPLETED supports BusinessEventOutboxServiceImpl.java by holding or executing the event order completed business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED"; + /** + * Purpose: BUSINESS_ORDER supports BusinessEventOutboxServiceImpl.java by holding or executing the business order business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String BUSINESS_ORDER = "ORDER"; + /** + * Purpose: STATUS_PENDING supports BusinessEventOutboxServiceImpl.java by holding or executing the status pending business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String STATUS_PENDING = "PENDING"; + + /** + * Purpose: outboxMapper supports BusinessEventOutboxServiceImpl.java by holding or executing the outbox mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final BusinessEventOutboxMapper outboxMapper; + + @Override + /** + * Purpose: enqueueOrderCompleted supports BusinessEventOutboxServiceImpl.java by holding or executing the enqueue order completed business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void enqueueOrderCompleted(Long orderId) { + if (orderId == null) { + return; + } + BusinessEventOutboxDO event = new BusinessEventOutboxDO(); + event.setEventKey("ORDER:" + orderId + ":COMPLETED"); + event.setEventType(EVENT_ORDER_COMPLETED); + event.setBusinessType(BUSINESS_ORDER); + event.setBusinessId(orderId); + event.setPayloadJson("{\"orderId\":" + orderId + "}"); + event.setStatus(STATUS_PENDING); + event.setRetryCount(0); + event.setNextRetryTime(LocalDateTime.now()); + event.setIsDelete(0); + try { + outboxMapper.insert(event); + } catch (DuplicateKeyException ignored) { + // The order-completed event is idempotent by event_key. + } + } + + @Override + /** + * Purpose: processDueEvents supports BusinessEventOutboxServiceImpl.java by holding or executing the process due events business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void processDueEvents() { + // Processing is owned by BusinessEventOutboxProcessor. This method remains on + // the public service contract for callers that only need enqueue capability. + } + + static String limit(String value, int max) { + if (!StringUtils.hasText(value) || value.length() <= max) { + return value; + } + return value.substring(0, max); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MapServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MapServiceImpl.java new file mode 100644 index 00000000..df27c20b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MapServiceImpl.java @@ -0,0 +1,61 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MapService; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriUtils; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + +@Service +/** + * Purpose: MapServiceImpl supports MapServiceImpl.java by holding or executing the map service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class MapServiceImpl implements MapService { + + @Override + /** + * Purpose: normalizeProvider supports MapServiceImpl.java by holding or executing the normalize provider business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String normalizeProvider(String provider) { + if (!StringUtils.hasText(provider)) { + return "TENCENT"; + } + String value = provider.trim().toUpperCase(); + return "AMAP".equals(value) || "TENCENT".equals(value) ? value : "TENCENT"; + } + + @Override + /** + * Purpose: buildNavigationUrls supports MapServiceImpl.java by holding or executing the build navigation urls business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude) { + Map urls = new LinkedHashMap<>(); + if (longitude == null || latitude == null) { + return urls; + } + String name = encode(StringUtils.hasText(shopName) ? shopName : "店铺位置"); + String addr = encode(StringUtils.hasText(address) ? address : ""); + String lon = longitude.stripTrailingZeros().toPlainString(); + String lat = latitude.stripTrailingZeros().toPlainString(); + + urls.put("AMAP", "https://uri.amap.com/navigation?to=" + lon + "," + lat + "," + name + "&mode=car&policy=1&src=jayucloud-artlist&coordinate=gaode&callnative=1"); + urls.put("TENCENT", "https://apis.map.qq.com/uri/v1/routeplan?type=drive&tocoord=" + lat + "," + lon + "&to=" + name + "&referer=jayucloud-artlist"); + urls.put("BROWSER", "https://apis.map.qq.com/uri/v1/marker?marker=coord:" + lat + "," + lon + ";title:" + name + ";addr:" + addr + "&referer=jayucloud-artlist"); + return urls; + } + + /** + * Purpose: encode supports MapServiceImpl.java by holding or executing the encode business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String encode(String value) { + return UriUtils.encode(value, StandardCharsets.UTF_8); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java new file mode 100644 index 00000000..9e4ab43d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -0,0 +1,170 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.artlist.core.config.BrandProperties; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHubPushConfigDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageBuilder; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +/** + * JayuCloudArtList 到 MessageHub 的投递客户端。 + * + *

JayuCloudArtList 只决定某个业务场景使用哪组 MessageHub 对接参数,不直接连接 Spug、 + * 阿里云等短信供应商。真实通道选择和供应商密钥仍归 MessageHub 管理。

+ */ +@Slf4j +@Service +@RefreshScope +@RequiredArgsConstructor +public class MessageHubClientServiceImpl implements MessageHubClientService { + /** + * Variable `rabbitTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RabbitTemplate rabbitTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `messageHubPushConfigService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigService messageHubPushConfigService; + /** + * 平台品牌文案配置。 + */ + private final BrandProperties brandProperties; + + @Value("${messagehub.client.sms-queue:smsQueue}") + /** + * Purpose: smsQueue supports MessageHubClientServiceImpl.java by holding or executing the sms queue business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String smsQueue; + + @Value("${messagehub.client.source-system:jayucloud-artlist}") + /** + * Purpose: sourceSystem supports MessageHubClientServiceImpl.java by holding or executing the source system business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sourceSystem; + + @Value("${messagehub.client.verify-template-code:SPUG0001}") + /** + * Purpose: verifyTemplateCode supports MessageHubClientServiceImpl.java by holding or executing the verify template code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String verifyTemplateCode; + + @Value("${messagehub.client.send-method:SPUG}") + /** + * Purpose: sendMethod supports MessageHubClientServiceImpl.java by holding or executing the send method business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sendMethod; + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + public void sendSmsVerificationCode(String phone, String code) { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, code); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + public void sendSmsVerificationCode(String sceneCode, String phone, String code) { + try { + MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode); + String messageId = snowflakeIdGenerator.nextIdString(); + Map messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId); + String jsonBody = objectMapper.writeValueAsString(messageBody); + Message message = MessageBuilder + .withBody(jsonBody.getBytes(StandardCharsets.UTF_8)) + .setContentType("application/json") + .setContentEncoding(StandardCharsets.UTF_8.name()) + .setMessageId(messageId) + .build(); + + String queueName = config == null ? smsQueue : config.getQueueName(); + rabbitTemplate.convertAndSend(queueName, message); + log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}", + sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); + } catch (Exception exception) { + log.error("发送短信验证码失败", exception); + throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); + } + } + + /** + * Run business method `buildSmsMessageBody`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map buildSmsMessageBody(MessageHubPushConfigDO config, String sceneCode, String phone, String code, String messageId) { + String platform = config == null ? "SMS" : config.getPlatform(); + String resolvedSendMethod = config == null ? sendMethod : config.getSendMethod(); + + Map messageBody = new HashMap<>(); + messageBody.put("receiver", phone); + messageBody.put("channelType", platform); + messageBody.put("platform", platform); + messageBody.put("msgType", config == null ? "VERIFICATION" : config.getMsgType()); + messageBody.put("templateCode", config == null ? verifyTemplateCode : config.getTemplateCode()); + messageBody.put("sourceSystem", config == null ? sourceSystem : config.getSourceSystem()); + messageBody.put("uniqueId", messageId); + messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"); + if (config != null && config.getChannelId() != null) { + messageBody.put("channelId", config.getChannelId()); + } + + Map templateParams = new HashMap<>(); + templateParams.put("name", brandProperties.getMessageTemplateName()); + templateParams.put("code", code); + templateParams.put("min", "5"); + templateParams.put("minutes", "5"); + templateParams.put("number", "5"); + templateParams.put("sceneCode", sceneCode); + messageBody.put("templateParams", templateParams); + return messageBody; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java new file mode 100644 index 00000000..ed0ee925 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java @@ -0,0 +1,328 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.MessageHubPushConfigDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.MessageHubPushTestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHubPushConfigDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.mapper.MessageHubPushConfigMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.MessageHubPushConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * MessageHubPushConfigServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class MessageHubPushConfigServiceImpl implements MessageHubPushConfigService { + /** + * Variable `configMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigMapper configMapper; + @Lazy + /** + * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubClientService messageHubClientService; + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listConfigs(UserDO currentUser) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + return configMapper.selectList(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .orderByAsc(MessageHubPushConfigDO::getSceneCode)) + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + String sceneCode = normalizeSceneCode(dto.getSceneCode()); + MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该场景编码已存在"); + } + MessageHubPushConfigDO config = new MessageHubPushConfigDO(); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(config, dto, sceneCode); + config.setIsDelete(0); + configMapper.insert(config); + return config.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + String sceneCode = normalizeSceneCode(dto.getSceneCode()); + MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .ne(MessageHubPushConfigDO::getId, id) + .last("LIMIT 1")); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该场景编码已存在"); + } + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(config, dto, sceneCode); + configMapper.updateById(config); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateStatus(UserDO currentUser, Long id, Integer enabled) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + config.setEnabled(Integer.valueOf(1).equals(enabled) ? 1 : 0); + configMapper.updateById(config); + return true; + } + + @Override + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + messageHubClientService.sendSmsVerificationCode(config.getSceneCode(), dto.getPhone(), "123456"); + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + public MessageHubPushConfigDO getEnabledConfig(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + return null; + } + return configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, normalizeSceneCode(sceneCode)) + .eq(MessageHubPushConfigDO::getEnabled, 1) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void apply(MessageHubPushConfigDO config, MessageHubPushConfigDTO dto, String sceneCode) { + config.setSceneCode(sceneCode); + config.setSceneName(dto.getSceneName().trim()); + config.setPlatform(normalizeUpper(dto.getPlatform(), "SMS")); + config.setMsgType(normalizeUpper(dto.getMsgType(), "VERIFICATION")); + config.setQueueName(dto.getQueueName().trim()); + config.setSourceSystem(dto.getSourceSystem().trim()); + config.setTemplateCode(dto.getTemplateCode().trim()); + config.setChannelId(dto.getChannelId()); + config.setSendMethod(StringUtils.hasText(dto.getSendMethod()) ? dto.getSendMethod().trim().toUpperCase(Locale.ROOT) : null); + config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); + config.setRemark(dto.getRemark()); + } + + /** + * Run business method `requireConfig`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + private MessageHubPushConfigDO requireConfig(Long id) { + MessageHubPushConfigDO config = configMapper.selectById(id); + if (config == null || Integer.valueOf(1).equals(config.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("MessageHub 推送配置不存在"); + } + return config; + } + + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅平台管理员可以管理消息推送配置"); + } + } + + /** + * Run business method `normalizeSceneCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeSceneCode(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("场景编码不能为空"); + } + return sceneCode.trim().toUpperCase(Locale.ROOT); + } + + /** + * Run business method `normalizeUpper`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param fallback parameter `fallback` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeUpper(String value, String fallback) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : fallback; + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @return private MessageHubPushConfigVO result consumed by the caller or returned to the frontend + */ + private MessageHubPushConfigVO toVO(MessageHubPushConfigDO config) { + MessageHubPushConfigVO vo = new MessageHubPushConfigVO(); + vo.setId(config.getId()); + vo.setSceneCode(config.getSceneCode()); + vo.setSceneName(config.getSceneName()); + vo.setPlatform(config.getPlatform()); + vo.setMsgType(config.getMsgType()); + vo.setQueueName(config.getQueueName()); + vo.setSourceSystem(config.getSourceSystem()); + vo.setTemplateCode(config.getTemplateCode()); + vo.setChannelId(config.getChannelId()); + vo.setSendMethod(config.getSendMethod()); + vo.setEnabled(config.getEnabled()); + vo.setRemark(config.getRemark()); + vo.setCreateTime(config.getCreateTime()); + vo.setUpdateTime(config.getUpdateTime()); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java new file mode 100644 index 00000000..e854db38 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -0,0 +1,762 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLoginResultVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +/** + * 微信小程序登录编排服务实现。 + */ +@Service +@Slf4j +@RequiredArgsConstructor +public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { + + /** + * Purpose: PHONE_REGEX supports WechatMiniAuthServiceImpl.java by holding or executing the phone regex business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; + /** + * Purpose: TICKET_KEY_PREFIX supports WechatMiniAuthServiceImpl.java by holding or executing the ticket key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:"; + private static final Duration TICKET_TTL = Duration.ofMinutes(5); + /** + * Variable `wechatMiniClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniClientService wechatMiniClientService; + /** + * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniBindingMapper wechatMiniBindingMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Override + /** + * Run business method `autoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + public WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO) { + WechatMiniClientService.SessionInfo sessionInfo; + try { + sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); + } catch (RuntimeException exception) { + log.warn("微信小程序自动登录识别失败,回退手动登录: {}", exception.getMessage()); + return WechatMiniLoginResultVO.needManualLogin("微信自动识别失败,请手动登录"); + } + + WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId()); + if (bindingDO == null) { + return WechatMiniLoginResultVO.needManualLogin("当前微信尚未绑定账号,请使用微信手机号一键登录。"); + } + + UserDO userDO = getAvailableBoundUser(bindingDO); + if (userDO == null) { + return WechatMiniLoginResultVO.needManualLogin("当前微信绑定已失效,请重新使用微信手机号一键登录。"); + } + + return loginOrSelectShop(userDO, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + + @Override + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + public WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO) { + WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); + String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode())); + if (!StringUtils.hasText(phone) || !phone.matches(PHONE_REGEX)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取到的微信手机号格式不正确"); + } + + WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId()); + if (bindingDO != null) { + UserDO boundUser = getAvailableBoundUser(bindingDO); + if (boundUser != null) { + UserDO phoneUser = findActiveUserByPhone(phone); + if (phoneUser != null && !Objects.equals(phoneUser.getId(), boundUser.getId())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("当前微信已绑定其他账号,无法关联该手机号"); + } + return loginOrSelectShop(boundUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + } + + UserDO phoneUser = findActiveUserByPhone(phone); + if (phoneUser != null) { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneUser parameter `phoneUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(phoneUser); + return loginOrSelectShop(phoneUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + + List shops = userShopBindingSupport.listAllActiveShopOptions(); + if (shops.isEmpty()) { + return WechatMiniLoginResultVO.needManualLogin("当前暂无可登录门店,请稍后再试。"); + } + return buildSelectShopResult( + "首次使用微信手机号一键登录,请先选择本次登录门店。", + shops, + new TicketPayload(null, phone, sessionInfo.openId(), sessionInfo.unionId(), true) + ); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `confirmLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + public WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO) { + Long shopId = normalizeShopId(requestDTO.getShopId()); + if (shopId == null) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("请选择登录门店"); + } + + TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket()); + LoginResponseVO loginResponse; + if (ticketPayload.getUserId() != null) { + loginResponse = userService.loginByUserId(ticketPayload.getUserId(), shopId); + } else if (StringUtils.hasText(ticketPayload.getPhone())) { + loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId); + } else { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("登录票据数据不完整,请重新发起微信一键登录"); + } + + ensureBinding(loginResponse.getUserInfo().getId(), ticketPayload.getOpenId(), ticketPayload.getUnionId()); + deleteTicketPayload(requestDTO.getTicket()); + return WechatMiniLoginResultVO.success( + Boolean.TRUE.equals(ticketPayload.getNewUser()) ? "注册并登录成功" : "登录成功", + loginResponse, + Boolean.TRUE.equals(ticketPayload.getNewUser()) + ); + } + + @Override + /** + * Run business method `invalidateBindingsByUserId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + public void invalidateBindingsByUserId(Long userId) { + if (userId == null) { + return; + } + wechatMiniBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(WechatMiniBindingDO::getUserId, userId) + .set(WechatMiniBindingDO::getStatus, 0) + .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) + ); + } + + private WechatMiniLoginResultVO loginOrSelectShop( + UserDO userDO, + Long preferredShopId, + WechatMiniClientService.SessionInfo sessionInfo, + boolean newUser + ) { + if (Integer.valueOf(4).equals(userDO.getType())) { + List platformAdminShops = resolvePlatformAdminLoginShops(userDO); + if (platformAdminShops.isEmpty()) { + LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), null); + ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId()); + return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser); + } + return buildSelectShopResult( + "平台管理员可选择任意门店作为本次登录门店。", + platformAdminShops, + new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser) + ); + } + + List activeShops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + if (activeShops.isEmpty()) { + return WechatMiniLoginResultVO.needManualLogin("当前账号没有可登录的门店,请联系管理员处理。"); + } + + Long resolvedShopId = resolvePreferredOrOnlyShop(activeShops, preferredShopId); + if (resolvedShopId != null) { + LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), resolvedShopId); + ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId()); + return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser); + } + + return buildSelectShopResult( + "该账号绑定了多家门店,请选择本次登录门店。", + activeShops, + new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser) + ); + } + + /** + * Purpose: resolvePlatformAdminLoginShops supports WechatMiniAuthServiceImpl.java by holding or executing the resolve platform admin login shops business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List resolvePlatformAdminLoginShops(UserDO userDO) { + LoginShopSelectionVO selection = null; + if (StringUtils.hasText(userDO.getPhone())) { + selection = userService.getLoginShopSelectionByPhone(userDO.getPhone()); + } else if (StringUtils.hasText(userDO.getAccount())) { + selection = userService.getLoginShopSelectionByAccount(userDO.getAccount()); + } + return selection == null || selection.getShops() == null ? List.of() : selection.getShops(); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bindingDO parameter `bindingDO` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO getAvailableBoundUser(WechatMiniBindingDO bindingDO) { + UserDO userDO = userMapper.selectById(bindingDO.getUserId()); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + deactivateBinding(bindingDO.getId()); + return null; + } + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + return userDO; + } + + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUserAvailable(UserDO userDO) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("账号不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("账号已停用"); + } + } + + /** + * Run business method `findActiveUserByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO findActiveUserByPhone(String phone) { + if (!StringUtils.hasText(phone)) { + return null; + } + return userMapper.selectOne( + new LambdaQueryWrapper() + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + } + + /** + * Run business method `findBindingByOpenId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openId parameter `openId` supplied by the caller + * @return private WechatMiniBindingDO result consumed by the caller or returned to the frontend + */ + private WechatMiniBindingDO findBindingByOpenId(String openId) { + return wechatMiniBindingMapper.selectOne( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId()) + .eq(WechatMiniBindingDO::getOpenId, openId) + .eq(WechatMiniBindingDO::getStatus, 1) + .last("limit 1") + ); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appId parameter `appId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listBindingsByOpenId(String appId, String openId) { + if (!StringUtils.hasText(openId)) { + return List.of(); + } + return wechatMiniBindingMapper.selectList( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getOpenId, openId) + .orderByDesc(WechatMiniBindingDO::getStatus) + .orderByDesc(WechatMiniBindingDO::getUpdateTime) + .orderByDesc(WechatMiniBindingDO::getCreateTime) + .orderByDesc(WechatMiniBindingDO::getId) + ); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appId parameter `appId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listBindingsByUserId(String appId, Long userId) { + if (userId == null) { + return List.of(); + } + return wechatMiniBindingMapper.selectList( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getUserId, userId) + .orderByDesc(WechatMiniBindingDO::getStatus) + .orderByDesc(WechatMiniBindingDO::getUpdateTime) + .orderByDesc(WechatMiniBindingDO::getCreateTime) + .orderByDesc(WechatMiniBindingDO::getId) + ); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `ensureBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + */ + protected void ensureBinding(Long userId, String openId, String unionId) { + if (userId == null || !StringUtils.hasText(openId)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信绑定信息不完整"); + } + + String appId = wechatMiniClientService.getConfiguredAppId(); + List openIdBindings = listBindingsByOpenId(appId, openId); + List userBindings = listBindingsByUserId(appId, userId); + + /** + * Run business method `validateExclusiveActiveBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param openIdBindings parameter `openIdBindings` supplied by the caller + * @param userBindings parameter `userBindings` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateExclusiveActiveBinding(userId, openId, openIdBindings, userBindings); + + WechatMiniBindingDO targetBinding = pickTargetBinding(userId, openId, openIdBindings, userBindings); + if (targetBinding == null) { + WechatMiniBindingDO bindingDO = new WechatMiniBindingDO(); + bindingDO.setUserId(userId); + bindingDO.setAppId(appId); + bindingDO.setOpenId(openId); + bindingDO.setUnionId(unionId); + bindingDO.setStatus(1); + wechatMiniBindingMapper.insert(bindingDO); + return; + } + + targetBinding.setUserId(userId); + targetBinding.setAppId(appId); + targetBinding.setOpenId(openId); + targetBinding.setUnionId(unionId); + targetBinding.setStatus(1); + targetBinding.setUpdateTime(LocalDateTime.now()); + wechatMiniBindingMapper.updateById(targetBinding); + + deactivateDuplicateBindings(targetBinding.getId(), mergeBindings(openIdBindings, userBindings)); + } + + /** + * Run business method `deactivateBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bindingId parameter `bindingId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deactivateBinding(Long bindingId) { + if (bindingId == null) { + return; + } + wechatMiniBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(WechatMiniBindingDO::getId, bindingId) + .set(WechatMiniBindingDO::getStatus, 0) + .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) + ); + } + + private void validateExclusiveActiveBinding( + Long userId, + String openId, + List openIdBindings, + List userBindings + ) { + boolean openIdBoundToOtherUser = openIdBindings.stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .anyMatch(binding -> !Objects.equals(binding.getUserId(), userId)); + if (openIdBoundToOtherUser) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("当前微信已绑定其他账号,无法完成登录"); + } + + boolean userBoundToOtherWechat = userBindings.stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .anyMatch(binding -> !Objects.equals(binding.getOpenId(), openId)); + if (userBoundToOtherWechat) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("当前账号已绑定其他微信,请联系管理员处理"); + } + } + + private WechatMiniBindingDO pickTargetBinding( + Long userId, + String openId, + List openIdBindings, + List userBindings + ) { + List mergedBindings = mergeBindings(openIdBindings, userBindings); + return mergedBindings.stream() + .filter(binding -> Objects.equals(binding.getUserId(), userId) && Objects.equals(binding.getOpenId(), openId)) + .findFirst() + .orElseGet(() -> mergedBindings.stream() + .filter(binding -> Objects.equals(binding.getOpenId(), openId)) + .findFirst() + .orElseGet(() -> mergedBindings.stream() + .filter(binding -> Objects.equals(binding.getUserId(), userId)) + .findFirst() + .orElse(null))); + } + + private List mergeBindings( + List openIdBindings, + List userBindings + ) { + List merged = new ArrayList<>(); + openIdBindings.forEach(binding -> appendUniqueBinding(merged, binding)); + userBindings.forEach(binding -> appendUniqueBinding(merged, binding)); + merged.sort(Comparator + .comparing((WechatMiniBindingDO binding) -> Integer.valueOf(1).equals(binding.getStatus()) ? 0 : 1) + .thenComparing(WechatMiniBindingDO::getUpdateTime, Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(WechatMiniBindingDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(WechatMiniBindingDO::getId, Comparator.nullsLast(Comparator.reverseOrder()))); + return merged; + } + + /** + * Run business method `appendUniqueBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param merged parameter `merged` supplied by the caller + * @param candidate parameter `candidate` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void appendUniqueBinding(List merged, WechatMiniBindingDO candidate) { + if (candidate == null) { + return; + } + boolean exists = merged.stream().anyMatch(item -> Objects.equals(item.getId(), candidate.getId())); + if (!exists) { + merged.add(candidate); + } + } + + /** + * Run business method `deactivateDuplicateBindings`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keepBindingId parameter `keepBindingId` supplied by the caller + * @param bindings parameter `bindings` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deactivateDuplicateBindings(Long keepBindingId, List bindings) { + bindings.stream() + .filter(binding -> binding.getId() != null && !Objects.equals(binding.getId(), keepBindingId)) + .forEach(binding -> deactivateBinding(binding.getId())); + } + + /** + * Run business method `resolvePreferredOrOnlyShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param preferredShopId parameter `preferredShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolvePreferredOrOnlyShop(List shops, Long preferredShopId) { + Long normalizedPreferredShopId = normalizeShopId(preferredShopId); + if (normalizedPreferredShopId != null) { + boolean matched = shops.stream().anyMatch(shop -> Objects.equals(shop.getId(), normalizedPreferredShopId)); + if (matched) { + return normalizedPreferredShopId; + } + } + if (shops.size() == 1) { + return shops.get(0).getId(); + } + return null; + } + + private WechatMiniLoginResultVO buildSelectShopResult( + String message, + List shops, + TicketPayload ticketPayload + ) { + String ticket = storeTicketPayload(ticketPayload); + return WechatMiniLoginResultVO.selectShop(message, ticket, Boolean.TRUE.equals(ticketPayload.getNewUser()), shops); + } + + /** + * Run business method `storeTicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticketPayload parameter `ticketPayload` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String storeTicketPayload(TicketPayload ticketPayload) { + String ticket = "wxmini_" + snowflakeIdGenerator.nextIdString(); + try { + redisTemplate.opsForValue().set( + TICKET_KEY_PREFIX + ticket, + objectMapper.writeValueAsString(ticketPayload), + TICKET_TTL + ); + return ticket; + } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("生成微信登录票据失败", exception); + } + } + + /** + * Run business method `readTicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticket parameter `ticket` supplied by the caller + * @return private TicketPayload result consumed by the caller or returned to the frontend + */ + private TicketPayload readTicketPayload(String ticket) { + String payloadJson = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + ticket); + if (!StringUtils.hasText(payloadJson)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("登录票据已失效,请重新发起微信一键登录"); + } + try { + return objectMapper.readValue(payloadJson, TicketPayload.class); + } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("解析微信登录票据失败", exception); + } + } + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticket parameter `ticket` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deleteTicketPayload(String ticket) { + redisTemplate.delete(TICKET_KEY_PREFIX + ticket); + } + + /** + * Run business method `normalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long normalizeShopId(Long shopId) { + return shopId != null && shopId > 0 ? shopId : null; + } + + /** + * Run business method `normalizePhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizePhone(String phone) { + return phone == null ? "" : phone.trim(); + } + + @Data + /** + * Purpose: TicketPayload supports WechatMiniAuthServiceImpl.java by holding or executing the ticket payload business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class TicketPayload { + /** + * Purpose: userId supports WechatMiniAuthServiceImpl.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: phone supports WechatMiniAuthServiceImpl.java by holding or executing the phone business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String phone; + /** + * Purpose: openId supports WechatMiniAuthServiceImpl.java by holding or executing the open id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String openId; + /** + * Purpose: unionId supports WechatMiniAuthServiceImpl.java by holding or executing the union id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String unionId; + /** + * Purpose: newUser supports WechatMiniAuthServiceImpl.java by holding or executing the new user business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean newUser; + + /** + * Run business method `TicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return public result consumed by the caller or returned to the frontend + */ + public TicketPayload() { + } + + /** + * Run business method `TicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + * @param newUser parameter `newUser` supplied by the caller + * @return public result consumed by the caller or returned to the frontend + */ + public TicketPayload(Long userId, String phone, String openId, String unionId, Boolean newUser) { + this.userId = userId; + this.phone = phone; + this.openId = openId; + this.unionId = unionId; + this.newUser = newUser; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java new file mode 100644 index 00000000..e6dcffab --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java @@ -0,0 +1,399 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniClientService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import java.time.Duration; +import java.util.Map; +import java.util.Objects; + +/** + * WeChat mini program API client. + */ +@Service +@RequiredArgsConstructor +public class WechatMiniClientServiceImpl implements WechatMiniClientService { + + /** + * Purpose: ACCESS_TOKEN_CACHE_KEY_PREFIX supports WechatMiniClientServiceImpl.java by holding or executing the access token cache key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ACCESS_TOKEN_CACHE_KEY_PREFIX = "wechat:mini:access-token:"; + /** + * Purpose: ACCESS_TOKEN_URL supports WechatMiniClientServiceImpl.java by holding or executing the access token url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; + /** + * Variable `restTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RestTemplate restTemplate; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + /** + * Variable `properties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniProperties properties; + + @Override + /** + * Run business method `code2Session`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wxCode parameter `wxCode` supplied by the caller + * @return SessionInfo result consumed by the caller or returned to the frontend + */ + public SessionInfo code2Session(String wxCode) { + if (!StringUtils.hasText(wxCode)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信登录凭证不能为空"); + } + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + requireConfiguredCredentials(); + Map response = readJsonResponse( + doGetForString( + UriComponentsBuilder.fromHttpUrl(properties.getCode2sessionUrl()) + .queryParam("appid", properties.getAppId()) + .queryParam("secret", properties.getAppSecret()) + .queryParam("js_code", wxCode) + .queryParam("grant_type", "authorization_code") + .build(true) + .toUriString(), + "获取微信登录身份失败" + ), + "获取微信登录身份失败" + ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertWechatResponseOk(response, "获取微信登录身份失败"); + String openId = asText(response.get("openid")); + if (!StringUtils.hasText(openId)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openid parameter `openid` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信登录身份失败:缺少 openid"); + } + return new SessionInfo(openId, asText(response.get("unionid")), asText(response.get("session_key"))); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneCode parameter `phoneCode` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ + public String getPhoneNumber(String phoneCode) { + if (!StringUtils.hasText(phoneCode)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信手机号凭证不能为空"); + } + + String accessToken = getAccessToken(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map response = readJsonResponse( + doPostForString( + UriComponentsBuilder.fromHttpUrl(properties.getPhoneNumberUrl()) + .queryParam("access_token", accessToken) + .build(true) + .toUriString(), + new HttpEntity<>(Map.of("code", phoneCode), headers), + "获取微信手机号失败" + ), + "获取微信手机号失败" + ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertWechatResponseOk(response, "获取微信手机号失败"); + + Object phoneInfoRaw = response.get("phone_info"); + if (phoneInfoRaw == null) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信手机号失败:未返回手机号信息"); + } + Map phoneInfo = objectMapper.convertValue(phoneInfoRaw, new TypeReference>() { + }); + if (phoneInfo == null || phoneInfo.isEmpty()) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信手机号失败:未返回手机号信息"); + } + + String phoneNumber = asText(phoneInfo.get("phoneNumber")); + if (!StringUtils.hasText(phoneNumber)) { + phoneNumber = asText(phoneInfo.get("purePhoneNumber")); + } + if (!StringUtils.hasText(phoneNumber)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信手机号失败:未返回手机号信息"); + } + return phoneNumber; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String getConfiguredAppId() { + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + requireConfiguredCredentials(); + return properties.getAppId(); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getAccessToken() { + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + requireConfiguredCredentials(); + String cacheKey = ACCESS_TOKEN_CACHE_KEY_PREFIX + properties.getAppId(); + String cachedToken = redisTemplate.opsForValue().get(cacheKey); + if (StringUtils.hasText(cachedToken)) { + return cachedToken; + } + + Map response = readJsonResponse( + doGetForString( + UriComponentsBuilder.fromHttpUrl(ACCESS_TOKEN_URL) + .queryParam("grant_type", "client_credential") + .queryParam("appid", properties.getAppId()) + .queryParam("secret", properties.getAppSecret()) + .build(true) + .toUriString(), + "获取微信 access_token 失败" + ), + "获取微信 access_token 失败" + ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertWechatResponseOk(response, "获取微信 access_token 失败"); + + String accessToken = asText(response.get("access_token")); + if (!StringUtils.hasText(accessToken)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param access_token parameter `access_token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信 access_token 失败:未返回 access_token"); + } + + long expiresIn = parseLong(response.get("expires_in"), 7200L); + long safeBuffer = Math.max(0L, Objects.requireNonNullElse(properties.getAccessTokenBufferSeconds(), 60)); + long ttlSeconds = Math.max(60L, expiresIn - safeBuffer); + redisTemplate.opsForValue().set(cacheKey, accessToken, Duration.ofSeconds(ttlSeconds)); + return accessToken; + } + + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void requireConfiguredCredentials() { + if (!StringUtils.hasText(properties.getAppId()) || !StringUtils.hasText(properties.getAppSecret())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appIdappSecret parameter `appIdappSecret` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信小程序登录未配置 appId/appSecret"); + } + } + + /** + * Run business method `doGetForString`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param url parameter `url` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String doGetForString(String url, String defaultMessage) { + try { + return restTemplate.getForObject(url, String.class); + } catch (RestClientException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); + } + } + + /** + * Run business method `doPostForString`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param url parameter `url` supplied by the caller + * @param requestEntity parameter `requestEntity` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String doPostForString(String url, HttpEntity requestEntity, String defaultMessage) { + try { + return restTemplate.postForObject(url, requestEntity, String.class); + } catch (RestClientException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); + } + } + + /** + * Run business method `readJsonResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param responseBody parameter `responseBody` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map readJsonResponse(String responseBody, String defaultMessage) { + if (!StringUtils.hasText(responseBody)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务未返回数据"); + } + try { + return objectMapper.readValue(responseBody, new TypeReference>() { + }); + } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务返回了无法解析的响应", exception); + } + } + + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertWechatResponseOk(Map response, String defaultMessage) { + long errCode = parseLong(response.get("errcode"), 0L); + if (errCode == 0L) { + return; + } + String errMsg = asText(response.get("errmsg")); + throw new BusinessException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode))); + } + + /** + * Run business method `parseLong`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param defaultValue parameter `defaultValue` supplied by the caller + * @return private long result consumed by the caller or returned to the frontend + */ + private long parseLong(Object value, long defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Number number) { + return number.longValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Long.parseLong(text); + } catch (NumberFormatException ignored) { + return defaultValue; + } + } + return defaultValue; + } + + /** + * Run business method `asText`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String asText(Object value) { + return value == null ? "" : String.valueOf(value).trim(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/vo/MessageHubPushConfigVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/vo/MessageHubPushConfigVO.java new file mode 100644 index 00000000..833ca360 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/vo/MessageHubPushConfigVO.java @@ -0,0 +1,69 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * MessageHubPushConfigVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushConfigVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform; + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType; + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/vo/WechatMiniLoginResultVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/vo/WechatMiniLoginResultVO.java new file mode 100644 index 00000000..8bfb8c98 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/vo/WechatMiniLoginResultVO.java @@ -0,0 +1,110 @@ +package com.xiaowang.jayucloud.artlist.core.modules.integration.vo; + +import lombok.Data; + +import java.util.List; + +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +/** + * 微信小程序登录结果。 + */ +@Data +public class WechatMiniLoginResultVO { + + /** + * Purpose: STATUS_SUCCESS supports WechatMiniLoginResultVO.java by holding or executing the status success business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String STATUS_SUCCESS = "SUCCESS"; + /** + * Purpose: STATUS_SELECT_SHOP supports WechatMiniLoginResultVO.java by holding or executing the status select shop business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String STATUS_SELECT_SHOP = "SELECT_SHOP"; + /** + * Purpose: STATUS_NEED_MANUAL_LOGIN supports WechatMiniLoginResultVO.java by holding or executing the status need manual login business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String STATUS_NEED_MANUAL_LOGIN = "NEED_MANUAL_LOGIN"; + + /** + * Field `status` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String status; + /** + * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String message; + /** + * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ticket; + /** + * Field `newUser` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean newUser; + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops; + /** + * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String accessToken; + /** + * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String refreshToken; + /** + * Field `userInfo` (LoginResponseVO.UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LoginResponseVO.UserInfo userInfo; + /** + * Field `needSetPassword` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean needSetPassword; + + /** + * Purpose: success supports WechatMiniLoginResultVO.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static WechatMiniLoginResultVO success(String message, LoginResponseVO loginResponse, boolean newUser) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_SUCCESS); + resultVO.setMessage(message); + resultVO.setNewUser(newUser); + resultVO.setAccessToken(loginResponse.getAccessToken()); + resultVO.setRefreshToken(loginResponse.getRefreshToken()); + resultVO.setUserInfo(loginResponse.getUserInfo()); + resultVO.setNeedSetPassword(loginResponse.isNeedSetPassword()); + return resultVO; + } + + public static WechatMiniLoginResultVO selectShop( + String message, + String ticket, + boolean newUser, + List shops + ) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_SELECT_SHOP); + resultVO.setMessage(message); + resultVO.setTicket(ticket); + resultVO.setNewUser(newUser); + resultVO.setShops(shops); + return resultVO; + } + + /** + * Purpose: needManualLogin supports WechatMiniLoginResultVO.java by holding or executing the need manual login business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static WechatMiniLoginResultVO needManualLogin(String message) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_NEED_MANUAL_LOGIN); + resultVO.setMessage(message); + resultVO.setNewUser(false); + return resultVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java new file mode 100644 index 00000000..362ba0fd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class InventoryAdjustDTO { + private String changeType; + private BigDecimal changeQuantity; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java new file mode 100644 index 00000000..c8213b4f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class InventoryItemDTO { + private Long shopId; + private String category; + private String itemName; + private String unit; + private BigDecimal stockQuantity; + private BigDecimal warningThreshold; + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java new file mode 100644 index 00000000..e6bc0072 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_inventory_item") +public class InventoryItemDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("category") + private String category; + @TableField("item_name") + private String itemName; + @TableField("unit") + private String unit; + @TableField("stock_quantity") + private BigDecimal stockQuantity; + @TableField("warning_threshold") + private BigDecimal warningThreshold; + @TableField("status") + private Integer status; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java new file mode 100644 index 00000000..7e035965 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_inventory_record") +public class InventoryRecordDO extends BaseEntity { + @TableField("inventory_item_id") + private Long inventoryItemId; + @TableField("shop_id") + private Long shopId; + @TableField("change_type") + private String changeType; + @TableField("change_quantity") + private BigDecimal changeQuantity; + @TableField("before_quantity") + private BigDecimal beforeQuantity; + @TableField("after_quantity") + private BigDecimal afterQuantity; + @TableField("operator_id") + private Long operatorId; + @TableField("remark") + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java new file mode 100644 index 00000000..6fecd165 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface InventoryItemMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java new file mode 100644 index 00000000..8e9c7022 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryRecordDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface InventoryRecordMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java new file mode 100644 index 00000000..c3b7931e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.service; + +import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryAdjustDTO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryItemDTO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.vo.InventoryItemVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; + +public interface InventoryService { + InventoryItemVO saveItem(InventoryItemDTO dto); + + InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto); + + PageResultVO listItems(Long shopId, Integer page, Integer size); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java new file mode 100644 index 00000000..52f9bcec --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java @@ -0,0 +1,99 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryAdjustDTO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryItemDTO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryRecordDO; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryRecordMapper; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.service.InventoryService; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.vo.InventoryItemVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; + +@Service +@RequiredArgsConstructor +public class InventoryServiceImpl implements InventoryService { + + private final InventoryItemMapper inventoryItemMapper; + private final InventoryRecordMapper inventoryRecordMapper; + + @Override + @Transactional + public InventoryItemVO saveItem(InventoryItemDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getItemName() == null || dto.getItemName().isBlank()) { + throw new RuntimeException("库存物料信息不完整"); + } + InventoryItemDO item = new InventoryItemDO(); + BeanUtils.copyProperties(dto, item); + item.setStockQuantity(dto.getStockQuantity() == null ? BigDecimal.ZERO : dto.getStockQuantity()); + item.setWarningThreshold(dto.getWarningThreshold() == null ? BigDecimal.ZERO : dto.getWarningThreshold()); + item.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + item.setIsDelete(0); + inventoryItemMapper.insert(item); + return toVO(item); + } + + @Override + @Transactional + public InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto) { + InventoryItemDO item = inventoryItemMapper.selectById(itemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("库存物料不存在"); + } + BigDecimal before = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity(); + BigDecimal delta = dto == null || dto.getChangeQuantity() == null ? BigDecimal.ZERO : dto.getChangeQuantity(); + BigDecimal after = before.add(delta); + if (after.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("库存不能小于 0"); + } + item.setStockQuantity(after); + inventoryItemMapper.updateById(item); + InventoryRecordDO record = new InventoryRecordDO(); + record.setInventoryItemId(item.getId()); + record.setShopId(item.getShopId()); + record.setChangeType(dto == null ? null : dto.getChangeType()); + record.setChangeQuantity(delta); + record.setBeforeQuantity(before); + record.setAfterQuantity(after); + record.setOperatorId(operatorId); + record.setRemark(dto == null ? null : dto.getRemark()); + inventoryRecordMapper.insert(record); + return toVO(item); + } + + @Override + public PageResultVO listItems(Long shopId, Integer page, Integer size) { + int current = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 10 : size; + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(InventoryItemDO::getIsDelete, 0) + .orderByDesc(InventoryItemDO::getCreateTime); + if (shopId != null) { + wrapper.eq(InventoryItemDO::getShopId, shopId); + } + Page result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper); + PageResultVO vo = new PageResultVO<>(); + vo.setList(result.getRecords().stream().map(this::toVO).toList()); + vo.setTotal(result.getTotal()); + vo.setPage(current); + vo.setSize(pageSize); + return vo; + } + + private InventoryItemVO toVO(InventoryItemDO item) { + InventoryItemVO vo = new InventoryItemVO(); + BeanUtils.copyProperties(item, vo); + BigDecimal stock = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity(); + BigDecimal warning = item.getWarningThreshold() == null ? BigDecimal.ZERO : item.getWarningThreshold(); + vo.setWarning(stock.compareTo(warning) <= 0); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java new file mode 100644 index 00000000..79c35fc2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.artlist.core.modules.inventory.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class InventoryItemVO { + private Long id; + private Long shopId; + private String category; + private String itemName; + private String unit; + private BigDecimal stockQuantity; + private BigDecimal warningThreshold; + private Boolean warning; + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java new file mode 100644 index 00000000..977f35b8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.modules.manager.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@Data +public class ManagerCustomerCreateDTO { + + @NotBlank(message = "客户姓名不能为空") + private String nickname; + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + private String phone; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/CouponController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/CouponController.java new file mode 100644 index 00000000..53adc41b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/CouponController.java @@ -0,0 +1,190 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.CouponVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.UserCouponVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 优惠券控制器 + */ +@RestController +@RequestMapping("/coupon") +@RequiredArgsConstructor +public class CouponController { + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponService couponService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建优惠券 + */ + @PostMapping("/create") + @RequirePermission("coupon:create") + public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); + Long couponId = couponService.createCoupon(couponDTO, shopId); + return Result.success(couponId); + } + + /** + * 更新优惠券 + */ + @PutMapping("/update/{id}") + @RequirePermission("coupon:edit") + public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); + Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); + shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); + boolean success = couponService.updateCoupon(id, couponDTO, shopId); + return Result.success(success); + } + + /** + * 删除优惠券 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("coupon:delete") + public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.deleteCoupon(id, shopId); + return Result.success(success); + } + + /** + * 获取优惠券详情 + */ + @GetMapping("/detail/{id}") + @RequirePermission("coupon:view") + public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); + } + return Result.success(couponVO); + } + + /** + * 获取优惠券列表 + */ + @GetMapping("/list") + @RequirePermission("coupon:view") + public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO pageResult = couponService.listCoupons(page, size, shopId); + return Result.success(pageResult); + } + + /** + * 为用户分配优惠券 + */ + @PostMapping("/assign") + @RequirePermission("coupon:assign") + public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(couponId); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.assignCouponToUser(userId, couponId, shopId); + return Result.success(success); + } + + /** + * 获取用户优惠券列表 + */ + @GetMapping("/user/list") + public Result> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) { + List userCoupons = couponService.listUserCoupons(userId, status); + return Result.success(userCoupons); + } + + /** + * 使用优惠券 + */ + @PostMapping("/use") + public Result useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) { + boolean success = couponService.useCoupon(userCouponId, userId); + return Result.success(success); + } + + /** + * 获取商品可用的优惠券 + */ + @GetMapping("/available") + public Result> getAvailableCoupons( + @RequestParam(required = false, defaultValue = "") String productTags, + @RequestParam Double productPrice, + @RequestParam(required = false) Long shopId, + @RequestAttribute("userId") Long userId + ) { + List availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId); + return Result.success(availableCoupons); + } + + /** + * 发放优惠券 + */ + @PostMapping("/distribute") + @RequirePermission("coupon:assign") + public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(couponId); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); + for (Long userId : userIds) { + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); + } + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); + return Result.success(success); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/GrowthController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/GrowthController.java new file mode 100644 index 00000000..06dd69e6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/GrowthController.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.GrowthService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.GrowthSummaryVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/growth") +@RequiredArgsConstructor +public class GrowthController { + + private final GrowthService growthService; + + @GetMapping("/summary") + public Result summary(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(growthService.getSummary(userId)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/ProductLikeController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/ProductLikeController.java new file mode 100644 index 00000000..18f761cd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/ProductLikeController.java @@ -0,0 +1,65 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.ProductLikeService; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +/** + * 商品点赞控制器 + * + * @author xiaowang + * @date 2026-03-05 + */ +@RestController +@RequestMapping("/product-like") +@RequiredArgsConstructor +public class ProductLikeController { + /** + * Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductLikeService productLikeService; + + /** + * 点赞商品 + * + * @param userId 当前用户ID + * @param productId 商品ID + * @return 是否成功 + */ + @PostMapping("/like/{productId}") + @OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { + productLikeService.addLike(userId, productId); + return Result.success(true); + } + + /** + * 取消点赞商品 + * + * @param userId 当前用户ID + * @param productId 商品ID + * @return 是否成功 + */ + @PostMapping("/unlike/{productId}") + @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { + productLikeService.removeLike(userId, productId); + return Result.success(true); + } + + /** + * 检查用户是否已点赞商品 + * + * @param userId 当前用户ID + * @param productId 商品ID + * @return 是否已点赞 + */ + @GetMapping("/check/{productId}") + public Result checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { + boolean isLiked = productLikeService.isProductLiked(userId, productId); + return Result.success(isLiked); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipBenefitController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipBenefitController.java new file mode 100644 index 00000000..b4072805 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipBenefitController.java @@ -0,0 +1,99 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipBenefitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipBenefitVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.VipBenefitService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * VIP权益信息表 Controller + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/vip-benefit", "/api/vip-benefit"}) +@RequiredArgsConstructor +public class VipBenefitController { + /** + * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipBenefitService vipBenefitService; + + /** + * 创建VIP权益 + * + * @param vipBenefitDTO VIP权益DTO + * @return VIP权益ID + */ + @PostMapping("/create") + public Result createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { + Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); + return Result.success(id); + } + + /** + * 更新VIP权益 + * + * @param id VIP权益ID + * @param vipBenefitDTO VIP权益DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { + boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); + return Result.success(success); + } + + /** + * 删除VIP权益 + * + * @param id VIP权益ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteVipBenefit(@PathVariable Long id) { + boolean success = vipBenefitService.deleteVipBenefit(id); + return Result.success(success); + } + + /** + * 根据ID查询VIP权益 + * + * @param id VIP权益ID + * @return VIP权益VO + */ + @GetMapping("/get/{id}") + public Result getVipBenefitById(@PathVariable Long id) { + VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); + return Result.success(vipBenefitVO); + } + + /** + * 查询所有VIP权益 + * + * @return VIP权益VO列表 + */ + @GetMapping("/list/all") + public Result> listAllVipBenefits() { + List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); + return Result.success(vipBenefitVOs); + } + + /** + * 根据所需VIP等级查询VIP权益 + * + * @param requiredVipLevel 所需VIP等级 + * @return VIP权益VO列表 + */ + @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") + public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { + List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); + return Result.success(vipBenefitVOs); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipInfoController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipInfoController.java new file mode 100644 index 00000000..e66344f3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipInfoController.java @@ -0,0 +1,99 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipInfoVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.VipInfoService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户VIP信息表 Controller + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/vip-info", "/api/vip-info"}) +@RequiredArgsConstructor +public class VipInfoController { + /** + * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipInfoService vipInfoService; + + /** + * 创建VIP信息 + * + * @param vipInfoDTO VIP信息DTO + * @return VIP信息ID + */ + @PostMapping("/create") + public Result createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { + Long id = vipInfoService.createVipInfo(vipInfoDTO); + return Result.success(id); + } + + /** + * 更新VIP信息 + * + * @param id VIP信息ID + * @param vipInfoDTO VIP信息DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { + boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); + return Result.success(success); + } + + /** + * 删除VIP信息 + * + * @param id VIP信息ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteVipInfo(@PathVariable Long id) { + boolean success = vipInfoService.deleteVipInfo(id); + return Result.success(success); + } + + /** + * 根据ID查询VIP信息 + * + * @param id VIP信息ID + * @return VIP信息VO + */ + @GetMapping("/get/{id}") + public Result getVipInfoById(@PathVariable Long id) { + VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); + return Result.success(vipInfoVO); + } + + /** + * 查询所有VIP信息 + * + * @return VIP信息VO列表 + */ + @GetMapping("/list/all") + public Result> listAllVipInfos() { + List vipInfoVOs = vipInfoService.listAllVipInfos(); + return Result.success(vipInfoVOs); + } + + /** + * 根据VIP等级查询VIP信息 + * + * @param vipLevel VIP等级 + * @return VIP信息VO列表 + */ + @GetMapping("/list/vipLevel/{vipLevel}") + public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { + List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); + return Result.success(vipInfoVOs); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipRechargePlanController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipRechargePlanController.java new file mode 100644 index 00000000..41741185 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/VipRechargePlanController.java @@ -0,0 +1,113 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipRechargePlanDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.VipRechargePlanService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipRechargePlanVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"}) +/** + * VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class VipRechargePlanController { + /** + * Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipRechargePlanService vipRechargePlanService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("user:vip:manage") + /** + * Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); + } + + @PostMapping("/admin/create") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); + } + + @PutMapping("/admin/{id}") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); + } + + @PutMapping("/admin/{id}/status") + @RequirePermission("user:vip:manage") + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMy(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(vipRechargePlanService.listMyPlans(userId)); + } + + @GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"}) + /** + * Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/WishlistController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/WishlistController.java new file mode 100644 index 00000000..cec6c3a5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/controller/front/WishlistController.java @@ -0,0 +1,100 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistAddWithGroupDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistGroupDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistMoveDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.WishlistService; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.WishlistGroupVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.WishlistInspirationVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/wishlist") +public class WishlistController { + + @Autowired + private WishlistService wishlistService; + + @PostMapping("/add") + @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { + wishlistService.addToWishlist(userId, request.get("productId")); + return Result.success("ok"); + } + + @PostMapping("/add-with-group") + @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { + wishlistService.addToWishlist(userId, request); + return Result.success("ok"); + } + + @PostMapping("/remove") + @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { + wishlistService.removeFromWishlist(userId, request.get("productId")); + return Result.success("ok"); + } + + @GetMapping("/check") + public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.isInWishlist(userId, productId)); + } + + @GetMapping("/list") + public Result> getWishlist(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.getWishlistByUserId(userId)); + } + + @GetMapping("/groups") + public Result> listGroups(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.listGroups(userId)); + } + + @PostMapping("/groups") + public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.createGroup(userId, request)); + } + + @PutMapping("/groups/{id}") + public Result updateGroup( + @PathVariable Long id, + @RequestBody WishlistGroupDTO request, + @RequestAttribute("userId") Long userId + ) { + return Result.success(wishlistService.updateGroup(userId, id, request)); + } + + @DeleteMapping("/groups/{id}") + public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.deleteGroup(userId, id)); + } + + @PostMapping("/move") + @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.moveWishlist(userId, request)); + } + + @GetMapping("/inspiration") + public Result getInspiration(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.getInspiration(userId)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/CampaignDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/CampaignDTO.java new file mode 100644 index 00000000..63c58665 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/CampaignDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class CampaignDTO { + private Long shopId; + private String title; + private String description; + private String scene; + private String productIds; + private String couponIds; + private Integer status; + private LocalDateTime startTime; + private LocalDateTime endTime; + private Integer sortOrder; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/CouponDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/CouponDTO.java new file mode 100644 index 00000000..df91e160 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/CouponDTO.java @@ -0,0 +1,86 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 优惠券DTO + */ +@Data +public class CouponDTO { + + /** + * 优惠券编码 + */ + private String couponCode; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 折扣值(如9.5表示95折) + */ + private BigDecimal discountValue; + + /** + * 满减券最低消费金额 + */ + private BigDecimal minAmount; + + /** + * 满减券减免金额 + */ + private BigDecimal reduceAmount; + + /** + * 优惠券总数量 + */ + private Integer totalCount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 所属店铺ID + */ + private Long shopId; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer autoMatch; + + /** + * 可用标签ID列表 + */ + private List availableTagIds; + + /** + * 不可用标签ID列表 + */ + private List unavailableTagIds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipBenefitDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipBenefitDTO.java new file mode 100644 index 00000000..d4f34fbe --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipBenefitDTO.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * VIP权益信息表 DTO + * 用于VIP权益信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipBenefitDTO { + + /** + * 权益详情(如折扣、专属服务) + */ + private String benefitInfo; + + /** + * 所需VIP等级 + */ + private String requiredVipLevel; + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer levelRank; + /** + * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeThreshold; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipInfoDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipInfoDTO.java new file mode 100644 index 00000000..37dcc712 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipInfoDTO.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户VIP信息表 DTO + * 用于VIP信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipInfoDTO { + + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * VIP等级(如青铜、白银) + */ + private String vipLevel; + + /** + * VIP开通时间 + */ + private LocalDateTime startTime; + + /** + * VIP到期时间 + */ + private LocalDateTime expireTime; + + /** + * VIP开通方式(如购买、赠送) + */ + private String activationMethod; + + /** + * 关联VIP权益信息表主键 + */ + private Long benefitId; + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer manualOverride; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipRechargePlanDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipRechargePlanDTO.java new file mode 100644 index 00000000..9a59d550 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/VipRechargePlanDTO.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.math.BigDecimal; + +@Data +/** + * VipRechargePlanDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanDTO { + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @NotBlank(message = "充值档位标题不能为空") + @Size(max = 100, message = "充值档位标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @NotNull(message = "充值金额不能为空") + @DecimalMin(value = "0.01", message = "充值金额必须大于0") + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + + @NotNull(message = "赠送金额不能为空") + @DecimalMin(value = "0.00", message = "赠送金额不能小于0") + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + + @NotBlank(message = "VIP等级不能为空") + @Size(max = 20, message = "VIP等级不能超过20个字符") + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + @Size(max = 255, message = "说明不能超过255个字符") + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder = 0; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status = 1; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistAddWithGroupDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistAddWithGroupDTO.java new file mode 100644 index 00000000..7cfad815 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistAddWithGroupDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +@Data +public class WishlistAddWithGroupDTO { + private Long productId; + private Long groupId; + private String note; + private Integer sortOrder; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistDTO.java new file mode 100644 index 00000000..6f185359 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistDTO.java @@ -0,0 +1,43 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.ProductVO; +import lombok.Data; + +/** + * 收藏夹 DTO + * 用于收藏夹商品信息的传输 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class WishlistDTO { + + /** + * 收藏记录ID + */ + private Long id; + + /** + * 用户ID + */ + private Long userId; + + /** + * 商品ID + */ + private Long productId; + + private Long groupId; + + private String groupName; + + private String note; + + private Integer sortOrder; + + /** + * 商品详细信息 + */ + private ProductVO product; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistGroupDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistGroupDTO.java new file mode 100644 index 00000000..85462188 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistGroupDTO.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +@Data +public class WishlistGroupDTO { + private String name; + private Integer sortOrder; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistMoveDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistMoveDTO.java new file mode 100644 index 00000000..c54e029a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/dto/WishlistMoveDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.dto; + +import lombok.Data; + +@Data +public class WishlistMoveDTO { + private Long wishlistId; + private Long productId; + private Long groupId; + private String note; + private Integer sortOrder; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CampaignDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CampaignDO.java new file mode 100644 index 00000000..baa6fe9a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CampaignDO.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_campaign") +public class CampaignDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("title") + private String title; + @TableField("description") + private String description; + @TableField("scene") + private String scene; + @TableField("product_ids") + private String productIds; + @TableField("coupon_ids") + private String couponIds; + @TableField("status") + private Integer status; + @TableField("start_time") + private LocalDateTime startTime; + @TableField("end_time") + private LocalDateTime endTime; + @TableField("sort_order") + private Integer sortOrder; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CouponDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CouponDO.java new file mode 100644 index 00000000..c372cd6d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CouponDO.java @@ -0,0 +1,102 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 优惠券信息表 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_coupon") +public class CouponDO extends BaseEntity { + + /** + * 优惠券编码 + */ + private String couponCode; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 折扣值(如9.5表示95折) + */ + private BigDecimal discountValue; + + /** + * 满减券最低消费金额 + */ + private BigDecimal minAmount; + + /** + * 满减券减免金额 + */ + private BigDecimal reduceAmount; + + /** + * 优惠券总数量 + */ + private Integer totalCount; + + /** + * 已使用数量 + */ + private Integer usedCount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 状态:1-可用,2-已过期,3-已用完 + */ + private Integer status; + + /** + * 所属店铺ID + */ + private Long shopId; + + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponScene; + + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer autoMatch; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CouponTagDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CouponTagDO.java new file mode 100644 index 00000000..3afa7cf3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/CouponTagDO.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 优惠券标签关联表 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_coupon_tag") +public class CouponTagDO extends BaseEntity { + + /** + * 关联优惠券表主键 + */ + private Long couponId; + + /** + * 关联标签表主键 + */ + private Long tagId; + + /** + * 是否可用:1-可用,0-不可用 + */ + private Integer isAvailable; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/ProductLikeDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/ProductLikeDO.java new file mode 100644 index 00000000..16360524 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/ProductLikeDO.java @@ -0,0 +1,40 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 商品点赞记录表 DO + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_product_like") +public class ProductLikeDO extends BaseEntity { + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 关联商品表主键 + */ + @TableField("product_id") + private Long productId; + + /** + * 逻辑删除标识:0-未删除,1-已删除 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/UserCouponDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/UserCouponDO.java new file mode 100644 index 00000000..dcf0f8d9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/UserCouponDO.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 用户优惠券关联表 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_coupon") +public class UserCouponDO extends BaseEntity { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 关联优惠券表主键 + */ + private Long couponId; + + /** + * 状态:1-未使用,2-已使用,3-已过期 + */ + private Integer status; + + /** + * 获取时间 + */ + private LocalDateTime obtainTime; + + /** + * 使用时间 + */ + private LocalDateTime useTime; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipBenefitDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipBenefitDO.java new file mode 100644 index 00000000..92515c1c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipBenefitDO.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * VIP权益信息表 DO + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_benefit") +public class VipBenefitDO extends BaseEntity { + + /** + * 权益详情(如折扣、专属服务) + */ + @TableField("benefit_info") + private String benefitInfo; + + /** + * 所需VIP等级 + */ + @TableField("required_vip_level") + private String requiredVipLevel; + + @TableField("level_rank") + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer levelRank; + + @TableField("recharge_threshold") + /** + * Field `rechargeThreshold` (java.math.BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private java.math.BigDecimal rechargeThreshold; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipInfoDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipInfoDO.java new file mode 100644 index 00000000..3b7f59d5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipInfoDO.java @@ -0,0 +1,64 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 用户VIP信息表 DO + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_info") +public class VipInfoDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * VIP等级(如青铜、白银) + */ + @TableField("vip_level") + private String vipLevel; + + /** + * VIP开通时间 + */ + @TableField("start_time") + private LocalDateTime startTime; + + /** + * VIP到期时间 + */ + @TableField("expire_time") + private LocalDateTime expireTime; + + /** + * VIP开通方式(如购买、赠送) + */ + @TableField("activation_method") + private String activationMethod; + + /** + * 关联VIP权益信息表主键 + */ + @TableField("benefit_id") + private Long benefitId; + + @TableField("manual_override") + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer manualOverride; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipRechargePlanDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipRechargePlanDO.java new file mode 100644 index 00000000..dd46ace5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/VipRechargePlanDO.java @@ -0,0 +1,75 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_recharge_plan") +/** + * VipRechargePlanDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanDO extends BaseEntity { + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("recharge_amount") + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + + @TableField("gift_amount") + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + + @TableField("vip_level") + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + @TableField("description") + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/WishlistDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/WishlistDO.java new file mode 100644 index 00000000..6bab293e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/WishlistDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@TableName("t_wishlist") +/** + * WishlistDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class WishlistDO extends BaseEntity { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + + @TableField("group_id") + private Long groupId; + + @TableField("note") + private String note; + + @TableField("sort_order") + private Integer sortOrder; + + @TableField("is_delete") + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/WishlistGroupDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/WishlistGroupDO.java new file mode 100644 index 00000000..5afd2d15 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/entity/WishlistGroupDO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_wishlist_group") +public class WishlistGroupDO extends BaseEntity { + + @TableField("user_id") + private Long userId; + + @TableField("name") + private String name; + + @TableField("sort_order") + private Integer sortOrder; + + @TableField("is_delete") + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CampaignMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CampaignMapper.java new file mode 100644 index 00000000..204a914e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CampaignMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CampaignDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface CampaignMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CouponMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CouponMapper.java new file mode 100644 index 00000000..7ea24e8e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CouponMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 优惠券Mapper + */ +@Mapper +public interface CouponMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CouponTagMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CouponTagMapper.java new file mode 100644 index 00000000..9e81e277 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/CouponTagMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponTagDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 优惠券标签关联Mapper + */ +@Mapper +public interface CouponTagMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/ProductLikeMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/ProductLikeMapper.java new file mode 100644 index 00000000..8bd1e632 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/ProductLikeMapper.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.ProductLikeDO; +import org.apache.ibatis.annotations.Param; + +/** + * 商品点赞记录表 Mapper + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +public interface ProductLikeMapper extends BaseMapper { + + /** + * 检查用户是否已点赞商品 + * + * @param userId 用户ID + * @param productId 商品ID + * @return 是否已点赞 + */ + boolean isProductLiked(@Param("userId") Long userId, @Param("productId") Long productId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/UserCouponMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/UserCouponMapper.java new file mode 100644 index 00000000..c5eadf44 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/UserCouponMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.UserCouponDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 用户优惠券Mapper + */ +@Mapper +public interface UserCouponMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipBenefitMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipBenefitMapper.java new file mode 100644 index 00000000..f7a26235 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipBenefitMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipBenefitDO; + +/** + * VIP权益信息表 Mapper + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipBenefitMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipInfoMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipInfoMapper.java new file mode 100644 index 00000000..89d27f30 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipInfoMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipInfoDO; + +/** + * 用户VIP信息表 Mapper + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipInfoMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipRechargePlanMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipRechargePlanMapper.java new file mode 100644 index 00000000..2f2e40fa --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/VipRechargePlanMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipRechargePlanDO; + +/** + * VipRechargePlanMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface VipRechargePlanMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/WishlistGroupMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/WishlistGroupMapper.java new file mode 100644 index 00000000..18dd70e5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/WishlistGroupMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.WishlistGroupDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface WishlistGroupMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/WishlistMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/WishlistMapper.java new file mode 100644 index 00000000..963667e1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/mapper/WishlistMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.WishlistDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * WishlistMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface WishlistMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/CampaignService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/CampaignService.java new file mode 100644 index 00000000..2c4aa3ac --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/CampaignService.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.CampaignDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.CampaignVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; + +public interface CampaignService { + CampaignVO saveCampaign(CampaignDTO dto); + + PageResultVO listCampaigns(Long shopId, Integer status, Integer page, Integer size); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/CouponService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/CouponService.java new file mode 100644 index 00000000..80fd7240 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/CouponService.java @@ -0,0 +1,114 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.CouponVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.UserCouponVO; + +import java.util.List; + +/** + * 优惠券服务 + */ +public interface CouponService extends IService { + + /** + * 创建优惠券 + * @param couponDTO 优惠券DTO + * @param shopId 店铺ID + * @return 优惠券ID + */ + Long createCoupon(CouponDTO couponDTO, Long shopId); + + /** + * 更新优惠券 + * @param id 优惠券ID + * @param couponDTO 优惠券DTO + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId); + + /** + * 删除优惠券 + * @param id 优惠券ID + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean deleteCoupon(Long id, Long shopId); + + /** + * 获取优惠券详情 + * @param id 优惠券ID + * @return 优惠券VO + */ + CouponVO getCouponById(Long id); + + /** + * 获取优惠券列表 + * @param page 页码 + * @param size 每页大小 + * @param shopId 店铺ID + * @return 分页结果 + */ + PageResultVO listCoupons(Integer page, Integer size, Long shopId); + + /** + * 获取所有优惠券 + * @return 优惠券列表 + */ + List listAllCoupons(); + + /** + * 为用户分配优惠券 + * @param userId 用户ID + * @param couponId 优惠券ID + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean assignCouponToUser(Long userId, Long couponId, Long shopId); + + /** + * 获取用户优惠券列表 + * @param userId 用户ID + * @param status 状态 + * @return 用户优惠券列表 + */ + List listUserCoupons(Long userId, Integer status); + + /** + * 使用优惠券 + * @param userCouponId 用户优惠券ID + * @param userId 用户ID + * @return 是否成功 + */ + boolean useCoupon(Long userCouponId, Long userId); + + /** + * 获取商品可用的优惠券 + * @param userId 用户ID + * @param productTags 商品标签 + * @param productPrice 商品价格 + * @return 可用优惠券列表 + */ + List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId); + + /** + * 为新店铺初始化默认 VIP 自动券模板 + * + * @param shopId 店铺ID + */ + void initializeDefaultVipAutoCoupons(Long shopId); + + /** + * 发放优惠券 + * @param couponId 优惠券ID + * @param userIds 用户ID列表 + * @param quantity 发放数量 + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/GrowthService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/GrowthService.java new file mode 100644 index 00000000..879044db --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/GrowthService.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.GrowthSummaryVO; + +public interface GrowthService { + GrowthSummaryVO getSummary(Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/ProductLikeService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/ProductLikeService.java new file mode 100644 index 00000000..259578d0 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/ProductLikeService.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.ProductLikeDO; + +/** + * 商品点赞记录表 Service + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +public interface ProductLikeService extends IService { + + /** + * 添加点赞记录 + * + * @param userId 用户ID + * @param productId 商品ID + */ + void addLike(Long userId, Long productId); + + /** + * 取消点赞 + * + * @param userId 用户ID + * @param productId 商品ID + */ + void removeLike(Long userId, Long productId); + + /** + * 检查用户是否已点赞商品 + * + * @param userId 用户ID + * @param productId 商品ID + * @return 是否已点赞 + */ + boolean isProductLiked(Long userId, Long productId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipBenefitService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipBenefitService.java new file mode 100644 index 00000000..7b458fea --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipBenefitService.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipBenefitDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipBenefitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipBenefitVO; + +import java.util.List; + +/** + * VIP权益信息表 Service + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipBenefitService extends IService { + + /** + * 创建VIP权益 + * + * @param vipBenefitDTO VIP权益DTO + * @return VIP权益ID + */ + Long createVipBenefit(VipBenefitDTO vipBenefitDTO); + + /** + * 更新VIP权益 + * + * @param id VIP权益ID + * @param vipBenefitDTO VIP权益DTO + * @return 是否更新成功 + */ + boolean updateVipBenefit(Long id, VipBenefitDTO vipBenefitDTO); + + /** + * 删除VIP权益 + * + * @param id VIP权益ID + * @return 是否删除成功 + */ + boolean deleteVipBenefit(Long id); + + /** + * 根据ID查询VIP权益 + * + * @param id VIP权益ID + * @return VIP权益VO + */ + VipBenefitVO getVipBenefitById(Long id); + + /** + * 查询所有VIP权益 + * + * @return VIP权益VO列表 + */ + List listAllVipBenefits(); + + /** + * 根据所需VIP等级查询VIP权益 + * + * @param requiredVipLevel 所需VIP等级 + * @return VIP权益VO列表 + */ + List listVipBenefitsByRequiredVipLevel(String requiredVipLevel); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipInfoService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipInfoService.java new file mode 100644 index 00000000..12083a3e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipInfoService.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipInfoVO; + +import java.util.List; + +/** + * 用户VIP信息表 Service + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipInfoService extends IService { + + /** + * 创建VIP信息 + * + * @param vipInfoDTO VIP信息DTO + * @return VIP信息ID + */ + Long createVipInfo(VipInfoDTO vipInfoDTO); + + /** + * 更新VIP信息 + * + * @param id VIP信息ID + * @param vipInfoDTO VIP信息DTO + * @return 是否更新成功 + */ + boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO); + + /** + * 删除VIP信息 + * + * @param id VIP信息ID + * @return 是否删除成功 + */ + boolean deleteVipInfo(Long id); + + /** + * 根据ID查询VIP信息 + * + * @param id VIP信息ID + * @return VIP信息VO + */ + VipInfoVO getVipInfoById(Long id); + + /** + * 查询所有VIP信息 + * + * @return VIP信息VO列表 + */ + List listAllVipInfos(); + + /** + * 根据VIP等级查询VIP信息 + * + * @param vipLevel VIP等级 + * @return VIP信息VO列表 + */ + List listVipInfosByVipLevel(String vipLevel); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipRechargePlanService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipRechargePlanService.java new file mode 100644 index 00000000..45d09108 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/VipRechargePlanService.java @@ -0,0 +1,59 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipRechargePlanDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipRechargePlanDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipRechargePlanVO; + +import java.util.List; + +/** + * VipRechargePlanService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface VipRechargePlanService extends IService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createPlan(UserDO currentUser, VipRechargePlanDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto); + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateStatus(UserDO currentUser, Long id, Integer status); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminPlans(UserDO currentUser, Long shopId); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyPlans(Long userId); + + List listVipLevelOptions(UserDO currentUser, Long shopId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/WishlistService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/WishlistService.java new file mode 100644 index 00000000..7829cc27 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/WishlistService.java @@ -0,0 +1,61 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistAddWithGroupDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistGroupDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistMoveDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.WishlistDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.WishlistGroupVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.WishlistInspirationVO; + +import java.util.List; + +/** + * WishlistService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface WishlistService extends IService { + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + void addToWishlist(Long userId, Long productId); + void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + void removeFromWishlist(Long userId, Long productId); + /** + * Run business method `isInWishlist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean isInWishlist(Long userId, Long productId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getWishlistByUserId(Long userId); + + List listGroups(Long userId); + + Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO); + + boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO); + + boolean deleteGroup(Long userId, Long groupId); + + boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO); + + WishlistInspirationVO getInspiration(Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/CampaignServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/CampaignServiceImpl.java new file mode 100644 index 00000000..1788db8b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/CampaignServiceImpl.java @@ -0,0 +1,65 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.CampaignDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CampaignDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.CampaignMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.CampaignService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.CampaignVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class CampaignServiceImpl implements CampaignService { + + private final CampaignMapper campaignMapper; + + @Override + @Transactional + public CampaignVO saveCampaign(CampaignDTO dto) { + if (dto == null || dto.getTitle() == null || dto.getTitle().isBlank()) { + throw new RuntimeException("活动标题不能为空"); + } + CampaignDO campaign = new CampaignDO(); + BeanUtils.copyProperties(dto, campaign); + campaign.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + campaign.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + campaign.setIsDelete(0); + campaignMapper.insert(campaign); + return toVO(campaign); + } + + @Override + public PageResultVO listCampaigns(Long shopId, Integer status, Integer page, Integer size) { + int current = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 10 : size; + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(CampaignDO::getIsDelete, 0) + .orderByAsc(CampaignDO::getSortOrder) + .orderByDesc(CampaignDO::getCreateTime); + if (shopId != null) { + wrapper.eq(CampaignDO::getShopId, shopId); + } + if (status != null) { + wrapper.eq(CampaignDO::getStatus, status); + } + Page result = campaignMapper.selectPage(new Page<>(current, pageSize), wrapper); + PageResultVO vo = new PageResultVO<>(); + vo.setList(result.getRecords().stream().map(this::toVO).toList()); + vo.setTotal(result.getTotal()); + vo.setPage(current); + vo.setSize(pageSize); + return vo; + } + + private CampaignVO toVO(CampaignDO campaign) { + CampaignVO vo = new CampaignVO(); + BeanUtils.copyProperties(campaign, vo); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/CouponServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/CouponServiceImpl.java new file mode 100644 index 00000000..01bf658b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/CouponServiceImpl.java @@ -0,0 +1,1233 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponTagDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.UserCouponDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.CouponTagMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.CouponVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.UserCouponVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +/** + * 优惠券服务实现 + */ +@Service +@RequiredArgsConstructor +public class CouponServiceImpl extends ServiceImpl implements CouponService { + + /** + * Purpose: COUPON_SOURCE_USER supports CouponServiceImpl.java by holding or executing the coupon source user business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_USER = "USER_COUPON"; + /** + * Purpose: COUPON_SOURCE_SYSTEM_VIP supports CouponServiceImpl.java by holding or executing the coupon source system vip business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; + /** + * Purpose: COUPON_SCENE_VIP_AUTO supports CouponServiceImpl.java by holding or executing the coupon scene vip auto business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SCENE_VIP_AUTO = "VIP_AUTO"; + /** + * Purpose: DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT supports CouponServiceImpl.java by holding or executing the default vip auto coupon total count business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT = 999999; + private static final LocalDateTime DEFAULT_VIP_AUTO_COUPON_END_TIME = LocalDateTime.of(2099, 12, 31, 23, 59, 59); + private static final List DEFAULT_SHOP_VIP_AUTO_COUPONS = List.of( + new VipAutoCouponTemplate("BRONZE_95", "青铜VIP自动95折券", "青铜", BigDecimal.valueOf(9.5)), + new VipAutoCouponTemplate("SILVER_92", "白银VIP自动92折券", "白银", BigDecimal.valueOf(9.2)), + new VipAutoCouponTemplate("GOLD_90", "黄金VIP自动90折券", "黄金", BigDecimal.valueOf(9.0)) + ); + /** + * Purpose: VIP_LEVEL_NORMAL supports CouponServiceImpl.java by holding or executing the vip level normal business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIP_LEVEL_NORMAL = "普通"; + /** + * Variable `couponTagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponTagMapper couponTagMapper; + /** + * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserCouponMapper userCouponMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Override + @Transactional + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDTO parameter `couponDTO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createCoupon(CouponDTO couponDTO, Long shopId) { + // 创建优惠券 + CouponDO couponDO = new CouponDO(); + couponDO.setCouponCode(resolveCouponCodeForCreate(couponDTO.getCouponCode())); + couponDO.setCouponName(couponDTO.getCouponName()); + couponDO.setCouponType(couponDTO.getCouponType()); + couponDO.setDiscountValue(couponDTO.getDiscountValue()); + couponDO.setMinAmount(couponDTO.getMinAmount()); + couponDO.setReduceAmount(couponDTO.getReduceAmount()); + couponDO.setTotalCount(couponDTO.getTotalCount()); + couponDO.setUsedCount(0); + couponDO.setStartTime(couponDTO.getStartTime()); + couponDO.setEndTime(couponDTO.getEndTime()); + couponDO.setStatus(1); + couponDO.setShopId(shopId); + couponDO.setCouponScene(couponDTO.getCouponScene()); + couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); + couponDO.setAutoMatch(couponDTO.getAutoMatch()); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + save(couponDO); + + // 处理标签关联 + handleCouponTags(couponDO.getId(), couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds()); + + return couponDO.getId(); + } + + @Override + @Transactional + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param couponDTO parameter `couponDTO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId) { + // 更新优惠券 + CouponDO couponDO = getById(id); + if (couponDO == null) { + return false; + } + + couponDO.setCouponCode(resolveCouponCodeForUpdate(couponDO.getCouponCode(), couponDTO.getCouponCode())); + couponDO.setCouponName(couponDTO.getCouponName()); + couponDO.setCouponType(couponDTO.getCouponType()); + couponDO.setDiscountValue(couponDTO.getDiscountValue()); + couponDO.setMinAmount(couponDTO.getMinAmount()); + couponDO.setReduceAmount(couponDTO.getReduceAmount()); + couponDO.setTotalCount(couponDTO.getTotalCount()); + couponDO.setStartTime(couponDTO.getStartTime()); + couponDO.setEndTime(couponDTO.getEndTime()); + couponDO.setShopId(shopId); + couponDO.setCouponScene(couponDTO.getCouponScene()); + couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); + couponDO.setAutoMatch(couponDTO.getAutoMatch()); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + refreshCouponDistributionStatus(id); + + // 处理标签关联 + handleCouponTags(id, couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds()); + + return true; + } + + @Override + @Transactional + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteCoupon(Long id, Long shopId) { + // 删除优惠券 + CouponDO couponDO = getById(id); + if (couponDO == null) { + return false; + } + couponDO.setIsDelete(1); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return updateById(couponDO); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return CouponVO result consumed by the caller or returned to the frontend + */ + public CouponVO getCouponById(Long id) { + CouponDO couponDO = getById(id); + if (couponDO == null || couponDO.getIsDelete() == 1) { + return null; + } + /** + * Run business method `convertToCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToCouponVO(couponDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO listCoupons(Integer page, Integer size, Long shopId) { + Page pageInfo = new Page<>(page, size); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0) + .orderByDesc(CouponDO::getCreateTime); + if (shopId != null) { + wrapper.eq(CouponDO::getShopId, shopId); + } + IPage couponPage = page(pageInfo, wrapper); + + List couponVOs = couponPage.getRecords().stream() + .map(this::convertToCouponVO) + .collect(Collectors.toList()); + + PageResultVO pageResult = new PageResultVO<>(); + pageResult.setList(couponVOs); + pageResult.setTotal(couponPage.getTotal()); + pageResult.setPage(page); + pageResult.setSize(size); + + return pageResult; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllCoupons() { + List couponDOs = list(new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0) + .orderByDesc(CouponDO::getCreateTime) + ); + return couponDOs.stream() + .map(this::convertToCouponVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional + /** + * Run business method `assignCouponToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param couponId parameter `couponId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean assignCouponToUser(Long userId, Long couponId, Long shopId) { + // 检查优惠券是否存在 + CouponDO couponDO = getById(couponId); + if (couponDO == null || couponDO.getIsDelete() == 1) { + return false; + } + + // 检查优惠券是否可用 + if (couponDO.getStatus() != 1) { + return false; + } + if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) { + return false; + } + if (isVipAutoCoupon(couponDO)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); + } + if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { + return false; + } + + // 检查是否已经分配 + UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getCouponId, couponId) + .eq(UserCouponDO::getIsDelete, 0) + ); + if (existing != null) { + return false; + } + if (!hasRemainingDistributionStock(couponDO, 1)) { + return false; + } + + // 分配优惠券 + UserCouponDO userCouponDO = new UserCouponDO(); + userCouponDO.setUserId(userId); + userCouponDO.setCouponId(couponId); + userCouponDO.setStatus(1); + userCouponDO.setObtainTime(LocalDateTime.now()); + userCouponMapper.insert(userCouponDO); + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + refreshCouponDistributionStatus(couponId); + + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listUserCoupons(Long userId, Integer status) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getIsDelete, 0); + + if (status != null) { + queryWrapper.eq(UserCouponDO::getStatus, status); + } + + List userCouponDOs = userCouponMapper.selectList(queryWrapper); + return userCouponDOs.stream() + .map(userCouponDO -> { + CouponDO couponDO = getById(userCouponDO.getCouponId()); + return couponDO == null ? null : convertToUserCouponVO(userCouponDO, couponDO); + }) + .filter(java.util.Objects::nonNull) + .collect(Collectors.toList()); + } + + @Override + @Transactional + /** + * Run business method `useCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean useCoupon(Long userCouponId, Long userId) { + // 检查用户优惠券是否存在 + UserCouponDO userCouponDO = userCouponMapper.selectById(userCouponId); + if (userCouponDO == null || userCouponDO.getIsDelete() == 1) { + return false; + } + + // 检查是否属于当前用户 + if (!userCouponDO.getUserId().equals(userId)) { + return false; + } + + // 检查是否未使用 + if (userCouponDO.getStatus() != 1) { + return false; + } + + // 检查优惠券是否过期 + CouponDO couponDO = getById(userCouponDO.getCouponId()); + if (couponDO == null || couponDO.getEndTime().isBefore(LocalDateTime.now())) { + return false; + } + + // 使用优惠券 + userCouponDO.setStatus(2); + userCouponDO.setUseTime(LocalDateTime.now()); + userCouponMapper.updateById(userCouponDO); + + // 更新优惠券使用数量 + incrementCouponUsedCount(couponDO.getId()); + + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productTags parameter `productTags` supplied by the caller + * @param productPrice parameter `productPrice` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId) { + BigDecimal orderAmount = productPrice == null ? BigDecimal.ZERO : BigDecimal.valueOf(productPrice); + LocalDateTime now = LocalDateTime.now(); + List availableCoupons = new ArrayList<>(); + + List userCouponDOs = userCouponMapper.selectList(new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getStatus, 1) + .eq(UserCouponDO::getIsDelete, 0) + ); + + for (UserCouponDO userCouponDO : userCouponDOs) { + CouponDO couponDO = getById(userCouponDO.getCouponId()); + if (!isCouponApplicable(couponDO, now, orderAmount, productTags, shopId)) { + continue; + } + availableCoupons.add(convertToUserCouponVO(userCouponDO, couponDO)); + } + + UserDO userDO = userMapper.selectById(userId); + String currentVipLevel = userDO != null ? userDO.getLevel() : null; + if (currentVipLevel != null && !currentVipLevel.isBlank() && !VIP_LEVEL_NORMAL.equals(currentVipLevel)) { + List vipCoupons = listVipAutoCouponsByShop(currentVipLevel, shopId); + + for (CouponDO couponDO : vipCoupons) { + if (!isCouponApplicable(couponDO, now, orderAmount, productTags, shopId)) { + continue; + } + availableCoupons.add(convertToSystemVipCouponVO(couponDO)); + } + } + + availableCoupons.sort(Comparator + .comparing((UserCouponVO item) -> calculateDiscountAmount(item, orderAmount)).reversed() + .thenComparing(UserCouponVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))); + return availableCoupons; + } + + @Override + @Transactional + /** + * Run business method `initializeDefaultVipAutoCoupons`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + */ + public void initializeDefaultVipAutoCoupons(Long shopId) { + if (shopId == null || shopId <= 0) { + return; + } + + LocalDateTime startTime = LocalDateTime.now(); + for (VipAutoCouponTemplate template : DEFAULT_SHOP_VIP_AUTO_COUPONS) { + String couponCode = buildShopVipAutoCouponCode(shopId, template.codeSuffix()); + CouponDO existingCoupon = lambdaQuery() + .eq(CouponDO::getCouponCode, couponCode) + .one(); + if (existingCoupon != null) { + continue; + } + + CouponDO couponDO = new CouponDO(); + couponDO.setCouponCode(couponCode); + couponDO.setCouponName(template.couponName()); + couponDO.setCouponType(1); + couponDO.setDiscountValue(template.discountValue()); + couponDO.setMinAmount(BigDecimal.ZERO); + couponDO.setReduceAmount(BigDecimal.ZERO); + couponDO.setTotalCount(DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT); + couponDO.setUsedCount(0); + couponDO.setStartTime(startTime); + couponDO.setEndTime(DEFAULT_VIP_AUTO_COUPON_END_TIME); + couponDO.setStatus(1); + couponDO.setShopId(shopId); + couponDO.setCouponScene(COUPON_SCENE_VIP_AUTO); + couponDO.setRequiredVipLevel(template.requiredVipLevel()); + couponDO.setAutoMatch(1); + couponDO.setIsDelete(0); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + save(couponDO); + } + } + + @Override + @Transactional + /** + * Run business method `distributeCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @param quantity parameter `quantity` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId) { + // 检查优惠券是否存在 + CouponDO couponDO = getById(couponId); + if (couponDO == null || couponDO.getIsDelete() == 1) { + return false; + } + + // 检查优惠券是否可用 + if (couponDO.getStatus() != 1) { + return false; + } + if (isVipAutoCoupon(couponDO)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); + } + + // 检查优惠券数量是否足够 + if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) { + return false; + } + if (userIds == null || userIds.isEmpty() || quantity == null || quantity < 1) { + return false; + } + if (quantity > 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户券受唯一索引限制,同一用户同一模板只能发放 1 张"); + } + List targetUserIds = userIds.stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (targetUserIds.isEmpty()) { + return false; + } + + for (Long userId : targetUserIds) { + if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { + return false; + } + UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getCouponId, couponId) + .eq(UserCouponDO::getIsDelete, 0)); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户已持有该优惠券,不能重复发放"); + } + } + + int totalNeeded = targetUserIds.size() * quantity; + if (!hasRemainingDistributionStock(couponDO, totalNeeded)) { + return false; + } + + // 发放优惠券 + LocalDateTime obtainTime = LocalDateTime.now(); + for (Long userId : targetUserIds) { + UserCouponDO userCouponDO = new UserCouponDO(); + userCouponDO.setUserId(userId); + userCouponDO.setCouponId(couponId); + userCouponDO.setStatus(1); + userCouponDO.setObtainTime(obtainTime); + userCouponMapper.insert(userCouponDO); + } + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + refreshCouponDistributionStatus(couponId); + + return true; + } + + /** + * 处理优惠券标签关联 + */ + private void handleCouponTags(Long couponId, List availableTagIds, List unavailableTagIds) { + // 先查询所有现有的标签关联 + List existingTags = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponId) + .eq(CouponTagDO::getIsDelete, 0) + ); + + // 构建现有标签的映射,方便快速查找 + java.util.Map existingTagMap = new java.util.HashMap<>(); + for (CouponTagDO tag : existingTags) { + existingTagMap.put(tag.getTagId(), tag); + } + + // 处理可用标签 + if (availableTagIds != null) { + for (Long tagId : availableTagIds) { + if (existingTagMap.containsKey(tagId)) { + // 如果标签已存在,更新其状态 + CouponTagDO existingTag = existingTagMap.get(tagId); + if (existingTag.getIsAvailable() != 1) { + existingTag.setIsAvailable(1); + couponTagMapper.updateById(existingTag); + } + existingTagMap.remove(tagId); // 标记为已处理 + } else { + // 如果标签不存在,创建新的 + CouponTagDO couponTagDO = new CouponTagDO(); + couponTagDO.setCouponId(couponId); + couponTagDO.setTagId(tagId); + couponTagDO.setIsAvailable(1); + couponTagMapper.insert(couponTagDO); + } + } + } + + // 处理不可用标签 + if (unavailableTagIds != null) { + for (Long tagId : unavailableTagIds) { + if (existingTagMap.containsKey(tagId)) { + // 如果标签已存在,更新其状态 + CouponTagDO existingTag = existingTagMap.get(tagId); + if (existingTag.getIsAvailable() != 0) { + existingTag.setIsAvailable(0); + couponTagMapper.updateById(existingTag); + } + existingTagMap.remove(tagId); // 标记为已处理 + } else { + // 如果标签不存在,创建新的 + CouponTagDO couponTagDO = new CouponTagDO(); + couponTagDO.setCouponId(couponId); + couponTagDO.setTagId(tagId); + couponTagDO.setIsAvailable(0); + couponTagMapper.insert(couponTagDO); + } + } + } + + // 删除剩余的标签关联(这些是不在新列表中的标签) + for (CouponTagDO tagToDelete : existingTagMap.values()) { + couponTagMapper.deleteById(tagToDelete.getId()); + } + } + + /** + * 检查标签是否匹配 + */ + private boolean checkTagMatch(Long couponId, String productTags) { + if (productTags == null || productTags.isEmpty()) { + return true; + } + + // 解析商品标签 + String[] tagNames = productTags.split(","); + + // 查询所有标签 + List allTags = tagMapper.selectList(new LambdaQueryWrapper<>()); + + // 找到匹配的标签ID + List productTagIds = allTags.stream() + .filter(tag -> { + for (String tagName : tagNames) { + if (tag.getTagName() != null && tag.getTagName().equals(tagName.trim())) { + return true; + } + } + return false; + }) + .map(tag -> tag.getId()) + .collect(Collectors.toList()); + + if (productTagIds.isEmpty()) { + return true; + } + + // 查询优惠券的所有标签关联 + List couponTagDOs = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponId) + ); + + // 分离可用标签和不可用标签 + List availableTagIds = couponTagDOs.stream() + .filter(tag -> tag.getIsAvailable() == 1) + .map(tag -> tag.getTagId()) + .collect(Collectors.toList()); + + List unavailableTagIds = couponTagDOs.stream() + .filter(tag -> tag.getIsAvailable() == 0) + .map(tag -> tag.getTagId()) + .collect(Collectors.toList()); + + // 检查是否有不可用标签 + for (Long tagId : productTagIds) { + if (unavailableTagIds.contains(tagId)) { + return false; + } + } + + // 检查是否只包含可用标签(如果有可用标签配置) + if (!availableTagIds.isEmpty()) { + for (Long tagId : productTagIds) { + if (!availableTagIds.contains(tagId)) { + return false; + } + } + } + + return true; + } + + /** + * 转换为CouponVO + */ + private List listVipAutoCouponsByShop(String requiredVipLevel, Long shopId) { + if (shopId != null && shopId > 0) { + List shopCoupons = list(buildVipAutoCouponQuery(requiredVipLevel) + .eq(CouponDO::getShopId, shopId)); + if (!shopCoupons.isEmpty()) { + return shopCoupons; + } + return list(buildVipAutoCouponQuery(requiredVipLevel) + .isNull(CouponDO::getShopId)); + } + return list(buildVipAutoCouponQuery(requiredVipLevel)); + } + + /** + * Run business method `buildVipAutoCouponQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller + * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ + private LambdaQueryWrapper buildVipAutoCouponQuery(String requiredVipLevel) { + return new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0) + .eq(CouponDO::getStatus, 1) + .eq(CouponDO::getAutoMatch, 1) + .eq(CouponDO::getCouponScene, COUPON_SCENE_VIP_AUTO) + .eq(CouponDO::getRequiredVipLevel, requiredVipLevel) + .orderByDesc(CouponDO::getDiscountValue) + .orderByAsc(CouponDO::getEndTime); + } + + /** + * Run business method `buildShopVipAutoCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param codeSuffix parameter `codeSuffix` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildShopVipAutoCouponCode(Long shopId, String codeSuffix) { + return String.format("VIP_AUTO_SHOP_%d_%s", shopId, codeSuffix); + } + + /** + * Run business method `resolveCouponCodeForCreate`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedCode parameter `requestedCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveCouponCodeForCreate(String requestedCode) { + if (StringUtils.hasText(requestedCode)) { + return requestedCode.trim(); + } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return result consumed by the caller or returned to the frontend + */ + return generateUniqueManualCouponCode(); + } + + /** + * Run business method `resolveCouponCodeForUpdate`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param existingCode parameter `existingCode` supplied by the caller + * @param requestedCode parameter `requestedCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveCouponCodeForUpdate(String existingCode, String requestedCode) { + if (StringUtils.hasText(requestedCode)) { + return requestedCode.trim(); + } + if (StringUtils.hasText(existingCode)) { + return existingCode.trim(); + } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return result consumed by the caller or returned to the frontend + */ + return generateUniqueManualCouponCode(); + } + + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String generateUniqueManualCouponCode() { + for (int attempt = 0; attempt < 10; attempt++) { + String candidate = "CPN_" + snowflakeIdGenerator.nextBase36String(13); + if (lambdaQuery().eq(CouponDO::getCouponCode, candidate).count() == 0) { + return candidate; + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("生成优惠券编码失败,请稍后重试"); + } + + /** + * Run business method `convertToCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private CouponVO result consumed by the caller or returned to the frontend + */ + private CouponVO convertToCouponVO(CouponDO couponDO) { + CouponVO couponVO = new CouponVO(); + couponVO.setId(couponDO.getId()); + couponVO.setCouponCode(couponDO.getCouponCode()); + couponVO.setCouponName(couponDO.getCouponName()); + couponVO.setCouponType(couponDO.getCouponType()); + couponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券"); + couponVO.setDiscountValue(couponDO.getDiscountValue()); + couponVO.setMinAmount(couponDO.getMinAmount()); + couponVO.setReduceAmount(couponDO.getReduceAmount()); + couponVO.setTotalCount(couponDO.getTotalCount()); + couponVO.setUsedCount(normalizeCount(couponDO.getUsedCount())); + couponVO.setRemainingCount(calculateRemainingDistributionCount(couponDO)); + couponVO.setStartTime(couponDO.getStartTime()); + couponVO.setEndTime(couponDO.getEndTime()); + couponVO.setStatus(couponDO.getStatus()); + couponVO.setShopId(couponDO.getShopId()); + couponVO.setCouponScene(couponDO.getCouponScene()); + couponVO.setRequiredVipLevel(couponDO.getRequiredVipLevel()); + couponVO.setAutoMatch(couponDO.getAutoMatch()); + + // 获取店铺名称 + if (couponDO.getShopId() != null) { + ShopDO shopDO = shopMapper.selectById(couponDO.getShopId()); + if (shopDO != null) { + couponVO.setShopName(shopDO.getShopName()); + } + } + + switch (couponDO.getStatus()) { + case 1: + couponVO.setStatusName("可用"); + break; + case 2: + couponVO.setStatusName("已过期"); + break; + case 3: + couponVO.setStatusName("已用完"); + break; + default: + couponVO.setStatusName("未知"); + } + + // 获取可用标签 + List availableTags = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponDO.getId()) + .eq(CouponTagDO::getIsAvailable, 1) + ).stream() + .map(couponTag -> { + TagVO tagVO = new TagVO(); + tagVO.setId(couponTag.getTagId()); + return tagVO; + }) + .collect(Collectors.toList()); + couponVO.setAvailableTags(availableTags); + + // 获取不可用标签 + List unavailableTags = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponDO.getId()) + .eq(CouponTagDO::getIsAvailable, 0) + ).stream() + .map(couponTag -> { + TagVO tagVO = new TagVO(); + tagVO.setId(couponTag.getTagId()); + return tagVO; + }) + .collect(Collectors.toList()); + couponVO.setUnavailableTags(unavailableTags); + + return couponVO; + } + + /** + * 转换为UserCouponVO + */ + private UserCouponVO convertToUserCouponVO(UserCouponDO userCouponDO, CouponDO couponDO) { + UserCouponVO userCouponVO = buildCouponOption(userCouponDO.getId(), couponDO, COUPON_SOURCE_USER, false); + userCouponVO.setStatus(userCouponDO.getStatus()); + switch (userCouponDO.getStatus()) { + case 1: + userCouponVO.setStatusName("未使用"); + break; + case 2: + userCouponVO.setStatusName("已使用"); + break; + case 3: + userCouponVO.setStatusName("已过期"); + break; + default: + userCouponVO.setStatusName("未知"); + } + userCouponVO.setObtainTime(userCouponDO.getObtainTime()); + userCouponVO.setUseTime(userCouponDO.getUseTime()); + return userCouponVO; + } + + /** + * Run business method `convertToSystemVipCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private UserCouponVO result consumed by the caller or returned to the frontend + */ + private UserCouponVO convertToSystemVipCouponVO(CouponDO couponDO) { + UserCouponVO userCouponVO = buildCouponOption(couponDO.getId(), couponDO, COUPON_SOURCE_SYSTEM_VIP, true); + userCouponVO.setStatus(1); + userCouponVO.setStatusName("系统自动匹配"); + return userCouponVO; + } + + /** + * Run business method `buildCouponOption`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param optionId parameter `optionId` supplied by the caller + * @param couponDO parameter `couponDO` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param autoMatched parameter `autoMatched` supplied by the caller + * @return private UserCouponVO result consumed by the caller or returned to the frontend + */ + private UserCouponVO buildCouponOption(Long optionId, CouponDO couponDO, String sourceType, boolean autoMatched) { + UserCouponVO userCouponVO = new UserCouponVO(); + userCouponVO.setId(optionId); + userCouponVO.setCouponId(couponDO.getId()); + userCouponVO.setCouponName(couponDO.getCouponName()); + userCouponVO.setCouponType(couponDO.getCouponType()); + userCouponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券"); + userCouponVO.setDiscountValue(couponDO.getDiscountValue() != null ? couponDO.getDiscountValue().toString() : ""); + userCouponVO.setMinAmount(couponDO.getMinAmount() != null ? couponDO.getMinAmount().toString() : ""); + userCouponVO.setReduceAmount(couponDO.getReduceAmount() != null ? couponDO.getReduceAmount().toString() : ""); + userCouponVO.setStartTime(couponDO.getStartTime()); + userCouponVO.setEndTime(couponDO.getEndTime()); + userCouponVO.setSourceType(sourceType); + userCouponVO.setRequiredVipLevel(couponDO.getRequiredVipLevel()); + userCouponVO.setAutoMatched(autoMatched); + return userCouponVO; + } + + /** + * Run business method `isCouponApplicable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param now parameter `now` supplied by the caller + * @param orderAmount parameter `orderAmount` supplied by the caller + * @param productTags parameter `productTags` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isCouponApplicable(CouponDO couponDO, LocalDateTime now, BigDecimal orderAmount, String productTags, Long shopId) { + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + return false; + } + if (couponDO.getStatus() == null || couponDO.getStatus() != 1) { + return false; + } + if (couponDO.getStartTime() != null && now.isBefore(couponDO.getStartTime())) { + return false; + } + if (couponDO.getEndTime() != null && now.isAfter(couponDO.getEndTime())) { + return false; + } + if (!matchesShop(couponDO, shopId)) { + return false; + } + if (couponDO.getCouponType() == 2 + && couponDO.getMinAmount() != null + && couponDO.getMinAmount().compareTo(orderAmount) > 0) { + return false; + } + return checkTagMatch(couponDO.getId(), productTags); + } + + /** + * Run business method `matchesShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean matchesShop(CouponDO couponDO, Long shopId) { + if (shopId == null || couponDO.getShopId() == null) { + return true; + } + return shopId.equals(couponDO.getShopId()); + } + + /** + * Run business method `isVipAutoCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVipAutoCoupon(CouponDO couponDO) { + return couponDO != null + && Integer.valueOf(1).equals(couponDO.getAutoMatch()) + && COUPON_SCENE_VIP_AUTO.equals(couponDO.getCouponScene()); + } + + /** + * Run business method `hasRemainingDistributionStock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param requiredCount parameter `requiredCount` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean hasRemainingDistributionStock(CouponDO couponDO, int requiredCount) { + return calculateRemainingDistributionCount(couponDO) >= requiredCount; + } + + /** + * Run business method `calculateRemainingDistributionCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int calculateRemainingDistributionCount(CouponDO couponDO) { + if (couponDO == null || couponDO.getId() == null) { + return 0; + } + int totalCount = normalizeCount(couponDO.getTotalCount()); + long issuedCount = userCouponMapper.selectCount(new LambdaQueryWrapper() + .eq(UserCouponDO::getCouponId, couponDO.getId()) + .eq(UserCouponDO::getIsDelete, 0)); + return Math.max(0, totalCount - (int) issuedCount); + } + + /** + * Run business method `incrementCouponUsedCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void incrementCouponUsedCount(Long couponId) { + CouponDO couponDO = getById(couponId); + if (couponDO == null) { + return; + } + couponDO.setUsedCount(normalizeCount(couponDO.getUsedCount()) + 1); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + } + + /** + * Run business method `decrementCouponUsedCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void decrementCouponUsedCount(Long couponId) { + CouponDO couponDO = getById(couponId); + if (couponDO == null) { + return; + } + couponDO.setUsedCount(Math.max(0, normalizeCount(couponDO.getUsedCount()) - 1)); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + } + + /** + * Run business method `isUserEligibleForCouponDistribution`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param couponDO parameter `couponDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isUserEligibleForCouponDistribution(Long userId, CouponDO couponDO, Long requestedShopId) { + if (userId == null) { + return false; + } + + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + if (requestedShopId != null && !userShopBindingSupport.isUserAccessibleInShop(userId, requestedShopId)) { + return false; + } + if (couponDO != null && couponDO.getShopId() != null + && !userShopBindingSupport.isUserAccessibleInShop(userId, couponDO.getShopId())) { + return false; + } + return true; + } + + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void refreshCouponDistributionStatus(Long couponId) { + CouponDO couponDO = getById(couponId); + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + return; + } + if (Integer.valueOf(2).equals(couponDO.getStatus())) { + return; + } + + int remainingCount = calculateRemainingDistributionCount(couponDO); + int targetStatus = remainingCount > 0 ? 1 : 3; + if (!Objects.equals(couponDO.getStatus(), targetStatus)) { + couponDO.setStatus(targetStatus); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + } + } + + /** + * Run business method `normalizeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param count parameter `count` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int normalizeCount(Integer count) { + return count == null ? 0 : count; + } + + /** + * Run business method `calculateDiscountAmount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponVO parameter `couponVO` supplied by the caller + * @param orderAmount parameter `orderAmount` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal calculateDiscountAmount(UserCouponVO couponVO, BigDecimal orderAmount) { + if (couponVO == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + if (couponVO.getCouponType() == 1 && couponVO.getDiscountValue() != null && !couponVO.getDiscountValue().isBlank()) { + BigDecimal discountValue = new BigDecimal(couponVO.getDiscountValue()); + BigDecimal actualAmount = orderAmount.multiply(discountValue) + .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); + return orderAmount.subtract(actualAmount); + } + if (couponVO.getCouponType() == 2 && couponVO.getReduceAmount() != null && !couponVO.getReduceAmount().isBlank()) { + return new BigDecimal(couponVO.getReduceAmount()); + } + return BigDecimal.ZERO; + } + + /** + * Purpose: VipAutoCouponTemplate supports CouponServiceImpl.java by holding or executing the vip auto coupon template business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + private record VipAutoCouponTemplate( + String codeSuffix, + String couponName, + String requiredVipLevel, + BigDecimal discountValue + ) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/GrowthServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/GrowthServiceImpl.java new file mode 100644 index 00000000..7075c445 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/GrowthServiceImpl.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserGrowthRecordDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserGrowthRecordMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.GrowthService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.GrowthSummaryVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class GrowthServiceImpl implements GrowthService { + + private final UserGrowthRecordMapper userGrowthRecordMapper; + + @Override + public GrowthSummaryVO getSummary(Long userId) { + Integer growthValue = userGrowthRecordMapper.selectList(new LambdaQueryWrapper() + .eq(UserGrowthRecordDO::getUserId, userId)) + .stream() + .map(UserGrowthRecordDO::getGrowthValue) + .filter(value -> value != null) + .reduce(0, Integer::sum); + GrowthSummaryVO vo = new GrowthSummaryVO(); + vo.setUserId(userId); + vo.setGrowthValue(growthValue); + vo.setLevelName(growthValue >= 1000 ? "黄金会员" : growthValue >= 300 ? "白银会员" : "成长新客"); + vo.setAppointmentCount(0); + vo.setReviewCount(0); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/ProductLikeServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/ProductLikeServiceImpl.java new file mode 100644 index 00000000..8dcf1754 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/ProductLikeServiceImpl.java @@ -0,0 +1,104 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.ProductLikeDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.ProductLikeMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.ProductLikeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * 商品点赞记录表 Service 实现 + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +@Service +public class ProductLikeServiceImpl extends ServiceImpl implements ProductLikeService { + + @Autowired + /** + * Purpose: productMapper supports ProductLikeServiceImpl.java by holding or executing the product mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductMapper productMapper; + + @Override + @Transactional + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + public void addLike(Long userId, Long productId) { + // 检查是否已点赞 + if (isProductLiked(userId, productId)) { + return; + } + + // 添加点赞记录 + ProductLikeDO productLikeDO = new ProductLikeDO(); + productLikeDO.setUserId(userId); + productLikeDO.setProductId(productId); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productLikeDO parameter `productLikeDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + save(productLikeDO); + + // 增加商品点赞数 + productMapper.incrementLikeCount(productId); + } + + @Override + @Transactional + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + public void removeLike(Long userId, Long productId) { + // 检查是否已点赞 + if (!isProductLiked(userId, productId)) { + return; + } + + // 删除点赞记录 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductLikeDO::getUserId, userId); + wrapper.eq(ProductLikeDO::getProductId, productId); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + remove(wrapper); + + // 减少商品点赞数 + productMapper.decrementLikeCount(productId); + } + + @Override + /** + * Run business method `isProductLiked`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isProductLiked(Long userId, Long productId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductLikeDO::getUserId, userId); + wrapper.eq(ProductLikeDO::getProductId, productId); + return count(wrapper) > 0; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipBenefitServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipBenefitServiceImpl.java new file mode 100644 index 00000000..1fccd346 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipBenefitServiceImpl.java @@ -0,0 +1,141 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipBenefitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipBenefitDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.VipBenefitMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.VipBenefitService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipBenefitVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * VIP权益信息表 Service 实现 + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class VipBenefitServiceImpl extends ServiceImpl implements VipBenefitService { + /** + * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipBenefitMapper vipBenefitMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createVipBenefit(VipBenefitDTO vipBenefitDTO) { + VipBenefitDO vipBenefitDO = new VipBenefitDO(); + vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); + vipBenefitDO.setRequiredVipLevel(vipBenefitDTO.getRequiredVipLevel()); + vipBenefitMapper.insert(vipBenefitDO); + return vipBenefitDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateVipBenefit(Long id, VipBenefitDTO vipBenefitDTO) { + VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); + if (vipBenefitDO == null) { + return false; + } + vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); + vipBenefitDO.setRequiredVipLevel(vipBenefitDTO.getRequiredVipLevel()); + return vipBenefitMapper.updateById(vipBenefitDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteVipBenefit(Long id) { + return vipBenefitMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return VipBenefitVO result consumed by the caller or returned to the frontend + */ + public VipBenefitVO getVipBenefitById(Long id) { + VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); + if (vipBenefitDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipBenefitDO parameter `vipBenefitDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(vipBenefitDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllVipBenefits() { + List vipBenefitDOs = vipBenefitMapper.selectList(null); + return vipBenefitDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listVipBenefitsByRequiredVipLevel(String requiredVipLevel) { + List vipBenefitDOs = vipBenefitMapper.selectList( + Wrappers.lambdaQuery(VipBenefitDO.class) + .eq(VipBenefitDO::getRequiredVipLevel, requiredVipLevel) + ); + return vipBenefitDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param vipBenefitDO VIP权益DO + * @return VIP权益VO + */ + private VipBenefitVO convertToVO(VipBenefitDO vipBenefitDO) { + VipBenefitVO vipBenefitVO = new VipBenefitVO(); + vipBenefitVO.setId(vipBenefitDO.getId()); + vipBenefitVO.setBenefitInfo(vipBenefitDO.getBenefitInfo()); + vipBenefitVO.setRequiredVipLevel(vipBenefitDO.getRequiredVipLevel()); + vipBenefitVO.setCreateTime(vipBenefitDO.getCreateTime()); + vipBenefitVO.setUpdateTime(vipBenefitDO.getUpdateTime()); + return vipBenefitVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipInfoServiceImpl.java new file mode 100644 index 00000000..a21949bd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipInfoServiceImpl.java @@ -0,0 +1,156 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.VipInfoMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.VipInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户VIP信息表 Service 实现 + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class VipInfoServiceImpl extends ServiceImpl implements VipInfoService { + /** + * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipInfoMapper vipInfoMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createVipInfo(VipInfoDTO vipInfoDTO) { + VipInfoDO vipInfoDO = new VipInfoDO(); + vipInfoDO.setUserId(vipInfoDTO.getUserId()); + vipInfoDO.setVipLevel(vipInfoDTO.getVipLevel()); + vipInfoDO.setStartTime(vipInfoDTO.getStartTime()); + vipInfoDO.setExpireTime(vipInfoDTO.getExpireTime()); + vipInfoDO.setActivationMethod(vipInfoDTO.getActivationMethod()); + vipInfoDO.setBenefitId(vipInfoDTO.getBenefitId()); + vipInfoDO.setManualOverride(vipInfoDTO.getManualOverride()); + vipInfoMapper.insert(vipInfoDO); + return vipInfoDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO) { + VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); + if (vipInfoDO == null) { + return false; + } + vipInfoDO.setUserId(vipInfoDTO.getUserId()); + vipInfoDO.setVipLevel(vipInfoDTO.getVipLevel()); + vipInfoDO.setStartTime(vipInfoDTO.getStartTime()); + vipInfoDO.setExpireTime(vipInfoDTO.getExpireTime()); + vipInfoDO.setActivationMethod(vipInfoDTO.getActivationMethod()); + vipInfoDO.setBenefitId(vipInfoDTO.getBenefitId()); + vipInfoDO.setManualOverride(vipInfoDTO.getManualOverride()); + return vipInfoMapper.updateById(vipInfoDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteVipInfo(Long id) { + return vipInfoMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return VipInfoVO result consumed by the caller or returned to the frontend + */ + public VipInfoVO getVipInfoById(Long id) { + VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); + if (vipInfoDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipInfoDO parameter `vipInfoDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(vipInfoDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllVipInfos() { + List vipInfoDOs = vipInfoMapper.selectList(null); + return vipInfoDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipLevel parameter `vipLevel` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listVipInfosByVipLevel(String vipLevel) { + List vipInfoDOs = vipInfoMapper.selectList( + Wrappers.lambdaQuery(VipInfoDO.class) + .eq(VipInfoDO::getVipLevel, vipLevel) + ); + return vipInfoDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param vipInfoDO VIP信息DO + * @return VIP信息VO + */ + private VipInfoVO convertToVO(VipInfoDO vipInfoDO) { + VipInfoVO vipInfoVO = new VipInfoVO(); + vipInfoVO.setId(vipInfoDO.getId()); + vipInfoVO.setUserId(vipInfoDO.getUserId()); + vipInfoVO.setVipLevel(vipInfoDO.getVipLevel()); + vipInfoVO.setStartTime(vipInfoDO.getStartTime()); + vipInfoVO.setExpireTime(vipInfoDO.getExpireTime()); + vipInfoVO.setActivationMethod(vipInfoDO.getActivationMethod()); + vipInfoVO.setBenefitId(vipInfoDO.getBenefitId()); + vipInfoVO.setManualOverride(vipInfoDO.getManualOverride()); + vipInfoVO.setCreateTime(vipInfoDO.getCreateTime()); + vipInfoVO.setUpdateTime(vipInfoDO.getUpdateTime()); + return vipInfoVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java new file mode 100644 index 00000000..56d81536 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java @@ -0,0 +1,397 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.VipRechargePlanDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipRechargePlanDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.VipRechargePlanMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.VipRechargePlanService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.VipRechargePlanVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * VipRechargePlanServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class VipRechargePlanServiceImpl extends ServiceImpl implements VipRechargePlanService { + public static final List DEFAULT_VIP_LEVELS = List.of("普通", "青铜", "白银", "黄金"); + /** + * Variable `planMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipRechargePlanMapper planMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createPlan(UserDO currentUser, VipRechargePlanDTO dto) { + Long shopId = resolveManagedShopId(currentUser, dto.getShopId()); + VipRechargePlanDO plan = new VipRechargePlanDO(); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(plan, dto, shopId); + plan.setIsDelete(0); + planMapper.insert(plan); + return plan.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto) { + VipRechargePlanDO plan = requirePlan(id); + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlanAccessible(currentUser, plan); + Long shopId = resolveManagedShopId(currentUser, dto.getShopId() == null ? plan.getShopId() : dto.getShopId()); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(plan, dto, shopId); + planMapper.updateById(plan); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateStatus(UserDO currentUser, Long id, Integer status) { + VipRechargePlanDO plan = requirePlan(id); + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlanAccessible(currentUser, plan); + plan.setStatus(Integer.valueOf(1).equals(status) ? 1 : 0); + planMapper.updateById(plan); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminPlans(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + if (scopedShopId != null && scopedShopId > 0) { + ensureDefaultPlans(scopedShopId); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByDesc(VipRechargePlanDO::getCreateTime); + if (scopedShopId != null && scopedShopId > 0) { + wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); + } + return toVOList(planMapper.selectList(wrapper)); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyPlans(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + Set shopIds = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) { + shopIds.add(user.getShopId()); + } + userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)) + .forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) shopIds.add(binding.getShopId()); + }); + if (shopIds.isEmpty()) { + return List.of(); + } + shopIds.forEach(this::ensureDefaultPlans); + return toVOList(planMapper.selectList(new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .eq(VipRechargePlanDO::getStatus, 1) + .in(VipRechargePlanDO::getShopId, shopIds) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByAsc(VipRechargePlanDO::getRechargeAmount))); + } + + @Override + /** + * Purpose: listVipLevelOptions supports VipRechargePlanServiceImpl.java by holding or executing the list vip level options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listVipLevelOptions(UserDO currentUser, Long shopId) { + Long scopedShopId = currentUser == null ? shopId : adminScopeHelper.resolveShopScope(currentUser, shopId); + if (scopedShopId != null && scopedShopId > 0) { + ensureDefaultPlans(scopedShopId); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .eq(VipRechargePlanDO::getStatus, 1) + .isNotNull(VipRechargePlanDO::getVipLevel) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByAsc(VipRechargePlanDO::getRechargeAmount); + if (scopedShopId != null && scopedShopId > 0) { + wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); + } + LinkedHashSet levels = new LinkedHashSet<>(DEFAULT_VIP_LEVELS); + planMapper.selectList(wrapper).stream() + .map(VipRechargePlanDO::getVipLevel) + .filter(level -> level != null && !level.trim().isEmpty()) + .map(String::trim) + .forEach(levels::add); + return List.copyOf(levels); + } + + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void apply(VipRechargePlanDO plan, VipRechargePlanDTO dto, Long shopId) { + /** + * Run business method `ensureShopExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopExists(shopId); + plan.setShopId(shopId); + plan.setTitle(dto.getTitle().trim()); + plan.setRechargeAmount(dto.getRechargeAmount()); + plan.setGiftAmount(dto.getGiftAmount()); + plan.setVipLevel(dto.getVipLevel().trim()); + plan.setDescription(dto.getDescription()); + plan.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + plan.setStatus(Integer.valueOf(0).equals(dto.getStatus()) ? 0 : 1); + } + + /** + * Run business method `resolveManagedShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveManagedShopId(UserDO currentUser, Long requestedShopId) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, requestedShopId); + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权维护其他店铺充值档位"); + return shopId; + } + + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePlanAccessible(UserDO currentUser, VipRechargePlanDO plan) { + adminScopeHelper.ensureShopAccessible(currentUser, plan.getShopId(), "无权维护其他店铺充值档位"); + } + + /** + * Run business method `requirePlan`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private VipRechargePlanDO result consumed by the caller or returned to the frontend + */ + private VipRechargePlanDO requirePlan(Long id) { + VipRechargePlanDO plan = planMapper.selectById(id); + if (plan == null || Integer.valueOf(1).equals(plan.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("充值档位不存在"); + } + return plan; + } + + /** + * Run business method `ensureShopExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureShopExists(Long shopId) { + ShopDO shop = shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店铺不存在"); + } + } + + /** + * Purpose: ensureDefaultPlans supports VipRechargePlanServiceImpl.java by holding or executing the ensure default plans business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensureDefaultPlans(Long shopId) { + if (shopId == null || shopId <= 0) { + return; + } + createDefaultPlanIfMissing(shopId, "青铜", new BigDecimal("99.00"), 10); + createDefaultPlanIfMissing(shopId, "白银", new BigDecimal("299.00"), 20); + createDefaultPlanIfMissing(shopId, "黄金", new BigDecimal("599.00"), 30); + } + + /** + * Purpose: createDefaultPlanIfMissing supports VipRechargePlanServiceImpl.java by holding or executing the create default plan if missing business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void createDefaultPlanIfMissing(Long shopId, String vipLevel, BigDecimal rechargeAmount, int sortOrder) { + Long count = planMapper.selectCount(new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getShopId, shopId) + .eq(VipRechargePlanDO::getVipLevel, vipLevel) + .eq(VipRechargePlanDO::getIsDelete, 0)); + if (count != null && count > 0) { + return; + } + VipRechargePlanDO plan = new VipRechargePlanDO(); + plan.setShopId(shopId); + plan.setTitle(vipLevel + "会员充值"); + plan.setRechargeAmount(rechargeAmount); + plan.setGiftAmount(BigDecimal.ZERO); + plan.setVipLevel(vipLevel); + plan.setDescription("系统默认配置,可按门店实际规则修改"); + plan.setSortOrder(sortOrder); + plan.setStatus(1); + plan.setIsDelete(0); + planMapper.insert(plan); + } + + /** + * Run business method `toVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plans parameter `plans` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toVOList(List plans) { + Set shopIds = plans.stream().map(VipRechargePlanDO::getShopId).filter(Objects::nonNull).collect(Collectors.toSet()); + Map shopNameMap = shopIds.isEmpty() + ? Map.of() + : shopMapper.selectList(new LambdaQueryWrapper().in(ShopDO::getId, shopIds)) + .stream() + .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + return plans.stream().map(plan -> { + VipRechargePlanVO vo = new VipRechargePlanVO(); + vo.setId(plan.getId()); + vo.setShopId(plan.getShopId()); + vo.setShopName(shopNameMap.get(plan.getShopId())); + vo.setTitle(plan.getTitle()); + vo.setRechargeAmount(plan.getRechargeAmount()); + vo.setGiftAmount(plan.getGiftAmount()); + vo.setVipLevel(plan.getVipLevel()); + vo.setDescription(plan.getDescription()); + vo.setSortOrder(plan.getSortOrder()); + vo.setStatus(plan.getStatus()); + vo.setCreateTime(plan.getCreateTime()); + vo.setUpdateTime(plan.getUpdateTime()); + return vo; + }).collect(Collectors.toList()); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/WishlistServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/WishlistServiceImpl.java new file mode 100644 index 00000000..2c834a65 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/service/impl/WishlistServiceImpl.java @@ -0,0 +1,384 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistAddWithGroupDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistGroupDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistMoveDTO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.WishlistDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.WishlistGroupDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.WishlistGroupMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.WishlistMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.ProductService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.WishlistService; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.ProductVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.WishlistGroupVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.WishlistInspirationVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class WishlistServiceImpl extends ServiceImpl implements WishlistService { + + private static final List PRESET_GROUP_NAMES = List.of( + "\u6700\u8fd1\u60f3\u505a", + "\u5a5a\u793c\u6b3e", + "\u590f\u5929\u6b3e" + ); + private static final int DEFAULT_SORT_ORDER = 100; + private static final int NOTE_MAX_LENGTH = 500; + + private final WishlistMapper wishlistMapper; + private final WishlistGroupMapper wishlistGroupMapper; + private final ProductService productService; + private final ProductMapper productMapper; + + @Override + @Transactional + public void addToWishlist(Long userId, Long productId) { + WishlistAddWithGroupDTO dto = new WishlistAddWithGroupDTO(); + dto.setProductId(productId); + addToWishlist(userId, dto); + } + + @Override + @Transactional + public void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO) { + Long productId = wishlistDTO == null ? null : wishlistDTO.getProductId(); + ProductDO product = getValidProduct(productId); + if (product == null) { + throw new RuntimeException("\u5546\u54c1\u4e0d\u5b58\u5728\u6216\u5df2\u4e0b\u67b6"); + } + + WishlistGroupDO group = resolveTargetGroup(userId, wishlistDTO == null ? null : wishlistDTO.getGroupId()); + WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); + if (existing == null) { + WishlistDO wishlistDO = new WishlistDO(); + wishlistDO.setUserId(userId); + wishlistDO.setProductId(productId); + wishlistDO.setGroupId(group.getId()); + wishlistDO.setNote(normalizeNote(wishlistDTO == null ? null : wishlistDTO.getNote())); + wishlistDO.setSortOrder(normalizeSortOrder(wishlistDTO == null ? null : wishlistDTO.getSortOrder())); + wishlistDO.setIsDelete(0); + wishlistMapper.insert(wishlistDO); + productMapper.incrementCollectCount(productId); + return; + } + + existing.setGroupId(group.getId()); + existing.setNote(normalizeNote(wishlistDTO.getNote())); + if (wishlistDTO.getSortOrder() != null) { + existing.setSortOrder(normalizeSortOrder(wishlistDTO.getSortOrder())); + } else if (existing.getSortOrder() == null) { + existing.setSortOrder(DEFAULT_SORT_ORDER); + } + wishlistMapper.updateById(existing); + } + + @Override + @Transactional + public void removeFromWishlist(Long userId, Long productId) { + WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); + if (existing == null) { + return; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getProductId, productId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wishlistMapper.delete(wrapper); + if (getValidProduct(productId) != null) { + productMapper.decrementCollectCount(productId); + } + } + + @Override + public boolean isInWishlist(Long userId, Long productId) { + if (getValidProduct(productId) == null) { + return false; + } + return findActiveWishlistByUserAndProduct(userId, productId) != null; + } + + @Override + public List getWishlistByUserId(Long userId) { + List groups = listGroups(userId); + Map groupNames = groups.stream() + .filter(group -> group.getId() != null) + .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); + return loadActiveWishlist(userId).stream() + .map(wishlistDO -> toWishlistDTO(wishlistDO, groupNames)) + .filter(wishlistDTO -> wishlistDTO.getProduct() != null) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public List listGroups(Long userId) { + return ensurePresetGroups(userId).stream() + .map(this::toGroupVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setUserId(userId); + group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); + group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); + group.setIsDelete(0); + wishlistGroupMapper.insert(group); + return group.getId(); + } + + @Override + @Transactional + public boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO) { + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + return false; + } + group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); + group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); + return wishlistGroupMapper.updateById(group) > 0; + } + + @Override + @Transactional + public boolean deleteGroup(Long userId, Long groupId) { + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + return false; + } + WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getGroupId, groupId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wishlistMapper.selectList(wrapper).forEach(wishlistDO -> { + wishlistDO.setGroupId(defaultGroup.getId()); + wishlistMapper.updateById(wishlistDO); + }); + group.setIsDelete(1); + return wishlistGroupMapper.updateById(group) > 0; + } + + @Override + @Transactional + public boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { + WishlistDO wishlistDO = findTargetWishlist(userId, wishlistMoveDTO); + if (wishlistDO == null) { + return false; + } + WishlistGroupDO group = resolveTargetGroup(userId, wishlistMoveDTO == null ? null : wishlistMoveDTO.getGroupId()); + wishlistDO.setGroupId(group.getId()); + wishlistDO.setNote(normalizeNote(wishlistMoveDTO == null ? null : wishlistMoveDTO.getNote())); + wishlistDO.setSortOrder(normalizeSortOrder(wishlistMoveDTO == null ? null : wishlistMoveDTO.getSortOrder())); + return wishlistMapper.updateById(wishlistDO) > 0; + } + + @Override + @Transactional + public WishlistInspirationVO getInspiration(Long userId) { + List groups = listGroups(userId); + Map groupMap = new LinkedHashMap<>(); + groups.forEach(group -> groupMap.put(group.getId(), group)); + + WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); + Map groupNames = groups.stream() + .filter(group -> group.getId() != null) + .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); + + List items = loadActiveWishlist(userId).stream() + .map(wishlistDO -> { + if (wishlistDO.getGroupId() == null || !groupMap.containsKey(wishlistDO.getGroupId())) { + wishlistDO.setGroupId(defaultGroup.getId()); + } + return toWishlistDTO(wishlistDO, groupNames); + }) + .filter(wishlistDTO -> wishlistDTO.getProduct() != null) + .collect(Collectors.toList()); + + items.forEach(item -> { + WishlistGroupVO group = groupMap.get(item.getGroupId()); + if (group != null) { + group.getItems().add(item); + } + }); + groups.forEach(group -> group.setItemCount(group.getItems().size())); + + WishlistInspirationVO inspirationVO = new WishlistInspirationVO(); + inspirationVO.setTotal(items.size()); + inspirationVO.setGroups(groups); + return inspirationVO; + } + + private WishlistDTO toWishlistDTO(WishlistDO wishlistDO, Map groupNames) { + WishlistDTO wishlistDTO = new WishlistDTO(); + BeanUtils.copyProperties(wishlistDO, wishlistDTO); + wishlistDTO.setGroupName(groupNames.get(wishlistDO.getGroupId())); + ProductVO productVO = productService.getProductById(wishlistDO.getProductId()); + wishlistDTO.setProduct(productVO); + return wishlistDTO; + } + + private WishlistGroupVO toGroupVO(WishlistGroupDO groupDO) { + WishlistGroupVO groupVO = new WishlistGroupVO(); + groupVO.setId(groupDO.getId()); + groupVO.setName(groupDO.getName()); + groupVO.setSortOrder(normalizeSortOrder(groupDO.getSortOrder())); + groupVO.setItemCount(0); + groupVO.setItems(new ArrayList<>()); + return groupVO; + } + + private WishlistDO findTargetWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { + if (wishlistMoveDTO == null) { + return null; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getIsDelete, 0); + if (wishlistMoveDTO.getWishlistId() != null) { + wrapper.eq(WishlistDO::getId, wishlistMoveDTO.getWishlistId()); + } else if (wishlistMoveDTO.getProductId() != null) { + wrapper.eq(WishlistDO::getProductId, wishlistMoveDTO.getProductId()); + } else { + return null; + } + wrapper.last("LIMIT 1"); + return wishlistMapper.selectOne(wrapper); + } + + private WishlistDO findActiveWishlistByUserAndProduct(Long userId, Long productId) { + if (userId == null || productId == null) { + return null; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getProductId, productId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wrapper.last("LIMIT 1"); + return wishlistMapper.selectOne(wrapper); + } + + private List loadActiveWishlist(Long userId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wrapper.orderByAsc(WishlistDO::getSortOrder); + wrapper.orderByDesc(WishlistDO::getCreateTime); + return wishlistMapper.selectList(wrapper); + } + + private List ensurePresetGroups(Long userId) { + List groups = loadActiveGroups(userId); + Map groupByName = groups.stream() + .collect(Collectors.toMap(WishlistGroupDO::getName, group -> group, (left, right) -> left)); + for (int index = 0; index < PRESET_GROUP_NAMES.size(); index++) { + String name = PRESET_GROUP_NAMES.get(index); + if (!groupByName.containsKey(name)) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setUserId(userId); + group.setName(name); + group.setSortOrder((index + 1) * 10); + group.setIsDelete(0); + wishlistGroupMapper.insert(group); + groups.add(group); + groupByName.put(name, group); + } + } + return groups.stream() + .sorted(Comparator + .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) + .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + private WishlistGroupDO resolveDefaultGroup(Long userId) { + return ensurePresetGroups(userId).stream() + .filter(group -> PRESET_GROUP_NAMES.get(0).equals(group.getName())) + .findFirst() + .orElseThrow(() -> new RuntimeException("\u9ed8\u8ba4\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728")); + } + + private WishlistGroupDO resolveTargetGroup(Long userId, Long groupId) { + if (groupId == null) { + return resolveDefaultGroup(userId); + } + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728"); + } + return group; + } + + private WishlistGroupDO findOwnedGroup(Long userId, Long groupId) { + if (userId == null || groupId == null) { + return null; + } + WishlistGroupDO group = wishlistGroupMapper.selectById(groupId); + if (group == null || Integer.valueOf(1).equals(group.getIsDelete()) || !userId.equals(group.getUserId())) { + return null; + } + return group; + } + + private List loadActiveGroups(Long userId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistGroupDO::getUserId, userId); + wrapper.eq(WishlistGroupDO::getIsDelete, 0); + return wishlistGroupMapper.selectList(wrapper).stream() + .sorted(Comparator + .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) + .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + private ProductDO getValidProduct(Long productId) { + if (productId == null) { + return null; + } + + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + return null; + } + + return product; + } + + private String normalizeGroupName(String name) { + if (!StringUtils.hasText(name)) { + throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a"); + } + return name.trim(); + } + + private String normalizeNote(String note) { + if (!StringUtils.hasText(note)) { + return null; + } + String trimmedNote = note.trim(); + return trimmedNote.length() > NOTE_MAX_LENGTH ? trimmedNote.substring(0, NOTE_MAX_LENGTH) : trimmedNote; + } + + private Integer normalizeSortOrder(Integer sortOrder) { + return sortOrder == null ? DEFAULT_SORT_ORDER : sortOrder; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/CampaignVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/CampaignVO.java new file mode 100644 index 00000000..9a6ca0b9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/CampaignVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class CampaignVO { + private Long id; + private Long shopId; + private String title; + private String description; + private String scene; + private String productIds; + private String couponIds; + private Integer status; + private LocalDateTime startTime; + private LocalDateTime endTime; + private Integer sortOrder; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/CouponVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/CouponVO.java new file mode 100644 index 00000000..7098056b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/CouponVO.java @@ -0,0 +1,122 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; +/** + * 优惠券VO + */ +@Data +public class CouponVO { + + /** + * 优惠券ID + */ + private Long id; + + /** + * 优惠券编码 + */ + private String couponCode; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 优惠券类型名称 + */ + private String couponTypeName; + + /** + * 折扣值(如9.5表示95折) + */ + private BigDecimal discountValue; + + /** + * 满减券最低消费金额 + */ + private BigDecimal minAmount; + + /** + * 满减券减免金额 + */ + private BigDecimal reduceAmount; + + /** + * 优惠券总数量 + */ + private Integer totalCount; + + /** + * 已使用数量 + */ + private Integer usedCount; + + /** + * 剩余数量 + */ + private Integer remainingCount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 状态:1-可用,2-已过期,3-已用完 + */ + private Integer status; + + /** + * 状态名称 + */ + private String statusName; + + /** + * 所属店铺ID + */ + private Long shopId; + + /** + * 所属店铺名称 + */ + private String shopName; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer autoMatch; + + /** + * 可用标签列表 + */ + private List availableTags; + + /** + * 不可用标签列表 + */ + private List unavailableTags; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/GrowthSummaryVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/GrowthSummaryVO.java new file mode 100644 index 00000000..84598eaf --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/GrowthSummaryVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +@Data +public class GrowthSummaryVO { + private Long userId; + private Integer growthValue; + private String levelName; + private Integer appointmentCount; + private Integer reviewCount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/UserCouponVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/UserCouponVO.java new file mode 100644 index 00000000..f995e6dd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/UserCouponVO.java @@ -0,0 +1,94 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户优惠券VO + */ +@Data +public class UserCouponVO { + + /** + * 关联ID + */ + private Long id; + + /** + * 优惠券ID + */ + private Long couponId; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 优惠券类型名称 + */ + private String couponTypeName; + + /** + * 折扣值(如9.5表示95折) + */ + private String discountValue; + + /** + * 满减券最低消费金额 + */ + private String minAmount; + + /** + * 满减券减免金额 + */ + private String reduceAmount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 状态:1-未使用,2-已使用,3-已过期 + */ + private Integer status; + + /** + * 状态名称 + */ + private String statusName; + + /** + * 获取时间 + */ + private LocalDateTime obtainTime; + + /** + * 使用时间 + */ + private LocalDateTime useTime; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + /** + * Field `autoMatched` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean autoMatched; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipBenefitVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipBenefitVO.java new file mode 100644 index 00000000..85a729c1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipBenefitVO.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * VIP权益信息表 VO + * 用于前端展示VIP权益信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipBenefitVO { + + /** + * VIP权益唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 权益详情(如折扣、专属服务) + */ + private String benefitInfo; + + /** + * 所需VIP等级 + */ + private String requiredVipLevel; + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer levelRank; + /** + * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeThreshold; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipInfoVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipInfoVO.java new file mode 100644 index 00000000..a0a22b2e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipInfoVO.java @@ -0,0 +1,70 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户VIP信息表 VO + * 用于前端展示VIP信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipInfoVO { + + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * VIP信息唯一主键ID(雪花ID) + */ + private Long id; + + /** + * VIP等级(如青铜、白银) + */ + private String vipLevel; + + /** + * VIP开通时间 + */ + private LocalDateTime startTime; + + /** + * VIP到期时间 + */ + private LocalDateTime expireTime; + + /** + * VIP开通方式(如购买、赠送) + */ + private String activationMethod; + + /** + * 关联VIP权益信息表主键 + */ + private Long benefitId; + + /** + * 权益详情 + */ + private String benefitInfo; + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer manualOverride; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipRechargePlanVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipRechargePlanVO.java new file mode 100644 index 00000000..b27f59ed --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/VipRechargePlanVO.java @@ -0,0 +1,62 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * VipRechargePlanVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/WishlistGroupVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/WishlistGroupVO.java new file mode 100644 index 00000000..5880c734 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/WishlistGroupVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.WishlistDTO; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class WishlistGroupVO { + private Long id; + private String name; + private Integer sortOrder; + private Integer itemCount; + private List items = new ArrayList<>(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/WishlistInspirationVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/WishlistInspirationVO.java new file mode 100644 index 00000000..fd025434 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/marketing/vo/WishlistInspirationVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.marketing.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class WishlistInspirationVO { + private Integer total; + private List groups = new ArrayList<>(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/controller/front/AnnouncementController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/controller/front/AnnouncementController.java new file mode 100644 index 00000000..be89810b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/controller/front/AnnouncementController.java @@ -0,0 +1,119 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.AnnouncementCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.service.AnnouncementService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.AnnouncementVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageTargetOptionsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/announcement", "/api/announcement", "/admin/announcement"}) +/** + * AnnouncementController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AnnouncementController { + /** + * Variable `announcementService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AnnouncementService announcementService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/admin/create") + @RequirePermission("announcement:create") + @OperationGuard(action = "announcement-create", ttlSeconds = 8, message = "公告发布处理中,请勿重复提交") + // 后台发布公告时,targetType 决定“全平台 / 指定店铺 / 指定用户”的范围。 + // 前端只需要按 target-options 返回值组装表单即可。 + /** + * Run business method `publish`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result publish(HttpServletRequest request, @Valid @RequestBody AnnouncementCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.publishAnnouncement(currentUser, dto)); + } + + @GetMapping("/admin/list") + @RequirePermission("announcement:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAdmin(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.listAdminAnnouncements(currentUser)); + } + + @GetMapping("/admin/{id}") + @RequirePermission("announcement:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getAdmin(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.getAdminAnnouncement(currentUser, id)); + } + + @PutMapping("/admin/{id}/revoke") + @RequirePermission("announcement:delete") + @OperationGuard(action = "announcement-revoke", ttlSeconds = 8, message = "公告撤回处理中,请勿重复操作") + /** + * Run business method `revoke`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result revoke(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.revokeAnnouncement(currentUser, id)); + } + + @GetMapping("/admin/target-options") + @RequirePermission("announcement:create") + /** + * Run business method `targetOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result targetOptions(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.listTargetOptions(currentUser)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMy(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(announcementService.listMyAnnouncements(userId)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/controller/front/SystemMessageController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/controller/front/SystemMessageController.java new file mode 100644 index 00000000..3c5769e2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/controller/front/SystemMessageController.java @@ -0,0 +1,181 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.SystemMessageCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.service.SystemMessageService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageUnreadCountVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.SystemMessageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/system-message", "/api/system-message", "/admin/system-message"}) +/** + * SystemMessageController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class SystemMessageController { + /** + * Variable `systemMessageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageService systemMessageService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/admin/create") + @RequirePermission("message:create") + @OperationGuard(action = "system-message-create", ttlSeconds = 8, message = "消息发布处理中,请勿重复提交") + /** + * Run business method `publish`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result publish(HttpServletRequest request, @Valid @RequestBody SystemMessageCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.publishMessage(currentUser, dto)); + } + + @GetMapping("/admin/list") + @RequirePermission("message:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAdminMessages(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.listAdminMessages(currentUser)); + } + + @GetMapping("/admin/{id}") + @RequirePermission("message:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getAdminMessage(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.getAdminMessage(currentUser, id)); + } + + @PutMapping("/admin/{id}/revoke") + @RequirePermission("message:delete") + @OperationGuard(action = "system-message-revoke", ttlSeconds = 8, message = "消息撤回处理中,请勿重复操作") + /** + * Run business method `revoke`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result revoke(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.revokeMessage(currentUser, id)); + } + + @GetMapping("/admin/target-options") + @RequirePermission("message:create") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result listTargetOptions(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.listTargetOptions(currentUser)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMyMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.listMyMessages(userId)); + } + + @GetMapping("/my/popup") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMyPopupMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.listMyPopupMessages(userId)); + } + + @GetMapping("/my/unread-count") + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result countMyUnreadMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(new MessageUnreadCountVO(systemMessageService.countMyUnreadMessages(userId))); + } + + @GetMapping("/my/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyMessage(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.getMyMessage(userId, id)); + } + + @PutMapping("/my/{id}/popup-shown") + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result markPopupShown(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.markPopupShown(userId, id)); + } + + @PutMapping("/my/{id}/read") + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result markRead(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.markRead(userId, id)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/dto/AnnouncementCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/dto/AnnouncementCreateDTO.java new file mode 100644 index 00000000..4b17b1bc --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/dto/AnnouncementCreateDTO.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.List; + +@Data +/** + * AnnouncementCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementCreateDTO { + + @NotBlank(message = "公告标题不能为空") + @Size(max = 100, message = "公告标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @NotBlank(message = "公告内容不能为空") + @Size(max = 1000, message = "公告内容不能超过1000个字符") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @NotBlank(message = "公告范围不能为空") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder = 0; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/dto/SystemMessageCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/dto/SystemMessageCreateDTO.java new file mode 100644 index 00000000..8aaca4cb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/dto/SystemMessageCreateDTO.java @@ -0,0 +1,69 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.dto; + +import lombok.Data; + +import javax.validation.constraints.Size; +import java.util.List; + +@Data +/** + * SystemMessageCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageCreateDTO { + + @Size(max = 100, message = "消息标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @Size(max = 2000, message = "消息内容不能超过2000个字符") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled = 1; + + /** + * Purpose: businessType supports SystemMessageCreateDTO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + + /** + * Purpose: businessId supports SystemMessageCreateDTO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + + /** + * Purpose: actionPath supports SystemMessageCreateDTO.java by holding or executing the action path business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String actionPath; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/AnnouncementDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/AnnouncementDO.java new file mode 100644 index 00000000..8b125ec5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/AnnouncementDO.java @@ -0,0 +1,87 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_announcement") +/** + * AnnouncementDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementDO extends BaseEntity { + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("content") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @TableField("publisher_id") + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + + @TableField("publisher_name") + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + + @TableField("publisher_type") + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + + @TableField("target_type") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + @TableField("target_ids") + /** + * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetIds; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("publish_time") + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/SystemMessageDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/SystemMessageDO.java new file mode 100644 index 00000000..74c2d29b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/SystemMessageDO.java @@ -0,0 +1,121 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_system_message") +/** + * SystemMessageDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageDO extends BaseEntity { + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("content") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @TableField("image_file_id") + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + + @TableField("publisher_id") + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + + @TableField("publisher_name") + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + + @TableField("publisher_type") + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + + @TableField("target_type") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + @TableField("target_ids") + /** + * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetIds; + + @TableField("business_type") + /** + * Purpose: businessType supports SystemMessageDO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + + @TableField("business_id") + /** + * Purpose: businessId supports SystemMessageDO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + + @TableField("action_path") + /** + * Purpose: actionPath supports SystemMessageDO.java by holding or executing the action path business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String actionPath; + + @TableField("idempotency_key") + /** + * Purpose: idempotencyKey supports SystemMessageDO.java by holding or executing the idempotency key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String idempotencyKey; + + @TableField("popup_enabled") + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("publish_time") + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/SystemMessageUserStateDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/SystemMessageUserStateDO.java new file mode 100644 index 00000000..7d972fa8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/entity/SystemMessageUserStateDO.java @@ -0,0 +1,63 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_system_message_user_state") +/** + * SystemMessageUserStateDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageUserStateDO extends BaseEntity { + + @TableField("message_id") + /** + * Field `messageId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long messageId; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("popup_shown") + /** + * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupShown; + + @TableField("read_status") + /** + * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer readStatus; + + @TableField("popup_time") + /** + * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime popupTime; + + @TableField("read_time") + /** + * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime readTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/AnnouncementMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/AnnouncementMapper.java new file mode 100644 index 00000000..ce344258 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/AnnouncementMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.AnnouncementDO; + +/** + * AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface AnnouncementMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/SystemMessageMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/SystemMessageMapper.java new file mode 100644 index 00000000..9e07ec6c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/SystemMessageMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * SystemMessageMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface SystemMessageMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/SystemMessageUserStateMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/SystemMessageUserStateMapper.java new file mode 100644 index 00000000..fa8692d1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/mapper/SystemMessageUserStateMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageUserStateDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * SystemMessageUserStateMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface SystemMessageUserStateMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/AnnouncementService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/AnnouncementService.java new file mode 100644 index 00000000..8c5d3404 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/AnnouncementService.java @@ -0,0 +1,62 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.AnnouncementCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.AnnouncementVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageTargetOptionsVO; + +import java.util.List; + +/** + * AnnouncementService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface AnnouncementService extends IService { + /** + * Run business method `publishAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminAnnouncements(UserDO currentUser); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return AnnouncementVO result consumed by the caller or returned to the frontend + */ + AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id); + /** + * Run business method `revokeAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean revokeAnnouncement(UserDO currentUser, Long id); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + MessageTargetOptionsVO listTargetOptions(UserDO currentUser); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyAnnouncements(Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/SystemMessageService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/SystemMessageService.java new file mode 100644 index 00000000..cf213590 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/SystemMessageService.java @@ -0,0 +1,111 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.SystemMessageCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.SystemMessageVO; + +import java.util.List; + +/** + * SystemMessageService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface SystemMessageService extends IService { + + /** + * Run business method `publishMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminMessages(UserDO currentUser); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId); + + /** + * Run business method `revokeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean revokeMessage(UserDO currentUser, Long messageId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + MessageTargetOptionsVO listTargetOptions(UserDO currentUser); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyMessages(Long userId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyPopupMessages(Long userId); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + SystemMessageVO getMyMessage(Long userId, Long messageId); + + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long countMyUnreadMessages(Long userId); + + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean markPopupShown(Long userId, Long messageId); + + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean markRead(Long userId, Long messageId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java new file mode 100644 index 00000000..a994fa33 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -0,0 +1,503 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.AnnouncementCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.mapper.AnnouncementMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.service.AnnouncementService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.AnnouncementVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageTargetOptionsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * AnnouncementServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AnnouncementServiceImpl extends ServiceImpl implements AnnouncementService { + + /** + * Purpose: TARGET_PLATFORM_ALL supports AnnouncementServiceImpl.java by holding or executing the target platform all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; + /** + * Purpose: TARGET_CURRENT_SHOP_ALL supports AnnouncementServiceImpl.java by holding or executing the target current shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; + /** + * Purpose: TARGET_SHOP_ALL supports AnnouncementServiceImpl.java by holding or executing the target shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_SHOP_ALL = "SHOP_ALL"; + /** + * Purpose: TARGET_SELECTED_SHOPS supports AnnouncementServiceImpl.java by holding or executing the target selected shops business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; + /** + * Purpose: TARGET_SELECTED_USERS supports AnnouncementServiceImpl.java by holding or executing the target selected users business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Variable `announcementMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AnnouncementMapper announcementMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `publishAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto) { + String targetType = normalizeTargetType(dto.getTargetType()); + List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); + AnnouncementDO announcement = new AnnouncementDO(); + announcement.setTitle(dto.getTitle().trim()); + announcement.setContent(dto.getContent().trim()); + announcement.setPublisherId(currentUser.getId()); + announcement.setPublisherName(resolvePublisherName(currentUser)); + announcement.setPublisherType(currentUser.getType()); + announcement.setTargetType(targetType); + announcement.setTargetIds(joinIds(targetIds)); + announcement.setStatus(1); + announcement.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + announcement.setPublishTime(LocalDateTime.now()); + announcement.setIsDelete(0); + announcementMapper.insert(announcement); + return announcement.getId(); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminAnnouncements(UserDO currentUser) { + return announcementMapper.selectList(new LambdaQueryWrapper() + .eq(AnnouncementDO::getIsDelete, 0) + .orderByDesc(AnnouncementDO::getPublishTime)) + .stream() + .filter(item -> canAdminSee(currentUser, item)) + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return AnnouncementVO result consumed by the caller or returned to the frontend + */ + public AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id) { + AnnouncementDO announcement = requireAnnouncement(id); + if (!canAdminSee(currentUser, announcement)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看该公告"); + } + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param announcement parameter `announcement` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(announcement); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `revokeAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean revokeAnnouncement(UserDO currentUser, Long id) { + AnnouncementDO announcement = requireAnnouncement(id); + if (!canAdminSee(currentUser, announcement)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权撤回该公告"); + } + announcement.setStatus(0); + announcementMapper.updateById(announcement); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { + MessageTargetOptionsVO options = new MessageTargetOptionsVO(); + List shops = adminScopeHelper.isPlatformAdmin(currentUser) + ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) + : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); + Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); + List users = shopIds.isEmpty() + ? List.of() + : userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .in(UserDO::getShopId, shopIds) + .orderByAsc(UserDO::getType) + .orderByAsc(UserDO::getNickname)); + options.setShops(shops.stream().map(shop -> { + MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); + vo.setId(shop.getId()); + vo.setShopName(shop.getShopName()); + return vo; + }).collect(Collectors.toList())); + options.setUsers(users.stream().map(user -> { + MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); + vo.setId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setAccount(user.getAccount()); + vo.setShopId(user.getShopId()); + vo.setShopName(shopNameMap.get(user.getShopId())); + vo.setType(user.getType()); + return vo; + }).collect(Collectors.toList())); + return options; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyAnnouncements(Long userId) { + UserDO user = requireUser(userId); + return announcementMapper.selectList(new LambdaQueryWrapper() + .eq(AnnouncementDO::getIsDelete, 0) + .eq(AnnouncementDO::getStatus, 1) + .orderByDesc(AnnouncementDO::getSortOrder) + .orderByDesc(AnnouncementDO::getPublishTime)) + .stream() + .filter(item -> isVisibleToUser(item, user)) + .map(this::toVO) + .collect(Collectors.toList()); + } + + /** + * Run business method `resolveAndValidateTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAndValidateTargets(UserDO currentUser, String targetType, AnnouncementCreateDTO dto) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + if (TARGET_PLATFORM_ALL.equals(targetType)) return List.of(); + if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + List shopIds = normalizeIds(dto.getShopIds()); + if (shopIds.isEmpty()) throw new RuntimeException("请选择公告店铺"); + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertShopsExist(shopIds); + return shopIds; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUsersExist(userIds); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("公告范围不正确"); + } + if (!Integer.valueOf(2).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只有管理员或店长可以发布公告"); + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { + return List.of(managedShopId); + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); + userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店长只能发布本店公告或本店指定用户公告"); + } + + /** + * Run business method `isVisibleToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param item parameter `item` supplied by the caller + * @param user parameter `user` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVisibleToUser(AnnouncementDO item, UserDO user) { + String targetType = item.getTargetType(); + Set targetIds = parseIds(item.getTargetIds()); + if (TARGET_PLATFORM_ALL.equals(targetType)) return true; + if (TARGET_SELECTED_USERS.equals(targetType)) return targetIds.contains(user.getId()); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + return getUserShopIds(user).stream().anyMatch(targetIds::contains); + } + return false; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set getUserShopIds(UserDO user) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) ids.add(user.getShopId()); + userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)) + .forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) ids.add(binding.getShopId()); + }); + return ids; + } + + /** + * Run business method `canAdminSee`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param item parameter `item` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean canAdminSee(UserDO currentUser, AnnouncementDO item) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) return true; + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(item.getTargetType()) || TARGET_SHOP_ALL.equals(item.getTargetType()) || TARGET_SELECTED_SHOPS.equals(item.getTargetType())) { + return parseIds(item.getTargetIds()).contains(managedShopId); + } + return Objects.equals(item.getPublisherId(), currentUser.getId()); + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param item parameter `item` supplied by the caller + * @return private AnnouncementVO result consumed by the caller or returned to the frontend + */ + private AnnouncementVO toVO(AnnouncementDO item) { + AnnouncementVO vo = new AnnouncementVO(); + vo.setId(item.getId()); + vo.setTitle(item.getTitle()); + vo.setContent(item.getContent()); + vo.setPublisherId(item.getPublisherId()); + vo.setPublisherName(item.getPublisherName()); + vo.setPublisherType(item.getPublisherType()); + vo.setTargetType(item.getTargetType()); + vo.setTargetTypeName(targetTypeName(item.getTargetType())); + vo.setTargetIds(new ArrayList<>(parseIds(item.getTargetIds()))); + vo.setStatus(item.getStatus()); + vo.setSortOrder(item.getSortOrder()); + vo.setPublishTime(item.getPublishTime()); + vo.setCreateTime(item.getCreateTime()); + return vo; + } + + /** + * Run business method `requireAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private AnnouncementDO result consumed by the caller or returned to the frontend + */ + private AnnouncementDO requireAnnouncement(Long id) { + AnnouncementDO item = announcementMapper.selectById(id); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) throw new RuntimeException("公告不存在"); + return item; + } + + /** + * Run business method `requireUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO requireUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new RuntimeException("用户不存在"); + return user; + } + + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertShopsExist(List shopIds) { + Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); + if (count == null || count < shopIds.size()) throw new RuntimeException("存在无效店铺"); + } + + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUsersExist(List userIds) { + Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); + if (count == null || count < userIds.size()) throw new RuntimeException("存在无效用户"); + } + + /** + * Run business method `normalizeTargetType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTargetType(String targetType) { + if (!StringUtils.hasText(targetType)) throw new RuntimeException("公告范围不能为空"); + return targetType.trim().toUpperCase(); + } + + /** + * Run business method `normalizeIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List normalizeIds(List ids) { + if (CollectionUtils.isEmpty(ids)) return List.of(); + return ids.stream().filter(Objects::nonNull).filter(id -> id > 0).distinct().collect(Collectors.toList()); + } + + /** + * Run business method `parseIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set parseIds(String ids) { + if (!StringUtils.hasText(ids)) return Set.of(); + return java.util.Arrays.stream(ids.split(",")).map(String::trim).filter(StringUtils::hasText).map(Long::valueOf).collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `joinIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String joinIds(List ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + /** + * Run business method `targetTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String targetTypeName(String targetType) { + return switch (targetType) { + case TARGET_PLATFORM_ALL -> "全平台"; + case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; + case TARGET_SELECTED_SHOPS -> "多个店铺"; + case TARGET_SELECTED_USERS -> "指定用户"; + default -> targetType; + }; + } + + /** + * Run business method `resolvePublisherName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolvePublisherName(UserDO currentUser) { + return StringUtils.hasText(currentUser.getNickname()) ? currentUser.getNickname() : currentUser.getAccount(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/SystemMessageServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/SystemMessageServiceImpl.java new file mode 100644 index 00000000..2f31b15f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/SystemMessageServiceImpl.java @@ -0,0 +1,886 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.SystemMessageCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageUserStateDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.mapper.SystemMessageUserStateMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.message.service.SystemMessageService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.artlist.core.modules.message.vo.SystemMessageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * SystemMessageServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class SystemMessageServiceImpl extends ServiceImpl implements SystemMessageService { + + /** + * Purpose: TARGET_PLATFORM_ALL supports SystemMessageServiceImpl.java by holding or executing the target platform all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; + /** + * Purpose: TARGET_CURRENT_SHOP_ALL supports SystemMessageServiceImpl.java by holding or executing the target current shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; + /** + * Purpose: TARGET_SHOP_ALL supports SystemMessageServiceImpl.java by holding or executing the target shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_SHOP_ALL = "SHOP_ALL"; + /** + * Purpose: TARGET_SELECTED_SHOPS supports SystemMessageServiceImpl.java by holding or executing the target selected shops business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; + /** + * Purpose: TARGET_SELECTED_USERS supports SystemMessageServiceImpl.java by holding or executing the target selected users business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Variable `systemMessageMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageMapper systemMessageMapper; + /** + * Variable `stateMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageUserStateMapper stateMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `publishMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto) { + String targetType = normalizeTargetType(dto.getTargetType()); + List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); + String title = dto.getTitle() == null ? "" : dto.getTitle().trim(); + String content = dto.getContent() == null ? "" : dto.getContent().trim(); + if (!StringUtils.hasText(title)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息标题不能为空"); + } + if (!StringUtils.hasText(content) && dto.getImageFileId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请填写消息内容或上传消息图片"); + } + if (dto.getImageFileId() != null) { + ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(dto.getImageFileId()); + if (imageFile == null || !Integer.valueOf(1).equals(imageFile.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息图片不存在或不可用"); + } + } + + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setImageFileId(dto.getImageFileId()); + message.setPublisherId(currentUser.getId()); + message.setPublisherName(resolvePublisherName(currentUser)); + message.setPublisherType(currentUser.getType()); + message.setTargetType(targetType); + message.setTargetIds(joinIds(targetIds)); + message.setBusinessType(trimToNull(dto.getBusinessType())); + message.setBusinessId(dto.getBusinessId()); + message.setActionPath(trimToNull(dto.getActionPath())); + message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + return message.getId(); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminMessages(UserDO currentUser) { + List messages = systemMessageMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageDO::getIsDelete, 0) + .orderByDesc(SystemMessageDO::getPublishTime)); + return messages.stream() + .filter(message -> canAdminSeeMessage(currentUser, message)) + .map(message -> toVO(message, null)) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + public SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId) { + SystemMessageDO message = requireMessage(messageId); + if (!canAdminSeeMessage(currentUser, message)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看该消息"); + } + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(message, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `revokeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean revokeMessage(UserDO currentUser, Long messageId) { + SystemMessageDO message = requireMessage(messageId); + if (!canAdminSeeMessage(currentUser, message)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权撤回该消息"); + } + message.setStatus(0); + systemMessageMapper.updateById(message); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { + MessageTargetOptionsVO options = new MessageTargetOptionsVO(); + List shops = adminScopeHelper.isPlatformAdmin(currentUser) + ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) + : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); + Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + + List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); + List users = shopIds.isEmpty() + ? List.of() + : userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .in(UserDO::getShopId, shopIds) + .orderByAsc(UserDO::getType) + .orderByAsc(UserDO::getNickname)); + + options.setShops(shops.stream().map(shop -> { + MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); + vo.setId(shop.getId()); + vo.setShopName(shop.getShopName()); + return vo; + }).collect(Collectors.toList())); + options.setUsers(users.stream().map(user -> { + MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); + vo.setId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setAccount(user.getAccount()); + vo.setShopId(user.getShopId()); + vo.setShopName(shopNameMap.get(user.getShopId())); + vo.setType(user.getType()); + return vo; + }).collect(Collectors.toList())); + return options; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .map(message -> toVO(message, stateMap.get(message.getId()))) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyPopupMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .filter(message -> Integer.valueOf(1).equals(message.getPopupEnabled())) + .filter(message -> { + SystemMessageUserStateDO state = stateMap.get(message.getId()); + return state == null || !Integer.valueOf(1).equals(state.getPopupShown()); + }) + .map(message -> toVO(message, stateMap.get(message.getId()))) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + public SystemMessageVO getMyMessage(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = findState(userId, messageId); + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param state parameter `state` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(message, state); + } + + @Override + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long countMyUnreadMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .filter(message -> { + SystemMessageUserStateDO state = stateMap.get(message.getId()); + return state == null || !Integer.valueOf(1).equals(state.getReadStatus()); + }) + .count(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean markPopupShown(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = getOrCreateState(userId, messageId); + if (!Integer.valueOf(1).equals(state.getPopupShown())) { + state.setPopupShown(1); + state.setPopupTime(LocalDateTime.now()); + stateMapper.updateById(state); + } + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean markRead(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = getOrCreateState(userId, messageId); + if (!Integer.valueOf(1).equals(state.getReadStatus())) { + state.setReadStatus(1); + state.setReadTime(LocalDateTime.now()); + stateMapper.updateById(state); + } + return true; + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listVisibleMessages(UserDO user) { + return systemMessageMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageDO::getIsDelete, 0) + .eq(SystemMessageDO::getStatus, 1) + .orderByDesc(SystemMessageDO::getPublishTime)) + .stream() + .filter(message -> isMessageVisibleToUser(message, user)) + .collect(Collectors.toList()); + } + + /** + * Run business method `isMessageVisibleToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param user parameter `user` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isMessageVisibleToUser(SystemMessageDO message, UserDO user) { + String targetType = message.getTargetType(); + Set targetIds = parseIds(message.getTargetIds()); + if (TARGET_PLATFORM_ALL.equals(targetType)) { + return true; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + return targetIds.contains(user.getId()); + } + Set userShopIds = getUserShopIds(user); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + return userShopIds.stream().anyMatch(targetIds::contains); + } + return false; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set getUserShopIds(UserDO user) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) { + ids.add(user.getShopId()); + } + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + bindings.forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) { + ids.add(binding.getShopId()); + } + }); + return ids; + } + + /** + * Run business method `resolveAndValidateTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAndValidateTargets(UserDO currentUser, String targetType, SystemMessageCreateDTO dto) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + /** + * Run business method `resolveAdminTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return resolveAdminTargets(targetType, dto); + } + if (!Integer.valueOf(2).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只有管理员或店长可以发布消息"); + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { + return List.of(managedShopId); + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收用户"); + } + userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店长只能发布本店全员或本店部分用户消息"); + } + + /** + * Run business method `resolveAdminTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAdminTargets(String targetType, SystemMessageCreateDTO dto) { + if (TARGET_PLATFORM_ALL.equals(targetType)) { + return List.of(); + } + if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + List shopIds = normalizeIds(dto.getShopIds()); + if (shopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收店铺"); + } + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertShopsExist(shopIds); + return shopIds; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收用户"); + } + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUsersExist(userIds); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员消息范围不正确"); + } + + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertShopsExist(List shopIds) { + Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); + if (count == null || count < shopIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效店铺"); + } + } + + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUsersExist(List userIds) { + Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); + if (count == null || count < userIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效用户"); + } + } + + /** + * Run business method `canAdminSeeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean canAdminSeeMessage(UserDO currentUser, SystemMessageDO message) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + return true; + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(message.getTargetType()) || TARGET_SHOP_ALL.equals(message.getTargetType()) || TARGET_SELECTED_SHOPS.equals(message.getTargetType())) { + return parseIds(message.getTargetIds()).contains(managedShopId); + } + return Objects.equals(message.getPublisherId(), currentUser.getId()); + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param state parameter `state` supplied by the caller + * @return private SystemMessageVO result consumed by the caller or returned to the frontend + */ + private SystemMessageVO toVO(SystemMessageDO message, SystemMessageUserStateDO state) { + SystemMessageVO vo = new SystemMessageVO(); + vo.setId(message.getId()); + vo.setTitle(message.getTitle()); + vo.setContent(message.getContent()); + vo.setImageFileId(message.getImageFileId()); + vo.setImageUrl(resolveImageUrl(message.getImageFileId())); + vo.setPublisherId(message.getPublisherId()); + vo.setPublisherName(message.getPublisherName()); + vo.setPublisherType(message.getPublisherType()); + vo.setTargetType(message.getTargetType()); + vo.setTargetTypeName(targetTypeName(message.getTargetType())); + vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds()))); + vo.setBusinessType(message.getBusinessType()); + vo.setBusinessId(message.getBusinessId()); + vo.setActionPath(message.getActionPath()); + vo.setPopupEnabled(message.getPopupEnabled()); + vo.setStatus(message.getStatus()); + vo.setPublishTime(message.getPublishTime()); + vo.setCreateTime(message.getCreateTime()); + vo.setPopupShown(state == null ? 0 : state.getPopupShown()); + vo.setReadStatus(state == null ? 0 : state.getReadStatus()); + vo.setPopupTime(state == null ? null : state.getPopupTime()); + vo.setReadTime(state == null ? null : state.getReadTime()); + return vo; + } + + /** + * Run business method `resolveImageUrl`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param imageFileId parameter `imageFileId` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveImageUrl(Long imageFileId) { + if (imageFileId == null || imageFileId <= 0) { + return null; + } + ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(imageFileId); + if (imageFile == null || !StringUtils.hasText(imageFile.getFileUrl())) { + return null; + } + return objectStorageUrlSupport.toAccessibleUrl(imageFile); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend + */ + private SystemMessageUserStateDO getOrCreateState(Long userId, Long messageId) { + SystemMessageUserStateDO state = findState(userId, messageId); + if (state != null) { + return state; + } + state = new SystemMessageUserStateDO(); + state.setMessageId(messageId); + state.setUserId(userId); + state.setPopupShown(0); + state.setReadStatus(0); + state.setIsDelete(0); + stateMapper.insert(state); + return state; + } + + /** + * Run business method `findState`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend + */ + private SystemMessageUserStateDO findState(Long userId, Long messageId) { + return stateMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemMessageUserStateDO::getUserId, userId) + .eq(SystemMessageUserStateDO::getMessageId, messageId) + .eq(SystemMessageUserStateDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Run business method `loadStateMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadStateMap(Long userId) { + return stateMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageUserStateDO::getUserId, userId) + .eq(SystemMessageUserStateDO::getIsDelete, 0)) + .stream() + .collect(Collectors.toMap(SystemMessageUserStateDO::getMessageId, Function.identity(), (a, b) -> a)); + } + + /** + * Run business method `requireMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageDO result consumed by the caller or returned to the frontend + */ + private SystemMessageDO requireMessage(Long messageId) { + SystemMessageDO message = systemMessageMapper.selectById(messageId); + if (message == null || Integer.valueOf(1).equals(message.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在"); + } + return message; + } + + /** + * Run business method `requireUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO requireUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + return user; + } + + /** + * Run business method `normalizeTargetType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTargetType(String targetType) { + if (!StringUtils.hasText(targetType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("接收范围不能为空"); + } + return targetType.trim().toUpperCase(); + } + + /** + * Purpose: trimToNull supports SystemMessageServiceImpl.java by holding or executing the trim to null business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String trimToNull(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + return value.trim(); + } + + /** + * Run business method `normalizeIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List normalizeIds(List ids) { + if (CollectionUtils.isEmpty(ids)) { + return List.of(); + } + return ids.stream() + .filter(Objects::nonNull) + .filter(id -> id > 0) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Run business method `parseIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set parseIds(String ids) { + if (!StringUtils.hasText(ids)) { + return Set.of(); + } + return java.util.Arrays.stream(ids.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .map(Long::valueOf) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `joinIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String joinIds(List ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + /** + * Run business method `targetTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String targetTypeName(String targetType) { + return switch (targetType) { + case TARGET_PLATFORM_ALL -> "全平台"; + case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; + case TARGET_SELECTED_SHOPS -> "多个店铺"; + case TARGET_SELECTED_USERS -> "指定用户"; + default -> targetType; + }; + } + + /** + * Run business method `resolvePublisherName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolvePublisherName(UserDO currentUser) { + if (StringUtils.hasText(currentUser.getNickname())) { + return currentUser.getNickname(); + } + return currentUser.getAccount(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/AnnouncementVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/AnnouncementVO.java new file mode 100644 index 00000000..ccb94088 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/AnnouncementVO.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * AnnouncementVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + /** + * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetTypeName; + /** + * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List targetIds; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/MessageTargetOptionsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/MessageTargetOptionsVO.java new file mode 100644 index 00000000..fbb73bf4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/MessageTargetOptionsVO.java @@ -0,0 +1,69 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * MessageTargetOptionsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageTargetOptionsVO { + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops; + /** + * Field `users` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List users; + + @Data + /** + * Purpose: ShopOptionVO supports MessageTargetOptionsVO.java by holding or executing the shop option vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class ShopOptionVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + } + + @Data + /** + * Purpose: UserOptionVO supports MessageTargetOptionsVO.java by holding or executing the user option vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class UserOptionVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer type; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/MessageUnreadCountVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/MessageUnreadCountVO.java new file mode 100644 index 00000000..64556da8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/MessageUnreadCountVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +/** + * MessageUnreadCountVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageUnreadCountVO { + /** + * Field `unreadCount` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long unreadCount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/SystemMessageVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/SystemMessageVO.java new file mode 100644 index 00000000..147bea51 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/vo/SystemMessageVO.java @@ -0,0 +1,105 @@ +package com.xiaowang.jayucloud.artlist.core.modules.message.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * SystemMessageVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + /** + * Field `imageUrl` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String imageUrl; + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + /** + * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetTypeName; + /** + * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List targetIds; + /** + * Purpose: businessType supports SystemMessageVO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + /** + * Purpose: businessId supports SystemMessageVO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + /** + * Purpose: actionPath supports SystemMessageVO.java by holding or executing the action path business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String actionPath; + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupShown; + /** + * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer readStatus; + /** + * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime popupTime; + /** + * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime readTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/AfterSaleController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/AfterSaleController.java new file mode 100644 index 00000000..f456095f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/AfterSaleController.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.AfterSaleApplyDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.AfterSaleService; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/after-sale") +@RequiredArgsConstructor +public class AfterSaleController { + + private final AfterSaleService afterSaleService; + + @PostMapping("/apply") + public Result apply(HttpServletRequest request, @RequestBody AfterSaleApplyDTO dto) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(afterSaleService.apply(userId, dto)); + } + + @GetMapping("/my") + public Result> listMy(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(afterSaleService.listMy(userId, page, size)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/CartController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/CartController.java new file mode 100644 index 00000000..2431ca4a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/CartController.java @@ -0,0 +1,116 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.CartDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.CartService; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CartVO; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/cart") +/** + * CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class CartController { + + @Resource + /** + * Purpose: cartService supports CartController.java by holding or executing the cart service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CartService cartService; + + @PostMapping("/add") + @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartDTO parameter `cartDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.addToCart(userId, cartDTO); + return Result.success(); + } + + @DeleteMapping("/remove/{productId}") + @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.removeFromCart(userId, productId); + return Result.success(); + } + + @PostMapping("/batch-remove") + @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartItemIds parameter `cartItemIds` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.batchRemoveFromCart(userId, cartItemIds); + return Result.success(); + } + + @PutMapping("/update") + @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartDTO parameter `cartDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.updateCartQuantity(userId, cartDTO); + return Result.success(); + } + + @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getCartList(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + List cartList = cartService.getCartList(userId); + return Result.success(cartList); + } + + @DeleteMapping("/clear") + @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result clearCart(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.clearCart(userId); + return Result.success(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/OrderController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/OrderController.java new file mode 100644 index 00000000..0119a4b9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/controller/front/OrderController.java @@ -0,0 +1,459 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.CheckoutPreviewDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistChangeRejectDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistChangeRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteReplyDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CheckoutPreviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistChangeRequestVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistReviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserVO; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDate; +import java.util.Comparator; +import java.util.List; + +@RestController +@RequestMapping("/order") +/** + * OrderController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class OrderController { + + @Resource + /** + * Purpose: orderService supports OrderController.java by holding or executing the order service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderService orderService; + + @Resource + /** + * Purpose: userService supports OrderController.java by holding or executing the user service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserService userService; + + @Resource + /** + * Purpose: securityAuditSupport supports OrderController.java by holding or executing the security audit support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private SecurityAuditSupport securityAuditSupport; + + @PostMapping("/create") + @OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + OrderVO orderVO = orderService.createOrder(userId, orderDTO); + return Result.success(orderVO); + } + + @PostMapping("/checkout-preview") + public Result checkoutPreview(@RequestBody CheckoutPreviewDTO checkoutPreviewDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.checkoutPreview(userId, checkoutPreviewDTO)); + } + + @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getOrderList(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + List orderList = orderService.getOrderList(userId); + return Result.success(orderList); + } + + @GetMapping("/detail/{orderId}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getOrderDetail(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + OrderVO orderVO = orderService.getOrderDetail(orderId, userId); + return Result.success(orderVO); + } + + @PutMapping("/cancel/{orderId}") + @OperationGuard(action = "order-cancel", ttlSeconds = 15, message = "操作进行中,请勿重复点击") + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + orderService.cancelOrder(orderId, userId); + return Result.success(); + } + + // 后台管理接口 + @PostMapping("/{orderId}/quote/reply") + @OperationGuard(action = "order-quote-reply", ttlSeconds = 10, message = "回复处理中,请勿重复提交") + public Result replyQuote(@PathVariable Long orderId, + @RequestBody(required = false) OrderQuoteReplyDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.replyQuote(orderId, userId, dto)); + } + + @PutMapping("/{orderId}/quote/confirm") + @OperationGuard(action = "order-quote-user-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") + public Result confirmUserQuote(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.confirmUserQuote(orderId, userId)); + } + + @RequirePermission("order:process") + @PostMapping("/{orderId}/quote/shop") + @OperationGuard(action = "order-shop-quote-submit", ttlSeconds = 10, message = "报价处理中,请勿重复提交") + public Result submitShopQuote(@PathVariable Long orderId, + @RequestBody OrderQuoteSubmitDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.submitShopQuote(orderId, userId, userType, dto)); + } + + @RequirePermission("order:process") + @PutMapping("/{orderId}/quote/shop/confirm") + @OperationGuard(action = "order-shop-quote-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") + public Result confirmShopQuote(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.confirmShopQuote(orderId, userId, userType)); + } + + @RequirePermission("order:view") + @GetMapping("/admin/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getAllOrders(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + List orderList; + if (Integer.valueOf(3).equals(userType)) { + orderList = orderService.getOrdersByArtistId(userId); + } else { + orderList = orderService.getAllOrders(); + } + if (!Integer.valueOf(4).equals(userType) && !Integer.valueOf(3).equals(userType)) { + UserVO currentUser = userService.getUserById(userId); + if (currentUser == null || currentUser.getShopId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号未绑定店铺"); + } + orderList = orderList.stream() + .filter(order -> currentUser.getShopId().equals(order.getShopId())) + .toList(); + } + return Result.success(orderList); + } + + @RequirePermission("order:process") + @PutMapping("/admin/process/{orderId}") + @OperationGuard(action = "admin-order-process", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + if (Integer.valueOf(3).equals(userType)) { + if (!Integer.valueOf(2).equals(status)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师只能完成属于自己的订单"); + } + try { + orderService.completeArtistOrder(orderId, userId); + securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId); + return Result.success(); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId + ",reason=" + exception.getMessage()); + throw exception; + } + } + if (!Integer.valueOf(4).equals(userType)) { + UserVO currentUser = userService.getUserById(userId); + if (currentUser == null || currentUser.getShopId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号未绑定店铺"); + } + OrderVO orderVO = orderService.getAllOrders().stream() + .filter(order -> orderId.equals(order.getId())) + .findFirst() + .orElse(null); + if (orderVO == null || !currentUser.getShopId().equals(orderVO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权处理其他店铺订单"); + } + } + try { + orderService.processOrder(orderId, status); + securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status); + return Result.success(); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",reason=" + exception.getMessage()); + throw exception; + } + } + + // 美甲师查看自己的订单 + @RequirePermission("order:view") + @GetMapping("/artist/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getArtistOrders(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师可查看自己的订单"); + } + List orderList; + if (Integer.valueOf(2).equals(userType)) { + UserVO currentUser = userService.getUserById(userId); + if (currentUser == null || currentUser.getShopId() == null) { + throw new RuntimeException("当前账号未绑定店铺"); + } + orderList = orderService.getAllOrders().stream() + .filter(order -> currentUser.getShopId().equals(order.getShopId())) + .peek(order -> { + order.setArtistOrderSource("SHOP"); + order.setArtistOrderSourceText("本店美甲师订单"); + }) + .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .toList(); + } else { + orderList = orderService.getArtistWorkbenchOrders(userId); + } + return Result.success(orderList); + } + + @RequirePermission("order:view") + @GetMapping("/artist/calendar/recent") + // 调用示例:GET /order/artist/calendar/recent?days=7 + // 只返回当前登录美甲师/参与制作店长自己的预约,前端不用再做二次过滤。 + public Result getArtistCalendarRecent(@RequestParam(value = "days", required = false) Integer days, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistCalendarRecent(userId, userType, days)); + } + + @RequirePermission("order:view") + @GetMapping("/artist/calendar/day") + // 调用示例:GET /order/artist/calendar/day?date=2026-05-17 + // date 使用 yyyy-MM-dd,适合日历点选某一天后拉取详情。 + public Result getArtistCalendarDay(@RequestParam("date") + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) + LocalDate date, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistCalendarDay(userId, userType, date)); + } + + @RequirePermission("order:process") + @PutMapping("/artist/complete/{orderId}") + @OperationGuard(action = "artist-order-complete", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师可完成自己的订单"); + } + try { + orderService.completeArtistOrder(orderId, userId); + securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId); + return Result.success(); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/review/my-pending") + /** + * Purpose: listMyPendingReviews supports OrderController.java by holding or executing the list my pending reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listMyPendingReviews(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.listMyPendingReviews(userId)); + } + + @GetMapping("/{orderId}/reviews") + /** + * Purpose: listOrderReviews supports OrderController.java by holding or executing the list order reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listOrderReviews(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listOrderReviews(orderId, userId, userType)); + } + + @PostMapping("/review/{reviewId}/submit") + @OperationGuard(action = "order-artist-review-submit", ttlSeconds = 15, message = "评价正在提交中,请勿重复操作") + public Result submitArtistReview(@PathVariable Long reviewId, + @RequestBody OrderArtistReviewSubmitDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.submitArtistReview(reviewId, userId, dto)); + } + + @RequirePermission("order:artist-change") + @GetMapping("/{orderId}/artist-change/options") + public Result getArtistChangeOptions(@PathVariable Long orderId, + @RequestParam Long orderItemId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistChangeOptions(orderId, orderItemId, userId, userType)); + } + + @RequirePermission("order:artist-change") + @PostMapping("/artist-change/request") + @OperationGuard(action = "order-artist-change-request", ttlSeconds = 15, message = "改派申请正在提交中,请勿重复操作") + public Result requestArtistChange(@RequestBody OrderArtistChangeRequestDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.requestArtistChange(userId, dto)); + } + + @GetMapping("/artist-change/my-pending") + /** + * Purpose: listMyPendingArtistChangeRequests supports OrderController.java by holding or executing the list my pending artist change requests business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listMyPendingArtistChangeRequests(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listMyPendingArtistChangeRequests(userId, userType)); + } + + @GetMapping("/{orderId}/artist-change/requests") + /** + * Purpose: listOrderArtistChangeRequests returns pending and processed artist-change records for one order. + * Usage: call it from order pages to build a timeline after the caller has an authenticated session. + */ + public Result> listOrderArtistChangeRequests(@PathVariable Long orderId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listOrderArtistChangeRequests(orderId, userId, userType)); + } + + @PutMapping("/artist-change/{requestId}/approve") + @OperationGuard(action = "order-artist-change-approve", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") + public Result approveArtistChange(@PathVariable Long requestId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + try { + OrderArtistChangeRequestVO result = orderService.approveArtistChange(requestId, userId, userType); + securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PutMapping("/artist-change/{requestId}/reject") + @OperationGuard(action = "order-artist-change-reject", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") + public Result rejectArtistChange(@PathVariable Long requestId, + @RequestBody(required = false) OrderArtistChangeRejectDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + try { + OrderArtistChangeRequestVO result = orderService.rejectArtistChange(requestId, userId, userType, dto); + securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId + ",reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/AfterSaleApplyDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/AfterSaleApplyDTO.java new file mode 100644 index 00000000..7514d3c1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/AfterSaleApplyDTO.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class AfterSaleApplyDTO { + private Long orderId; + private Long orderItemId; + private String type; + private String reason; + private BigDecimal refundAmount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/AfterSaleAuditDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/AfterSaleAuditDTO.java new file mode 100644 index 00000000..6cb24ed9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/AfterSaleAuditDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +@Data +public class AfterSaleAuditDTO { + private String auditReason; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/CartDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/CartDTO.java new file mode 100644 index 00000000..c55719c7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/CartDTO.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +/** + * 购物车 DTO + * 用于购物车商品信息的传输 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class CartDTO { + + /** + * 商品ID + */ + private Long productId; + + /** + * 商品数量 + */ + private Integer quantity; +} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/CheckoutPreviewDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/CheckoutPreviewDTO.java new file mode 100644 index 00000000..f7396d10 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/CheckoutPreviewDTO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 结算预览请求,只做金额和优惠说明,不创建订单。 + */ +@Data +public class CheckoutPreviewDTO { + + /** + * 已选择的优惠选项ID:用户券传用户券ID,VIP自动券传券模板ID。 + */ + private Long couponId; + + /** + * 优惠来源:USER_COUPON、SYSTEM_VIP、NONE。 + */ + private String couponSourceType; + private String remark; + + /** + * 本次预览的商品列表。 + */ + private List items; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistChangeRejectDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistChangeRejectDTO.java new file mode 100644 index 00000000..c7a1340c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistChangeRejectDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +@Data +/** + * Purpose: OrderArtistChangeRejectDTO supports OrderArtistChangeRejectDTO.java by holding or executing the order artist change reject dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRejectDTO { + /** + * Purpose: rejectReason supports OrderArtistChangeRejectDTO.java by holding or executing the reject reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String rejectReason; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistChangeRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistChangeRequestDTO.java new file mode 100644 index 00000000..6bd53f5c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistChangeRequestDTO.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +@Data +/** + * Purpose: OrderArtistChangeRequestDTO supports OrderArtistChangeRequestDTO.java by holding or executing the order artist change request dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRequestDTO { + /** + * Purpose: orderId supports OrderArtistChangeRequestDTO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistChangeRequestDTO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: requestedArtistId supports OrderArtistChangeRequestDTO.java by holding or executing the requested artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requestedArtistId; + /** + * Purpose: reason supports OrderArtistChangeRequestDTO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistReviewSubmitDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistReviewSubmitDTO.java new file mode 100644 index 00000000..2b65a112 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderArtistReviewSubmitDTO.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +@Data +/** + * Purpose: OrderArtistReviewSubmitDTO supports OrderArtistReviewSubmitDTO.java by holding or executing the order artist review submit dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistReviewSubmitDTO { + /** + * Purpose: rating supports OrderArtistReviewSubmitDTO.java by holding or executing the rating business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal rating; + /** + * Purpose: content supports OrderArtistReviewSubmitDTO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + /** + * Purpose: imageFileIds supports OrderArtistReviewSubmitDTO.java by holding or executing the image file ids business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private List imageFileIds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderDTO.java new file mode 100644 index 00000000..008618f5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderDTO.java @@ -0,0 +1,32 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 订单 DTO + * 用于订单创建请求 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class OrderDTO { + + /** + * 优惠券ID + */ + private Long couponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponSourceType; + private String remark; + private String clientRequestId; + + /** + * 订单商品列表 + */ + private List items; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderItemDTO.java new file mode 100644 index 00000000..82f26391 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderItemDTO.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +/** + * 订单商品项 DTO + * 用于订单中的单个商品信息 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class OrderItemDTO { + + /** + * 商品ID + */ + private Long productId; + + /** + * 商品数量 + */ + private Integer quantity; + + /** + * 美甲师ID + */ + private Long artistId; + + /** + * 预约开始时间 + */ + private String appointmentTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteItemDTO.java new file mode 100644 index 00000000..dc39c47d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteItemDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OrderQuoteItemDTO { + private Long orderItemId; + private BigDecimal quotedPrice; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteReplyDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteReplyDTO.java new file mode 100644 index 00000000..373f9c18 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteReplyDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +@Data +public class OrderQuoteReplyDTO { + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteSubmitDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteSubmitDTO.java new file mode 100644 index 00000000..bc9ef64c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/dto/OrderQuoteSubmitDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class OrderQuoteSubmitDTO { + private String remark; + private List items; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/AfterSaleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/AfterSaleDO.java new file mode 100644 index 00000000..b496c6f3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/AfterSaleDO.java @@ -0,0 +1,46 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_after_sale") +public class AfterSaleDO extends BaseEntity { + @TableField("after_sale_no") + private String afterSaleNo; + @TableField("order_id") + private Long orderId; + @TableField("order_item_id") + private Long orderItemId; + @TableField("user_id") + private Long userId; + @TableField("shop_id") + private Long shopId; + @TableField("type") + private String type; + @TableField("reason") + private String reason; + @TableField("refund_amount") + private BigDecimal refundAmount; + @TableField("status") + private String status; + @TableField("audit_user_id") + private Long auditUserId; + @TableField("audit_reason") + private String auditReason; + @TableField("audit_time") + private LocalDateTime auditTime; + @TableField("refund_order_id") + private Long refundOrderId; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/AfterSaleLogDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/AfterSaleLogDO.java new file mode 100644 index 00000000..b0cb0543 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/AfterSaleLogDO.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_after_sale_log") +public class AfterSaleLogDO extends BaseEntity { + @TableField("after_sale_id") + private Long afterSaleId; + @TableField("action") + private String action; + @TableField("from_status") + private String fromStatus; + @TableField("to_status") + private String toStatus; + @TableField("operator_id") + private Long operatorId; + @TableField("operator_type") + private String operatorType; + @TableField("remark") + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/CartDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/CartDO.java new file mode 100644 index 00000000..e150e803 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/CartDO.java @@ -0,0 +1,40 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@TableName("t_cart") +/** + * CartDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class CartDO extends BaseEntity { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderArtistChangeRequestDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderArtistChangeRequestDO.java new file mode 100644 index 00000000..850c8bf1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderArtistChangeRequestDO.java @@ -0,0 +1,138 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_order_artist_change_request") +/** + * Purpose: OrderArtistChangeRequestDO supports OrderArtistChangeRequestDO.java by holding or executing the order artist change request do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRequestDO extends BaseEntity { + + @TableField("order_id") + /** + * Purpose: orderId supports OrderArtistChangeRequestDO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + + @TableField("order_item_id") + /** + * Purpose: orderItemId supports OrderArtistChangeRequestDO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + + @TableField("product_id") + /** + * Purpose: productId supports OrderArtistChangeRequestDO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + + @TableField("shop_id") + /** + * Purpose: shopId supports OrderArtistChangeRequestDO.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + + @TableField("customer_id") + /** + * Purpose: customerId supports OrderArtistChangeRequestDO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + + @TableField("from_artist_id") + /** + * Purpose: fromArtistId supports OrderArtistChangeRequestDO.java by holding or executing the from artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long fromArtistId; + + @TableField("to_artist_id") + /** + * Purpose: toArtistId supports OrderArtistChangeRequestDO.java by holding or executing the to artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long toArtistId; + + @TableField("requester_id") + /** + * Purpose: requesterId supports OrderArtistChangeRequestDO.java by holding or executing the requester id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requesterId; + + @TableField("status") + /** + * Purpose: status supports OrderArtistChangeRequestDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String status; + + @TableField("reason") + /** + * Purpose: reason supports OrderArtistChangeRequestDO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + + @TableField("reject_reason") + /** + * Purpose: rejectReason supports OrderArtistChangeRequestDO.java by holding or executing the reject reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String rejectReason; + + @TableField("message_id") + /** + * Purpose: messageId supports OrderArtistChangeRequestDO.java by holding or executing the message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long messageId; + + @TableField("pending_key") + /** + * Purpose: pendingKey supports OrderArtistChangeRequestDO.java by holding or executing the pending key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String pendingKey; + + @TableField("approved_time") + /** + * Purpose: approvedTime supports OrderArtistChangeRequestDO.java by holding or executing the approved time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime approvedTime; + + @TableField("rejected_time") + /** + * Purpose: rejectedTime supports OrderArtistChangeRequestDO.java by holding or executing the rejected time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime rejectedTime; + + @TableField("expire_time") + /** + * Purpose: expireTime supports OrderArtistChangeRequestDO.java by holding or executing the expire time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime expireTime; + + @TableField("is_delete") + /** + * Purpose: isDelete supports OrderArtistChangeRequestDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderArtistReviewDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderArtistReviewDO.java new file mode 100644 index 00000000..7c53570d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderArtistReviewDO.java @@ -0,0 +1,111 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_order_artist_review") +/** + * Purpose: OrderArtistReviewDO supports OrderArtistReviewDO.java by holding or executing the order artist review do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistReviewDO extends BaseEntity { + + @TableField("order_id") + /** + * Purpose: orderId supports OrderArtistReviewDO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + + @TableField("order_item_id") + /** + * Purpose: orderItemId supports OrderArtistReviewDO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + + @TableField("product_id") + /** + * Purpose: productId supports OrderArtistReviewDO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + + @TableField("artist_id") + /** + * Purpose: artistId supports OrderArtistReviewDO.java by holding or executing the artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long artistId; + + @TableField("shop_id") + /** + * Purpose: shopId supports OrderArtistReviewDO.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + + @TableField("customer_id") + /** + * Purpose: customerId supports OrderArtistReviewDO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + + @TableField("status") + /** + * Purpose: status supports OrderArtistReviewDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + + @TableField("rating_score") + /** + * Purpose: ratingScore supports OrderArtistReviewDO.java by holding or executing the rating score business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal ratingScore; + + @TableField("content") + /** + * Purpose: content supports OrderArtistReviewDO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + + @TableField("image_file_ids") + /** + * Purpose: imageFileIds supports OrderArtistReviewDO.java by holding or executing the image file ids business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String imageFileIds; + + @TableField("reminder_message_id") + /** + * Purpose: reminderMessageId supports OrderArtistReviewDO.java by holding or executing the reminder message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long reminderMessageId; + + @TableField("submitted_at") + /** + * Purpose: submittedAt supports OrderArtistReviewDO.java by holding or executing the submitted at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime submittedAt; + + @TableField("is_delete") + /** + * Purpose: isDelete supports OrderArtistReviewDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderDO.java new file mode 100644 index 00000000..bd72a73b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderDO.java @@ -0,0 +1,78 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@TableName("t_order") +/** + * OrderDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderDO extends BaseEntity { + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long couponId; + /** + * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userCouponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponSourceType; + private String paymentStatus; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private LocalDateTime payTime; + private String paymentMethod; + private String paymentOrderNo; + private String refundStatus; + private String customerRemark; + private String quoteStatus; + private Integer quoteUserConfirmed; + private Integer quoteShopConfirmed; + private LocalDateTime quoteExpireTime; + private LocalDateTime quoteConfirmedTime; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderItemDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderItemDO.java new file mode 100644 index 00000000..3be7c2f1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderItemDO.java @@ -0,0 +1,60 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@TableName("t_order_item") +/** + * OrderItemDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderItemDO extends BaseEntity { + /** + * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + private BigDecimal referencePrice; + private BigDecimal quotedPrice; + private BigDecimal confirmedPrice; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + + @TableField("appointment_time") + /** + * Field `appointmentTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentTime; + + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderQuoteMessageDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderQuoteMessageDO.java new file mode 100644 index 00000000..7efc5594 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/entity/OrderQuoteMessageDO.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_order_quote_message") +public class OrderQuoteMessageDO extends BaseEntity { + + @TableField("order_id") + private Long orderId; + + @TableField("actor_id") + private Long actorId; + + @TableField("actor_type") + private String actorType; + + @TableField("action") + private String action; + + @TableField("remark") + private String remark; + + @TableField("items_snapshot") + private String itemsSnapshot; + + @TableField("is_delete") + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/AfterSaleLogMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/AfterSaleLogMapper.java new file mode 100644 index 00000000..6d7fe42c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/AfterSaleLogMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleLogDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AfterSaleLogMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/AfterSaleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/AfterSaleMapper.java new file mode 100644 index 00000000..7dd78797 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/AfterSaleMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AfterSaleMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/CartMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/CartMapper.java new file mode 100644 index 00000000..1103252b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/CartMapper.java @@ -0,0 +1,39 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.CartDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +@Mapper +/** + * CartMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface CartMapper extends BaseMapper { + @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND is_delete = 0") + List selectByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND product_id = #{productId} AND is_delete = 0") + CartDO selectByUserIdAndProductId(@Param("userId") Long userId, @Param("productId") Long productId); + + @Select({ + "" + }) + List selectByUserIdAndProductIdsForUpdate( + @Param("userId") Long userId, + @Param("productIds") List productIds + ); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderArtistChangeRequestMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderArtistChangeRequestMapper.java new file mode 100644 index 00000000..365195d8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderArtistChangeRequestMapper.java @@ -0,0 +1,47 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistChangeRequestDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDateTime; + +import java.util.List; + +@Mapper +/** + * Purpose: OrderArtistChangeRequestMapper supports OrderArtistChangeRequestMapper.java by holding or executing the order artist change request mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface OrderArtistChangeRequestMapper extends BaseMapper { + + @Select("SELECT * FROM t_order_artist_change_request WHERE order_item_id = #{orderItemId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) LIMIT 1") + OrderArtistChangeRequestDO selectPendingByOrderItemId(@Param("orderItemId") Long orderItemId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE customer_id = #{userId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") + List selectPendingByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE (from_artist_id = #{artistId} OR to_artist_id = #{artistId} OR requester_id = #{artistId}) AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") + List selectPendingByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE shop_id = #{shopId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") + List selectPendingByShopId(@Param("shopId") Long shopId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); + + @Update("UPDATE t_order_artist_change_request SET status = 'APPROVED', approved_time = #{approvedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{approvedTime})") + int approvePending(@Param("id") Long id, @Param("approvedTime") LocalDateTime approvedTime); + + @Update("UPDATE t_order_artist_change_request SET status = 'REJECTED', reject_reason = #{rejectReason}, rejected_time = #{rejectedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{rejectedTime})") + int rejectPending(@Param("id") Long id, @Param("rejectReason") String rejectReason, @Param("rejectedTime") LocalDateTime rejectedTime); + + @Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}") + int expirePendingById(@Param("id") Long id, @Param("now") LocalDateTime now); + + @Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}") + int expirePendingBefore(@Param("now") LocalDateTime now); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderArtistReviewMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderArtistReviewMapper.java new file mode 100644 index 00000000..dc4fccd0 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderArtistReviewMapper.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistReviewDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.math.BigDecimal; +import java.util.List; + +@Mapper +/** + * Purpose: OrderArtistReviewMapper supports OrderArtistReviewMapper.java by holding or executing the order artist review mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface OrderArtistReviewMapper extends BaseMapper { + + @Select("SELECT * FROM t_order_artist_review WHERE customer_id = #{userId} AND status = 0 AND is_delete = 0 ORDER BY create_time DESC, id DESC") + List selectPendingByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_order_artist_review WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); + + @Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1") + OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId); + + @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0") + BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderItemMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderItemMapper.java new file mode 100644 index 00000000..80e42b7d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderItemMapper.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.time.LocalDateTime; +import java.util.List; + +@Mapper +/** + * OrderItemMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface OrderItemMapper extends BaseMapper { + @Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}") + List selectByOrderId(@Param("orderId") Long orderId); + + @Select("SELECT * FROM t_order_item WHERE id = #{id} FOR UPDATE") + OrderItemDO selectByIdForUpdate(@Param("id") Long id); + + @Select("SELECT oi.* FROM t_order_item oi " + + "INNER JOIN t_order o ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} " + + "AND oi.is_delete = 0 " + + "AND o.is_delete = 0 " + + "AND o.status = 1 " + + "AND oi.appointment_time IS NOT NULL") + List selectActiveAppointmentItemsByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT oi.* FROM t_order_item oi " + + "INNER JOIN t_order o ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} " + + "AND oi.is_delete = 0 " + + "AND o.is_delete = 0 " + + "AND o.status = 1 " + + "AND oi.appointment_time >= #{startTime} " + + "AND oi.appointment_time < #{endTime} " + + "ORDER BY oi.appointment_time ASC, oi.id ASC") + List selectArtistCalendarItems(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(DISTINCT oi.order_id) as count FROM t_order_item oi " + + "JOIN t_product p ON oi.product_id = p.id " + + "JOIN t_order o ON oi.order_id = o.id " + + "WHERE p.shop_id = #{shopId} AND o.create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND o.is_delete = 0") + java.util.Map countTodayOrdersByShopId(@Param("shopId") Long shopId, @Param("todayStart") String todayStart); + + @Select("SELECT COUNT(DISTINCT id) as count FROM t_order WHERE create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND is_delete = 0") + java.util.Map countTodayOrders(@Param("todayStart") String todayStart); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderMapper.java new file mode 100644 index 00000000..37fc2ecb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderMapper.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.util.List; + +@Mapper +/** + * OrderMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface OrderMapper extends BaseMapper { + @Select("SELECT * FROM t_order WHERE user_id = #{userId}") + List selectByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_order WHERE order_no = #{orderNo}") + OrderDO selectByOrderNo(@Param("orderNo") String orderNo); + + @Select("SELECT DISTINCT o.* FROM t_order o " + + "INNER JOIN t_order_item oi ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " + + "ORDER BY o.create_time DESC") + List selectByArtistId(@Param("artistId") Long artistId); + + @Update("UPDATE t_order SET status = #{toStatus} WHERE id = #{orderId} AND status = #{fromStatus} AND is_delete = 0") + int updateStatusIfCurrent(@Param("orderId") Long orderId, + @Param("fromStatus") Integer fromStatus, + @Param("toStatus") Integer toStatus); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderQuoteMessageMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderQuoteMessageMapper.java new file mode 100644 index 00000000..f053123c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/mapper/OrderQuoteMessageMapper.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderQuoteMessageDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +@Mapper +public interface OrderQuoteMessageMapper extends BaseMapper { + + @Select("SELECT * FROM t_order_quote_message WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/AfterSaleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/AfterSaleService.java new file mode 100644 index 00000000..d11da473 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/AfterSaleService.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.service; + +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.AfterSaleApplyDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.AfterSaleAuditDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; + +public interface AfterSaleService { + AfterSaleVO apply(Long userId, AfterSaleApplyDTO dto); + + PageResultVO listMy(Long userId, Integer page, Integer size); + + PageResultVO listAdmin(Long shopId, String status, Integer page, Integer size); + + AfterSaleVO approve(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto); + + AfterSaleVO reject(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/CartService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/CartService.java new file mode 100644 index 00000000..6f05d139 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/CartService.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.service; + +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.CartDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CartVO; + +import java.util.List; + +/** + * CartService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface CartService { + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + void addToCart(Long userId, CartDTO cartDTO); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + void removeFromCart(Long userId, Long productId); + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartItemIds parameter `cartItemIds` supplied by the caller + */ + void batchRemoveFromCart(Long userId, List cartItemIds); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + void updateCartQuantity(Long userId, CartDTO cartDTO); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getCartList(Long userId); + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + void clearCart(Long userId); +} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/OrderService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/OrderService.java new file mode 100644 index 00000000..43e45cd1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/OrderService.java @@ -0,0 +1,141 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.service; + +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.CheckoutPreviewDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistChangeRejectDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistChangeRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteReplyDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistCalendarAppointmentVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CheckoutPreviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistChangeRequestVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistReviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderVO; + +import java.time.LocalDate; +import java.util.List; + +/** + * OrderService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface OrderService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + OrderVO createOrder(Long userId, OrderDTO orderDTO); + + /** + * Preview checkout pricing and coupon explanations without creating an order. + */ + CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getOrderList(Long userId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + OrderVO getOrderDetail(Long orderId, Long userId); + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + */ + void cancelOrder(Long orderId, Long userId); + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + */ + void processOrder(Long orderId, Integer status); + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + */ + void completeArtistOrder(Long orderId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + List getAllOrders(); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getOrdersByArtistId(Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistWorkbenchOrders(Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param days parameter `days` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistCalendarRecent(Long userId, Integer userType, Integer days); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param date parameter `date` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistCalendarDay(Long userId, Integer userType, LocalDate date); + + List listMyPendingReviews(Long userId); + + List listOrderReviews(Long orderId, Long userId, Integer userType); + + OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto); + + OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType); + + OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto); + + List listMyPendingArtistChangeRequests(Long userId, Integer userType); + + List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType); + + OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType); + + OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto); + + OrderVO submitShopQuote(Long orderId, Long operatorId, Integer operatorType, OrderQuoteSubmitDTO dto); + + OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType); + + OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto); + + OrderVO confirmUserQuote(Long orderId, Long userId); + + int expirePendingQuoteOrders(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/AfterSaleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/AfterSaleServiceImpl.java new file mode 100644 index 00000000..ffb8acb2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/AfterSaleServiceImpl.java @@ -0,0 +1,171 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.AfterSaleApplyDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.AfterSaleAuditDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleLogDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.AfterSaleLogMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.AfterSaleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.AfterSaleService; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class AfterSaleServiceImpl implements AfterSaleService { + + private static final String STATUS_PENDING = "PENDING"; + private static final String STATUS_APPROVED = "APPROVED"; + private static final String STATUS_REJECTED = "REJECTED"; + + private final AfterSaleMapper afterSaleMapper; + private final AfterSaleLogMapper afterSaleLogMapper; + private final OrderMapper orderMapper; + private final SystemMessageMapper systemMessageMapper; + + @Override + @Transactional + public AfterSaleVO apply(Long userId, AfterSaleApplyDTO dto) { + if (dto == null || dto.getOrderId() == null) { + throw new RuntimeException("售后订单信息不完整"); + } + OrderDO order = orderMapper.selectById(dto.getOrderId()); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + if (!order.getUserId().equals(userId)) { + throw new RuntimeException("无权申请该订单售后"); + } + if (Integer.valueOf(0).equals(order.getStatus())) { + throw new RuntimeException("询价预约确认价格前暂不能申请售后"); + } + AfterSaleDO afterSale = new AfterSaleDO(); + afterSale.setAfterSaleNo("AS" + System.currentTimeMillis() + dto.getOrderId()); + afterSale.setOrderId(order.getId()); + afterSale.setOrderItemId(dto.getOrderItemId()); + afterSale.setUserId(userId); + afterSale.setShopId(order.getShopId()); + afterSale.setType(dto.getType()); + afterSale.setReason(dto.getReason()); + afterSale.setRefundAmount(dto.getRefundAmount()); + afterSale.setStatus(STATUS_PENDING); + afterSale.setIsDelete(0); + afterSaleMapper.insert(afterSale); + writeLog(afterSale.getId(), "CREATE", null, STATUS_PENDING, userId, "USER", dto.getReason()); + return toVO(afterSale); + } + + @Override + public PageResultVO listMy(Long userId, Integer page, Integer size) { + return pageByWrapper(new LambdaQueryWrapper() + .eq(AfterSaleDO::getUserId, userId) + .eq(AfterSaleDO::getIsDelete, 0) + .orderByDesc(AfterSaleDO::getCreateTime), page, size); + } + + @Override + public PageResultVO listAdmin(Long shopId, String status, Integer page, Integer size) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(AfterSaleDO::getIsDelete, 0) + .orderByDesc(AfterSaleDO::getCreateTime); + if (shopId != null) { + wrapper.eq(AfterSaleDO::getShopId, shopId); + } + if (status != null && !status.isBlank()) { + wrapper.eq(AfterSaleDO::getStatus, status); + } + return pageByWrapper(wrapper, page, size); + } + + @Override + @Transactional + public AfterSaleVO approve(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto) { + return audit(operatorId, afterSaleId, dto, STATUS_APPROVED, "APPROVE"); + } + + @Override + @Transactional + public AfterSaleVO reject(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto) { + return audit(operatorId, afterSaleId, dto, STATUS_REJECTED, "REJECT"); + } + + private AfterSaleVO audit(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto, String targetStatus, String action) { + AfterSaleDO afterSale = afterSaleMapper.selectById(afterSaleId); + if (afterSale == null || Integer.valueOf(1).equals(afterSale.getIsDelete())) { + throw new RuntimeException("售后单不存在"); + } + if (!STATUS_PENDING.equals(afterSale.getStatus())) { + throw new RuntimeException("售后单已处理"); + } + String fromStatus = afterSale.getStatus(); + afterSale.setStatus(targetStatus); + afterSale.setAuditUserId(operatorId); + afterSale.setAuditReason(dto == null ? null : dto.getAuditReason()); + afterSale.setAuditTime(LocalDateTime.now()); + afterSaleMapper.updateById(afterSale); + writeLog(afterSale.getId(), action, fromStatus, targetStatus, operatorId, "ADMIN", afterSale.getAuditReason()); + notifyCustomer(afterSale, targetStatus); + return toVO(afterSale); + } + + private void writeLog(Long afterSaleId, String action, String fromStatus, String toStatus, + Long operatorId, String operatorType, String remark) { + AfterSaleLogDO log = new AfterSaleLogDO(); + log.setAfterSaleId(afterSaleId); + log.setAction(action); + log.setFromStatus(fromStatus); + log.setToStatus(toStatus); + log.setOperatorId(operatorId); + log.setOperatorType(operatorType); + log.setRemark(remark); + afterSaleLogMapper.insert(log); + } + + private void notifyCustomer(AfterSaleDO afterSale, String status) { + SystemMessageDO message = new SystemMessageDO(); + message.setTitle("售后处理进度更新"); + message.setContent("您的售后申请已更新为:" + status); + message.setTargetType("SELECTED_USERS"); + message.setTargetIds(String.valueOf(afterSale.getUserId())); + message.setBusinessType("AFTER_SALE_" + status); + message.setBusinessId(afterSale.getId()); + message.setActionPath("/after-sales?afterSaleId=" + afterSale.getId()); + message.setPopupEnabled(1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + } + + private PageResultVO pageByWrapper(LambdaQueryWrapper wrapper, Integer page, Integer size) { + int current = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 10 : size; + Page result = afterSaleMapper.selectPage(new Page<>(current, pageSize), wrapper); + PageResultVO vo = new PageResultVO<>(); + List list = result.getRecords().stream().map(this::toVO).toList(); + vo.setList(list); + vo.setTotal(result.getTotal()); + vo.setPage(current); + vo.setSize(pageSize); + return vo; + } + + private AfterSaleVO toVO(AfterSaleDO afterSale) { + AfterSaleVO vo = new AfterSaleVO(); + BeanUtils.copyProperties(afterSale, vo); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/CartServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/CartServiceImpl.java new file mode 100644 index 00000000..9f5c5ebc --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/CartServiceImpl.java @@ -0,0 +1,361 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.CartDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.CartDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.CartMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.CartService; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.TagService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CartArtistVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CartVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +@Service +/** + * CartServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class CartServiceImpl implements CartService { + + @Resource + /** + * Purpose: cartMapper supports CartServiceImpl.java by holding or executing the cart mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CartMapper cartMapper; + + @Resource + /** + * Purpose: productMapper supports CartServiceImpl.java by holding or executing the product mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductMapper productMapper; + + @Resource + /** + * Purpose: tagService supports CartServiceImpl.java by holding or executing the tag service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TagService tagService; + + @Resource + /** + * Purpose: userMapper supports CartServiceImpl.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserMapper userMapper; + + @Resource + /** + * Purpose: userShopBindingSupport supports CartServiceImpl.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserShopBindingSupport userShopBindingSupport; + + @Resource + /** + * Purpose: bookableArtistSupport supports CartServiceImpl.java by holding or executing the bookable artist support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BookableArtistSupport bookableArtistSupport; + + @Resource + /** + * Purpose: objectStorageUrlSupport supports CartServiceImpl.java by holding or executing the object storage url support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + @Transactional + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + public void addToCart(Long userId, CartDTO cartDTO) { + validateQuantity(cartDTO.getQuantity()); + + ProductDO product = productMapper.selectById(cartDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("商品不存在"); + } + + CartDO existingCart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); + if (existingCart != null) { + existingCart.setQuantity(existingCart.getQuantity() + cartDTO.getQuantity()); + cartMapper.updateById(existingCart); + return; + } + + CartDO newCart = new CartDO(); + newCart.setUserId(userId); + newCart.setProductId(cartDTO.getProductId()); + newCart.setQuantity(cartDTO.getQuantity()); + newCart.setIsDelete(0); + cartMapper.insert(newCart); + } + + @Override + @Transactional + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + public void removeFromCart(Long userId, Long productId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId) + .eq("product_id", productId) + .eq("is_delete", 0); + cartMapper.delete(wrapper); + } + + @Override + @Transactional + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartItemIds parameter `cartItemIds` supplied by the caller + */ + public void batchRemoveFromCart(Long userId, List cartItemIds) { + if (cartItemIds == null || cartItemIds.isEmpty()) { + return; + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId) + .in("id", cartItemIds) + .eq("is_delete", 0); + cartMapper.delete(wrapper); + } + + @Override + @Transactional + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + public void updateCartQuantity(Long userId, CartDTO cartDTO) { + validateQuantity(cartDTO.getQuantity()); + CartDO cart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); + if (cart != null) { + cart.setQuantity(cartDTO.getQuantity()); + cartMapper.updateById(cart); + return; + } + + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("购物车商品不存在"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getCartList(Long userId) { + List cartList = cartMapper.selectByUserId(userId); + List cartVOList = new ArrayList<>(); + + for (CartDO cart : cartList) { + if (!Integer.valueOf(0).equals(cart.getIsDelete())) { + continue; + } + + ProductDO product = productMapper.selectById(cart.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + continue; + } + + CartVO cartVO = new CartVO(); + cartVO.setId(cart.getId()); + cartVO.setProductId(product.getId()); + cartVO.setShopId(product.getShopId()); + cartVO.setProductTitle(product.getTitle()); + + String imageFileIds = product.getImageFileIds(); + if (StringUtils.hasText(imageFileIds)) { + String firstImageId = imageFileIds.split(",")[0]; + cartVO.setProductImage("/api/file/get/" + firstImageId); + } + + cartVO.setPrice(product.getPrice()); + cartVO.setQuantity(cart.getQuantity()); + cartVO.setTotalPrice(product.getPrice().multiply(new BigDecimal(cart.getQuantity()))); + cartVO.setTags(product.getTags()); + cartVO.setTagNames(resolveTagNames(product.getTags())); + cartVO.setApproximateDuration(product.getApproximateDuration()); + + String validBookableArtists = bookableArtistSupport.filterValidBookableArtists(product.getShopId(), product.getBookableArtists()); + List availableArtists = resolveAvailableArtists(product.getShopId(), product.getBookableArtists(), validBookableArtists); + cartVO.setBookableArtists(validBookableArtists); + cartVO.setAvailableBookableArtistCount(availableArtists.size()); + cartVO.setBookableArtistRestricted(StringUtils.hasText(product.getBookableArtists())); + cartVO.setAvailableArtists(availableArtists); + + cartVOList.add(cartVO); + } + + return cartVOList; + } + + @Override + @Transactional + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + public void clearCart(Long userId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId) + .eq("is_delete", 0); + cartMapper.delete(wrapper); + } + + /** + * Run business method `validateQuantity`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param quantity parameter `quantity` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateQuantity(Integer quantity) { + if (quantity == null || quantity < 1 || quantity > 99) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("购物车数量必须在 1 到 99 之间"); + } + } + + /** + * Run business method `resolveTagNames`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagIds parameter `tagIds` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveTagNames(String tagIds) { + if (!StringUtils.hasText(tagIds)) { + return ""; + } + + return List.of(tagIds.split(";")).stream() + .map(String::trim) + .filter(tagId -> !tagId.isEmpty()) + .map(tagId -> { + try { + TagVO tagVO = tagService.getTagById(Long.parseLong(tagId)); + return tagVO != null ? tagVO.getTagName() : null; + } catch (NumberFormatException ex) { + return null; + } + }) + .filter(tagName -> tagName != null && !tagName.isBlank()) + .collect(Collectors.joining(",")); + } + + /** + * Run business method `resolveAvailableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller + * @param validBookableArtists parameter `validBookableArtists` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAvailableArtists(Long shopId, String rawBookableArtists, String validBookableArtists) { + LinkedHashSet candidateArtistIds = new LinkedHashSet<>(); + if (StringUtils.hasText(validBookableArtists)) { + for (String artistIdText : validBookableArtists.split(",")) { + if (!StringUtils.hasText(artistIdText)) { + continue; + } + try { + candidateArtistIds.add(Long.parseLong(artistIdText.trim())); + } catch (NumberFormatException ignored) { + // Ignore invalid ids and keep valid artists only. + } + } + } else if (!StringUtils.hasText(rawBookableArtists) && shopId != null && shopId > 0) { + candidateArtistIds.addAll(userShopBindingSupport.listUserIdsByShopId(shopId, true)); + } + + if (candidateArtistIds.isEmpty()) { + return List.of(); + } + + List artistUsers = userMapper.selectList( + new QueryWrapper() + .in("id", candidateArtistIds) + .in("type", List.of(2, 3)) + .eq("status", 1) + .eq("is_delete", 0) + ); + if (artistUsers.isEmpty()) { + return List.of(); + } + + Map artistMap = artistUsers.stream() + .collect(Collectors.toMap(UserDO::getId, artist -> artist, (left, right) -> left)); + + return candidateArtistIds.stream() + .map(artistMap::get) + .filter(Objects::nonNull) + .filter(bookableArtistSupport::isBookableServiceUser) + .map(this::buildCartArtist) + .collect(Collectors.toList()); + } + + /** + * Run business method `buildCartArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artist parameter `artist` supplied by the caller + * @return private CartArtistVO result consumed by the caller or returned to the frontend + */ + private CartArtistVO buildCartArtist(UserDO artist) { + CartArtistVO cartArtistVO = new CartArtistVO(); + cartArtistVO.setId(artist.getId()); + cartArtistVO.setName(artist.getNickname()); + cartArtistVO.setAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + cartArtistVO.setUserType(artist.getType()); + cartArtistVO.setRoleLabel(Integer.valueOf(2).equals(artist.getType()) ? "店长 · 参与制作" : "美甲师"); + cartArtistVO.setParticipateProduction(Integer.valueOf(2).equals(artist.getType())); + return cartArtistVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/OrderServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/OrderServiceImpl.java new file mode 100644 index 00000000..19769de2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/service/impl/OrderServiceImpl.java @@ -0,0 +1,4639 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.CheckoutPreviewDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistChangeRejectDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistChangeRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderItemDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteItemDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteReplyDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.CartDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistChangeRequestDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderQuoteMessageDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.UserCouponDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.CartMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistChangeRequestMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderQuoteMessageMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.BusinessEventOutboxService; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.TagService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStateMachine; +import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistCalendarAppointmentVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CheckoutCouponPreviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CheckoutPreviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.CheckoutPreviewVO.CheckoutIssueVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistChangeRequestVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderArtistReviewVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderItemVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderQuoteItemVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderQuoteMessageVO; +import com.xiaowang.jayucloud.artlist.core.modules.order.vo.OrderVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.vo.UserCouponVO; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import javax.annotation.PreDestroy; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +@Service +/** + * OrderServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class OrderServiceImpl implements OrderService { + + private static final DateTimeFormatter ORDER_NO_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + private static final DateTimeFormatter APPOINTMENT_OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + /** + * Purpose: COUPON_SOURCE_NONE supports OrderServiceImpl.java by holding or executing the coupon source none business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_NONE = "NONE"; + /** + * Purpose: COUPON_SOURCE_USER supports OrderServiceImpl.java by holding or executing the coupon source user business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_USER = "USER_COUPON"; + /** + * Purpose: COUPON_SOURCE_SYSTEM_VIP supports OrderServiceImpl.java by holding or executing the coupon source system vip business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; + private static final int BOOKING_UNAVAILABLE_CODE = 409; + private static final String ISSUE_ORDER_ITEM = "ORDER_ITEM"; + private static final String ISSUE_PRODUCT_UNAVAILABLE = "PRODUCT_UNAVAILABLE"; + private static final String ISSUE_SHOP_MISMATCH = "SHOP_MISMATCH"; + private static final String ISSUE_ARTIST_UNAVAILABLE = "ARTIST_UNAVAILABLE"; + private static final String ISSUE_ARTIST_MISMATCH = "ARTIST_MISMATCH"; + private static final String ISSUE_APPOINTMENT_TIME = "APPOINTMENT_TIME"; + private static final String ISSUE_BUSINESS_HOURS = "BUSINESS_HOURS"; + private static final String ISSUE_ORDER_CONFLICT = "ORDER_CONFLICT"; + private static final String ISSUE_EXISTING_CONFLICT = "EXISTING_CONFLICT"; + private static final String QUOTE_STATUS_CONFIRMING = "CONFIRMING"; + private static final String QUOTE_STATUS_CONFIRMED = "CONFIRMED"; + private static final String QUOTE_STATUS_EXPIRED = "EXPIRED"; + private static final String QUOTE_ACTOR_USER = "USER"; + private static final String QUOTE_ACTOR_SHOP = "SHOP"; + private static final String QUOTE_ACTOR_SYSTEM = "SYSTEM"; + private static final String QUOTE_ACTION_CREATE = "CREATE"; + private static final String QUOTE_ACTION_SHOP_QUOTE = "SHOP_QUOTE"; + private static final String QUOTE_ACTION_USER_REPLY = "USER_REPLY"; + private static final String QUOTE_ACTION_USER_CONFIRM = "USER_CONFIRM"; + private static final String QUOTE_ACTION_SHOP_CONFIRM = "SHOP_CONFIRM"; + private static final String QUOTE_ACTION_SYSTEM_CONFIRM = "SYSTEM_CONFIRM"; + private static final String QUOTE_ACTION_SYSTEM_EXPIRE = "SYSTEM_EXPIRE"; + private static final String QUOTE_BUSINESS_TYPE = "ORDER_QUOTE"; + private static final int USER_TYPE_SHOP_OWNER = 2; + private static final int QUOTE_EXPIRE_HOURS = 24; + /** + * Purpose: REVIEW_STATUS_PENDING supports OrderServiceImpl.java by holding or executing the review status pending business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int REVIEW_STATUS_PENDING = 0; + /** + * Purpose: REVIEW_STATUS_SUBMITTED supports OrderServiceImpl.java by holding or executing the review status submitted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int REVIEW_STATUS_SUBMITTED = 1; + /** + * Purpose: CHANGE_STATUS_PENDING supports OrderServiceImpl.java by holding or executing the change status pending business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_PENDING = "PENDING"; + /** + * Purpose: CHANGE_STATUS_APPROVED supports OrderServiceImpl.java by holding or executing the change status approved business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_APPROVED = "APPROVED"; + /** + * Purpose: CHANGE_STATUS_REJECTED supports OrderServiceImpl.java by holding or executing the change status rejected business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_REJECTED = "REJECTED"; + /** + * Purpose: CHANGE_STATUS_EXPIRED supports OrderServiceImpl.java by holding or executing the change status expired business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_EXPIRED = "EXPIRED"; + /** + * Purpose: ARTIST_CHANGE_PENDING_KEY_PREFIX supports OrderServiceImpl.java by holding or executing the artist change pending key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ARTIST_CHANGE_PENDING_KEY_PREFIX = "ORDER_ITEM:"; + /** + * Purpose: MESSAGE_TARGET_SELECTED_USERS supports OrderServiceImpl.java by holding or executing the message target selected users business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String MESSAGE_TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Purpose: REVIEW_BUSINESS_TYPE supports OrderServiceImpl.java by holding or executing the review business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String REVIEW_BUSINESS_TYPE = "ORDER_ARTIST_REVIEW"; + /** + * Purpose: CHANGE_BUSINESS_TYPE supports OrderServiceImpl.java by holding or executing the change business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_BUSINESS_TYPE = "ORDER_ARTIST_CHANGE"; + /** + * Purpose: ORDER_CREATE_USER_LOCK_PREFIX supports OrderServiceImpl.java by holding or executing the order create user lock prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:"; + /** + * Purpose: ORDER_CREATE_ARTIST_LOCK_PREFIX supports OrderServiceImpl.java by holding or executing the order create artist lock prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:"; + private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15); + private static final long ORDER_CREATE_LOCK_TTL_MILLIS = ORDER_CREATE_LOCK_TTL.toMillis(); + /** + * Purpose: ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS supports OrderServiceImpl.java by holding or executing the order create lock renew interval millis business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS = 5000L; + /** + * Purpose: ARTIST_LOCK_RETRY_INTERVAL_MILLIS supports OrderServiceImpl.java by holding or executing the artist lock retry interval millis business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long ARTIST_LOCK_RETRY_INTERVAL_MILLIS = 150L; + /** + * Purpose: ARTIST_LOCK_WAIT_TIMEOUT_MILLIS supports OrderServiceImpl.java by holding or executing the artist lock wait timeout millis business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long ARTIST_LOCK_WAIT_TIMEOUT_MILLIS = 1500L; + private static final List APPOINTMENT_INPUT_FORMATTERS = Arrays.asList( + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"), + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm") + ); + private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)"); + private static final Pattern BUSINESS_HOURS_PATTERN = Pattern.compile("^(\\d{1,2}:\\d{2})\\s*[-~至]\\s*(\\d{1,2}:\\d{2})$"); + /** + * Purpose: DEFAULT_SERVICE_DURATION_MINUTES supports OrderServiceImpl.java by holding or executing the default service duration minutes business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L; + private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); + private static final DefaultRedisScript RENEW_LOCK_SCRIPT = new DefaultRedisScript<>(); + private static final ScheduledExecutorService LOCK_RENEW_EXECUTOR = Executors.newSingleThreadScheduledExecutor(new LockRenewThreadFactory()); + + static { + RELEASE_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) " + + "else return 0 end" + ); + RELEASE_LOCK_SCRIPT.setResultType(Long.class); + + RENEW_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('pexpire', KEYS[1], ARGV[2]) " + + "else return 0 end" + ); + RENEW_LOCK_SCRIPT.setResultType(Long.class); + } + + @Resource + /** + * Purpose: orderMapper supports OrderServiceImpl.java by holding or executing the order mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderMapper orderMapper; + + @Resource + /** + * Purpose: orderItemMapper supports OrderServiceImpl.java by holding or executing the order item mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemMapper orderItemMapper; + + @Resource + /** + * Purpose: orderArtistReviewMapper supports OrderServiceImpl.java by holding or executing the order artist review mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewMapper orderArtistReviewMapper; + + @Resource + /** + * Purpose: orderArtistChangeRequestMapper supports OrderServiceImpl.java by holding or executing the order artist change request mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + + @Resource + private OrderQuoteMessageMapper orderQuoteMessageMapper; + + @Resource + /** + * Purpose: cartMapper supports OrderServiceImpl.java by holding or executing the cart mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CartMapper cartMapper; + + @Resource + /** + * Purpose: productMapper supports OrderServiceImpl.java by holding or executing the product mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductMapper productMapper; + + @Resource + /** + * Purpose: couponMapper supports OrderServiceImpl.java by holding or executing the coupon mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CouponMapper couponMapper; + + @Resource + /** + * Purpose: nailArtistInfoMapper supports OrderServiceImpl.java by holding or executing the nail artist info mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private NailArtistInfoMapper nailArtistInfoMapper; + + @Resource + /** + * Purpose: userCouponMapper supports OrderServiceImpl.java by holding or executing the user coupon mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserCouponMapper userCouponMapper; + + @Resource + /** + * Purpose: userMapper supports OrderServiceImpl.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserMapper userMapper; + + @Resource + /** + * Purpose: shopMapper supports OrderServiceImpl.java by holding or executing the shop mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ShopMapper shopMapper; + + @Resource + /** + * Purpose: systemMessageMapper supports OrderServiceImpl.java by holding or executing the system message mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private SystemMessageMapper systemMessageMapper; + + @Resource + /** + * Purpose: couponService supports OrderServiceImpl.java by holding or executing the coupon service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CouponService couponService; + + @Resource + /** + * Purpose: tagService supports OrderServiceImpl.java by holding or executing the tag service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TagService tagService; + + @Resource + /** + * Purpose: userShopBindingSupport supports OrderServiceImpl.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserShopBindingSupport userShopBindingSupport; + + @Resource + /** + * Purpose: bookableArtistSupport supports OrderServiceImpl.java by holding or executing the bookable artist support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BookableArtistSupport bookableArtistSupport; + + @Resource + /** + * Purpose: businessEventOutboxService supports OrderServiceImpl.java by holding or executing the business event outbox service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BusinessEventOutboxService businessEventOutboxService; + + @Resource + /** + * Purpose: snowflakeIdGenerator supports OrderServiceImpl.java by holding or executing the snowflake id generator business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Resource + /** + * Purpose: stringRedisTemplate supports OrderServiceImpl.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private StringRedisTemplate stringRedisTemplate; + + @Resource + /** + * Purpose: objectStorageUrlSupport supports OrderServiceImpl.java by holding or executing the object storage url support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ObjectStorageUrlSupport objectStorageUrlSupport; + + @Resource + /** + * Purpose: transactionTemplate supports OrderServiceImpl.java by holding or executing the transaction template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TransactionTemplate transactionTemplate; + + @Resource + private AppointmentCapacityService appointmentCapacityService; + + @Resource + private AppointmentReservationMapper appointmentReservationMapper; + + @PreDestroy + /** + * Run business method `shutdownOrderLockRenewExecutor`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ + public void shutdownOrderLockRenewExecutor() { + LOCK_RENEW_EXECUTOR.shutdownNow(); + } + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + public OrderVO createOrder(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("订单项不能为空"); + } + + String userLockKey = ORDER_CREATE_USER_LOCK_PREFIX + userId; + String userLockToken = UUID.randomUUID().toString(); + if (!tryAcquireOrderLock(userLockKey, userLockToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单正在提交中,请勿重复点击"); + } + + LockLease userLockLease = startOrderLockRenewal(userLockKey, userLockToken); + + String artistLockKey = null; + String artistLockToken = null; + LockLease artistLockLease = null; + try { + Long artistId; + try { + artistId = resolveRequestedArtistId(orderDTO.getItems()); + } catch (RuntimeException exception) { + if (isBookingValidationMessage(exception.getMessage())) { + throw bookingUnavailable(exception.getMessage()); + } + throw exception; + } + artistLockKey = ORDER_CREATE_ARTIST_LOCK_PREFIX + artistId; + artistLockToken = UUID.randomUUID().toString(); + if (!tryAcquireArtistOrderLock(artistLockKey, artistLockToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("当前美甲师预约繁忙,请稍后再试"); + } + + artistLockLease = startOrderLockRenewal(artistLockKey, artistLockToken); + + OrderVO orderVO = transactionTemplate.execute(status -> createOrderInTransaction(userId, orderDTO)); + if (orderVO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单创建失败,请稍后重试"); + } + notifyQuoteCreated(orderVO); + return orderVO; + } finally { + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistLockLease parameter `artistLockLease` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + stopOrderLockRenewal(artistLockLease); + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistLockKey parameter `artistLockKey` supplied by the caller + * @param artistLockToken parameter `artistLockToken` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + releaseOrderLock(artistLockKey, artistLockToken); + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userLockLease parameter `userLockLease` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + stopOrderLockRenewal(userLockLease); + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userLockKey parameter `userLockKey` supplied by the caller + * @param userLockToken parameter `userLockToken` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + releaseOrderLock(userLockKey, userLockToken); + } + } + + @Override + public CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO) { + OrderDTO orderDTO = toOrderDTO(checkoutPreviewDTO); + CheckoutPricingContext pricingContext = buildCheckoutPricingContext(userId, orderDTO); + List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); + List availableCouponOptions = couponService.getAvailableCoupons( + userId, + pricingContext.getProductTagNames(), + pricingContext.getTotalAmount().doubleValue(), + pricingContext.getShopId() + ); + if (availableCouponOptions == null) { + availableCouponOptions = List.of(); + } + + List availableCoupons = availableCouponOptions.stream() + .map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount())) + .sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed() + .thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))) + .toList(); + + CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons); + if (bestCoupon != null) { + bestCoupon.setBest(true); + } + + CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon); + BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount()); + BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount); + if (payableAmount.compareTo(BigDecimal.ZERO) < 0) { + payableAmount = BigDecimal.ZERO; + } + + CheckoutPreviewVO preview = new CheckoutPreviewVO(); + preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount())); + preview.setSavedAmount(scaleMoney(savedAmount)); + preview.setPayableAmount(scaleMoney(payableAmount)); + preview.setBestCoupon(bestCoupon); + preview.setAvailableCoupons(availableCoupons); + preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext)); + preview.setBookingAvailable(bookingIssues.isEmpty()); + preview.setBookingIssues(bookingIssues); + preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons)); + preview.setSummaryText(buildCheckoutSummaryText(preview)); + return preview; + } + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ + private OrderVO createOrderInTransaction(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("订单项不能为空"); + } + + List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); + if (!bookingIssues.isEmpty()) { + throw bookingUnavailable(bookingIssues.get(0).getMessage()); + } + + List orderItemDTOs = orderDTO.getItems(); + BigDecimal totalAmount = BigDecimal.ZERO; + List orderItems = new ArrayList<>(); + List requestedSlots = new ArrayList<>(); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + Set selectedTagNames = new LinkedHashSet<>(); + Long shopId = null; + Long selectedArtistId = null; + Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); + List requestedProductIds = new ArrayList<>(requestedQuantityByProductId.keySet()); + Map lockedCartItemMap = loadLockedCartItems(userId, requestedProductIds); + + try { + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + validateOrderQuantity(orderItemDTO.getQuantity()); + + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("商品不存在或已下架"); + } + productCache.put(product.getId(), product); + + CartDO cartItem = lockedCartItemMap.get(orderItemDTO.getProductId()); + if (cartItem == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先将商品加入购物车后再结算"); + } + Integer requestedQuantity = requestedQuantityByProductId.get(orderItemDTO.getProductId()); + if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); + } + + UserDO artist = validateArtistForProduct(product, orderItemDTO.getArtistId()); + + if (shopId == null) { + shopId = product.getShopId(); + /** + * Run business method `validateUserCanCreateOrderInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateUserCanCreateOrderInShop(userId, shopId); + } else if (!shopId.equals(product.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("跨店铺商品请分开下单"); + } + + if (selectedArtistId == null) { + selectedArtistId = artist.getId(); + } else if (!selectedArtistId.equals(artist.getId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("不同美甲师的项目请分开下单"); + } + + LocalDateTime appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime()); + validateAppointmentTime(appointmentTime, product.getTitle()); + + long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity(); + LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes); + validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle()); + requestedSlots.add(new AppointmentSlot(product.getTitle(), appointmentTime, appointmentEndTime)); + + collectTagNames(selectedTagNames, product.getTags()); + + BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(orderItemDTO.getQuantity())); + totalAmount = totalAmount.add(itemTotal); + + OrderItemDO orderItem = new OrderItemDO(); + orderItem.setProductId(product.getId()); + orderItem.setQuantity(orderItemDTO.getQuantity()); + orderItem.setPrice(product.getPrice()); + orderItem.setReferencePrice(product.getPrice()); + orderItem.setArtistId(orderItemDTO.getArtistId()); + orderItem.setAppointmentTime(appointmentTime); + orderItems.add(orderItem); + } + + /** + * Run business method `validateRequestedSlotConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateRequestedSlotConflicts(requestedSlots); + /** + * Run business method `validateArtistScheduleConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param selectedArtistId parameter `selectedArtistId` supplied by the caller + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateArtistScheduleConflicts(selectedArtistId, requestedSlots, productCache); + } catch (BusinessException exception) { + throw exception; + } catch (RuntimeException exception) { + if (isBookingValidationMessage(exception.getMessage())) { + throw bookingUnavailable(exception.getMessage()); + } + throw exception; + } + + if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单金额无效"); + } + + String productTagNames = String.join(",", selectedTagNames); + List availableCouponOptions = couponService.getAvailableCoupons( + userId, + productTagNames, + totalAmount.doubleValue(), + shopId + ); + + BigDecimal actualAmount = totalAmount; + Long couponId = null; + Long userCouponId = null; + String couponSourceType = null; + + CouponSelection couponSelection = resolveRequestedCoupon(orderDTO, availableCouponOptions); + if (couponSelection == null && !isExplicitNoCoupon(orderDTO)) { + couponSelection = selectBestAvailableCoupon(availableCouponOptions, totalAmount); + } + + if (couponSelection != null) { + CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); + if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete()) || coupon.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券不存在或已失效"); + } + if (shopId != null && coupon.getShopId() != null && !shopId.equals(coupon.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该优惠券不适用于当前店铺"); + } + + actualAmount = applyCouponDiscount(totalAmount, coupon); + couponId = coupon.getId(); + userCouponId = couponSelection.getUserCouponId(); + couponSourceType = couponSelection.getSourceType(); + + } + + String orderNo = "ORD" + snowflakeIdGenerator.nextIdString(); + + OrderDO order = new OrderDO(); + order.setOrderNo(orderNo); + order.setUserId(userId); + order.setShopId(shopId); + order.setTotalAmount(totalAmount); + order.setActualAmount(actualAmount); + order.setCouponId(couponId); + order.setUserCouponId(userCouponId); + order.setCouponSourceType(couponSourceType); + order.setCustomerRemark(trimToNull(orderDTO.getRemark())); + order.setQuoteStatus(QUOTE_STATUS_CONFIRMING); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + order.setQuoteExpireTime(LocalDateTime.now().plusHours(QUOTE_EXPIRE_HOURS)); + order.setPaymentStatus("UNPAID"); + order.setPayAmount(actualAmount); + order.setPaidAmount(BigDecimal.ZERO); + order.setStatus(OrderStatus.PRICE_CONFIRMING.getCode()); + order.setIsDelete(0); + orderMapper.insert(order); + + for (OrderItemDO item : orderItems) { + item.setOrderId(order.getId()); + item.setIsDelete(0); + orderItemMapper.insert(item); + ProductDO product = productCache.get(item.getProductId()); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + appointmentCapacityService.reservePendingQuoteOrThrow( + order.getId(), + item.getId(), + order.getShopId(), + item.getArtistId(), + product == null ? null : product.getTitle(), + item.getAppointmentTime(), + item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes), + trimToNull(orderDTO.getClientRequestId()) + ); + } + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_CREATE, order.getCustomerRemark()); + + QueryWrapper cartWrapper = new QueryWrapper<>(); + cartWrapper.eq("user_id", userId) + .eq("is_delete", 0) + .in("product_id", requestedProductIds); + cartMapper.delete(cartWrapper); + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildOrderVO(order); + } + + private OrderDTO toOrderDTO(CheckoutPreviewDTO checkoutPreviewDTO) { + OrderDTO orderDTO = new OrderDTO(); + if (checkoutPreviewDTO == null) { + return orderDTO; + } + orderDTO.setCouponId(checkoutPreviewDTO.getCouponId()); + orderDTO.setCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); + orderDTO.setRemark(checkoutPreviewDTO.getRemark()); + orderDTO.setItems(checkoutPreviewDTO.getItems()); + return orderDTO; + } + + private CheckoutPricingContext buildCheckoutPricingContext(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + throw new RuntimeException("订单项不能为空"); + } + + List orderItemDTOs = orderDTO.getItems(); + Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); + BigDecimal totalAmount = BigDecimal.ZERO; + Set selectedTagNames = new LinkedHashSet<>(); + Long shopId = null; + + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + validateOrderQuantity(orderItemDTO.getQuantity()); + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + throw new RuntimeException("商品不存在或已下架"); + } + + CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId()); + Integer requestedQuantity = requestedQuantityByProductId.get(product.getId()); + if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) { + throw new RuntimeException("请先将商品加入购物车后再结算"); + } + if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { + throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); + } + + if (shopId == null) { + shopId = product.getShopId(); + validateUserCanCreateOrderInShop(userId, shopId); + } else if (!shopId.equals(product.getShopId())) { + throw new RuntimeException("跨店铺商品请分开下单"); + } + + collectPreviewTagNames(selectedTagNames, product.getTags()); + BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()))); + } + + if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { + throw new RuntimeException("订单金额无效"); + } + return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames)); + } + + private List collectCheckoutBookingIssues(Long userId, OrderDTO orderDTO) { + List issues = new ArrayList<>(); + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单项不能为空", (OrderItemDTO) null, (ProductDO) null)); + return issues; + } + + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + List requestedSlots = new ArrayList<>(); + Long shopId = null; + Long selectedArtistId = null; + + for (OrderItemDTO orderItemDTO : orderDTO.getItems()) { + if (orderItemDTO == null || orderItemDTO.getProductId() == null) { + issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单项信息不完整", orderItemDTO, null)); + continue; + } + + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + issues.add(checkoutIssue(ISSUE_PRODUCT_UNAVAILABLE, "商品不存在或已下架", orderItemDTO, null)); + continue; + } + productCache.put(product.getId(), product); + + if (orderItemDTO.getQuantity() == null || orderItemDTO.getQuantity() < 1) { + issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单商品数量必须大于 0", orderItemDTO, product)); + continue; + } + + if (shopId == null) { + shopId = product.getShopId(); + } else if (!Objects.equals(shopId, product.getShopId())) { + issues.add(checkoutIssue(ISSUE_SHOP_MISMATCH, "跨店铺商品请分开下单", orderItemDTO, product)); + } + + UserDO artist = null; + try { + artist = validateArtistForProduct(product, orderItemDTO.getArtistId()); + } catch (RuntimeException exception) { + issues.add(checkoutIssue(ISSUE_ARTIST_UNAVAILABLE, bookingMessage(exception, "美甲师当前不可预约"), orderItemDTO, product)); + } + + if (artist != null) { + if (selectedArtistId == null) { + selectedArtistId = artist.getId(); + } else if (!selectedArtistId.equals(artist.getId())) { + issues.add(checkoutIssue(ISSUE_ARTIST_MISMATCH, "不同美甲师的项目请分开下单", orderItemDTO, product)); + } + } + + LocalDateTime appointmentTime; + try { + appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime()); + validateAppointmentTime(appointmentTime, product.getTitle()); + } catch (RuntimeException exception) { + issues.add(checkoutIssue(ISSUE_APPOINTMENT_TIME, bookingMessage(exception, "预约时间不正确"), orderItemDTO, product)); + continue; + } + + long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity(); + LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes); + try { + validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle()); + } catch (RuntimeException exception) { + issues.add(checkoutIssue(ISSUE_BUSINESS_HOURS, bookingMessage(exception, "预约时间超出门店营业时间"), orderItemDTO, product)); + continue; + } + + requestedSlots.add(new BookingValidationSlot( + orderItemDTO.getProductId(), + product.getTitle(), + appointmentTime, + appointmentEndTime + )); + } + + collectRequestedSlotIssues(requestedSlots, issues); + collectExistingAppointmentIssues(selectedArtistId, requestedSlots, productCache, issues); + return issues; + } + + private void collectRequestedSlotIssues(List requestedSlots, List issues) { + if (requestedSlots.size() <= 1) { + return; + } + + List sortedSlots = new ArrayList<>(requestedSlots); + sortedSlots.sort(Comparator.comparing(BookingValidationSlot::getStartTime)); + for (int i = 1; i < sortedSlots.size(); i++) { + BookingValidationSlot previous = sortedSlots.get(i - 1); + BookingValidationSlot current = sortedSlots.get(i); + if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) { + issues.add(checkoutIssue( + ISSUE_ORDER_CONFLICT, + "所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间", + current.getProductId(), + current.getProductTitle() + )); + } + } + } + + private void collectExistingAppointmentIssues(Long artistId, + List requestedSlots, + Map productCache, + List issues) { + if (artistId == null || requestedSlots.isEmpty()) { + return; + } + + Set occupiedSlotKeys = new LinkedHashSet<>(); + for (BookingValidationSlot requestedSlot : requestedSlots) { + int activeOccupancyCount = appointmentReservationMapper.countOverlappingActive( + artistId, + requestedSlot.getStartTime(), + requestedSlot.getEndTime() + ); + if (activeOccupancyCount > 0) { + occupiedSlotKeys.add(bookingSlotKey(requestedSlot)); + issues.add(checkoutIssue( + ISSUE_EXISTING_CONFLICT, + "商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约占用冲突,请重新选择", + requestedSlot.getProductId(), + requestedSlot.getProductTitle() + )); + } + } + + List existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId); + if (existingAppointments == null || existingAppointments.isEmpty()) { + return; + } + + for (OrderItemDO existingItem : existingAppointments) { + if (existingItem == null || existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) { + continue; + } + + ProductDO existingProduct = getProductForBookingCheck(existingItem.getProductId(), productCache); + if (existingProduct == null) { + continue; + } + + int existingQuantity = existingItem.getQuantity() == null ? 1 : Math.max(1, existingItem.getQuantity()); + long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * existingQuantity; + LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes); + + for (BookingValidationSlot requestedSlot : requestedSlots) { + if (occupiedSlotKeys.contains(bookingSlotKey(requestedSlot))) { + continue; + } + if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) { + issues.add(checkoutIssue( + ISSUE_EXISTING_CONFLICT, + "商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择", + requestedSlot.getProductId(), + requestedSlot.getProductTitle() + )); + } + } + } + } + + private String bookingSlotKey(BookingValidationSlot requestedSlot) { + return requestedSlot.getProductId() + "|" + requestedSlot.getStartTime() + "|" + requestedSlot.getEndTime(); + } + + private ProductDO getProductForBookingCheck(Long productId, Map productCache) { + if (productId == null) { + return null; + } + if (productCache.containsKey(productId)) { + return productCache.get(productId); + } + + ProductDO product = productMapper.selectById(productId); + if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) { + product = null; + } + productCache.put(productId, product); + return product; + } + + private CheckoutIssueVO checkoutIssue(String code, String message, OrderItemDTO orderItemDTO, ProductDO product) { + Long productId = product == null ? orderItemDTO == null ? null : orderItemDTO.getProductId() : product.getId(); + String productTitle = product == null ? "订单项" : resolveProductTitle(product); + return checkoutIssue(code, message, productId, productTitle); + } + + private CheckoutIssueVO checkoutIssue(String code, String message, Long productId, String productTitle) { + CheckoutIssueVO issue = new CheckoutIssueVO(); + issue.setCode(code); + issue.setMessage(normalizeBookingMessage(message)); + issue.setProductId(productId); + issue.setProductTitle(StringUtils.hasText(productTitle) ? productTitle : "订单项"); + return issue; + } + + private String resolveProductTitle(ProductDO product) { + return product != null && StringUtils.hasText(product.getTitle()) ? product.getTitle() : "订单项"; + } + + private String bookingMessage(RuntimeException exception, String fallbackMessage) { + if (exception != null && StringUtils.hasText(exception.getMessage())) { + return exception.getMessage(); + } + return fallbackMessage; + } + + private BusinessException bookingUnavailable(String message) { + return new BusinessException(BOOKING_UNAVAILABLE_CODE, normalizeBookingMessage(message)); + } + + private boolean isBookingValidationMessage(String message) { + if (!StringUtils.hasText(message)) { + return false; + } + return message.contains("订单项") + || message.contains("订单商品数量") + || message.contains("商品不存在") + || message.contains("跨店铺") + || message.contains("美甲师") + || message.contains("预约时间") + || message.contains("不可预约") + || message.contains("冲突") + || message.contains("營業時間") + || message.contains("营业时间") + || message.contains("涓嶅彲棰勭害") + || message.contains("宸茬害婊") + || message.contains("褰撳墠缇庣敳甯堣"); + } + + private String normalizeBookingMessage(String message) { + if (!StringUtils.hasText(message)) { + return "当前预约不可用,请重新选择预约时间"; + } + + String normalized = message.trim(); + if (normalized.contains("涓嶅彲棰勭害")) { + return "当前美甲师该时段不可预约,请重新选择预约时间"; + } + if (normalized.contains("宸茬害婊") || normalized.contains("褰撳墠缇庣敳甯堣")) { + return "当前美甲师该时间段已约满,请重新选择预约时间"; + } + return normalized; + } + + private void collectPreviewTagNames(Set tagNames, String tags) { + if (tagNames == null || tags == null || tags.isBlank()) { + return; + } + for (String rawTag : tags.split("[,;]")) { + if (rawTag == null || rawTag.isBlank()) { + continue; + } + String tagText = rawTag.trim(); + try { + Long tagId = Long.parseLong(tagText); + if (tagService != null) { + TagVO tagVO = tagService.getTagById(tagId); + if (tagVO != null && StringUtils.hasText(tagVO.getTagName())) { + tagNames.add(tagVO.getTagName()); + } + } + } catch (NumberFormatException ignored) { + tagNames.add(tagText); + } + } + } + + private CheckoutCouponPreviewVO buildAvailableCouponPreview(UserCouponVO coupon, BigDecimal totalAmount) { + CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); + preview.setId(coupon.getId()); + preview.setCouponId(coupon.getCouponId()); + preview.setUserCouponId(COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null); + preview.setSourceType(coupon.getSourceType()); + preview.setCouponName(coupon.getCouponName()); + preview.setCouponType(coupon.getCouponType()); + preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); + preview.setDiscountValue(parseMoney(coupon.getDiscountValue())); + preview.setMinAmount(parseMoney(coupon.getMinAmount())); + preview.setReduceAmount(parseMoney(coupon.getReduceAmount())); + preview.setDiscountAmount(capDiscount(calculateCouponDiscountAmount(coupon, totalAmount), totalAmount)); + preview.setAvailable(true); + preview.setBest(false); + preview.setVipAuto(COUPON_SOURCE_SYSTEM_VIP.equals(coupon.getSourceType())); + preview.setDisplayText(buildCouponDisplayText(preview)); + preview.setSavingText(buildSavingText(preview.getDiscountAmount())); + preview.setStartTime(coupon.getStartTime()); + preview.setEndTime(coupon.getEndTime()); + return preview; + } + + private CheckoutCouponPreviewVO findBestCouponPreview(List availableCoupons) { + if (availableCoupons == null || availableCoupons.isEmpty()) { + return null; + } + return availableCoupons.stream() + .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) + .orElse(null); + } + + private CheckoutCouponPreviewVO resolvePreviewSelectedCoupon(CheckoutPreviewDTO checkoutPreviewDTO, + List availableCoupons, + CheckoutCouponPreviewVO bestCoupon) { + if (checkoutPreviewDTO != null + && checkoutPreviewDTO.getCouponId() == null + && COUPON_SOURCE_NONE.equalsIgnoreCase(checkoutPreviewDTO.getCouponSourceType())) { + return null; + } + if (checkoutPreviewDTO == null || checkoutPreviewDTO.getCouponId() == null || checkoutPreviewDTO.getCouponId() <= 0) { + return bestCoupon; + } + + String requestedSourceType = normalizeCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); + return availableCoupons.stream() + .filter(coupon -> checkoutPreviewDTO.getCouponId().equals(coupon.getId())) + .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) + .findFirst() + .orElseThrow(() -> new RuntimeException("当前订单不可使用所选优惠券")); + } + + private List buildUnavailableCouponPreviews(List availableCoupons, + CheckoutPricingContext pricingContext) { + Set availableCouponIds = availableCoupons == null ? Collections.emptySet() : availableCoupons.stream() + .map(CheckoutCouponPreviewVO::getCouponId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + List coupons = couponMapper.selectList(new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0)); + if (coupons == null || coupons.isEmpty()) { + return List.of(); + } + + LocalDateTime now = LocalDateTime.now(); + return coupons.stream() + .filter(coupon -> coupon != null && coupon.getId() != null) + .filter(coupon -> !availableCouponIds.contains(coupon.getId())) + .map(coupon -> buildUnavailableCouponPreview(coupon, pricingContext, now)) + .filter(Objects::nonNull) + .toList(); + } + + private CheckoutCouponPreviewVO buildUnavailableCouponPreview(CouponDO coupon, + CheckoutPricingContext pricingContext, + LocalDateTime now) { + String reason = resolveUnavailableCouponReason(coupon, pricingContext, now); + if (!StringUtils.hasText(reason)) { + reason = "本单暂不可用"; + } + + CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); + preview.setId(coupon.getId()); + preview.setCouponId(coupon.getId()); + preview.setSourceType(isVipAutoCoupon(coupon) ? COUPON_SOURCE_SYSTEM_VIP : COUPON_SOURCE_USER); + preview.setCouponName(coupon.getCouponName()); + preview.setCouponType(coupon.getCouponType()); + preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); + preview.setDiscountValue(coupon.getDiscountValue()); + preview.setMinAmount(coupon.getMinAmount()); + preview.setReduceAmount(coupon.getReduceAmount()); + preview.setDiscountAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); + preview.setAvailable(false); + preview.setBest(false); + preview.setVipAuto(isVipAutoCoupon(coupon)); + preview.setDisplayText(buildCouponDisplayText(preview)); + preview.setUnavailableReason(reason); + preview.setStartTime(coupon.getStartTime()); + preview.setEndTime(coupon.getEndTime()); + return preview; + } + + private String resolveUnavailableCouponReason(CouponDO coupon, CheckoutPricingContext pricingContext, LocalDateTime now) { + if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete())) { + return "优惠券已失效"; + } + if (coupon.getStatus() == null || coupon.getStatus() != 1) { + return "优惠券已失效"; + } + if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) { + return "还未到可用时间"; + } + if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) { + return "优惠券已过期"; + } + if (coupon.getShopId() != null + && pricingContext.getShopId() != null + && !coupon.getShopId().equals(pricingContext.getShopId())) { + return "仅限其他门店使用"; + } + if (Integer.valueOf(2).equals(coupon.getCouponType()) + && coupon.getMinAmount() != null + && coupon.getMinAmount().compareTo(pricingContext.getTotalAmount()) > 0) { + return "还差 " + formatMoney(coupon.getMinAmount().subtract(pricingContext.getTotalAmount())) + " 可用"; + } + return "本单商品暂不适用"; + } + + private String buildVipTip(Long userId, BigDecimal totalAmount, List availableCoupons) { + CheckoutCouponPreviewVO vipCoupon = availableCoupons == null ? null : availableCoupons.stream() + .filter(coupon -> Boolean.TRUE.equals(coupon.getVipAuto())) + .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) + .orElse(null); + UserDO userDO = userMapper.selectById(userId); + String vipLevel = userDO == null ? null : userDO.getLevel(); + if (vipCoupon != null && safeAmount(vipCoupon.getDiscountAmount()).compareTo(BigDecimal.ZERO) > 0) { + String levelText = StringUtils.hasText(vipLevel) ? vipLevel + "VIP" : "VIP"; + return levelText + "本单可省 " + formatMoney(vipCoupon.getDiscountAmount()) + ",已为你计算。"; + } + if (StringUtils.hasText(vipLevel) && !"普通".equals(vipLevel)) { + return vipLevel + "VIP暂无本单可用自动优惠,已为你保留其他可用优惠。"; + } + if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) { + return "开通VIP后,可在结算页自动匹配VIP优惠。"; + } + return null; + } + + private String buildCheckoutSummaryText(CheckoutPreviewVO preview) { + return "参考价小计 " + formatMoney(preview.getSubtotalAmount()) + + ",预估优惠 " + formatMoney(preview.getSavedAmount()) + + ",预估应付 " + formatMoney(preview.getPayableAmount()) + "。"; + } + + private String buildCouponDisplayText(CheckoutCouponPreviewVO coupon) { + String prefix = Boolean.TRUE.equals(coupon.getVipAuto()) ? "VIP自动优惠" : "优惠券"; + String benefit; + if (Integer.valueOf(1).equals(coupon.getCouponType()) && coupon.getDiscountValue() != null) { + benefit = coupon.getDiscountValue().stripTrailingZeros().toPlainString() + "折"; + } else if (Integer.valueOf(2).equals(coupon.getCouponType())) { + benefit = "满" + formatMoneyValue(coupon.getMinAmount()) + "减" + formatMoneyValue(coupon.getReduceAmount()); + } else { + benefit = "优惠"; + } + return prefix + ":" + coupon.getCouponName() + "," + benefit; + } + + private String buildSavingText(BigDecimal discountAmount) { + BigDecimal amount = safeAmount(discountAmount); + if (amount.compareTo(BigDecimal.ZERO) <= 0) { + return "本单暂不省钱"; + } + return "本单可省 " + formatMoney(amount); + } + + private boolean isVipAutoCoupon(CouponDO coupon) { + return coupon != null + && Integer.valueOf(1).equals(coupon.getAutoMatch()) + && "VIP_AUTO".equals(coupon.getCouponScene()); + } + + private String resolveCouponTypeName(Integer couponType) { + if (Integer.valueOf(1).equals(couponType)) { + return "折扣券"; + } + if (Integer.valueOf(2).equals(couponType)) { + return "满减券"; + } + return "优惠券"; + } + + private BigDecimal parseMoney(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + try { + return new BigDecimal(value.trim()); + } catch (NumberFormatException exception) { + return null; + } + } + + private BigDecimal capDiscount(BigDecimal discountAmount, BigDecimal totalAmount) { + BigDecimal discount = safeAmount(discountAmount); + BigDecimal total = safeAmount(totalAmount); + if (discount.compareTo(total) > 0) { + return scaleMoney(total); + } + return scaleMoney(discount); + } + + private BigDecimal safeAmount(BigDecimal amount) { + return amount == null ? BigDecimal.ZERO : amount; + } + + private BigDecimal scaleMoney(BigDecimal amount) { + return safeAmount(amount).setScale(2, RoundingMode.HALF_UP); + } + + private String formatMoney(BigDecimal amount) { + return "¥" + scaleMoney(amount).toPlainString(); + } + + private String formatMoneyValue(BigDecimal amount) { + return scaleMoney(amount).stripTrailingZeros().toPlainString(); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getOrderList(Long userId) { + List orderList = orderMapper.selectByUserId(userId); + List orderVOList = new ArrayList<>(); + for (OrderDO order : orderList) { + if (!Integer.valueOf(1).equals(order.getIsDelete())) { + orderVOList.add(buildOrderVO(order)); + } + } + return orderVOList; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + public OrderVO getOrderDetail(Long orderId, Long userId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (!order.getUserId().equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看此订单"); + } + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildOrderVO(order); + } + + @Override + @Transactional + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + */ + public void cancelOrder(Long orderId, Long userId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (!order.getUserId().equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权操作此订单"); + } + if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) + && !Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单状态不允许取消"); + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.CANCELLED.getCode()); + order.setStatus(3); + if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { + order.setQuoteStatus(QUOTE_STATUS_EXPIRED); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_SYSTEM_EXPIRE, "用户取消询价预约"); + } + orderMapper.updateById(order); + appointmentCapacityService.releaseByOrder(orderId); + /** + * Run business method `restoreUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + restoreUserCoupon(order, userId); + } + + @Override + @Transactional + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + */ + public void processOrder(Long orderId, Integer status) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (status != 2 && status != 3) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无效的订单状态"); + } + OrderStatus targetStatus = OrderStatus.requireKnown(status); + if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) + && !(Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status))) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单状态不允许处理"); + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), status); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), status) == 0) { + throw new RuntimeException("订单状态已变化,请刷新后重试"); + } + order.setStatus(status); + if (targetStatus == OrderStatus.COMPLETED) { + businessEventOutboxService.enqueueOrderCompleted(order.getId()); + } + if (targetStatus == OrderStatus.CANCELLED) { + appointmentCapacityService.releaseByOrder(order.getId()); + restoreUserCoupon(order, order.getUserId()); + if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { + order.setQuoteStatus(QUOTE_STATUS_EXPIRED); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), 0L, QUOTE_ACTOR_SYSTEM, QUOTE_ACTION_SYSTEM_EXPIRE, "询价预约已取消"); + } + } + } + + @Override + @Transactional + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + */ + public void completeArtistOrder(Long orderId, Long artistId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (order.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前订单状态不允许完成"); + } + + List activeItems = orderItemMapper.selectByOrderId(orderId).stream() + .filter(item -> !Integer.valueOf(1).equals(item.getIsDelete())) + .toList(); + if (activeItems.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单商品不存在"); + } + + boolean allBelongToArtist = activeItems.stream().allMatch(item -> artistId.equals(item.getArtistId())); + if (!allBelongToArtist) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能完成全部由自己承接的订单"); + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.COMPLETED.getCode()); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.COMPLETED.getCode()) == 0) { + throw new RuntimeException("订单状态已变化,请刷新后重试"); + } + order.setStatus(OrderStatus.COMPLETED.getCode()); + businessEventOutboxService.enqueueOrderCompleted(order.getId()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllOrders() { + List orderList = orderMapper.selectList(new QueryWrapper().eq("is_delete", 0)); + List orderVOList = new ArrayList<>(); + for (OrderDO order : orderList) { + orderVOList.add(buildOrderVO(order)); + } + return orderVOList; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getOrdersByArtistId(Long artistId) { + List orderList = orderMapper.selectByArtistId(artistId); + List orderVOList = new ArrayList<>(); + for (OrderDO order : orderList) { + OrderVO orderVO = buildOrderVO(order, artistId); + if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { + orderVOList.add(orderVO); + } + } + return orderVOList; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistWorkbenchOrders(Long artistId) { + Map orderMap = new LinkedHashMap<>(); + List serviceOrders = orderMapper.selectByArtistId(artistId); + for (OrderDO order : serviceOrders) { + OrderVO orderVO = buildOrderVO(order, artistId); + if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { + orderVO.setArtistOrderSource("SERVICE"); + orderVO.setArtistOrderSourceText("客户预约我的订单"); + orderMap.put(orderVO.getId(), orderVO); + } + } + + List selfOrders = orderMapper.selectByUserId(artistId); + for (OrderDO order : selfOrders) { + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + continue; + } + OrderVO existing = orderMap.get(order.getId()); + if (existing != null) { + existing.setArtistOrderSource("BOTH"); + existing.setArtistOrderSourceText("我下的订单 / 客户预约我的订单"); + continue; + } + OrderVO orderVO = buildOrderVO(order); + orderVO.setArtistOrderSource("SELF"); + orderVO.setArtistOrderSourceText("我下的订单"); + orderMap.put(orderVO.getId(), orderVO); + } + + return orderMap.values().stream() + .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .toList(); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param days parameter `days` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistCalendarRecent(Long userId, Integer userType, Integer days) { + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureCalendarAccess(userId, userType); + int normalizedDays = days == null ? 7 : Math.max(1, Math.min(days, 31)); + LocalDate startDate = LocalDate.now(); + return listArtistCalendarAppointments(userId, startDate.atStartOfDay(), startDate.plusDays(normalizedDays).atStartOfDay()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param date parameter `date` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistCalendarDay(Long userId, Integer userType, LocalDate date) { + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureCalendarAccess(userId, userType); + LocalDate targetDate = date == null ? LocalDate.now() : date; + return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay()); + } + + @Override + /** + * Purpose: listMyPendingReviews supports OrderServiceImpl.java by holding or executing the list my pending reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listMyPendingReviews(Long userId) { + return orderArtistReviewMapper.selectPendingByUserId(userId).stream() + .map(this::buildArtistReviewVO) + .toList(); + } + + @Override + /** + * Purpose: listOrderReviews supports OrderServiceImpl.java by holding or executing the list order reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listOrderReviews(Long orderId, Long userId, Integer userType) { + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("无权查看该订单评价"); + } + return orderArtistReviewMapper.selectByOrderId(orderId).stream() + .map(this::buildArtistReviewVO) + .toList(); + } + + @Override + @Transactional + /** + * Purpose: submitArtistReview supports OrderServiceImpl.java by holding or executing the submit artist review business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto) { + OrderArtistReviewDO review = orderArtistReviewMapper.selectById(reviewId); + if (review == null || Integer.valueOf(1).equals(review.getIsDelete())) { + throw new RuntimeException("评价任务不存在"); + } + if (!Objects.equals(userId, review.getCustomerId())) { + throw new RuntimeException("只能提交自己的评价"); + } + if (!Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) { + throw new RuntimeException("评价已提交,不能重复提交"); + } + + BigDecimal rating = normalizeReviewRating(dto == null ? null : dto.getRating()); + review.setRatingScore(rating); + review.setContent(trimToNull(dto == null ? null : dto.getContent())); + review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds())); + review.setStatus(REVIEW_STATUS_SUBMITTED); + review.setSubmittedAt(LocalDateTime.now()); + orderArtistReviewMapper.updateById(review); + refreshArtistRating(review.getArtistId()); + return buildArtistReviewVO(review); + } + + @Override + @Transactional + public OrderVO submitShopQuote(Long orderId, Long operatorId, Integer operatorType, OrderQuoteSubmitDTO dto) { + OrderDO order = requireQuoteOrder(orderId); + ensureShopQuoteOperator(order, operatorId, operatorType); + if (dto == null || dto.getItems() == null || dto.getItems().isEmpty()) { + throw new RuntimeException("请至少填写一个作品报价"); + } + + Map itemMap = loadActiveOrderItemMap(order.getId()); + for (OrderQuoteItemDTO quoteItem : dto.getItems()) { + if (quoteItem == null || quoteItem.getOrderItemId() == null) { + continue; + } + OrderItemDO item = itemMap.get(quoteItem.getOrderItemId()); + if (item == null) { + throw new RuntimeException("报价作品不属于当前订单"); + } + BigDecimal quotedPrice = normalizeQuotePrice(quoteItem.getQuotedPrice()); + item.setQuotedPrice(quotedPrice); + if (item.getReferencePrice() == null) { + item.setReferencePrice(item.getPrice()); + } + orderItemMapper.updateById(item); + } + ensureAllItemsQuoted(order.getId()); + + order.setQuoteStatus(QUOTE_STATUS_CONFIRMING); + order.setQuoteShopConfirmed(1); + order.setQuoteUserConfirmed(0); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), operatorId, QUOTE_ACTOR_SHOP, QUOTE_ACTION_SHOP_QUOTE, trimToNull(dto.getRemark())); + notifyQuoteUser(order, "门店已回复询价预约", "门店已回复您的询价预约,请查看并确认价格。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType) { + OrderDO order = requireQuoteOrder(orderId); + ensureShopQuoteOperator(order, operatorId, operatorType); + ensureAllItemsQuoted(order.getId()); + order.setQuoteShopConfirmed(1); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), operatorId, QUOTE_ACTOR_SHOP, QUOTE_ACTION_SHOP_CONFIRM, "店长确认当前报价"); + if (Integer.valueOf(1).equals(order.getQuoteUserConfirmed())) { + return finalizeConfirmedQuote(order, operatorId, QUOTE_ACTOR_SHOP); + } + notifyQuoteUser(order, "门店已确认询价价格", "门店已确认当前询价价格,请查看并确认。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto) { + OrderDO order = requireQuoteOrder(orderId); + ensureQuoteOwner(order, userId); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + orderMapper.updateById(order); + String remark = trimToNull(dto == null ? null : dto.getRemark()); + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_USER_REPLY, remark); + notifyQuoteShopAndArtist(order, "用户已回复询价预约", "用户已回复询价预约,请查看备注并继续确认价格。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public OrderVO confirmUserQuote(Long orderId, Long userId) { + OrderDO order = requireQuoteOrder(orderId); + ensureQuoteOwner(order, userId); + ensureAllItemsQuoted(order.getId()); + order.setQuoteUserConfirmed(1); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_USER_CONFIRM, "用户确认当前报价"); + if (Integer.valueOf(1).equals(order.getQuoteShopConfirmed())) { + return finalizeConfirmedQuote(order, userId, QUOTE_ACTOR_USER); + } + notifyQuoteShopAndArtist(order, "用户已确认询价价格", "用户已确认当前价格,请店长完成确认。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public int expirePendingQuoteOrders() { + LocalDateTime now = LocalDateTime.now(); + List expiredOrders = orderMapper.selectList(new LambdaQueryWrapper() + .eq(OrderDO::getStatus, OrderStatus.PRICE_CONFIRMING.getCode()) + .eq(OrderDO::getQuoteStatus, QUOTE_STATUS_CONFIRMING) + .le(OrderDO::getQuoteExpireTime, now) + .eq(OrderDO::getIsDelete, 0)); + int expiredCount = 0; + for (OrderDO order : expiredOrders) { + order.setStatus(OrderStatus.CANCELLED.getCode()); + order.setQuoteStatus(QUOTE_STATUS_EXPIRED); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + orderMapper.updateById(order); + appointmentCapacityService.releaseByOrder(order.getId()); + writeQuoteMessage(order.getId(), 0L, QUOTE_ACTOR_SYSTEM, QUOTE_ACTION_SYSTEM_EXPIRE, "询价预约超过24小时未确认,已自动取消"); + expiredCount++; + } + return expiredCount; + } + + @Scheduled(fixedDelay = 60000) + public void expirePendingQuoteOrdersScheduled() { + expirePendingQuoteOrders(); + } + + @Override + /** + * Purpose: getArtistChangeOptions supports OrderServiceImpl.java by holding or executing the get artist change options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType) { + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("无权查看该订单改派选项"); + } + OrderItemDO item = requireOrderItem(orderItemId, orderId); + ProductDO product = requireActiveProduct(item.getProductId()); + + OrderArtistChangeOptionsVO vo = new OrderArtistChangeOptionsVO(); + vo.setOrderId(orderId); + vo.setOrderItemId(orderItemId); + vo.setCurrentArtistId(item.getArtistId()); + UserDO currentArtist = item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId()); + vo.setCurrentArtistName(currentArtist == null ? null : currentArtist.getNickname()); + vo.setArtists(parseIdSet(product.getBookableArtists()).stream() + .filter(artistId -> !Objects.equals(artistId, item.getArtistId())) + .filter(artistId -> isArtistAvailableForItem(order.getShopId(), artistId, item, product)) + .map(this::buildArtistOptionVO) + .filter(Objects::nonNull) + .toList()); + return vo; + } + + @Override + @Transactional + /** + * Purpose: requestArtistChange supports OrderServiceImpl.java by holding or executing the request artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto) { + if (dto == null || dto.getOrderId() == null || dto.getOrderItemId() == null || dto.getRequestedArtistId() == null) { + throw new RuntimeException("改派申请信息不完整"); + } + ensureArtistChangeRequester(userId); + OrderDO order = requireActiveOrder(dto.getOrderId()); + if (!canAccessOrder(order, userId, null)) { + throw new RuntimeException("只能为自己的订单申请改派"); + } + if (!Integer.valueOf(1).equals(order.getStatus())) { + throw new RuntimeException("仅待服务订单允许申请改派"); + } + OrderItemDO item = requireOrderItemForUpdate(dto.getOrderItemId(), order.getId()); + if (!canRequestArtistChangeForItem(order, item, userId)) { + throw new RuntimeException("只能为自己承接的待服务订单项申请改派"); + } + if (item.getArtistId() == null) { + throw new RuntimeException("订单项未分配美甲师"); + } + if (Objects.equals(item.getArtistId(), dto.getRequestedArtistId())) { + throw new RuntimeException("新美甲师不能与原美甲师相同"); + } + if (orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()) != null) { + throw new RuntimeException("该订单项已有待处理改派申请"); + } + ProductDO product = requireActiveProduct(item.getProductId()); + validateRequestedArtistForItem(order.getShopId(), dto.getRequestedArtistId(), item, product); + + OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO(); + request.setOrderId(order.getId()); + request.setOrderItemId(item.getId()); + request.setProductId(item.getProductId()); + request.setShopId(order.getShopId()); + request.setCustomerId(order.getUserId()); + request.setFromArtistId(item.getArtistId()); + request.setToArtistId(dto.getRequestedArtistId()); + request.setRequesterId(userId); + request.setStatus(CHANGE_STATUS_PENDING); + request.setReason(trimToNull(dto.getReason())); + request.setPendingKey(buildArtistChangePendingKey(item.getId())); + request.setExpireTime(LocalDateTime.now().plusDays(2)); + request.setIsDelete(0); + try { + orderArtistChangeRequestMapper.insert(request); + } catch (DuplicateKeyException exception) { + throw new RuntimeException("该订单项已有待处理改派申请"); + } + createArtistChangeMessage(order, request); + return buildArtistChangeRequestVO(request, item); + } + + @Override + /** + * Purpose: listMyPendingArtistChangeRequests supports OrderServiceImpl.java by holding or executing the list my pending artist change requests business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listMyPendingArtistChangeRequests(Long userId, Integer userType) { + expireDueArtistChangeRequests(); + List requests; + if (Integer.valueOf(2).equals(userType)) { + UserDO user = userMapper.selectById(userId); + requests = user != null && user.getShopId() != null + ? orderArtistChangeRequestMapper.selectPendingByShopId(user.getShopId()) + : orderArtistChangeRequestMapper.selectPendingByArtistId(userId); + } else if (Integer.valueOf(3).equals(userType)) { + requests = orderArtistChangeRequestMapper.selectPendingByArtistId(userId); + } else { + requests = orderArtistChangeRequestMapper.selectPendingByUserId(userId); + } + return requests.stream() + .map(this::buildArtistChangeRequestVO) + .toList(); + } + + @Override + /** + * Purpose: listOrderArtistChangeRequests returns every artist-change request for one accessible order. + * Usage: call it from order detail/list pages to build a customer-facing order timeline with pending and historical changes. + */ + public List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType) { + expireDueArtistChangeRequests(); + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("[ORDER_ARTIST_CHANGE_FORBIDDEN] 无权查看该订单改派记录"); + } + return orderArtistChangeRequestMapper.selectByOrderId(orderId).stream() + .map(this::buildArtistChangeRequestVO) + .toList(); + } + + @Override + @Transactional + /** + * Purpose: approveArtistChange supports OrderServiceImpl.java by holding or executing the approve artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType) { + OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId); + assertCanProcessArtistChange(request, userId, userType); + + OrderDO order = requireActiveOrder(request.getOrderId()); + if (!Integer.valueOf(1).equals(order.getStatus())) { + throw new RuntimeException("仅待服务订单允许改派"); + } + if (!Objects.equals(order.getUserId(), request.getCustomerId())) { + throw new RuntimeException("改派申请客户与订单不匹配"); + } + + OrderItemDO item = orderItemMapper.selectByIdForUpdate(request.getOrderItemId()); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), order.getId())) { + throw new RuntimeException("订单项不存在"); + } + if (!Objects.equals(item.getArtistId(), request.getFromArtistId())) { + throw new RuntimeException("原美甲师已变更,无法继续改派"); + } + + ProductDO product = requireActiveProduct(item.getProductId()); + validateRequestedArtistForItem(order.getShopId(), request.getToArtistId(), item, product); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + appointmentCapacityService.moveReservationForArtistChange( + order.getId(), + item.getId(), + order.getShopId(), + request.getFromArtistId(), + request.getToArtistId(), + product.getTitle(), + item.getAppointmentTime(), + item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes) + ); + + LocalDateTime approvedTime = LocalDateTime.now(); + if (orderArtistChangeRequestMapper.approvePending(request.getId(), approvedTime) == 0) { + throw new RuntimeException("改派申请已处理"); + } + item.setArtistId(request.getToArtistId()); + orderItemMapper.updateById(item); + request.setStatus(CHANGE_STATUS_APPROVED); + request.setApprovedTime(approvedTime); + request.setPendingKey(null); + return buildArtistChangeRequestVO(request, item); + } + + @Override + @Transactional + /** + * Purpose: rejectArtistChange supports OrderServiceImpl.java by holding or executing the reject artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto) { + OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId); + assertCanProcessArtistChange(request, userId, userType); + LocalDateTime rejectedTime = LocalDateTime.now(); + String rejectReason = trimToNull(dto == null ? null : dto.getRejectReason()); + if (orderArtistChangeRequestMapper.rejectPending(request.getId(), rejectReason, rejectedTime) == 0) { + throw new RuntimeException("改派申请已处理"); + } + request.setStatus(CHANGE_STATUS_REJECTED); + request.setRejectReason(rejectReason); + request.setRejectedTime(rejectedTime); + request.setPendingKey(null); + return buildArtistChangeRequestVO(request); + } + + /** + * Purpose: createPendingArtistReviewTasksAndNotifyFromOutbox supports OrderServiceImpl.java by holding or executing the create pending artist review tasks and notify from outbox business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void createPendingArtistReviewTasksAndNotifyFromOutbox(OrderDO order) { + createPendingArtistReviewTasksAndNotify(order); + } + + /** + * Purpose: createPendingArtistReviewTasksAndNotify supports OrderServiceImpl.java by holding or executing the create pending artist review tasks and notify business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void createPendingArtistReviewTasksAndNotify(OrderDO order) { + if (order == null || order.getId() == null || !Integer.valueOf(2).equals(order.getStatus())) { + return; + } + List items = orderItemMapper.selectByOrderId(order.getId()); + if (items == null || items.isEmpty()) { + return; + } + for (OrderItemDO item : items) { + if (item == null + || item.getId() == null + || Integer.valueOf(1).equals(item.getIsDelete()) + || item.getArtistId() == null) { + continue; + } + if (orderArtistReviewMapper.selectByOrderItemId(item.getId()) != null) { + continue; + } + ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>()); + OrderArtistReviewDO review = new OrderArtistReviewDO(); + review.setOrderId(order.getId()); + review.setOrderItemId(item.getId()); + review.setProductId(item.getProductId()); + review.setShopId(order.getShopId()); + review.setArtistId(item.getArtistId()); + review.setCustomerId(order.getUserId()); + review.setStatus(REVIEW_STATUS_PENDING); + review.setIsDelete(0); + review = insertPendingArtistReview(review); + if (review == null || review.getId() == null) { + continue; + } + Long messageId = createReviewReminderMessage(order, item, product, review); + if (messageId != null) { + review.setReminderMessageId(messageId); + orderArtistReviewMapper.updateById(review); + } + } + } + + /** + * Purpose: insertPendingArtistReview supports OrderServiceImpl.java by holding or executing the insert pending artist review business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewDO insertPendingArtistReview(OrderArtistReviewDO review) { + try { + orderArtistReviewMapper.insert(review); + return review; + } catch (DuplicateKeyException exception) { + OrderArtistReviewDO existingReview = review == null || review.getOrderItemId() == null + ? null + : orderArtistReviewMapper.selectByOrderItemId(review.getOrderItemId()); + if (existingReview != null) { + return existingReview; + } + throw exception; + } + } + + /** + * Purpose: createReviewReminderMessage supports OrderServiceImpl.java by holding or executing the create review reminder message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long createReviewReminderMessage(OrderDO order, OrderItemDO item, ProductDO product, OrderArtistReviewDO review) { + String productTitle = product == null ? "订单项目" : product.getTitle(); + UserDO artist = item == null || item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId()); + String artistName = artist == null || !StringUtils.hasText(artist.getNickname()) ? "美甲师" : artist.getNickname(); + return createSystemBusinessMessage( + order == null ? null : order.getUserId(), + "订单已完成,记得评价美甲师", + "您预约的「" + productTitle + "」已完成,请为" + artistName + "提交本次服务评价。", + REVIEW_BUSINESS_TYPE, + review == null ? null : review.getId(), + order == null ? null : "/orders?orderId=" + order.getId(), + 0L, + "系统通知", + 4 + ); + } + + /** + * Purpose: buildArtistReviewVO supports OrderServiceImpl.java by holding or executing the build artist review vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewVO buildArtistReviewVO(OrderArtistReviewDO review) { + if (review == null) { + return null; + } + OrderArtistReviewVO vo = new OrderArtistReviewVO(); + vo.setId(review.getId()); + vo.setOrderId(review.getOrderId()); + vo.setOrderItemId(review.getOrderItemId()); + vo.setProductId(review.getProductId()); + ProductDO product = getProductFromCache(review.getProductId(), new HashMap<>()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setArtistId(review.getArtistId()); + UserDO artist = review.getArtistId() == null ? null : userMapper.selectById(review.getArtistId()); + vo.setArtistName(artist == null ? null : artist.getNickname()); + vo.setArtistAvatar(artist == null ? null : objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + vo.setUserId(review.getCustomerId()); + vo.setCustomerId(review.getCustomerId()); + vo.setRating(review.getRatingScore()); + vo.setRatingScore(review.getRatingScore()); + vo.setContent(review.getContent()); + vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds()))); + vo.setStatus(review.getStatus()); + vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价"); + vo.setReminderMessageId(review.getReminderMessageId()); + vo.setSubmitTime(review.getSubmittedAt()); + vo.setSubmittedAt(review.getSubmittedAt()); + vo.setCreateTime(review.getCreateTime()); + return vo; + } + + /** + * Purpose: requireActiveOrder supports OrderServiceImpl.java by holding or executing the require active order business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderDO requireActiveOrder(Long orderId) { + if (orderId == null) { + throw new RuntimeException("订单信息不完整"); + } + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + return order; + } + + /** + * Purpose: canAccessOrder supports OrderServiceImpl.java by holding or executing the can access order business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean canAccessOrder(OrderDO order, Long userId, Integer userType) { + if (order == null || userId == null) { + return false; + } + if (Objects.equals(order.getUserId(), userId)) { + return true; + } + UserDO user = userMapper.selectById(userId); + Integer effectiveType = userType == null && user != null ? user.getType() : userType; + if (Integer.valueOf(4).equals(effectiveType)) { + return true; + } + if (order.getShopId() != null && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId())) { + return true; + } + List items = orderItemMapper.selectByOrderId(order.getId()); + return items != null && items.stream() + .filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete())) + .anyMatch(item -> Objects.equals(item.getArtistId(), userId)); + } + + /** + * Purpose: normalizeReviewRating supports OrderServiceImpl.java by holding or executing the normalize review rating business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal normalizeReviewRating(BigDecimal rating) { + if (rating == null) { + throw new RuntimeException("评分不能为空"); + } + BigDecimal normalized; + try { + normalized = rating.setScale(1, RoundingMode.UNNECESSARY); + } catch (ArithmeticException exception) { + throw new RuntimeException("评分必须按0.5分递增"); + } + if (normalized.compareTo(new BigDecimal("0.5")) < 0 || normalized.compareTo(new BigDecimal("5.0")) > 0) { + throw new RuntimeException("评分必须在0.5到5分之间"); + } + BigDecimal doubled = normalized.multiply(new BigDecimal("2")); + if (doubled.stripTrailingZeros().scale() > 0) { + throw new RuntimeException("评分必须按0.5分递增"); + } + return normalized; + } + + /** + * Purpose: trimToNull supports OrderServiceImpl.java by holding or executing the trim to null business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String trimToNull(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + return value.trim(); + } + + /** + * Purpose: joinLongIds supports OrderServiceImpl.java by holding or executing the join long ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String joinLongIds(List ids) { + if (ids == null || ids.isEmpty()) { + return null; + } + String joined = ids.stream() + .filter(Objects::nonNull) + .distinct() + .map(String::valueOf) + .collect(Collectors.joining(",")); + return joined.isBlank() ? null : joined; + } + + /** + * Purpose: parseIdSet supports OrderServiceImpl.java by holding or executing the parse id set business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set parseIdSet(String rawIds) { + if (!StringUtils.hasText(rawIds)) { + return Collections.emptySet(); + } + LinkedHashSet result = new LinkedHashSet<>(); + for (String part : rawIds.split("[,;]")) { + if (!StringUtils.hasText(part)) { + continue; + } + try { + result.add(Long.parseLong(part.trim())); + } catch (NumberFormatException ignored) { + } + } + return result; + } + + /** + * Purpose: refreshArtistRating supports OrderServiceImpl.java by holding or executing the refresh artist rating business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void refreshArtistRating(Long artistId) { + if (artistId == null) { + return; + } + BigDecimal average = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); + if (average == null) { + return; + } + NailArtistInfoDO artistInfo = getArtistInfoByUserId(artistId); + if (artistInfo == null) { + return; + } + artistInfo.setRating(average.setScale(1, RoundingMode.HALF_UP)); + nailArtistInfoMapper.updateById(artistInfo); + } + + /** + * Purpose: requireOrderItem supports OrderServiceImpl.java by holding or executing the require order item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemDO requireOrderItem(Long orderItemId, Long orderId) { + return requireOrderItem(orderItemId, orderId, false); + } + + /** + * Purpose: requireOrderItemForUpdate supports OrderServiceImpl.java by holding or executing the require order item for update business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemDO requireOrderItemForUpdate(Long orderItemId, Long orderId) { + return requireOrderItem(orderItemId, orderId, true); + } + + /** + * Purpose: buildArtistChangePendingKey supports OrderServiceImpl.java by holding or executing the build artist change pending key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildArtistChangePendingKey(Long orderItemId) { + return orderItemId == null ? null : ARTIST_CHANGE_PENDING_KEY_PREFIX + orderItemId; + } + + /** + * Purpose: requireOrderItem supports OrderServiceImpl.java by holding or executing the require order item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemDO requireOrderItem(Long orderItemId, Long orderId, boolean forUpdate) { + if (orderItemId == null) { + throw new RuntimeException("订单项信息不完整"); + } + OrderItemDO item = forUpdate + ? orderItemMapper.selectByIdForUpdate(orderItemId) + : orderItemMapper.selectById(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), orderId)) { + throw new RuntimeException("订单项不存在"); + } + return item; + } + + /** + * Purpose: requireActiveProduct supports OrderServiceImpl.java by holding or executing the require active product business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductDO requireActiveProduct(Long productId) { + ProductDO product = getProductFromCache(productId, new HashMap<>()); + if (product == null) { + throw new RuntimeException("商品不存在或已删除"); + } + return product; + } + + /** + * Purpose: isArtistAvailableForItem supports OrderServiceImpl.java by holding or executing the is artist available for item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isArtistAvailableForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) { + try { + validateRequestedArtistForItem(shopId, artistId, item, product); + return true; + } catch (RuntimeException exception) { + return false; + } + } + + private OrderArtistChangeOptionsVO.ArtistOptionVO buildArtistOptionVO(Long artistId) { + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) || !bookableArtistSupport.isBookableServiceUser(artist)) { + return null; + } + NailArtistInfoDO info = getArtistInfoByUserId(artistId); + OrderArtistChangeOptionsVO.ArtistOptionVO vo = new OrderArtistChangeOptionsVO.ArtistOptionVO(); + vo.setArtistId(artist.getId()); + vo.setArtistName(artist.getNickname()); + vo.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + vo.setUserType(artist.getType()); + vo.setParticipateProduction(info != null && Integer.valueOf(1).equals(info.getParticipateProduction())); + return vo; + } + + /** + * Purpose: validateRequestedArtistForItem supports OrderServiceImpl.java by holding or executing the validate requested artist for item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void validateRequestedArtistForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) { + validateArtistForProduct(product, artistId); + if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { + throw new RuntimeException("新美甲师不可预约或不属于当前店铺"); + } + if (item == null || item.getAppointmentTime() == null) { + return; + } + int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + long durationMinutes = resolveServiceDurationMinutes(product) * quantity; + LocalDateTime startTime = item.getAppointmentTime(); + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + validateBusinessHours(getShopFromCache(shopId == null ? product.getShopId() : shopId, new HashMap<>()), startTime, endTime, product.getTitle()); + validateArtistScheduleConflicts(artistId, Collections.singletonList(new AppointmentSlot(product.getTitle(), startTime, endTime)), new HashMap<>()); + } + + /** + * Purpose: createArtistChangeMessage supports OrderServiceImpl.java by holding or executing the create artist change message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long createArtistChangeMessage(OrderDO order, OrderArtistChangeRequestDO request) { + ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>()); + UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId()); + UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId()); + String fromName = fromArtist == null || !StringUtils.hasText(fromArtist.getNickname()) ? "原美甲师" : fromArtist.getNickname(); + String toName = toArtist == null || !StringUtils.hasText(toArtist.getNickname()) ? "新美甲师" : toArtist.getNickname(); + Long messageId = createSystemBusinessMessage( + request.getCustomerId(), + "美甲师改派申请待确认", + "您的订单项目「" + (product == null ? "订单项目" : product.getTitle()) + "」申请由" + fromName + "改派给" + toName + ",请在订单页确认。", + CHANGE_BUSINESS_TYPE, + request.getId(), + order == null ? null : "/orders?orderId=" + order.getId(), + request.getRequesterId(), + fromName, + 3 + ); + if (messageId != null) { + request.setMessageId(messageId); + orderArtistChangeRequestMapper.updateById(request); + } + return messageId; + } + + /** + * Purpose: buildArtistChangeRequestVO supports OrderServiceImpl.java by holding or executing the build artist change request vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request) { + return buildArtistChangeRequestVO(request, null); + } + + /** + * Purpose: buildArtistChangeRequestVO converts a change request plus optional order item into the client timeline payload. + * Usage: pass the locked/current order item when the caller already has it so the conversion does not issue extra reads. + */ + private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request, OrderItemDO requestItem) { + if (request == null) { + return null; + } + OrderArtistChangeRequestVO vo = new OrderArtistChangeRequestVO(); + vo.setId(request.getId()); + vo.setOrderId(request.getOrderId()); + vo.setOrderItemId(request.getOrderItemId()); + vo.setProductId(request.getProductId()); + ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setShopId(request.getShopId()); + vo.setUserId(request.getCustomerId()); + vo.setCustomerId(request.getCustomerId()); + vo.setOriginalArtistId(request.getFromArtistId()); + vo.setFromArtistId(request.getFromArtistId()); + UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId()); + vo.setOriginalArtistName(fromArtist == null ? null : fromArtist.getNickname()); + vo.setFromArtistName(fromArtist == null ? null : fromArtist.getNickname()); + vo.setRequestedArtistId(request.getToArtistId()); + vo.setToArtistId(request.getToArtistId()); + UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId()); + vo.setRequestedArtistName(toArtist == null ? null : toArtist.getNickname()); + vo.setToArtistName(toArtist == null ? null : toArtist.getNickname()); + vo.setRequesterId(request.getRequesterId()); + UserDO requester = request.getRequesterId() == null ? null : userMapper.selectById(request.getRequesterId()); + vo.setRequesterName(requester == null ? null : requester.getNickname()); + vo.setStatus(request.getStatus()); + vo.setStatusText(resolveArtistChangeStatusText(request.getStatus())); + vo.setReason(request.getReason()); + vo.setRejectReason(request.getRejectReason()); + OrderItemDO item = requestItem != null ? requestItem : request.getOrderItemId() == null ? null : orderItemMapper.selectById(request.getOrderItemId()); + if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) { + vo.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); + vo.setOriginalPrice(item.getPrice()); + vo.setNewPrice(item.getPrice()); + vo.setTimeAffected(false); + vo.setTimeImpactText("预约时间不变"); + vo.setPriceAffected(false); + vo.setPriceImpactText("订单价格不变"); + } else { + vo.setTimeImpactText("暂无法确认预约时间,请联系门店"); + vo.setPriceImpactText("暂无法确认订单价格,请联系门店"); + } + vo.setReviewerId(request.getCustomerId()); + vo.setMessageId(request.getMessageId()); + vo.setReviewTime(request.getApprovedTime() != null ? request.getApprovedTime() : request.getRejectedTime()); + vo.setApprovedTime(request.getApprovedTime()); + vo.setRejectedTime(request.getRejectedTime()); + vo.setExpireTime(request.getExpireTime()); + vo.setCreateTime(request.getCreateTime()); + return vo; + } + + /** + * Purpose: requirePendingArtistChangeRequest supports OrderServiceImpl.java by holding or executing the require pending artist change request business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestDO requirePendingArtistChangeRequest(Long requestId) { + if (requestId == null) { + throw new RuntimeException("改派申请信息不完整"); + } + OrderArtistChangeRequestDO request = orderArtistChangeRequestMapper.selectById(requestId); + if (request == null || Integer.valueOf(1).equals(request.getIsDelete())) { + throw new RuntimeException("改派申请不存在"); + } + if (!CHANGE_STATUS_PENDING.equals(request.getStatus())) { + throw new RuntimeException("改派申请已处理"); + } + LocalDateTime now = LocalDateTime.now(); + if (request.getExpireTime() != null && !request.getExpireTime().isAfter(now)) { + orderArtistChangeRequestMapper.expirePendingById(request.getId(), now); + request.setStatus(CHANGE_STATUS_EXPIRED); + request.setPendingKey(null); + throw new RuntimeException("改派申请已过期"); + } + return request; + } + + /** + * Purpose: assertCanProcessArtistChange supports OrderServiceImpl.java by holding or executing the assert can process artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void assertCanProcessArtistChange(OrderArtistChangeRequestDO request, Long userId, Integer userType) { + if (request == null || userId == null || !Objects.equals(request.getCustomerId(), userId)) { + throw new RuntimeException("仅订单客户可以处理改派申请"); + } + } + + @org.springframework.scheduling.annotation.Scheduled(fixedDelay = 300000L) + /** + * Purpose: expireDueArtistChangeRequests supports OrderServiceImpl.java by holding or executing the expire due artist change requests business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void expireDueArtistChangeRequests() { + orderArtistChangeRequestMapper.expirePendingBefore(LocalDateTime.now()); + } + + /** + * Purpose: canRequestArtistChangeForItem supports OrderServiceImpl.java by holding or executing the can request artist change for item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean canRequestArtistChangeForItem(OrderDO order, OrderItemDO item, Long userId) { + if (order == null || item == null || userId == null) { + return false; + } + if (Objects.equals(item.getArtistId(), userId)) { + return true; + } + UserDO user = userMapper.selectById(userId); + if (user == null || !Integer.valueOf(2).equals(user.getType())) { + return false; + } + NailArtistInfoDO info = getArtistInfoByUserId(userId); + return info != null + && Integer.valueOf(1).equals(info.getParticipateProduction()) + && order.getShopId() != null + && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId()); + } + + /** + * Purpose: ensureArtistChangeRequester supports OrderServiceImpl.java by holding or executing the ensure artist change requester business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensureArtistChangeRequester(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { + throw new RuntimeException("请先登录有效账号"); + } + if (Integer.valueOf(3).equals(user.getType())) { + return; + } + if (Integer.valueOf(2).equals(user.getType())) { + NailArtistInfoDO info = getArtistInfoByUserId(userId); + if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { + return; + } + } + throw new RuntimeException("仅美甲师或参与制作的店长可以申请改派"); + } + + /** + * Purpose: getArtistInfoByUserId supports OrderServiceImpl.java by holding or executing the get artist info by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private NailArtistInfoDO getArtistInfoByUserId(Long userId) { + if (userId == null) { + return null; + } + return nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Purpose: resolveArtistChangeStatusText supports OrderServiceImpl.java by holding or executing the resolve artist change status text business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveArtistChangeStatusText(String status) { + if (CHANGE_STATUS_APPROVED.equals(status)) { + return "已同意"; + } + if (CHANGE_STATUS_REJECTED.equals(status)) { + return "已拒绝"; + } + return "待确认"; + } + + private OrderDO requireQuoteOrder(Long orderId) { + OrderDO order = requireActiveOrder(orderId); + if (!Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + throw new RuntimeException("仅确认价格中的询价预约可以进行报价操作"); + } + if (QUOTE_STATUS_EXPIRED.equals(order.getQuoteStatus())) { + throw new RuntimeException("询价预约已过期"); + } + return order; + } + + private void ensureQuoteOwner(OrderDO order, Long userId) { + if (order == null || userId == null || !userId.equals(order.getUserId())) { + throw new RuntimeException("无权处理该询价预约"); + } + } + + private void ensureShopQuoteOperator(OrderDO order, Long operatorId, Integer operatorType) { + if (!Integer.valueOf(USER_TYPE_SHOP_OWNER).equals(operatorType)) { + throw new RuntimeException("只有店长可以确认或回复价格"); + } + if (order == null || operatorId == null + || !userShopBindingSupport.canUserAccessShop(operatorId, order.getShopId(), true, operatorType)) { + throw new RuntimeException("无权处理其他店铺的询价预约"); + } + } + + private BigDecimal normalizeQuotePrice(BigDecimal price) { + if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) { + throw new RuntimeException("报价金额必须大于0"); + } + return scaleMoney(price); + } + + private Map loadActiveOrderItemMap(Long orderId) { + return orderItemMapper.selectByOrderId(orderId).stream() + .filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete())) + .collect(Collectors.toMap(OrderItemDO::getId, item -> item, (left, right) -> left, LinkedHashMap::new)); + } + + private List loadActiveOrderItems(Long orderId) { + return new ArrayList<>(loadActiveOrderItemMap(orderId).values()); + } + + private List ensureAllItemsQuoted(Long orderId) { + List items = loadActiveOrderItems(orderId); + if (items.isEmpty()) { + throw new RuntimeException("询价预约作品不存在"); + } + for (OrderItemDO item : items) { + if (item.getQuotedPrice() == null || item.getQuotedPrice().compareTo(BigDecimal.ZERO) <= 0) { + throw new RuntimeException("请先为每个作品填写报价"); + } + } + return items; + } + + private OrderVO finalizeConfirmedQuote(OrderDO order, Long actorId, String actorType) { + order = requireQuoteOrder(order.getId()); + if (!Integer.valueOf(1).equals(order.getQuoteUserConfirmed()) + || !Integer.valueOf(1).equals(order.getQuoteShopConfirmed())) { + return buildOrderVO(order); + } + + List items = ensureAllItemsQuoted(order.getId()); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + Set selectedTagNames = new LinkedHashSet<>(); + List requestedSlots = new ArrayList<>(); + BigDecimal finalTotal = BigDecimal.ZERO; + Long selectedArtistId = null; + + try { + for (OrderItemDO item : items) { + ProductDO product = requireActiveProduct(item.getProductId()); + productCache.put(product.getId(), product); + validateRequestedArtistForItem(order.getShopId(), item.getArtistId(), item, product); + if (selectedArtistId == null) { + selectedArtistId = item.getArtistId(); + } else if (!Objects.equals(selectedArtistId, item.getArtistId())) { + throw bookingUnavailable("不同美甲师的项目请分开确认"); + } + validateAppointmentTime(item.getAppointmentTime(), product.getTitle()); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + LocalDateTime endTime = item.getAppointmentTime().plusMinutes(durationMinutes); + validateBusinessHours(getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache), + item.getAppointmentTime(), endTime, product.getTitle()); + requestedSlots.add(new AppointmentSlot(product.getTitle(), item.getAppointmentTime(), endTime)); + collectTagNames(selectedTagNames, product.getTags()); + BigDecimal confirmedPrice = scaleMoney(item.getQuotedPrice()); + item.setPrice(confirmedPrice); + item.setConfirmedPrice(confirmedPrice); + finalTotal = finalTotal.add(confirmedPrice.multiply(BigDecimal.valueOf(Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity())))); + } + validateRequestedSlotConflicts(requestedSlots); + } catch (BusinessException exception) { + throw exception; + } catch (RuntimeException exception) { + if (isBookingValidationMessage(exception.getMessage())) { + throw bookingUnavailable(exception.getMessage()); + } + throw exception; + } + + CouponSelection couponSelection = resolveFinalCouponSelection(order, selectedTagNames, finalTotal); + BigDecimal actualAmount = finalTotal; + Long couponId = null; + Long userCouponId = null; + String couponSourceType = null; + if (couponSelection != null) { + CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); + if (coupon != null && !Integer.valueOf(1).equals(coupon.getIsDelete()) && coupon.getStatus() != null && coupon.getStatus() == 1) { + actualAmount = applyCouponDiscount(finalTotal, coupon); + couponId = coupon.getId(); + userCouponId = couponSelection.getUserCouponId(); + couponSourceType = couponSelection.getSourceType(); + if (COUPON_SOURCE_USER.equals(couponSourceType)) { + consumeUserCoupon(userCouponId, order.getUserId()); + } + } + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()) == 0) { + throw new RuntimeException("询价预约状态已变化,请刷新后重试"); + } + + for (OrderItemDO item : items) { + orderItemMapper.updateById(item); + ProductDO product = productCache.get(item.getProductId()); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + appointmentCapacityService.confirmReservationOrThrow( + order.getId(), + item.getId(), + order.getShopId(), + item.getArtistId(), + product == null ? null : product.getTitle(), + item.getAppointmentTime(), + item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes) + ); + } + + order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setTotalAmount(scaleMoney(finalTotal)); + order.setActualAmount(scaleMoney(actualAmount)); + order.setCouponId(couponId); + order.setUserCouponId(userCouponId); + order.setCouponSourceType(couponSourceType); + order.setQuoteStatus(QUOTE_STATUS_CONFIRMED); + order.setQuoteUserConfirmed(1); + order.setQuoteShopConfirmed(1); + order.setQuoteConfirmedTime(LocalDateTime.now()); + order.setPaymentStatus(actualAmount.compareTo(BigDecimal.ZERO) <= 0 ? "PAID" : "UNPAID"); + order.setPayAmount(scaleMoney(actualAmount)); + order.setPaidAmount(actualAmount.compareTo(BigDecimal.ZERO) <= 0 ? scaleMoney(actualAmount) : BigDecimal.ZERO); + orderMapper.updateById(order); + + writeQuoteMessage(order.getId(), actorId, actorType, QUOTE_ACTION_SYSTEM_CONFIRM, "双方已确认价格,订单进入待完成"); + notifyQuoteUser(order, "询价预约价格已确认", "双方已确认价格,订单已进入待完成状态。"); + notifyQuoteShopAndArtist(order, "询价预约价格已确认", "双方已确认价格,订单已进入待完成状态。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + private CouponSelection resolveFinalCouponSelection(OrderDO order, Set selectedTagNames, BigDecimal finalTotal) { + List availableCouponOptions = couponService.getAvailableCoupons( + order.getUserId(), + String.join(",", selectedTagNames), + finalTotal.doubleValue(), + order.getShopId() + ); + if (availableCouponOptions == null) { + availableCouponOptions = List.of(); + } + OrderDTO couponRequest = new OrderDTO(); + couponRequest.setCouponSourceType(order.getCouponSourceType()); + if (COUPON_SOURCE_USER.equals(order.getCouponSourceType())) { + couponRequest.setCouponId(order.getUserCouponId()); + } else if (COUPON_SOURCE_SYSTEM_VIP.equals(order.getCouponSourceType())) { + couponRequest.setCouponId(order.getCouponId()); + } + try { + CouponSelection selected = resolveRequestedCoupon(couponRequest, availableCouponOptions); + if (selected != null) { + return selected; + } + } catch (RuntimeException ignored) { + } + if (COUPON_SOURCE_NONE.equalsIgnoreCase(order.getCouponSourceType())) { + return null; + } + return selectBestAvailableCoupon(availableCouponOptions, finalTotal); + } + + private void writeQuoteMessage(Long orderId, Long actorId, String actorType, String action, String remark) { + OrderQuoteMessageDO message = new OrderQuoteMessageDO(); + message.setOrderId(orderId); + message.setActorId(actorId); + message.setActorType(actorType); + message.setAction(action); + message.setRemark(remark); + message.setItemsSnapshot(buildQuoteItemsSnapshot(orderId)); + message.setIsDelete(0); + orderQuoteMessageMapper.insert(message); + } + + private String buildQuoteItemsSnapshot(Long orderId) { + List items = buildQuoteItemVOs(orderId); + StringBuilder builder = new StringBuilder("["); + for (int i = 0; i < items.size(); i++) { + OrderQuoteItemVO item = items.get(i); + if (i > 0) { + builder.append(','); + } + builder.append('{'); + appendJsonField(builder, "orderItemId", item.getOrderItemId()); + builder.append(','); + appendJsonField(builder, "productId", item.getProductId()); + builder.append(','); + appendJsonField(builder, "productTitle", item.getProductTitle()); + builder.append(','); + appendJsonField(builder, "quantity", item.getQuantity()); + builder.append(','); + appendJsonField(builder, "referencePrice", item.getReferencePrice()); + builder.append(','); + appendJsonField(builder, "quotedPrice", item.getQuotedPrice()); + builder.append(','); + appendJsonField(builder, "confirmedPrice", item.getConfirmedPrice()); + builder.append('}'); + } + return builder.append(']').toString(); + } + + private void appendJsonField(StringBuilder builder, String name, Object value) { + builder.append('"').append(name).append('"').append(':'); + if (value == null) { + builder.append("null"); + return; + } + if (value instanceof Number) { + builder.append(value); + return; + } + builder.append('"').append(jsonEscape(String.valueOf(value))).append('"'); + } + + private String jsonEscape(String value) { + return value == null ? "" : value.replace("\\", "\\\\").replace("\"", "\\\""); + } + + private List buildQuoteItemVOs(Long orderId) { + return loadActiveOrderItems(orderId).stream() + .map(item -> { + ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>()); + OrderQuoteItemVO vo = new OrderQuoteItemVO(); + vo.setOrderItemId(item.getId()); + vo.setProductId(item.getProductId()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setQuantity(item.getQuantity()); + vo.setReferencePrice(item.getReferencePrice() == null ? item.getPrice() : item.getReferencePrice()); + vo.setQuotedPrice(item.getQuotedPrice()); + vo.setConfirmedPrice(item.getConfirmedPrice()); + return vo; + }) + .toList(); + } + + private OrderQuoteMessageVO buildQuoteMessageVO(OrderQuoteMessageDO message) { + OrderQuoteMessageVO vo = new OrderQuoteMessageVO(); + vo.setId(message.getId()); + vo.setOrderId(message.getOrderId()); + vo.setActorId(message.getActorId()); + vo.setActorType(message.getActorType()); + vo.setActorTypeText(resolveQuoteActorTypeText(message.getActorType())); + vo.setAction(message.getAction()); + vo.setActionText(resolveQuoteActionText(message.getAction())); + vo.setRemark(message.getRemark()); + vo.setItems(buildQuoteItemVOs(message.getOrderId())); + vo.setCreateTime(message.getCreateTime()); + return vo; + } + + private String resolveQuoteActorTypeText(String actorType) { + if (QUOTE_ACTOR_USER.equals(actorType)) { + return "用户"; + } + if (QUOTE_ACTOR_SHOP.equals(actorType)) { + return "门店"; + } + return "系统"; + } + + private String resolveQuoteActionText(String action) { + if (QUOTE_ACTION_CREATE.equals(action)) return "发起询价预约"; + if (QUOTE_ACTION_SHOP_QUOTE.equals(action)) return "门店报价"; + if (QUOTE_ACTION_USER_REPLY.equals(action)) return "用户回复"; + if (QUOTE_ACTION_USER_CONFIRM.equals(action)) return "用户确认"; + if (QUOTE_ACTION_SHOP_CONFIRM.equals(action)) return "店长确认"; + if (QUOTE_ACTION_SYSTEM_CONFIRM.equals(action)) return "价格已确认"; + if (QUOTE_ACTION_SYSTEM_EXPIRE.equals(action)) return "询价已过期"; + return "询价动态"; + } + + private String resolveQuoteStatusText(String quoteStatus, Integer orderStatus) { + if (QUOTE_STATUS_CONFIRMED.equals(quoteStatus)) { + return "价格已确认"; + } + if (QUOTE_STATUS_EXPIRED.equals(quoteStatus)) { + return "询价已过期"; + } + if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(orderStatus)) { + return "确认价格中"; + } + return "价格已确认"; + } + + private void notifyQuoteCreated(OrderVO orderVO) { + if (orderVO == null || orderVO.getId() == null) { + return; + } + OrderDO order = orderMapper.selectById(orderVO.getId()); + notifyQuoteShopAndArtist(order, "新的询价预约", "用户发起了新的询价预约,请查看并确认价格。"); + } + + private void notifyQuoteUser(OrderDO order, String title, String content) { + if (order == null) { + return; + } + createQuoteNotification(order.getUserId(), title, content, "/orders?orderId=" + order.getId(), order.getId(), 0L, "系统通知", 4); + } + + private void notifyQuoteShopAndArtist(OrderDO order, String title, String content) { + if (order == null || order.getId() == null) { + return; + } + Set targetIds = new LinkedHashSet<>(); + if (order.getShopId() != null) { + List owners = userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getShopId, order.getShopId()) + .eq(UserDO::getType, USER_TYPE_SHOP_OWNER) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1)); + owners.stream().map(UserDO::getId).filter(Objects::nonNull).forEach(targetIds::add); + userShopBindingSupport.listUserIdsByShopId(order.getShopId(), true).forEach(userId -> { + UserDO user = userMapper.selectById(userId); + if (user != null && Integer.valueOf(USER_TYPE_SHOP_OWNER).equals(user.getType())) { + targetIds.add(userId); + } + }); + } + loadActiveOrderItems(order.getId()).stream() + .map(OrderItemDO::getArtistId) + .filter(Objects::nonNull) + .forEach(targetIds::add); + targetIds.remove(order.getUserId()); + targetIds.forEach(targetId -> createQuoteNotification( + targetId, + title, + content, + "/admin/orders?orderId=" + order.getId(), + order.getId(), + order.getUserId(), + "用户询价预约", + 0 + )); + } + + private void createQuoteNotification(Long targetUserId, + String title, + String content, + String actionPath, + Long businessId, + Long publisherId, + String publisherName, + Integer publisherType) { + if (targetUserId == null) { + return; + } + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setPublisherId(publisherId == null ? 0L : publisherId); + message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知"); + message.setPublisherType(publisherType == null ? 4 : publisherType); + message.setTargetType(MESSAGE_TARGET_SELECTED_USERS); + message.setTargetIds(String.valueOf(targetUserId)); + message.setBusinessType(QUOTE_BUSINESS_TYPE); + message.setBusinessId(businessId); + message.setActionPath(actionPath); + message.setPopupEnabled(1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + } + + private Long createSystemBusinessMessage(Long targetUserId, + String title, + String content, + String businessType, + Long businessId, + String actionPath, + Long publisherId, + String publisherName, + Integer publisherType) { + if (targetUserId == null) { + return null; + } + String targetIds = String.valueOf(targetUserId); + String idempotencyKey = buildSystemMessageIdempotencyKey(businessType, businessId, targetUserId); + if (StringUtils.hasText(idempotencyKey)) { + Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey); + if (existingMessageId != null) { + return existingMessageId; + } + } + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setPublisherId(publisherId == null ? 0L : publisherId); + message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知"); + message.setPublisherType(publisherType == null ? 4 : publisherType); + message.setTargetType(MESSAGE_TARGET_SELECTED_USERS); + message.setTargetIds(targetIds); + message.setBusinessType(businessType); + message.setBusinessId(businessId); + message.setActionPath(actionPath); + message.setIdempotencyKey(idempotencyKey); + message.setPopupEnabled(1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + try { + systemMessageMapper.insert(message); + } catch (DuplicateKeyException exception) { + Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey); + if (existingMessageId != null) { + return existingMessageId; + } + throw exception; + } + return message.getId(); + } + + /** + * Purpose: buildSystemMessageIdempotencyKey supports OrderServiceImpl.java by holding or executing the build system message idempotency key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildSystemMessageIdempotencyKey(String businessType, Long businessId, Long targetUserId) { + if (!StringUtils.hasText(businessType) || businessId == null || targetUserId == null) { + return null; + } + return businessType + ":" + businessId + ":" + targetUserId; + } + + private Long findSystemBusinessMessageId(String businessType, + Long businessId, + String targetIds, + String idempotencyKey) { + if (!StringUtils.hasText(idempotencyKey)) { + return null; + } + SystemMessageDO existingMessage = systemMessageMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemMessageDO::getBusinessType, businessType) + .eq(SystemMessageDO::getBusinessId, businessId) + .eq(SystemMessageDO::getTargetType, MESSAGE_TARGET_SELECTED_USERS) + .eq(SystemMessageDO::getTargetIds, targetIds) + .eq(SystemMessageDO::getIsDelete, 0) + .and(wrapper -> wrapper + .eq(SystemMessageDO::getIdempotencyKey, idempotencyKey) + .or() + .isNull(SystemMessageDO::getIdempotencyKey)) + .last("LIMIT 1")); + return existingMessage == null ? null : existingMessage.getId(); + } + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ + private OrderVO buildOrderVO(OrderDO order) { + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildOrderVO(order, null); + } + + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureCalendarAccess(Long userId, Integer userType) { + if (userId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录"); + } + if (Integer.valueOf(3).equals(userType)) { + return; + } + if (Integer.valueOf(2).equals(userType)) { + NailArtistInfoDO info = nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { + return; + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师或参与制作的店长可查看预约日历"); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @param startTime parameter `startTime` supplied by the caller + * @param endTime parameter `endTime` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listArtistCalendarAppointments(Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + List items = orderItemMapper.selectArtistCalendarItems(artistId, startTime, endTime); + if (items == null || items.isEmpty()) { + return Collections.emptyList(); + } + + Map userCache = new HashMap<>(); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + UserDO artist = getUserFromCache(artistId, userCache); + List result = new ArrayList<>(); + + for (OrderItemDO item : items) { + OrderDO order = orderMapper.selectById(item.getOrderId()); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || Integer.valueOf(3).equals(order.getStatus())) { + continue; + } + ProductDO product = getProductFromCache(item.getProductId(), productCache); + if (product == null || item.getAppointmentTime() == null) { + continue; + } + ShopDO shop = getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache); + UserDO customer = getUserFromCache(order.getUserId(), userCache); + long singleDuration = resolveServiceDurationMinutes(product); + int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + long durationMinutes = singleDuration * quantity; + + ArtistCalendarAppointmentVO vo = new ArtistCalendarAppointmentVO(); + vo.setOrderId(order.getId()); + vo.setOrderNo(order.getOrderNo()); + vo.setTotalAmount(order.getTotalAmount()); + vo.setActualAmount(order.getActualAmount()); + vo.setOrderStatus(order.getStatus()); + vo.setOrderStatusText(resolveOrderStatusText(order.getStatus())); + vo.setOrderItemId(item.getId()); + vo.setProductId(product.getId()); + vo.setProductTitle(product.getTitle()); + vo.setArtistId(artistId); + vo.setArtistName(artist == null ? null : artist.getNickname()); + vo.setCustomerNickname(resolveCustomerNickname(customer)); + vo.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); + vo.setShopId(order.getShopId() == null ? product.getShopId() : order.getShopId()); + vo.setShopName(shop == null ? null : shop.getShopName()); + vo.setAppointmentStartTime(item.getAppointmentTime()); + vo.setAppointmentEndTime(item.getAppointmentTime().plusMinutes(durationMinutes)); + vo.setQuantity(item.getQuantity()); + vo.setDurationMinutes(durationMinutes); + result.add(vo); + } + result.sort(Comparator.comparing(ArtistCalendarAppointmentVO::getAppointmentStartTime)); + return result; + } + + /** + * Run business method `resolveOrderStatusText`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveOrderStatusText(Integer status) { + if (Integer.valueOf(0).equals(status)) { + return "确认价格中"; + } + if (Integer.valueOf(1).equals(status)) { + return "待完成"; + } + if (Integer.valueOf(1).equals(status)) { + return "待服务"; + } + if (Integer.valueOf(2).equals(status)) { + return "已完成"; + } + if (Integer.valueOf(3).equals(status)) { + return "已取消"; + } + return "未知状态"; + } + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param artistIdFilter parameter `artistIdFilter` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ + private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) { + OrderVO orderVO = new OrderVO(); + Map userCache = new HashMap<>(); + orderVO.setId(order.getId()); + orderVO.setOrderNo(order.getOrderNo()); + orderVO.setUserId(order.getUserId()); + orderVO.setShopId(order.getShopId()); + if (order.getShopId() != null) { + ShopDO shop = shopMapper.selectById(order.getShopId()); + orderVO.setShopName(shop == null ? null : shop.getShopName()); + } + orderVO.setTotalAmount(order.getTotalAmount()); + orderVO.setActualAmount(order.getActualAmount()); + orderVO.setCouponId(order.getCouponId()); + orderVO.setUserCouponId(order.getUserCouponId()); + orderVO.setCouponSourceType(order.getCouponSourceType()); + orderVO.setPaymentStatus(order.getPaymentStatus()); + orderVO.setPayAmount(order.getPayAmount()); + orderVO.setPaidAmount(order.getPaidAmount()); + orderVO.setPayTime(order.getPayTime()); + orderVO.setPaymentMethod(order.getPaymentMethod()); + orderVO.setPaymentOrderNo(order.getPaymentOrderNo()); + orderVO.setRefundStatus(order.getRefundStatus()); + orderVO.setCustomerRemark(order.getCustomerRemark()); + orderVO.setQuoteStatus(order.getQuoteStatus()); + orderVO.setQuoteStatusText(resolveQuoteStatusText(order.getQuoteStatus(), order.getStatus())); + orderVO.setQuoteUserConfirmed(Integer.valueOf(1).equals(order.getQuoteUserConfirmed())); + orderVO.setQuoteShopConfirmed(Integer.valueOf(1).equals(order.getQuoteShopConfirmed())); + orderVO.setQuoteExpireTime(order.getQuoteExpireTime()); + orderVO.setQuoteConfirmedTime(order.getQuoteConfirmedTime()); + if (orderQuoteMessageMapper != null) { + orderVO.setQuoteMessages(orderQuoteMessageMapper.selectByOrderId(order.getId()).stream() + .map(this::buildQuoteMessageVO) + .toList()); + } + UserDO customer = getUserFromCache(order.getUserId(), userCache); + orderVO.setCustomerNickname(resolveCustomerNickname(customer)); + orderVO.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); + orderVO.setStatus(order.getStatus()); + + switch (order.getStatus()) { + case 0: + orderVO.setStatusText("确认价格中"); + break; + case 1: + orderVO.setStatusText("待使用"); + break; + case 2: + orderVO.setStatusText("已完成"); + break; + case 3: + orderVO.setStatusText("已取消"); + break; + default: + orderVO.setStatusText("未知状态"); + } + + if (Integer.valueOf(1).equals(order.getStatus())) { + orderVO.setStatusText("待完成"); + } + + if (artistIdFilter == null && order.getCouponId() != null && order.getCouponId() > 0) { + CouponDO coupon = couponMapper.selectById(order.getCouponId()); + if (coupon != null) { + orderVO.setCouponName(coupon.getCouponName()); + } + } + + orderVO.setCreateTime(order.getCreateTime()); + + List orderItemVOs = new ArrayList<>(); + BigDecimal filteredTotal = BigDecimal.ZERO; + List orderItems = orderItemMapper.selectByOrderId(order.getId()); + + for (OrderItemDO item : orderItems) { + if (Integer.valueOf(1).equals(item.getIsDelete())) { + continue; + } + if (artistIdFilter != null && !artistIdFilter.equals(item.getArtistId())) { + continue; + } + + ProductDO product = productMapper.selectById(item.getProductId()); + if (product == null) { + continue; + } + + OrderItemVO itemVO = new OrderItemVO(); + itemVO.setId(item.getId()); + itemVO.setProductId(product.getId()); + itemVO.setProductTitle(product.getTitle()); + + String imageFileIds = product.getImageFileIds(); + if (imageFileIds != null && !imageFileIds.isEmpty()) { + String firstImageId = imageFileIds.split(",")[0]; + itemVO.setProductImage("/api/file/get/" + firstImageId); + } + + itemVO.setQuantity(item.getQuantity()); + itemVO.setPrice(item.getPrice()); + itemVO.setReferencePrice(item.getReferencePrice() == null ? item.getPrice() : item.getReferencePrice()); + itemVO.setQuotedPrice(item.getQuotedPrice()); + itemVO.setConfirmedPrice(item.getConfirmedPrice()); + BigDecimal displayPrice = item.getConfirmedPrice() == null ? item.getPrice() : item.getConfirmedPrice(); + itemVO.setPrice(displayPrice); + itemVO.setTotalPrice(displayPrice.multiply(BigDecimal.valueOf(item.getQuantity()))); + itemVO.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); + String occupancyStatus = resolveOrderItemOccupancyStatus(order); + itemVO.setOccupancyStatus(occupancyStatus); + itemVO.setCanEdit(canEditOrderItem(order)); + itemVO.setCanCancel(canCancelOrderItem(order)); + itemVO.setConflictReason(resolveOrderItemConflictReason(occupancyStatus)); + filteredTotal = filteredTotal.add(itemVO.getTotalPrice()); + + if (item.getArtistId() != null) { + itemVO.setArtistId(item.getArtistId()); + UserDO artist = getUserFromCache(item.getArtistId(), userCache); + if (artist != null) { + itemVO.setArtistName(artist.getNickname()); + itemVO.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + } + } + + OrderArtistReviewDO review = orderArtistReviewMapper.selectByOrderItemId(item.getId()); + if (review != null) { + OrderArtistReviewVO reviewVO = buildArtistReviewVO(review); + if (Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) { + itemVO.setPendingReview(reviewVO); + } else if (Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus())) { + itemVO.setReviewSummary(reviewVO); + } + } + + OrderArtistChangeRequestDO pendingChangeRequest = orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()); + if (pendingChangeRequest != null) { + itemVO.setPendingArtistChangeRequest(buildArtistChangeRequestVO(pendingChangeRequest)); + } + + orderItemVOs.add(itemVO); + } + + orderVO.setItems(orderItemVOs); + if (artistIdFilter != null) { + orderVO.setTotalAmount(filteredTotal); + orderVO.setActualAmount(filteredTotal); + } + return orderVO; + } + + private String resolveOrderItemOccupancyStatus(OrderDO order) { + if (order == null || order.getStatus() == null) { + return "UNKNOWN"; + } + if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + return "PENDING_QUOTE"; + } + if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + return "CONFIRMED"; + } + if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { + return "CANCELLED"; + } + if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { + return "COMPLETED"; + } + return "UNKNOWN"; + } + + private Boolean canEditOrderItem(OrderDO order) { + if (order == null || order.getStatus() == null) { + return false; + } + return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); + } + + private Boolean canCancelOrderItem(OrderDO order) { + if (order == null || order.getStatus() == null) { + return false; + } + return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); + } + + private String resolveOrderItemConflictReason(String occupancyStatus) { + if ("PENDING_QUOTE".equals(occupancyStatus)) { + return "该时段已作为待报价预约保留"; + } + if ("CONFIRMED".equals(occupancyStatus)) { + return "该时段已确认占用"; + } + return null; + } + + /** + * Run business method `buildRequestedQuantityMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map buildRequestedQuantityMap(List orderItemDTOs) { + Map requestedQuantityByProductId = new HashMap<>(); + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + if (orderItemDTO == null || orderItemDTO.getProductId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单商品信息不完整"); + } + requestedQuantityByProductId.merge( + orderItemDTO.getProductId(), + orderItemDTO.getQuantity() == null ? 0 : orderItemDTO.getQuantity(), + Integer::sum + ); + } + return requestedQuantityByProductId; + } + + /** + * Run business method `loadLockedCartItems`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param requestedProductIds parameter `requestedProductIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadLockedCartItems(Long userId, List requestedProductIds) { + if (requestedProductIds == null || requestedProductIds.isEmpty()) { + return Collections.emptyMap(); + } + + List lockedCartItems = cartMapper.selectByUserIdAndProductIdsForUpdate(userId, requestedProductIds); + Map lockedCartItemMap = new HashMap<>(); + for (CartDO cartDO : lockedCartItems) { + if (cartDO != null && cartDO.getProductId() != null) { + lockedCartItemMap.put(cartDO.getProductId(), cartDO); + } + } + return lockedCartItemMap; + } + + /** + * Run business method `validateUserCanCreateOrderInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateUserCanCreateOrderInShop(Long userId, Long shopId) { + if (!userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号已不可在该店铺下单,请切换门店后重试"); + } + } + + /** + * Run business method `resolveRequestedArtistId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveRequestedArtistId(List orderItemDTOs) { + Long artistId = null; + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + if (orderItemDTO == null || orderItemDTO.getArtistId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择美甲师"); + } + if (artistId == null) { + artistId = orderItemDTO.getArtistId(); + continue; + } + if (!artistId.equals(orderItemDTO.getArtistId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不同美甲师的项目请分开下单"); + } + } + if (artistId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择美甲师"); + } + return artistId; + } + + /** + * Run business method `tryAcquireOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean tryAcquireOrderLock(String lockKey, String lockToken) { + return Boolean.TRUE.equals( + stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockToken, ORDER_CREATE_LOCK_TTL) + ); + } + + /** + * Run business method `tryAcquireArtistOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean tryAcquireArtistOrderLock(String lockKey, String lockToken) { + long deadline = System.currentTimeMillis() + ARTIST_LOCK_WAIT_TIMEOUT_MILLIS; + while (System.currentTimeMillis() <= deadline) { + if (tryAcquireOrderLock(lockKey, lockToken)) { + return true; + } + try { + Thread.sleep(ARTIST_LOCK_RETRY_INTERVAL_MILLIS); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + return false; + } + } + return false; + } + + // 慢事务期间持续续租,避免下单锁在事务未完成时提前过期。 + /** + * Run business method `startOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private LockLease result consumed by the caller or returned to the frontend + */ + private LockLease startOrderLockRenewal(String lockKey, String lockToken) { + if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { + return null; + } + + LockLease lockLease = new LockLease(lockKey, lockToken); + ScheduledFuture future = LOCK_RENEW_EXECUTOR.scheduleWithFixedDelay( + () -> renewOrderLock(lockLease), + ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS, + ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS, + TimeUnit.MILLISECONDS + ); + lockLease.attachFuture(future); + return lockLease; + } + + /** + * Run business method `renewOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockLease parameter `lockLease` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void renewOrderLock(LockLease lockLease) { + if (lockLease == null || !lockLease.isActive()) { + return; + } + try { + Long renewResult = stringRedisTemplate.execute( + RENEW_LOCK_SCRIPT, + Collections.singletonList(lockLease.getLockKey()), + lockLease.getLockToken(), + String.valueOf(ORDER_CREATE_LOCK_TTL_MILLIS) + ); + if (!Long.valueOf(1L).equals(renewResult)) { + lockLease.cancel(); + } + } catch (Exception ignored) { + } + } + + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockLease parameter `lockLease` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void stopOrderLockRenewal(LockLease lockLease) { + if (lockLease == null) { + return; + } + lockLease.cancel(); + } + + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void releaseOrderLock(String lockKey, String lockToken) { + if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { + return; + } + stringRedisTemplate.execute(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey), lockToken); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userCache parameter `userCache` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO getUserFromCache(Long userId, Map userCache) { + if (userId == null) { + return null; + } + if (userCache.containsKey(userId)) { + return userCache.get(userId); + } + UserDO userDO = userMapper.selectById(userId); + userCache.put(userId, userDO); + return userDO; + } + + /** + * Run business method `resolveCustomerNickname`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param customer parameter `customer` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveCustomerNickname(UserDO customer) { + if (customer == null) { + return "用户"; + } + if (StringUtils.hasText(customer.getNickname())) { + return customer.getNickname(); + } + if (StringUtils.hasText(customer.getAccount())) { + return customer.getAccount(); + } + return "用户"; + } + + /** + * Run business method `maskPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskPhone(String phone) { + if (!StringUtils.hasText(phone)) { + return null; + } + String normalizedPhone = phone.trim(); + if (normalizedPhone.length() < 7) { + return normalizedPhone; + } + return normalizedPhone.substring(0, 3) + + "****" + + normalizedPhone.substring(normalizedPhone.length() - 4); + } + + /** + * Run business method `validateOrderQuantity`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param quantity parameter `quantity` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateOrderQuantity(Integer quantity) { + if (quantity == null || quantity < 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 0 parameter `0` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单商品数量必须大于 0"); + } + } + + /** + * Run business method `validateArtistForProduct`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param product parameter `product` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO validateArtistForProduct(ProductDO product, Long artistId) { + if (artistId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择美甲师"); + } + + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师不存在或已删除"); + } + if (!bookableArtistSupport.isBookableServiceUser(artist)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("指定用户不是可预约美甲服务人员"); + } + if (!Integer.valueOf(1).equals(artist.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师当前不可预约"); + } + if (product.getShopId() != null && !userShopBindingSupport.isUserAccessibleInShop(artistId, product.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该美甲师不属于当前商品店铺"); + } + + if (product.getBookableArtists() != null && !product.getBookableArtists().isEmpty()) { + String[] artistIds = product.getBookableArtists().split(","); + boolean isBookable = false; + for (String currentArtistId : artistIds) { + if (currentArtistId.trim().equals(artistId.toString())) { + isBookable = true; + break; + } + } + if (!isBookable) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该美甲师无法预约此商品"); + } + } + + return artist; + } + + /** + * Run business method `collectTagNames`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagNames parameter `tagNames` supplied by the caller + * @param tags parameter `tags` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void collectTagNames(Set tagNames, String tags) { + if (tags == null || tags.isBlank()) { + return; + } + + for (String tagId : tags.split(";")) { + if (tagId == null || tagId.isBlank()) { + continue; + } + try { + TagVO tagVO = tagService.getTagById(Long.parseLong(tagId.trim())); + if (tagVO != null && tagVO.getTagName() != null && !tagVO.getTagName().isBlank()) { + tagNames.add(tagVO.getTagName()); + } + } catch (NumberFormatException ignored) { + } + } + } + + /** + * Run business method `parseAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ + private LocalDateTime parseAppointmentTime(String appointmentTime) { + if (appointmentTime == null || appointmentTime.isBlank()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择预约时间"); + } + + String normalized = appointmentTime.trim(); + for (DateTimeFormatter formatter : APPOINTMENT_INPUT_FORMATTERS) { + try { + return LocalDateTime.parse(normalized, formatter); + } catch (DateTimeParseException ignored) { + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("预约时间格式不正确"); + } + + /** + * Run business method `validateAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @param productTitle parameter `productTitle` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateAppointmentTime(LocalDateTime appointmentTime, String productTitle) { + if (!appointmentTime.isAfter(LocalDateTime.now())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("商品「" + productTitle + "」的预约时间必须晚于当前时间"); + } + } + + /** + * Run business method `validateBusinessHours`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shop parameter `shop` supplied by the caller + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @param appointmentEndTime parameter `appointmentEndTime` supplied by the caller + * @param productTitle parameter `productTitle` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateBusinessHours(ShopDO shop, LocalDateTime appointmentTime, LocalDateTime appointmentEndTime, String productTitle) { + if (shop == null || shop.getBusinessHours() == null || shop.getBusinessHours().isBlank()) { + return; + } + + String normalizedBusinessHours = shop.getBusinessHours() + .replace(':', ':') + .replace('-', '-') + .replace('—', '-') + .trim(); + Matcher matcher = BUSINESS_HOURS_PATTERN.matcher(normalizedBusinessHours); + if (!matcher.matches()) { + return; + } + + LocalTime openTime = LocalTime.parse(matcher.group(1), DateTimeFormatter.ofPattern("H:mm")); + LocalTime closeTime = LocalTime.parse(matcher.group(2), DateTimeFormatter.ofPattern("H:mm")); + if (!closeTime.isAfter(openTime)) { + return; + } + + if (!appointmentTime.toLocalDate().equals(appointmentEndTime.toLocalDate()) + || appointmentTime.toLocalTime().isBefore(openTime) + || appointmentEndTime.toLocalTime().isAfter(closeTime)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("商品「" + productTitle + "」的预约时间超出门店营业时间"); + } + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param shopCache parameter `shopCache` supplied by the caller + * @return private ShopDO result consumed by the caller or returned to the frontend + */ + private ShopDO getShopFromCache(Long shopId, Map shopCache) { + if (shopId == null) { + return null; + } + if (shopCache.containsKey(shopId)) { + return shopCache.get(shopId); + } + + ShopDO shop = shopMapper.selectById(shopId); + if (shop != null && Integer.valueOf(1).equals(shop.getIsDelete())) { + shop = null; + } + shopCache.put(shopId, shop); + return shop; + } + + /** + * Run business method `validateRequestedSlotConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateRequestedSlotConflicts(List requestedSlots) { + if (requestedSlots.size() <= 1) { + return; + } + + requestedSlots.sort(Comparator.comparing(AppointmentSlot::getStartTime)); + for (int i = 1; i < requestedSlots.size(); i++) { + AppointmentSlot previous = requestedSlots.get(i - 1); + AppointmentSlot current = requestedSlots.get(i); + if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) { + throw new RuntimeException("所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间"); + } + } + } + + /** + * Run business method `validateArtistScheduleConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateArtistScheduleConflicts(Long artistId, List requestedSlots, Map productCache) { + if (artistId == null || requestedSlots.isEmpty()) { + return; + } + + for (AppointmentSlot requestedSlot : requestedSlots) { + int activeOccupancyCount = appointmentReservationMapper.countOverlappingActive( + artistId, + requestedSlot.getStartTime(), + requestedSlot.getEndTime() + ); + if (activeOccupancyCount > 0) { + throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约占用冲突,请重新选择"); + } + } + + List existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId); + if (existingAppointments == null || existingAppointments.isEmpty()) { + return; + } + + for (OrderItemDO existingItem : existingAppointments) { + if (existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) { + continue; + } + + ProductDO existingProduct = getProductFromCache(existingItem.getProductId(), productCache); + if (existingProduct == null) { + continue; + } + + long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * Math.max(1, existingItem.getQuantity()); + LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes); + + for (AppointmentSlot requestedSlot : requestedSlots) { + if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) { + throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择"); + } + } + } + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return private ProductDO result consumed by the caller or returned to the frontend + */ + private ProductDO getProductFromCache(Long productId, Map productCache) { + if (productId == null) { + return null; + } + if (productCache.containsKey(productId)) { + return productCache.get(productId); + } + + ProductDO product = productMapper.selectById(productId); + if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) { + product = null; + } + productCache.put(productId, product); + return product; + } + + /** + * Run business method `resolveServiceDurationMinutes`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param product parameter `product` supplied by the caller + * @return private long result consumed by the caller or returned to the frontend + */ + private long resolveServiceDurationMinutes(ProductDO product) { + if (product == null || product.getApproximateDuration() == null || product.getApproximateDuration().isBlank()) { + return DEFAULT_SERVICE_DURATION_MINUTES; + } + + Matcher matcher = DURATION_PATTERN.matcher(product.getApproximateDuration()); + if (matcher.find()) { + try { + return Math.max(1L, Long.parseLong(matcher.group(1))); + } catch (NumberFormatException ignored) { + } + } + return DEFAULT_SERVICE_DURATION_MINUTES; + } + + /** + * Run business method `hasOverlap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param startA parameter `startA` supplied by the caller + * @param endA parameter `endA` supplied by the caller + * @param startB parameter `startB` supplied by the caller + * @param endB parameter `endB` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean hasOverlap(LocalDateTime startA, LocalDateTime endA, LocalDateTime startB, LocalDateTime endB) { + return startA.isBefore(endB) && startB.isBefore(endA); + } + + /** + * Run business method `formatAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String formatAppointmentTime(LocalDateTime appointmentTime) { + if (appointmentTime == null) { + return null; + } + return appointmentTime.format(APPOINTMENT_OUTPUT_FORMATTER); + } + + /** + * Run business method `resolveRequestedCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @return private CouponSelection result consumed by the caller or returned to the frontend + */ + private CouponSelection resolveRequestedCoupon(OrderDTO orderDTO, List availableCoupons) { + if (orderDTO == null || orderDTO.getCouponId() == null || orderDTO.getCouponId() <= 0) { + return null; + } + + String requestedSourceType = normalizeCouponSourceType(orderDTO.getCouponSourceType()); + List matchedCoupons = availableCoupons.stream() + .filter(coupon -> orderDTO.getCouponId().equals(coupon.getId())) + .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) + .toList(); + + if (matchedCoupons.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前订单不可使用所选优惠券"); + } + + UserCouponVO selectedCoupon = matchedCoupons.stream() + .filter(coupon -> COUPON_SOURCE_USER.equals(coupon.getSourceType())) + .findFirst() + .orElse(matchedCoupons.get(0)); + + return new CouponSelection( + selectedCoupon.getSourceType(), + selectedCoupon.getCouponId(), + COUPON_SOURCE_USER.equals(selectedCoupon.getSourceType()) ? selectedCoupon.getId() : null + ); + } + + /** + * Run business method `selectBestAvailableCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @param totalAmount parameter `totalAmount` supplied by the caller + * @return private CouponSelection result consumed by the caller or returned to the frontend + */ + private CouponSelection selectBestAvailableCoupon(List availableCoupons, BigDecimal totalAmount) { + return availableCoupons.stream() + .filter(coupon -> coupon.getCouponId() != null) + .max(Comparator.comparing(coupon -> calculateCouponDiscountAmount(coupon, totalAmount))) + .map(coupon -> new CouponSelection( + coupon.getSourceType(), + coupon.getCouponId(), + COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null + )) + .orElse(null); + } + + /** + * Run business method `normalizeCouponSourceType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponSourceType parameter `couponSourceType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeCouponSourceType(String couponSourceType) { + if (couponSourceType == null || couponSourceType.isBlank()) { + return null; + } + return couponSourceType.trim().toUpperCase(); + } + + /** + * Run business method `isExplicitNoCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isExplicitNoCoupon(OrderDTO orderDTO) { + return orderDTO != null + && orderDTO.getCouponId() == null + && COUPON_SOURCE_NONE.equalsIgnoreCase(orderDTO.getCouponSourceType()); + } + + /** + * Run business method `calculateCouponDiscountAmount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param coupon parameter `coupon` supplied by the caller + * @param totalAmount parameter `totalAmount` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal calculateCouponDiscountAmount(UserCouponVO coupon, BigDecimal totalAmount) { + if (coupon == null || totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + + if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null && !coupon.getDiscountValue().isBlank()) { + BigDecimal discountValue = new BigDecimal(coupon.getDiscountValue()); + BigDecimal discountedAmount = totalAmount.multiply(discountValue) + .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); + return totalAmount.subtract(discountedAmount); + } + + if (coupon.getCouponType() == 2 && coupon.getReduceAmount() != null && !coupon.getReduceAmount().isBlank()) { + return new BigDecimal(coupon.getReduceAmount()); + } + + return BigDecimal.ZERO; + } + + /** + * Run business method `applyCouponDiscount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param totalAmount parameter `totalAmount` supplied by the caller + * @param coupon parameter `coupon` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal applyCouponDiscount(BigDecimal totalAmount, CouponDO coupon) { + if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null) { + return totalAmount.multiply(coupon.getDiscountValue()) + .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); + } + if (coupon.getCouponType() == 2 && coupon.getReduceAmount() != null) { + BigDecimal actualAmount = totalAmount.subtract(coupon.getReduceAmount()); + return actualAmount.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : actualAmount; + } + return totalAmount; + } + + /** + * Run business method `consumeUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void consumeUserCoupon(Long userCouponId, Long userId) { + if (userCouponId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户优惠券信息缺失"); + } + + UserCouponDO userCoupon = userCouponMapper.selectById(userCouponId); + if (userCoupon == null || Integer.valueOf(1).equals(userCoupon.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券不存在或已失效"); + } + if (!userId.equals(userCoupon.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券不属于当前用户"); + } + if (userCoupon.getStatus() == null || userCoupon.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券已被使用或不可用"); + } + + userCoupon.setStatus(2); + userCoupon.setUseTime(LocalDateTime.now()); + userCouponMapper.updateById(userCoupon); + updateCouponUsedCount(userCoupon.getCouponId(), 1); + } + + /** + * Run business method `restoreUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void restoreUserCoupon(OrderDO order, Long userId) { + if (order == null + || !COUPON_SOURCE_USER.equals(order.getCouponSourceType()) + || order.getUserCouponId() == null + || userId == null) { + return; + } + + UserCouponDO userCoupon = userCouponMapper.selectById(order.getUserCouponId()); + if (userCoupon == null || !userId.equals(userCoupon.getUserId()) || userCoupon.getStatus() == null || userCoupon.getStatus() != 2) { + return; + } + + userCoupon.setStatus(1); + userCoupon.setUseTime(null); + userCouponMapper.updateById(userCoupon); + updateCouponUsedCount(userCoupon.getCouponId(), -1); + } + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @param delta parameter `delta` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void updateCouponUsedCount(Long couponId, int delta) { + if (couponId == null || delta == 0) { + return; + } + + CouponDO couponDO = couponMapper.selectById(couponId); + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + return; + } + + int currentUsedCount = couponDO.getUsedCount() == null ? 0 : couponDO.getUsedCount(); + couponDO.setUsedCount(Math.max(0, currentUsedCount + delta)); + couponMapper.updateById(couponDO); + } + + /** + * Purpose: LockLease supports OrderServiceImpl.java by holding or executing the lock lease business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class LockLease { + /** + * Variable `lockKey`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String lockKey; + /** + * Variable `lockToken`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String lockToken; + /** + * Purpose: future supports OrderServiceImpl.java by holding or executing the future business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private volatile ScheduledFuture future; + /** + * Purpose: active supports OrderServiceImpl.java by holding or executing the active business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private volatile boolean active = true; + + /** + * Run business method `LockLease`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private LockLease(String lockKey, String lockToken) { + this.lockKey = lockKey; + this.lockToken = lockToken; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getLockKey() { + return lockKey; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getLockToken() { + return lockToken; + } + + /** + * Run business method `isActive`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isActive() { + return active; + } + + /** + * Run business method `attachFuture`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param future parameter `future` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void attachFuture(ScheduledFuture future) { + this.future = future; + if (!active && future != null) { + future.cancel(false); + } + } + + /** + * Run business method `cancel`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void cancel() { + active = false; + ScheduledFuture currentFuture = future; + if (currentFuture != null) { + currentFuture.cancel(false); + } + } + } + + /** + * Purpose: LockRenewThreadFactory supports OrderServiceImpl.java by holding or executing the lock renew thread factory business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class LockRenewThreadFactory implements ThreadFactory { + @Override + /** + * Run business method `newThread`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param runnable parameter `runnable` supplied by the caller + * @return Thread result consumed by the caller or returned to the frontend + */ + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "order-lock-renew"); + thread.setDaemon(true); + return thread; + } + } + + /** + * Purpose: CouponSelection supports OrderServiceImpl.java by holding or executing the coupon selection business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class CouponSelection { + /** + * Variable `sourceType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String sourceType; + /** + * Variable `couponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final Long couponId; + /** + * Variable `userCouponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final Long userCouponId; + + /** + * Run business method `CouponSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sourceType parameter `sourceType` supplied by the caller + * @param couponId parameter `couponId` supplied by the caller + * @param userCouponId parameter `userCouponId` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private CouponSelection(String sourceType, Long couponId, Long userCouponId) { + this.sourceType = sourceType; + this.couponId = couponId; + this.userCouponId = userCouponId; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getSourceType() { + return sourceType; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long getCouponId() { + return couponId; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long getUserCouponId() { + return userCouponId; + } + } + + private static final class CheckoutPricingContext { + private final BigDecimal totalAmount; + private final Long shopId; + private final String productTagNames; + + private CheckoutPricingContext(BigDecimal totalAmount, Long shopId, String productTagNames) { + this.totalAmount = totalAmount; + this.shopId = shopId; + this.productTagNames = productTagNames; + } + + private BigDecimal getTotalAmount() { + return totalAmount; + } + + private Long getShopId() { + return shopId; + } + + private String getProductTagNames() { + return productTagNames; + } + } + + private static final class BookingValidationSlot { + private final Long productId; + private final String productTitle; + private final LocalDateTime startTime; + private final LocalDateTime endTime; + + private BookingValidationSlot(Long productId, String productTitle, LocalDateTime startTime, LocalDateTime endTime) { + this.productId = productId; + this.productTitle = productTitle; + this.startTime = startTime; + this.endTime = endTime; + } + + private Long getProductId() { + return productId; + } + + private String getProductTitle() { + return productTitle; + } + + private LocalDateTime getStartTime() { + return startTime; + } + + private LocalDateTime getEndTime() { + return endTime; + } + } + + /** + * Purpose: AppointmentSlot supports OrderServiceImpl.java by holding or executing the appointment slot business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class AppointmentSlot { + /** + * Variable `productTitle`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String productTitle; + /** + * Variable `startTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LocalDateTime startTime; + /** + * Variable `endTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LocalDateTime endTime; + + /** + * Run business method `AppointmentSlot`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productTitle parameter `productTitle` supplied by the caller + * @param startTime parameter `startTime` supplied by the caller + * @param endTime parameter `endTime` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private AppointmentSlot(String productTitle, LocalDateTime startTime, LocalDateTime endTime) { + this.productTitle = productTitle; + this.startTime = startTime; + this.endTime = endTime; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getProductTitle() { + return productTitle; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ + private LocalDateTime getStartTime() { + return startTime; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ + private LocalDateTime getEndTime() { + return endTime; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/support/OrderStateMachine.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/support/OrderStateMachine.java new file mode 100644 index 00000000..6ef2730a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/support/OrderStateMachine.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.support; + +/** + * Purpose: OrderStateMachine supports OrderStateMachine.java by holding or executing the order state machine business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class OrderStateMachine { + + private OrderStateMachine() { + } + + /** + * Purpose: isAllowedTransition supports OrderStateMachine.java by holding or executing the is allowed transition business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean isAllowedTransition(Integer fromStatus, Integer toStatus) { + OrderStatus from = OrderStatus.requireKnown(fromStatus); + OrderStatus to = OrderStatus.requireKnown(toStatus); + if (from == OrderStatus.PRICE_CONFIRMING) { + return to == OrderStatus.PENDING_SERVICE || to == OrderStatus.CANCELLED; + } + return from == OrderStatus.PENDING_SERVICE + && (to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED); + } + + /** + * Purpose: requireAllowedTransition supports OrderStateMachine.java by holding or executing the require allowed transition business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static void requireAllowedTransition(Integer fromStatus, Integer toStatus) { + if (!isAllowedTransition(fromStatus, toStatus)) { + throw new RuntimeException("订单状态不允许处理"); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/support/OrderStatus.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/support/OrderStatus.java new file mode 100644 index 00000000..a21a2595 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/support/OrderStatus.java @@ -0,0 +1,43 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.support; + +import java.util.Arrays; + +/** + * Purpose: OrderStatus supports OrderStatus.java by holding or executing the order status business role. + * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. + */ +public enum OrderStatus { + PRICE_CONFIRMING(0), + PENDING_SERVICE(1), + COMPLETED(2), + CANCELLED(3); + + /** + * Purpose: code supports OrderStatus.java by holding or executing the code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final int code; + + OrderStatus(int code) { + this.code = code; + } + + /** + * Purpose: getCode supports OrderStatus.java by holding or executing the get code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public int getCode() { + return code; + } + + /** + * Purpose: requireKnown supports OrderStatus.java by holding or executing the require known business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static OrderStatus requireKnown(Integer code) { + return Arrays.stream(values()) + .filter(status -> Integer.valueOf(status.code).equals(code)) + .findFirst() + .orElseThrow(() -> new RuntimeException("无效的订单状态")); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/AfterSaleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/AfterSaleVO.java new file mode 100644 index 00000000..1ad0ba6f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/AfterSaleVO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +public class AfterSaleVO { + private Long id; + private String afterSaleNo; + private Long orderId; + private Long orderItemId; + private Long userId; + private Long shopId; + private String type; + private String reason; + private BigDecimal refundAmount; + private String status; + private Long auditUserId; + private String auditReason; + private LocalDateTime auditTime; + private Long refundOrderId; + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CartArtistVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CartArtistVO.java new file mode 100644 index 00000000..a46f4eb3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CartArtistVO.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +@Data +/** + * CartArtistVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class CartArtistVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `name` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String name; + /** + * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String avatar; + /** + * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer userType; + /** + * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleLabel; + /** + * Field `participateProduction` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean participateProduction; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CartVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CartVO.java new file mode 100644 index 00000000..f417a1a7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CartVO.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +@Data +/** + * CartVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class CartVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productImage; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalPrice; + /** + * Field `tags` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String tags; + /** + * Field `tagNames` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String tagNames; + /** + * Field `approximateDuration` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String approximateDuration; + /** + * Field `bookableArtists` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String bookableArtists; + /** + * Field `availableBookableArtistCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer availableBookableArtistCount; + /** + * Field `bookableArtistRestricted` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean bookableArtistRestricted; + /** + * Field `availableArtists` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List availableArtists; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CheckoutCouponPreviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CheckoutCouponPreviewVO.java new file mode 100644 index 00000000..6dd804ee --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CheckoutCouponPreviewVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 结算预览里的单张优惠说明。 + */ +@Data +public class CheckoutCouponPreviewVO { + + private Long id; + + private Long couponId; + + private Long userCouponId; + + private String sourceType; + + private String couponName; + + private Integer couponType; + + private String couponTypeName; + + private BigDecimal discountValue; + + private BigDecimal minAmount; + + private BigDecimal reduceAmount; + + private BigDecimal discountAmount; + + private Boolean available; + + private Boolean best; + + private Boolean vipAuto; + + private String displayText; + + private String savingText; + + private String unavailableReason; + + private LocalDateTime startTime; + + private LocalDateTime endTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CheckoutPreviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CheckoutPreviewVO.java new file mode 100644 index 00000000..243a6f4d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/CheckoutPreviewVO.java @@ -0,0 +1,47 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * 结算页展示用预览结果。 + */ +@Data +public class CheckoutPreviewVO { + + private BigDecimal subtotalAmount = BigDecimal.ZERO; + + private BigDecimal savedAmount = BigDecimal.ZERO; + + private BigDecimal payableAmount = BigDecimal.ZERO; + + private CheckoutCouponPreviewVO bestCoupon; + + private List availableCoupons = new ArrayList<>(); + + private List unavailableCoupons = new ArrayList<>(); + + private Boolean bookingAvailable; + + private List bookingIssues = new ArrayList<>(); + + private String vipTip; + + private String summaryText; + + @Data + public static class CheckoutIssueVO { + private String code; + + private String message; + + private Long itemId; + + private Long productId; + + private String productTitle; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistChangeOptionsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistChangeOptionsVO.java new file mode 100644 index 00000000..4e8c7b90 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistChangeOptionsVO.java @@ -0,0 +1,71 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * Purpose: OrderArtistChangeOptionsVO supports OrderArtistChangeOptionsVO.java by holding or executing the order artist change options vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeOptionsVO { + /** + * Purpose: orderId supports OrderArtistChangeOptionsVO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistChangeOptionsVO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: currentArtistId supports OrderArtistChangeOptionsVO.java by holding or executing the current artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long currentArtistId; + /** + * Purpose: currentArtistName supports OrderArtistChangeOptionsVO.java by holding or executing the current artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String currentArtistName; + /** + * Purpose: artists supports OrderArtistChangeOptionsVO.java by holding or executing the artists business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private List artists; + + @Data + /** + * Purpose: ArtistOptionVO supports OrderArtistChangeOptionsVO.java by holding or executing the artist option vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class ArtistOptionVO { + /** + * Purpose: artistId supports OrderArtistChangeOptionsVO.java by holding or executing the artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long artistId; + /** + * Purpose: artistName supports OrderArtistChangeOptionsVO.java by holding or executing the artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistName; + /** + * Purpose: artistAvatar supports OrderArtistChangeOptionsVO.java by holding or executing the artist avatar business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistAvatar; + /** + * Purpose: userType supports OrderArtistChangeOptionsVO.java by holding or executing the user type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer userType; + /** + * Purpose: participateProduction supports OrderArtistChangeOptionsVO.java by holding or executing the participate production business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean participateProduction; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistChangeRequestVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistChangeRequestVO.java new file mode 100644 index 00000000..1ddfa313 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistChangeRequestVO.java @@ -0,0 +1,194 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * Purpose: OrderArtistChangeRequestVO supports OrderArtistChangeRequestVO.java by holding or executing the order artist change request vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRequestVO { + /** + * Purpose: id supports OrderArtistChangeRequestVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: orderId supports OrderArtistChangeRequestVO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistChangeRequestVO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: productId supports OrderArtistChangeRequestVO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + /** + * Purpose: productTitle supports OrderArtistChangeRequestVO.java by holding or executing the product title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String productTitle; + /** + * Purpose: shopId supports OrderArtistChangeRequestVO.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + /** + * Purpose: userId supports OrderArtistChangeRequestVO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: customerId supports OrderArtistChangeRequestVO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + /** + * Purpose: originalArtistId supports OrderArtistChangeRequestVO.java by holding or executing the original artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long originalArtistId; + /** + * Purpose: originalArtistName supports OrderArtistChangeRequestVO.java by holding or executing the original artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String originalArtistName; + /** + * Purpose: requestedArtistId supports OrderArtistChangeRequestVO.java by holding or executing the requested artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requestedArtistId; + /** + * Purpose: requestedArtistName supports OrderArtistChangeRequestVO.java by holding or executing the requested artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String requestedArtistName; + /** + * Purpose: fromArtistId supports OrderArtistChangeRequestVO.java by holding or executing the from artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long fromArtistId; + /** + * Purpose: fromArtistName supports OrderArtistChangeRequestVO.java by holding or executing the from artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String fromArtistName; + /** + * Purpose: toArtistId supports OrderArtistChangeRequestVO.java by holding or executing the to artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long toArtistId; + /** + * Purpose: toArtistName supports OrderArtistChangeRequestVO.java by holding or executing the to artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String toArtistName; + /** + * Purpose: requesterId supports OrderArtistChangeRequestVO.java by holding or executing the requester id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requesterId; + /** + * Purpose: requesterName supports OrderArtistChangeRequestVO.java by holding or executing the requester name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String requesterName; + /** + * Purpose: status supports OrderArtistChangeRequestVO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String status; + /** + * Purpose: statusText supports OrderArtistChangeRequestVO.java by holding or executing the status text business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String statusText; + /** + * Purpose: reason supports OrderArtistChangeRequestVO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + /** + * Purpose: rejectReason supports OrderArtistChangeRequestVO.java by holding or executing the reject reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String rejectReason; + /** + * Purpose: appointmentTime exposes the affected order-item appointment for customer-facing timelines. + * Usage: render this value beside the change request so users can confirm the change does not move their booking. + */ + private String appointmentTime; + /** + * Purpose: timeAffected tells clients whether the artist change modifies the booking time. + * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. + */ + private Boolean timeAffected; + /** + * Purpose: timeImpactText gives ready-to-display wording for the time impact. + * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. + */ + private String timeImpactText; + /** + * Purpose: originalPrice records the original order-item unit price for impact display. + * Usage: compare it with newPrice when rendering customer-facing price impact copy. + */ + private BigDecimal originalPrice; + /** + * Purpose: newPrice records the post-change order-item unit price for impact display. + * Usage: show it only when priceAffected is true or when detailed impact wording is needed. + */ + private BigDecimal newPrice; + /** + * Purpose: priceAffected tells clients whether the artist change modifies the order amount. + * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. + */ + private Boolean priceAffected; + /** + * Purpose: priceImpactText gives ready-to-display wording for the price impact. + * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. + */ + private String priceImpactText; + /** + * Purpose: reviewerId supports OrderArtistChangeRequestVO.java by holding or executing the reviewer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long reviewerId; + /** + * Purpose: messageId supports OrderArtistChangeRequestVO.java by holding or executing the message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long messageId; + /** + * Purpose: reviewTime supports OrderArtistChangeRequestVO.java by holding or executing the review time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime reviewTime; + /** + * Purpose: approvedTime supports OrderArtistChangeRequestVO.java by holding or executing the approved time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime approvedTime; + /** + * Purpose: rejectedTime supports OrderArtistChangeRequestVO.java by holding or executing the rejected time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime rejectedTime; + /** + * Purpose: expireTime supports OrderArtistChangeRequestVO.java by holding or executing the expire time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime expireTime; + /** + * Purpose: createTime supports OrderArtistChangeRequestVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistReviewVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistReviewVO.java new file mode 100644 index 00000000..d082d5d9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderArtistReviewVO.java @@ -0,0 +1,115 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * Purpose: OrderArtistReviewVO supports OrderArtistReviewVO.java by holding or executing the order artist review vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistReviewVO { + /** + * Purpose: id supports OrderArtistReviewVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: orderId supports OrderArtistReviewVO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistReviewVO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: productId supports OrderArtistReviewVO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + /** + * Purpose: productTitle supports OrderArtistReviewVO.java by holding or executing the product title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String productTitle; + /** + * Purpose: artistId supports OrderArtistReviewVO.java by holding or executing the artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long artistId; + /** + * Purpose: artistName supports OrderArtistReviewVO.java by holding or executing the artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistName; + /** + * Purpose: artistAvatar supports OrderArtistReviewVO.java by holding or executing the artist avatar business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistAvatar; + /** + * Purpose: userId supports OrderArtistReviewVO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: customerId supports OrderArtistReviewVO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + /** + * Purpose: rating supports OrderArtistReviewVO.java by holding or executing the rating business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal rating; + /** + * Purpose: ratingScore supports OrderArtistReviewVO.java by holding or executing the rating score business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal ratingScore; + /** + * Purpose: content supports OrderArtistReviewVO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + /** + * Purpose: imageFileIds supports OrderArtistReviewVO.java by holding or executing the image file ids business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private List imageFileIds; + /** + * Purpose: status supports OrderArtistReviewVO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + /** + * Purpose: statusText supports OrderArtistReviewVO.java by holding or executing the status text business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String statusText; + /** + * Purpose: reminderMessageId supports OrderArtistReviewVO.java by holding or executing the reminder message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long reminderMessageId; + /** + * Purpose: submitTime supports OrderArtistReviewVO.java by holding or executing the submit time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime submitTime; + /** + * Purpose: submittedAt supports OrderArtistReviewVO.java by holding or executing the submitted at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime submittedAt; + /** + * Purpose: createTime supports OrderArtistReviewVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderItemVO.java new file mode 100644 index 00000000..799ba15a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderItemVO.java @@ -0,0 +1,79 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +/** + * OrderItemVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderItemVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productImage; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + private BigDecimal referencePrice; + private BigDecimal quotedPrice; + private BigDecimal confirmedPrice; + /** + * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalPrice; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + /** + * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistName; + /** + * Field `artistAvatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistAvatar; + /** + * Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String appointmentTime; + private String occupancyStatus; + private Boolean canEdit; + private Boolean canCancel; + private String conflictReason; + /** + * Purpose: pendingReview supports OrderItemVO.java by holding or executing the pending review business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewVO pendingReview; + /** + * Purpose: reviewSummary supports OrderItemVO.java by holding or executing the review summary business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewVO reviewSummary; + /** + * Purpose: pendingArtistChangeRequest supports OrderItemVO.java by holding or executing the pending artist change request business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestVO pendingArtistChangeRequest; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderQuoteItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderQuoteItemVO.java new file mode 100644 index 00000000..bf25d6c5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderQuoteItemVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OrderQuoteItemVO { + private Long orderItemId; + private Long productId; + private String productTitle; + private Integer quantity; + private BigDecimal referencePrice; + private BigDecimal quotedPrice; + private BigDecimal confirmedPrice; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderQuoteMessageVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderQuoteMessageVO.java new file mode 100644 index 00000000..ef2509e9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderQuoteMessageVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class OrderQuoteMessageVO { + private Long id; + private Long orderId; + private Long actorId; + private String actorType; + private String actorTypeText; + private String action; + private String actionText; + private String remark; + private List items; + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderVO.java new file mode 100644 index 00000000..94ab80aa --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/order/vo/OrderVO.java @@ -0,0 +1,107 @@ +package com.xiaowang.jayucloud.artlist.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * OrderVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Purpose: shopName supports OrderVO.java by holding or executing the shop name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String shopName; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long couponId; + /** + * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userCouponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponSourceType; + /** + * Field `couponName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponName; + private String paymentStatus; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private LocalDateTime payTime; + private String paymentMethod; + private String paymentOrderNo; + private String refundStatus; + private String customerRemark; + private String quoteStatus; + private String quoteStatusText; + private Boolean quoteUserConfirmed; + private Boolean quoteShopConfirmed; + private LocalDateTime quoteExpireTime; + private LocalDateTime quoteConfirmedTime; + private List quoteMessages; + /** + * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerNickname; + /** + * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerPhoneMasked; + /** + * Field `artistOrderSource` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistOrderSource; + /** + * Field `artistOrderSourceText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistOrderSourceText; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `statusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String statusText; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `items` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List items; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/BalanceChangeDetailController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/BalanceChangeDetailController.java new file mode 100644 index 00000000..fe0360b2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/BalanceChangeDetailController.java @@ -0,0 +1,99 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.BalanceChangeDetailDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.service.BalanceChangeDetailService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户余额变动明细表 Controller + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"}) +@RequiredArgsConstructor +public class BalanceChangeDetailController { + /** + * Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceChangeDetailService balanceChangeDetailService; + + /** + * 创建余额变动明细 + * + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 余额变动明细ID + */ + @PostMapping("/create") + public Result createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { + Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO); + return Result.success(id); + } + + /** + * 更新余额变动明细 + * + * @param id 余额变动明细ID + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { + boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO); + return Result.success(success); + } + + /** + * 删除余额变动明细 + * + * @param id 余额变动明细ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteBalanceChangeDetail(@PathVariable Long id) { + boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id); + return Result.success(success); + } + + /** + * 根据ID查询余额变动明细 + * + * @param id 余额变动明细ID + * @return 余额变动明细VO + */ + @GetMapping("/get/{id}") + public Result getBalanceChangeDetailById(@PathVariable Long id) { + BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id); + return Result.success(balanceChangeDetailVO); + } + + /** + * 查询所有余额变动明细 + * + * @return 余额变动明细VO列表 + */ + @GetMapping("/list/all") + public Result> listAllBalanceChangeDetails() { + List balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails(); + return Result.success(balanceChangeDetailVOs); + } + + /** + * 根据用户ID查询余额变动明细 + * + * @param userId 用户ID + * @return 余额变动明细VO列表 + */ + @GetMapping("/list/user/{userId}") + public Result> listBalanceChangeDetailsByUserId(@PathVariable Long userId) { + List balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId); + return Result.success(balanceChangeDetailVOs); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/BalanceController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/BalanceController.java new file mode 100644 index 00000000..a9e34e77 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/BalanceController.java @@ -0,0 +1,99 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.BalanceDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceVO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.service.BalanceService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户余额信息表 Controller + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/balance", "/api/balance"}) +@RequiredArgsConstructor +public class BalanceController { + /** + * Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceService balanceService; + + /** + * 创建余额 + * + * @param balanceDTO 余额DTO + * @return 余额ID + */ + @PostMapping("/create") + public Result createBalance(@RequestBody BalanceDTO balanceDTO) { + Long id = balanceService.createBalance(balanceDTO); + return Result.success(id); + } + + /** + * 更新余额 + * + * @param id 余额ID + * @param balanceDTO 余额DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) { + boolean success = balanceService.updateBalance(id, balanceDTO); + return Result.success(success); + } + + /** + * 删除余额 + * + * @param id 余额ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteBalance(@PathVariable Long id) { + boolean success = balanceService.deleteBalance(id); + return Result.success(success); + } + + /** + * 根据ID查询余额 + * + * @param id 余额ID + * @return 余额VO + */ + @GetMapping("/get/{id}") + public Result getBalanceById(@PathVariable Long id) { + BalanceVO balanceVO = balanceService.getBalanceById(id); + return Result.success(balanceVO); + } + + /** + * 查询所有余额 + * + * @return 余额VO列表 + */ + @GetMapping("/list/all") + public Result> listAllBalances() { + List balanceVOs = balanceService.listAllBalances(); + return Result.success(balanceVOs); + } + + /** + * 根据用户ID查询余额 + * + * @param userId 用户ID + * @return 余额VO + */ + @GetMapping("/get/user/{userId}") + public Result getBalanceByUserId(@PathVariable Long userId) { + BalanceVO balanceVO = balanceService.getBalanceByUserId(userId); + return Result.success(balanceVO); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java new file mode 100644 index 00000000..4bdbc341 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java @@ -0,0 +1,32 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.payment.service.PaymentService; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.PaymentOrderVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/payment") +@RequiredArgsConstructor +public class PaymentController { + + private final PaymentService paymentService; + + @PostMapping("/order/{orderId}/prepare") + public Result prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(paymentService.prepareOrderPayment(userId, orderId)); + } + + @PostMapping("/order/{orderId}/mock-success") + public Result mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/dto/BalanceChangeDetailDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/dto/BalanceChangeDetailDTO.java new file mode 100644 index 00000000..34164578 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/dto/BalanceChangeDetailDTO.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额变动明细表 DTO + * 用于余额变动明细信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceChangeDetailDTO { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 本次变动金额(正数为增加,负数为减少) + */ + private BigDecimal amount; + + /** + * 变动类型(如充值、消费、退款) + */ + private String type; + + /** + * 变动后的当前余额 + */ + private BigDecimal currentBalance; + /** + * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal beforeBalance; + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal afterBalance; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relatedOrderNo; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long operatorId; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + /** + * 变动时间 + */ + private LocalDateTime changeTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/dto/BalanceDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/dto/BalanceDTO.java new file mode 100644 index 00000000..cd9d724a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/dto/BalanceDTO.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额信息表 DTO + * 用于余额信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceDTO { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 当前余额 + */ + private BigDecimal amount; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/BalanceChangeDetailDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/BalanceChangeDetailDO.java new file mode 100644 index 00000000..d4439e28 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/BalanceChangeDetailDO.java @@ -0,0 +1,106 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额变动明细表 DO + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@TableName("t_balance_change_detail") +public class BalanceChangeDetailDO { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 本次变动金额(正数为增加,负数为减少) + */ + @TableField("amount") + private BigDecimal amount; + + /** + * 变动类型(如充值、消费、退款) + */ + @TableField("type") + private String type; + + /** + * 变动后的当前余额 + */ + @TableField("current_balance") + private BigDecimal currentBalance; + + /** + * 变动时间 + */ + @TableField("before_balance") + private BigDecimal beforeBalance; + + @TableField("after_balance") + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal afterBalance; + + @TableField("change_scene") + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + + @TableField("related_order_id") + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + + @TableField("related_order_no") + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relatedOrderNo; + + @TableField("external_order_no") + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + + @TableField("operator_id") + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long operatorId; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("change_time") + /** + * Field `changeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime changeTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/BalanceDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/BalanceDO.java new file mode 100644 index 00000000..db99f284 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/BalanceDO.java @@ -0,0 +1,67 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额信息表 DO + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@TableName("t_balance") +public class BalanceDO { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Purpose: id supports BalanceDO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + + @TableField(fill = FieldFill.INSERT) + /** + * Purpose: createTime supports BalanceDO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 当前余额 + */ + @TableField("amount") + private BigDecimal amount; + + /** + * 最近一次更新时间 + */ + @TableField("total_recharge_amount") + private BigDecimal totalRechargeAmount; + + @TableField("last_recharge_time") + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; + + @TableField("last_update_time") + /** + * Field `lastUpdateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastUpdateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/PaymentOrderDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/PaymentOrderDO.java new file mode 100644 index 00000000..d2fc5c73 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/PaymentOrderDO.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_payment_order") +public class PaymentOrderDO extends BaseEntity { + @TableField("pay_no") + private String payNo; + @TableField("order_id") + private Long orderId; + @TableField("order_no") + private String orderNo; + @TableField("user_id") + private Long userId; + @TableField("shop_id") + private Long shopId; + @TableField("channel") + private String channel; + @TableField("status") + private String status; + @TableField("pay_amount") + private BigDecimal payAmount; + @TableField("paid_amount") + private BigDecimal paidAmount; + @TableField("pay_time") + private LocalDateTime payTime; + @TableField("expire_time") + private LocalDateTime expireTime; + @TableField("operator_id") + private Long operatorId; + @TableField("remark") + private String remark; + @TableField("idempotency_key") + private String idempotencyKey; + @TableField("raw_payload") + private String rawPayload; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/RefundOrderDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/RefundOrderDO.java new file mode 100644 index 00000000..8b8da4e9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/entity/RefundOrderDO.java @@ -0,0 +1,42 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_refund_order") +public class RefundOrderDO extends BaseEntity { + @TableField("refund_no") + private String refundNo; + @TableField("after_sale_id") + private Long afterSaleId; + @TableField("payment_order_id") + private Long paymentOrderId; + @TableField("order_id") + private Long orderId; + @TableField("status") + private String status; + @TableField("refund_amount") + private BigDecimal refundAmount; + @TableField("refund_time") + private LocalDateTime refundTime; + @TableField("channel") + private String channel; + @TableField("external_refund_no") + private String externalRefundNo; + @TableField("fail_reason") + private String failReason; + @TableField("idempotency_key") + private String idempotencyKey; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/BalanceChangeDetailMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/BalanceChangeDetailMapper.java new file mode 100644 index 00000000..ef3dfd86 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/BalanceChangeDetailMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceChangeDetailDO; + +/** + * 用户余额变动明细表 Mapper + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceChangeDetailMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/BalanceMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/BalanceMapper.java new file mode 100644 index 00000000..26295d6a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/BalanceMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceDO; + +/** + * 用户余额信息表 Mapper + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/PaymentOrderMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/PaymentOrderMapper.java new file mode 100644 index 00000000..d6fdbdad --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/PaymentOrderMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.PaymentOrderDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +@Mapper +public interface PaymentOrderMapper extends BaseMapper { + @Select("SELECT * FROM t_payment_order WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time DESC, id DESC LIMIT 1") + PaymentOrderDO selectLatestByOrderId(@Param("orderId") Long orderId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/RefundOrderMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/RefundOrderMapper.java new file mode 100644 index 00000000..9c125c4a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/mapper/RefundOrderMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.RefundOrderDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface RefundOrderMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/BalanceChangeDetailService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/BalanceChangeDetailService.java new file mode 100644 index 00000000..e5d25795 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/BalanceChangeDetailService.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceChangeDetailDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.BalanceChangeDetailDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceChangeDetailVO; + +import java.util.List; + +/** + * 用户余额变动明细表 Service + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceChangeDetailService extends IService { + + /** + * 创建余额变动明细 + * + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 余额变动明细ID + */ + Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO); + + /** + * 更新余额变动明细 + * + * @param id 余额变动明细ID + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 是否更新成功 + */ + boolean updateBalanceChangeDetail(Long id, BalanceChangeDetailDTO balanceChangeDetailDTO); + + /** + * 删除余额变动明细 + * + * @param id 余额变动明细ID + * @return 是否删除成功 + */ + boolean deleteBalanceChangeDetail(Long id); + + /** + * 根据ID查询余额变动明细 + * + * @param id 余额变动明细ID + * @return 余额变动明细VO + */ + BalanceChangeDetailVO getBalanceChangeDetailById(Long id); + + /** + * 查询所有余额变动明细 + * + * @return 余额变动明细VO列表 + */ + List listAllBalanceChangeDetails(); + + /** + * 根据用户ID查询余额变动明细 + * + * @param userId 用户ID + * @return 余额变动明细VO列表 + */ + List listBalanceChangeDetailsByUserId(Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/BalanceService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/BalanceService.java new file mode 100644 index 00000000..28cea2f2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/BalanceService.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.BalanceDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceVO; + +import java.util.List; + +/** + * 用户余额信息表 Service + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceService extends IService { + + /** + * 创建余额 + * + * @param balanceDTO 余额DTO + * @return 余额ID + */ + Long createBalance(BalanceDTO balanceDTO); + + /** + * 更新余额 + * + * @param id 余额ID + * @param balanceDTO 余额DTO + * @return 是否更新成功 + */ + boolean updateBalance(Long id, BalanceDTO balanceDTO); + + /** + * 删除余额 + * + * @param id 余额ID + * @return 是否删除成功 + */ + boolean deleteBalance(Long id); + + /** + * 根据ID查询余额 + * + * @param id 余额ID + * @return 余额VO + */ + BalanceVO getBalanceById(Long id); + + /** + * 查询所有余额 + * + * @return 余额VO列表 + */ + List listAllBalances(); + + /** + * 根据用户ID查询余额 + * + * @param userId 用户ID + * @return 余额VO + */ + BalanceVO getBalanceByUserId(Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java new file mode 100644 index 00000000..87ed325a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.service; + +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.PaymentOrderVO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.RefundOrderVO; + +public interface PaymentService { + PaymentOrderVO prepareOrderPayment(Long userId, Long orderId); + + PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark); + + RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java new file mode 100644 index 00000000..a8cbc9b3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java @@ -0,0 +1,172 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceChangeDetailDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.BalanceChangeDetailDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.mapper.BalanceChangeDetailMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.service.BalanceChangeDetailService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户余额变动明细表 Service 实现 + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class BalanceChangeDetailServiceImpl extends ServiceImpl implements BalanceChangeDetailService { + /** + * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceChangeDetailMapper balanceChangeDetailMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO) { + BalanceChangeDetailDO balanceChangeDetailDO = new BalanceChangeDetailDO(); + balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); + balanceChangeDetailDO.setAmount(balanceChangeDetailDTO.getAmount()); + balanceChangeDetailDO.setType(balanceChangeDetailDTO.getType()); + balanceChangeDetailDO.setCurrentBalance(balanceChangeDetailDTO.getCurrentBalance()); + balanceChangeDetailDO.setBeforeBalance(balanceChangeDetailDTO.getBeforeBalance()); + balanceChangeDetailDO.setAfterBalance(balanceChangeDetailDTO.getAfterBalance()); + balanceChangeDetailDO.setChangeScene(balanceChangeDetailDTO.getChangeScene()); + balanceChangeDetailDO.setRelatedOrderId(balanceChangeDetailDTO.getRelatedOrderId()); + balanceChangeDetailDO.setRelatedOrderNo(balanceChangeDetailDTO.getRelatedOrderNo()); + balanceChangeDetailDO.setExternalOrderNo(balanceChangeDetailDTO.getExternalOrderNo()); + balanceChangeDetailDO.setOperatorId(balanceChangeDetailDTO.getOperatorId()); + balanceChangeDetailDO.setRemark(balanceChangeDetailDTO.getRemark()); + balanceChangeDetailDO.setChangeTime(balanceChangeDetailDTO.getChangeTime()); + balanceChangeDetailMapper.insert(balanceChangeDetailDO); + return balanceChangeDetailDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateBalanceChangeDetail(Long id, BalanceChangeDetailDTO balanceChangeDetailDTO) { + BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); + if (balanceChangeDetailDO == null) { + return false; + } + balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); + balanceChangeDetailDO.setAmount(balanceChangeDetailDTO.getAmount()); + balanceChangeDetailDO.setType(balanceChangeDetailDTO.getType()); + balanceChangeDetailDO.setCurrentBalance(balanceChangeDetailDTO.getCurrentBalance()); + balanceChangeDetailDO.setBeforeBalance(balanceChangeDetailDTO.getBeforeBalance()); + balanceChangeDetailDO.setAfterBalance(balanceChangeDetailDTO.getAfterBalance()); + balanceChangeDetailDO.setChangeScene(balanceChangeDetailDTO.getChangeScene()); + balanceChangeDetailDO.setRelatedOrderId(balanceChangeDetailDTO.getRelatedOrderId()); + balanceChangeDetailDO.setRelatedOrderNo(balanceChangeDetailDTO.getRelatedOrderNo()); + balanceChangeDetailDO.setExternalOrderNo(balanceChangeDetailDTO.getExternalOrderNo()); + balanceChangeDetailDO.setOperatorId(balanceChangeDetailDTO.getOperatorId()); + balanceChangeDetailDO.setRemark(balanceChangeDetailDTO.getRemark()); + balanceChangeDetailDO.setChangeTime(balanceChangeDetailDTO.getChangeTime()); + return balanceChangeDetailMapper.updateById(balanceChangeDetailDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteBalanceChangeDetail(Long id) { + return balanceChangeDetailMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return BalanceChangeDetailVO result consumed by the caller or returned to the frontend + */ + public BalanceChangeDetailVO getBalanceChangeDetailById(Long id) { + BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); + if (balanceChangeDetailDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceChangeDetailDO parameter `balanceChangeDetailDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(balanceChangeDetailDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllBalanceChangeDetails() { + List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList(null); + return balanceChangeDetailDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listBalanceChangeDetailsByUserId(Long userId) { + List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList( + Wrappers.lambdaQuery(BalanceChangeDetailDO.class) + .eq(BalanceChangeDetailDO::getUserId, userId) + ); + return balanceChangeDetailDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param balanceChangeDetailDO 余额变动明细DO + * @return 余额变动明细VO + */ + private BalanceChangeDetailVO convertToVO(BalanceChangeDetailDO balanceChangeDetailDO) { + BalanceChangeDetailVO balanceChangeDetailVO = new BalanceChangeDetailVO(); + balanceChangeDetailVO.setId(balanceChangeDetailDO.getId()); + balanceChangeDetailVO.setUserId(balanceChangeDetailDO.getUserId()); + balanceChangeDetailVO.setAmount(balanceChangeDetailDO.getAmount()); + balanceChangeDetailVO.setType(balanceChangeDetailDO.getType()); + balanceChangeDetailVO.setCurrentBalance(balanceChangeDetailDO.getCurrentBalance()); + balanceChangeDetailVO.setBeforeBalance(balanceChangeDetailDO.getBeforeBalance()); + balanceChangeDetailVO.setAfterBalance(balanceChangeDetailDO.getAfterBalance()); + balanceChangeDetailVO.setChangeScene(balanceChangeDetailDO.getChangeScene()); + balanceChangeDetailVO.setRelatedOrderId(balanceChangeDetailDO.getRelatedOrderId()); + balanceChangeDetailVO.setRelatedOrderNo(balanceChangeDetailDO.getRelatedOrderNo()); + balanceChangeDetailVO.setExternalOrderNo(balanceChangeDetailDO.getExternalOrderNo()); + balanceChangeDetailVO.setOperatorId(balanceChangeDetailDO.getOperatorId()); + balanceChangeDetailVO.setRemark(balanceChangeDetailDO.getRemark()); + balanceChangeDetailVO.setChangeTime(balanceChangeDetailDO.getChangeTime()); + return balanceChangeDetailVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/BalanceServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/BalanceServiceImpl.java new file mode 100644 index 00000000..0deec31f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/BalanceServiceImpl.java @@ -0,0 +1,157 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.BalanceDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.mapper.BalanceMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.service.BalanceService; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户余额信息表 Service 实现 + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class BalanceServiceImpl extends ServiceImpl implements BalanceService { + /** + * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceMapper balanceMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDTO parameter `balanceDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createBalance(BalanceDTO balanceDTO) { + BalanceDO balanceDO = new BalanceDO(); + balanceDO.setUserId(balanceDTO.getUserId()); + balanceDO.setAmount(balanceDTO.getAmount()); + balanceDO.setTotalRechargeAmount(balanceDTO.getTotalRechargeAmount()); + balanceDO.setLastRechargeTime(balanceDTO.getLastRechargeTime()); + balanceDO.setLastUpdateTime(LocalDateTime.now()); + balanceMapper.insert(balanceDO); + return balanceDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param balanceDTO parameter `balanceDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateBalance(Long id, BalanceDTO balanceDTO) { + BalanceDO balanceDO = balanceMapper.selectById(id); + if (balanceDO == null) { + return false; + } + balanceDO.setUserId(balanceDTO.getUserId()); + balanceDO.setAmount(balanceDTO.getAmount()); + balanceDO.setTotalRechargeAmount(balanceDTO.getTotalRechargeAmount()); + balanceDO.setLastRechargeTime(balanceDTO.getLastRechargeTime()); + balanceDO.setLastUpdateTime(LocalDateTime.now()); + return balanceMapper.updateById(balanceDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteBalance(Long id) { + return balanceMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return BalanceVO result consumed by the caller or returned to the frontend + */ + public BalanceVO getBalanceById(Long id) { + BalanceDO balanceDO = balanceMapper.selectById(id); + if (balanceDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDO parameter `balanceDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(balanceDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllBalances() { + List balanceDOs = balanceMapper.selectList(null); + return balanceDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return BalanceVO result consumed by the caller or returned to the frontend + */ + public BalanceVO getBalanceByUserId(Long userId) { + BalanceDO balanceDO = balanceMapper.selectOne( + Wrappers.lambdaQuery(BalanceDO.class) + .eq(BalanceDO::getUserId, userId) + ); + if (balanceDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDO parameter `balanceDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(balanceDO); + } + + /** + * 将 DO 转换为 VO + * + * @param balanceDO 余额DO + * @return 余额VO + */ + private BalanceVO convertToVO(BalanceDO balanceDO) { + BalanceVO balanceVO = new BalanceVO(); + balanceVO.setId(balanceDO.getId()); + balanceVO.setUserId(balanceDO.getUserId()); + balanceVO.setAmount(balanceDO.getAmount()); + balanceVO.setTotalRechargeAmount(balanceDO.getTotalRechargeAmount()); + balanceVO.setLastRechargeTime(balanceDO.getLastRechargeTime()); + balanceVO.setCreateTime(balanceDO.getCreateTime()); + balanceVO.setLastUpdateTime(balanceDO.getLastUpdateTime()); + return balanceVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java new file mode 100644 index 00000000..b31d0ad3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java @@ -0,0 +1,157 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.PaymentOrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.RefundOrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.mapper.PaymentOrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.mapper.RefundOrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.service.PaymentService; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.PaymentOrderVO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.RefundOrderVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class PaymentServiceImpl implements PaymentService { + + private static final String CHANNEL_MANUAL = "MANUAL"; + private static final String STATUS_UNPAID = "UNPAID"; + private static final String STATUS_PAYING = "PAYING"; + private static final String STATUS_PAID = "PAID"; + private static final String STATUS_REFUNDED = "REFUNDED"; + + private final OrderMapper orderMapper; + private final PaymentOrderMapper paymentOrderMapper; + private final RefundOrderMapper refundOrderMapper; + + @Override + @Transactional + public PaymentOrderVO prepareOrderPayment(Long userId, Long orderId) { + OrderDO order = requirePayableOrder(userId, orderId); + PaymentOrderDO latest = paymentOrderMapper.selectLatestByOrderId(orderId); + if (latest != null && (STATUS_PAYING.equals(latest.getStatus()) || STATUS_PAID.equals(latest.getStatus()))) { + return toVO(latest); + } + PaymentOrderDO payment = new PaymentOrderDO(); + payment.setPayNo("PAY" + System.currentTimeMillis() + orderId); + payment.setOrderId(order.getId()); + payment.setOrderNo(order.getOrderNo()); + payment.setUserId(order.getUserId()); + payment.setShopId(order.getShopId()); + payment.setChannel(CHANNEL_MANUAL); + payment.setStatus(STATUS_PAYING); + payment.setPayAmount(order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()); + payment.setPaidAmount(BigDecimal.ZERO); + payment.setExpireTime(LocalDateTime.now().plusMinutes(30)); + payment.setIdempotencyKey("PAY:" + order.getId()); + payment.setIsDelete(0); + paymentOrderMapper.insert(payment); + order.setPaymentStatus(STATUS_PAYING); + order.setPaymentOrderNo(payment.getPayNo()); + order.setPayAmount(payment.getPayAmount()); + orderMapper.updateById(order); + return toVO(payment); + } + + @Override + @Transactional + public PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark) { + OrderDO order = requirePayableOrder(null, orderId); + PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); + if (payment == null) { + prepareOrderPayment(order.getUserId(), orderId); + payment = paymentOrderMapper.selectLatestByOrderId(orderId); + } + if (payment == null) { + throw new RuntimeException("支付单创建失败"); + } + payment.setStatus(STATUS_PAID); + payment.setPaidAmount(payment.getPayAmount()); + payment.setPayTime(LocalDateTime.now()); + payment.setOperatorId(operatorId); + payment.setRemark(remark); + paymentOrderMapper.updateById(payment); + + order.setPaymentStatus(STATUS_PAID); + order.setPaidAmount(payment.getPayAmount()); + order.setPayTime(payment.getPayTime()); + order.setPaymentMethod(payment.getChannel()); + order.setPaymentOrderNo(payment.getPayNo()); + orderMapper.updateById(order); + return toVO(payment); + } + + @Override + @Transactional + public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("璁㈠崟涓嶅瓨鍦?"); + } + if (!STATUS_PAID.equals(order.getPaymentStatus())) { + throw new RuntimeException("鏈敮浠樿鍗曚笉鍏佽閫€娆?"); + } + PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); + if (payment == null || !STATUS_PAID.equals(payment.getStatus())) { + throw new RuntimeException("鏈壘鍒板凡鏀粯鏀粯鍗?"); + } + RefundOrderDO refund = new RefundOrderDO(); + refund.setRefundNo("RF" + System.currentTimeMillis() + orderId); + refund.setAfterSaleId(afterSaleId); + refund.setPaymentOrderId(payment.getId()); + refund.setOrderId(order.getId()); + refund.setStatus(STATUS_REFUNDED); + refund.setRefundAmount(payment.getPaidAmount() == null ? payment.getPayAmount() : payment.getPaidAmount()); + refund.setRefundTime(LocalDateTime.now()); + refund.setChannel(payment.getChannel()); + refund.setExternalRefundNo(refund.getRefundNo()); + refund.setFailReason(remark); + refund.setIdempotencyKey("REFUND:" + order.getId() + ":" + (afterSaleId == null ? 0 : afterSaleId)); + refund.setIsDelete(0); + refundOrderMapper.insert(refund); + + order.setRefundStatus(STATUS_REFUNDED); + order.setPaymentStatus(STATUS_REFUNDED); + orderMapper.updateById(order); + return toVO(refund); + } + + private OrderDO requirePayableOrder(Long userId, Long orderId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + if (userId != null && !userId.equals(order.getUserId())) { + throw new RuntimeException("无权支付该订单"); + } + if (Integer.valueOf(0).equals(order.getStatus())) { + throw new RuntimeException("询价预约确认价格前暂不能支付"); + } + if (STATUS_PAID.equals(order.getPaymentStatus())) { + throw new RuntimeException("订单已支付"); + } + if (order.getPaymentStatus() == null) { + order.setPaymentStatus(STATUS_UNPAID); + } + return order; + } + + private PaymentOrderVO toVO(PaymentOrderDO payment) { + PaymentOrderVO vo = new PaymentOrderVO(); + BeanUtils.copyProperties(payment, vo); + return vo; + } + + private RefundOrderVO toVO(RefundOrderDO refund) { + RefundOrderVO vo = new RefundOrderVO(); + BeanUtils.copyProperties(refund, vo); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/BalanceChangeDetailVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/BalanceChangeDetailVO.java new file mode 100644 index 00000000..82d1d0d4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/BalanceChangeDetailVO.java @@ -0,0 +1,84 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额变动明细表 VO + * 用于前端展示余额变动明细信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceChangeDetailVO { + + /** + * 变动记录唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 本次变动金额(正数为增加,负数为减少) + */ + private BigDecimal amount; + + /** + * 变动类型(如充值、消费、退款) + */ + private String type; + + /** + * 变动后的当前余额 + */ + private BigDecimal currentBalance; + /** + * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal beforeBalance; + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal afterBalance; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relatedOrderNo; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long operatorId; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + /** + * 变动时间 + */ + private LocalDateTime changeTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/BalanceVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/BalanceVO.java new file mode 100644 index 00000000..aa381034 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/BalanceVO.java @@ -0,0 +1,55 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额信息表 VO + * 用于前端展示余额信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceVO { + + /** + * 余额记录唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 当前余额 + */ + private BigDecimal amount; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; + + /** + * 余额账户创建时间 + */ + private LocalDateTime createTime; + + /** + * 最近一次更新时间 + */ + private LocalDateTime lastUpdateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/PaymentOrderVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/PaymentOrderVO.java new file mode 100644 index 00000000..8cfcff31 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/PaymentOrderVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +public class PaymentOrderVO { + private Long id; + private String payNo; + private Long orderId; + private String orderNo; + private Long userId; + private Long shopId; + private String channel; + private String status; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private LocalDateTime payTime; + private LocalDateTime expireTime; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/RefundOrderVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/RefundOrderVO.java new file mode 100644 index 00000000..34f6528e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/vo/RefundOrderVO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.artlist.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +public class RefundOrderVO { + private Long id; + private String refundNo; + private Long afterSaleId; + private Long paymentOrderId; + private Long orderId; + private String status; + private BigDecimal refundAmount; + private LocalDateTime refundTime; + private String channel; + private String externalRefundNo; + private String failReason; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java new file mode 100644 index 00000000..adbf959a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class PlanningAppointmentCreateDTO { + private Long customerUserId; + private String customerName; + private String phone; + private Long productId; + private Integer quantity; + private Long artistId; + private String appointmentDate; + private String appointmentTime; + private String appointmentStartTime; + private Integer durationMinutes; + private String manualProductTitle; + private BigDecimal manualProductPrice; + private String manualProductDescription; + private String manualProductTags; + private String manualProductTargetAudience; + private String manualProductPrecautions; + private String manualProductImageFileIds; + private String remark; + private String clientRequestId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java new file mode 100644 index 00000000..c3b5aafb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.dto; + +import lombok.Data; + +@Data +public class PlanningAppointmentMoveDTO { + private Long artistId; + private String appointmentDate; + private String appointmentTime; + private String appointmentStartTime; + private Integer durationMinutes; + private String clientRequestId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java new file mode 100644 index 00000000..12d8b336 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.dto; + +import lombok.Data; + +@Data +public class PlanningAppointmentStatusDTO { + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningManagerRegisterDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningManagerRegisterDTO.java new file mode 100644 index 00000000..d6e66623 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningManagerRegisterDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class PlanningManagerRegisterDTO { + + private String phone; + + private String code; + + private String password; + + private String confirmPassword; + + private String shopName; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/entity/AppointmentReservationDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/entity/AppointmentReservationDO.java new file mode 100644 index 00000000..f5fa07b6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/entity/AppointmentReservationDO.java @@ -0,0 +1,37 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_appointment_reservation") +public class AppointmentReservationDO extends BaseEntity { + @TableField("order_id") + private Long orderId; + @TableField("order_item_id") + private Long orderItemId; + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("product_title") + private String productTitle; + @TableField("appointment_start_time") + private LocalDateTime appointmentStartTime; + @TableField("appointment_end_time") + private LocalDateTime appointmentEndTime; + @TableField("status") + private String status; + @TableField("client_request_id") + private String clientRequestId; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/mapper/AppointmentReservationMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/mapper/AppointmentReservationMapper.java new file mode 100644 index 00000000..595f712d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/mapper/AppointmentReservationMapper.java @@ -0,0 +1,92 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.entity.AppointmentReservationDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Mapper +public interface AppointmentReservationMapper extends BaseMapper { + String ACTIVE_STATUS_SQL = "('LOCKED','PENDING_QUOTE','CONFIRMED')"; + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") + int countOverlappingActiveForUpdate(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + + "AND order_item_id <> #{orderItemId} AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") + int countOverlappingActiveForUpdateExcludingOrderItem(@Param("artistId") Long artistId, + @Param("orderItemId") Long orderItemId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime}") + int countOverlappingActive(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) FOR UPDATE") + int countActiveByArtistAndDateForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) " + + "AND (TIME(appointment_start_time) < #{startTime} OR TIME(appointment_end_time) > #{endTime}) FOR UPDATE") + int countActiveOutsideScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") java.time.LocalTime startTime, + @Param("endTime") java.time.LocalTime endTime); + + @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + + "WHERE order_id = #{orderId} AND is_delete = 0") + int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status); + + @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + + "WHERE order_item_id = #{orderItemId} AND is_delete = 0") + int releaseByOrderItem(@Param("orderItemId") Long orderItemId, @Param("status") String status); + + @Update("UPDATE t_appointment_reservation SET order_id = #{orderId}, shop_id = #{shopId}, " + + "artist_id = #{artistId}, product_title = #{productTitle}, " + + "appointment_start_time = #{startTime}, appointment_end_time = #{endTime}, " + + "status = #{status}, is_delete = 0, update_time = NOW() " + + "WHERE order_item_id = #{orderItemId} AND is_delete = 0") + int updateActiveReservationForOrderItem(@Param("orderItemId") Long orderItemId, + @Param("orderId") Long orderId, + @Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("productTitle") String productTitle, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime, + @Param("status") String status); + + @Update("UPDATE t_appointment_reservation SET order_id = #{orderId}, shop_id = #{shopId}, " + + "artist_id = #{artistId}, product_title = #{productTitle}, " + + "appointment_start_time = #{startTime}, appointment_end_time = #{endTime}, " + + "status = #{status}, client_request_id = COALESCE(#{clientRequestId}, client_request_id), is_delete = 0, update_time = NOW() " + + "WHERE order_item_id = #{orderItemId} AND is_delete = 0") + int updateActiveReservationForOrderItemWithClientRequest(@Param("orderItemId") Long orderItemId, + @Param("orderId") Long orderId, + @Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("productTitle") String productTitle, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime, + @Param("status") String status, + @Param("clientRequestId") String clientRequestId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/AppointmentCapacityService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/AppointmentCapacityService.java new file mode 100644 index 00000000..a8927fd2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/AppointmentCapacityService.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.service; + +import java.time.LocalDateTime; + +public interface AppointmentCapacityService { + void reserveOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime); + + void reservePendingQuoteOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId); + + void reserveConfirmedOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId); + + void confirmReservationOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime); + + void releaseByOrder(Long orderId); + + void moveReservationForArtistChange(Long orderId, Long orderItemId, Long shopId, Long fromArtistId, + Long toArtistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java new file mode 100644 index 00000000..e1de78fa --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java @@ -0,0 +1,22 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.service; + +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentMoveDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningAppointmentVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningCalendarVO; + +import java.time.LocalDate; + +public interface PlanningService { + PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId); + + PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto); + + PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId); + + PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto); + + Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java new file mode 100644 index 00000000..74ec743f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java @@ -0,0 +1,153 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.service.impl; + +import com.xiaowang.jayucloud.artlist.core.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.service.AppointmentCapacityService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class AppointmentCapacityServiceImpl implements AppointmentCapacityService { + + private static final int MIN_CAPACITY = 1; + public static final String STATUS_PENDING_QUOTE = "PENDING_QUOTE"; + private static final String STATUS_CONFIRMED = "CONFIRMED"; + private static final String STATUS_RELEASED = "RELEASED"; + private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害"; + private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿"; + + private final AppointmentReservationMapper reservationMapper; + private final ArtistScheduleMapper scheduleMapper; + + @Override + @Transactional + public void reserveOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_CONFIRMED, null, null); + } + + @Override + @Transactional + public void reservePendingQuoteOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_PENDING_QUOTE, clientRequestId, null); + } + + @Override + @Transactional + public void reserveConfirmedOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_CONFIRMED, clientRequestId, null); + } + + @Override + @Transactional + public void confirmReservationOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_CONFIRMED, null, orderItemId); + } + + private void reserveWithStatusOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String status, + String clientRequestId, Long excludedOrderItemId) { + if (orderId == null || orderItemId == null || shopId == null || artistId == null || startTime == null || endTime == null) { + return; + } + assertCapacityAvailable(shopId, artistId, excludedOrderItemId, startTime, endTime); + int updated = reservationMapper.updateActiveReservationForOrderItemWithClientRequest( + orderItemId, + orderId, + shopId, + artistId, + productTitle, + startTime, + endTime, + status, + clientRequestId + ); + if (updated > 0) { + return; + } + AppointmentReservationDO reservation = new AppointmentReservationDO(); + reservation.setOrderId(orderId); + reservation.setOrderItemId(orderItemId); + reservation.setShopId(shopId); + reservation.setArtistId(artistId); + reservation.setProductTitle(productTitle); + reservation.setAppointmentStartTime(startTime); + reservation.setAppointmentEndTime(endTime); + reservation.setStatus(status); + reservation.setClientRequestId(clientRequestId); + reservation.setIsDelete(0); + reservationMapper.insert(reservation); + } + + @Override + @Transactional + public void releaseByOrder(Long orderId) { + if (orderId != null) { + reservationMapper.releaseByOrderId(orderId, STATUS_RELEASED); + } + } + + @Override + @Transactional + public void moveReservationForArtistChange(Long orderId, Long orderItemId, Long shopId, Long fromArtistId, + Long toArtistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime) { + if (orderItemId == null || orderId == null || shopId == null || toArtistId == null || startTime == null || endTime == null) { + return; + } + assertCapacityAvailable(shopId, toArtistId, orderItemId, startTime, endTime); + int updated = reservationMapper.updateActiveReservationForOrderItem( + orderItemId, + orderId, + shopId, + toArtistId, + productTitle, + startTime, + endTime, + STATUS_CONFIRMED + ); + if (updated == 0) { + reserveOrThrow(orderId, orderItemId, shopId, toArtistId, productTitle, startTime, endTime); + } + } + + private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId, + LocalDateTime startTime, LocalDateTime endTime) { + int capacity = resolveCapacity(shopId, artistId, startTime, endTime); + int used = excludedOrderItemId == null + ? reservationMapper.countOverlappingActiveForUpdate(artistId, startTime, endTime) + : reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime); + if (used >= capacity) { + throw new RuntimeException(FULL_MESSAGE); + } + } + + private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule( + shopId, + artistId, + startTime.toLocalDate(), + startTime.toLocalTime(), + endTime.toLocalTime() + ); + if (schedule == null || Integer.valueOf(1).equals(schedule.getIsDelete()) + || !Integer.valueOf(1).equals(schedule.getStatus()) + || schedule.getCapacity() == null || schedule.getCapacity() < MIN_CAPACITY) { + throw new RuntimeException(UNAVAILABLE_MESSAGE); + } + return schedule.getCapacity(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java new file mode 100644 index 00000000..e8e19b27 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -0,0 +1,901 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentMoveDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.jayucloud.artlist.core.modules.order.service.OrderService; +import com.xiaowang.jayucloud.artlist.core.modules.planning.service.PlanningService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.artlist.core.modules.planning.support.PlanningCalendarSupport; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningAppointmentVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningArtistCountVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningArtistVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningCalendarVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningDaySummaryVO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningScheduleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class PlanningServiceImpl implements PlanningService { + + private static final int DEFAULT_SLOT_MINUTES = 30; + private static final int DEFAULT_DURATION_MINUTES = 60; + private static final int MONTH_AVAILABLE_MINUTES = 90; + private static final String RESERVATION_PENDING_QUOTE = "PENDING_QUOTE"; + private static final String RESERVATION_CONFIRMED = "CONFIRMED"; + private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT"; + private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; + private static final List ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED); + private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private static final List ARTIST_COLORS = List.of( + "#7BA7C7", "#8FB89A", "#A894C7", "#D7A86E", "#D98DA5", "#79A6A3", "#B9A16B", "#9BA9C8" + ); + + private final AdminScopeHelper adminScopeHelper; + private final UserMapper userMapper; + private final NailArtistInfoMapper nailArtistInfoMapper; + private final ArtistScheduleMapper artistScheduleMapper; + private final AppointmentReservationMapper appointmentReservationMapper; + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final ProductMapper productMapper; + private final ShopMapper shopMapper; + private final AppointmentCapacityService appointmentCapacityService; + private final OrderService orderService; + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Override + public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) { + LocalDate start = startDate == null ? LocalDate.now() : startDate; + LocalDate end = endDate == null ? start : endDate; + if (end.isBefore(start)) { + end = start; + } + if (start.plusDays(61).isBefore(end)) { + end = start.plusDays(61); + } + + Long shopId = requirePlanningShopId(currentUser); + ShopDO shop = shopMapper.selectById(shopId); + PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours( + shop == null ? null : shop.getBusinessHours() + ); + + List artists = listArtists(shopId, artistId); + List schedules = listSchedules(shopId, start, end, artistId); + List scheduleVos = schedules.stream() + .map(schedule -> toScheduleVO(schedule, artists)) + .sorted(Comparator.comparing(PlanningScheduleVO::getDate) + .thenComparing(PlanningScheduleVO::getStartTime) + .thenComparing(PlanningScheduleVO::getArtistName, Comparator.nullsLast(String::compareTo))) + .toList(); + + LocalDateTime rangeStart = start.atStartOfDay(); + LocalDateTime rangeEnd = end.plusDays(1).atStartOfDay(); + List appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists); + Map countByArtist = appointments.stream() + .filter(appointment -> appointment.getArtistId() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); + artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue())); + + PlanningCalendarVO vo = new PlanningCalendarVO(); + vo.setBusinessStartTime(businessHours.start().toString()); + vo.setBusinessEndTime(businessHours.end().toString()); + vo.setSlotMinutes(DEFAULT_SLOT_MINUTES); + vo.setArtists(artists); + vo.setSchedules(scheduleVos); + vo.setAppointments(appointments); + vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments)); + return vo; + } + + @Override + @Transactional + public PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto) { + if (dto == null) { + throw new RuntimeException("预约信息不能为空"); + } + if (Integer.valueOf(3).equals(currentUser.getType())) { + throw new RuntimeException("美甲师账号只能查看预约,不能新建预约"); + } + Long shopId = requirePlanningShopId(currentUser); + requireAppointmentDuration(dto.getDurationMinutes()); + ProductDO product = resolveAppointmentProduct(dto, shopId); + UserDO artist = requireActiveArtist(dto.getArtistId(), shopId); + UserDO customer = resolveCustomer(shopId, dto); + + int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity(); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity; + LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureWithinBusinessHours(shopId, startTime, endTime); + + BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity)); + + OrderDO order = new OrderDO(); + order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); + order.setUserId(customer.getId()); + order.setShopId(shopId); + order.setTotalAmount(amount); + order.setActualAmount(amount); + order.setCustomerRemark(trimToNull(dto.getRemark())); + order.setQuoteStatus("CONFIRMED"); + order.setQuoteUserConfirmed(1); + order.setQuoteShopConfirmed(1); + order.setQuoteConfirmedTime(LocalDateTime.now()); + order.setPaymentStatus("UNPAID"); + order.setPayAmount(amount); + order.setPaidAmount(BigDecimal.ZERO); + order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setIsDelete(0); + orderMapper.insert(order); + + OrderItemDO item = new OrderItemDO(); + item.setOrderId(order.getId()); + item.setProductId(product.getId()); + item.setQuantity(quantity); + item.setPrice(unitPrice); + item.setArtistId(artist.getId()); + item.setAppointmentTime(startTime); + item.setIsDelete(0); + orderItemMapper.insert(item); + + appointmentCapacityService.reserveConfirmedOrThrow( + order.getId(), + item.getId(), + shopId, + artist.getId(), + product.getTitle(), + startTime, + endTime, + trimToNull(dto.getClientRequestId()) + ); + + return getAppointment(currentUser, item.getId()); + } + + @Override + public PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId) { + if (orderItemId == null) { + throw new RuntimeException("预约ID不能为空"); + } + OrderItemDO item = orderItemMapper.selectById(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("预约不存在"); + } + OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); + ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId()); + AppointmentReservationDO reservation = findActiveReservation(orderItemId); + Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() + .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); + Map customerMap = loadUsers(Set.of(order.getUserId())); + return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); + } + + @Override + @Transactional + public PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto) { + if (orderItemId == null || dto == null) { + throw new RuntimeException("改派信息不能为空"); + } + OrderItemDO item = orderItemMapper.selectByIdForUpdate(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("预约不存在"); + } + OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); + ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId()); + Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId(); + UserDO artist = requireActiveArtist(targetArtistId, order.getShopId()); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * + Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime()) + ? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()) + : item.getAppointmentTime(); + if (startTime == null) { + throw new RuntimeException("预约时间不能为空"); + } + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureWithinBusinessHours(order.getShopId(), startTime, endTime); + + appointmentCapacityService.moveReservationForArtistChange( + order.getId(), + item.getId(), + order.getShopId(), + item.getArtistId(), + artist.getId(), + product.getTitle(), + startTime, + endTime + ); + + item.setArtistId(artist.getId()); + item.setAppointmentTime(startTime); + orderItemMapper.updateById(item); + return getAppointment(currentUser, item.getId()); + } + + @Override + @Transactional + public Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto) { + if (orderId == null || dto == null || dto.getStatus() == null) { + throw new RuntimeException("预约状态不能为空"); + } + OrderDO order = requireAccessibleOrder(currentUser, orderId); + int targetStatus = dto.getStatus(); + if (targetStatus == OrderStatus.PENDING_SERVICE.getCode()) { + if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); + } + return true; + } + orderService.processOrder(orderId, targetStatus); + return true; + } + + private Long requirePlanningShopId(UserDO currentUser) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + if (shopId == null || shopId <= 0) { + throw new RuntimeException("请先选择店铺后再查看规划"); + } + return shopId; + } + + private List listArtists(Long shopId, Long artistId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("shop_id", shopId) + .eq("type", 3) + .eq("is_delete", 0) + .orderByAsc("id"); + if (artistId != null && artistId > 0) { + wrapper.eq("id", artistId); + } + List artists = userMapper.selectList(wrapper); + if (artists == null || artists.isEmpty()) { + return List.of(); + } + Set artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new)); + Map infoMap = loadArtistInfo(artistIds); + List result = new ArrayList<>(); + for (int i = 0; i < artists.size(); i++) { + UserDO user = artists.get(i); + NailArtistInfoDO info = infoMap.get(user.getId()); + PlanningArtistVO vo = new PlanningArtistVO(); + vo.setId(user.getId()); + vo.setName(firstNonBlank(user.getNickname(), user.getAccount(), "美甲师" + (i + 1))); + vo.setShortName(PlanningCalendarSupport.shortName(vo.getName())); + vo.setPhone(firstNonBlank(user.getContactPhone(), user.getPhone(), "")); + vo.setAvatar(user.getAvatar()); + vo.setColor(colorForArtist(user.getId(), i)); + vo.setStatus(info == null || info.getStatus() == null ? user.getStatus() : info.getStatus()); + vo.setStatusText(Integer.valueOf(0).equals(vo.getStatus()) ? "休息" : "可预约"); + vo.setWorkStartTime(info == null || info.getWorkStartTime() == null ? null : info.getWorkStartTime().toString()); + vo.setWorkEndTime(info == null || info.getWorkEndTime() == null ? null : info.getWorkEndTime().toString()); + vo.setRangeCount(0); + result.add(vo); + } + return result; + } + + private Map loadArtistInfo(Set artistIds) { + if (artistIds == null || artistIds.isEmpty()) { + return Map.of(); + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.in("user_id", artistIds).eq("is_delete", 0); + return nailArtistInfoMapper.selectList(wrapper).stream() + .collect(Collectors.toMap(NailArtistInfoDO::getUserId, Function.identity(), (a, b) -> a)); + } + + private List listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("shop_id", shopId) + .between("work_date", start, end) + .eq("is_delete", 0) + .orderByAsc("work_date") + .orderByAsc("start_time"); + if (artistId != null && artistId > 0) { + wrapper.eq("artist_id", artistId); + } + return artistScheduleMapper.selectList(wrapper); + } + + private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, List artists) { + Map artistNames = artists.stream() + .collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a)); + PlanningScheduleVO vo = new PlanningScheduleVO(); + vo.setId(schedule.getId()); + vo.setArtistId(schedule.getArtistId()); + vo.setArtistName(artistNames.get(schedule.getArtistId())); + vo.setDate(schedule.getWorkDate() == null ? null : schedule.getWorkDate().toString()); + vo.setStartTime(schedule.getStartTime() == null ? null : schedule.getStartTime().toString()); + vo.setEndTime(schedule.getEndTime() == null ? null : schedule.getEndTime().toString()); + vo.setCapacity(schedule.getCapacity()); + vo.setStatus(schedule.getStatus()); + vo.setStatusText(Integer.valueOf(1).equals(schedule.getStatus()) ? "可预约" : "请假"); + vo.setRemark(schedule.getRemark()); + return vo; + } + + private List listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd, + Long artistId, List artists) { + QueryWrapper reservationWrapper = new QueryWrapper<>(); + reservationWrapper.eq("shop_id", shopId) + .eq("is_delete", 0) + .in("status", ACTIVE_RESERVATION_STATUS) + .lt("appointment_start_time", rangeEnd) + .gt("appointment_end_time", rangeStart) + .orderByAsc("appointment_start_time"); + if (artistId != null && artistId > 0) { + reservationWrapper.eq("artist_id", artistId); + } + List reservations = appointmentReservationMapper.selectList(reservationWrapper); + + QueryWrapper itemWrapper = new QueryWrapper<>(); + itemWrapper.eq("is_delete", 0) + .isNotNull("appointment_time") + .ge("appointment_time", rangeStart) + .lt("appointment_time", rangeEnd) + .orderByAsc("appointment_time"); + if (artistId != null && artistId > 0) { + itemWrapper.eq("artist_id", artistId); + } + List fallbackItems = orderItemMapper.selectList(itemWrapper); + + return buildAppointmentList(shopId, reservations, fallbackItems, artists); + } + + private List buildAppointmentList(Long shopId, List reservations, + List fallbackItems, List artists) { + Set itemIds = new HashSet<>(); + Set orderIds = new HashSet<>(); + for (AppointmentReservationDO reservation : safeList(reservations)) { + if (reservation.getOrderItemId() != null) { + itemIds.add(reservation.getOrderItemId()); + } + if (reservation.getOrderId() != null) { + orderIds.add(reservation.getOrderId()); + } + } + for (OrderItemDO item : safeList(fallbackItems)) { + if (item.getId() != null) { + itemIds.add(item.getId()); + } + if (item.getOrderId() != null) { + orderIds.add(item.getOrderId()); + } + } + + Map itemMap = loadOrderItems(itemIds); + Map orderMap = loadOrders(orderIds); + Set productIds = itemMap.values().stream() + .map(OrderItemDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + Set customerIds = orderMap.values().stream() + .map(OrderDO::getUserId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + Map productMap = loadProducts(productIds); + Map customerMap = loadUsers(customerIds); + Map artistMap = artists.stream() + .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); + + List result = new ArrayList<>(); + Set reservationItemIds = new HashSet<>(); + for (AppointmentReservationDO reservation : safeList(reservations)) { + OrderItemDO item = itemMap.get(reservation.getOrderItemId()); + OrderDO order = orderMap.get(reservation.getOrderId()); + if (!isVisibleOrder(order, shopId)) { + continue; + } + ProductDO product = item == null ? null : productMap.get(item.getProductId()); + UserDO customer = customerMap.get(order.getUserId()); + result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap)); + if (reservation.getOrderItemId() != null) { + reservationItemIds.add(reservation.getOrderItemId()); + } + } + for (OrderItemDO item : safeList(fallbackItems)) { + if (item.getId() != null && reservationItemIds.contains(item.getId())) { + continue; + } + OrderDO order = orderMap.get(item.getOrderId()); + if (!isVisibleOrder(order, shopId)) { + continue; + } + ProductDO product = productMap.get(item.getProductId()); + UserDO customer = customerMap.get(order.getUserId()); + result.add(toAppointmentVO(null, item, order, product, customer, artistMap)); + } + result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo)) + .thenComparing(PlanningAppointmentVO::getArtistName, Comparator.nullsLast(String::compareTo))); + return result; + } + + private PlanningAppointmentVO toAppointmentVO(AppointmentReservationDO reservation, OrderItemDO item, OrderDO order, + ProductDO product, UserDO customer, Map artistMap) { + LocalDateTime start = reservation == null ? null : reservation.getAppointmentStartTime(); + if (start == null && item != null) { + start = item.getAppointmentTime(); + } + int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity()); + LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime(); + if (end == null && start != null) { + end = start.plusMinutes(durationMinutes); + } + + Long artistId = reservation != null && reservation.getArtistId() != null + ? reservation.getArtistId() + : item == null ? null : item.getArtistId(); + PlanningArtistVO artist = artistId == null ? null : artistMap.get(artistId); + + PlanningAppointmentVO vo = new PlanningAppointmentVO(); + vo.setOrderId(order == null ? null : order.getId()); + vo.setOrderNo(order == null ? null : order.getOrderNo()); + vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId()); + vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId()); + vo.setCustomerName(customer == null ? "到店客户" : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); + vo.setCustomerPhone(customer == null ? null : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); + vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId()); + vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle()) + ? reservation.getProductTitle() + : product == null ? "预约作品" : product.getTitle()); + vo.setArtistId(artistId); + vo.setArtistName(artist == null ? "未分配" : artist.getName()); + vo.setArtistColor(artist == null ? ARTIST_COLORS.get(0) : artist.getColor()); + vo.setDate(start == null ? null : start.toLocalDate().toString()); + vo.setStartTime(start == null ? null : DATE_TIME_FORMATTER.format(start)); + vo.setEndTime(end == null ? null : DATE_TIME_FORMATTER.format(end)); + vo.setStartMinute(start == null ? null : start.toLocalTime().toSecondOfDay() / 60); + vo.setDurationMinutes(start == null || end == null ? durationMinutes : Math.toIntExact(Duration.between(start, end).toMinutes())); + vo.setStatus(order == null ? null : order.getStatus()); + vo.setStatusText(statusText(order == null ? null : order.getStatus())); + String occupancyStatus = resolveOccupancyStatus(reservation, order); + vo.setOccupancyStatus(occupancyStatus); + vo.setCanEdit(canEditAppointment(order, occupancyStatus)); + vo.setCanCancel(canCancelAppointment(order, occupancyStatus)); + vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus)); + vo.setAmount(order == null ? null : order.getActualAmount()); + vo.setRemark(order == null ? null : order.getCustomerRemark()); + return vo; + } + + private List buildDaySummaries(LocalDate start, LocalDate end, List artists, + List schedules, List appointments) { + Map> appointmentsByDate = appointments.stream() + .filter(appointment -> appointment.getDate() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getDate)); + Map> schedulesByDate = schedules.stream() + .filter(schedule -> schedule.getWorkDate() != null) + .collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString())); + + List summaries = new ArrayList<>(); + LocalDate cursor = start; + while (!cursor.isAfter(end)) { + String date = cursor.toString(); + List dayAppointments = appointmentsByDate.getOrDefault(date, List.of()); + Map countByArtist = dayAppointments.stream() + .filter(appointment -> appointment.getArtistId() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); + List daySchedules = schedulesByDate.getOrDefault(date, List.of()); + Map scheduleByArtist = daySchedules.stream() + .collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a)); + + List artistCounts = new ArrayList<>(); + int workingArtistCount = 0; + int fullWorkingArtistCount = 0; + for (PlanningArtistVO artist : artists) { + int count = countByArtist.getOrDefault(artist.getId(), 0L).intValue(); + ArtistScheduleDO schedule = scheduleByArtist.get(artist.getId()); + List artistAppointments = dayAppointments.stream() + .filter(appointment -> Objects.equals(appointment.getArtistId(), artist.getId())) + .toList(); + String artistStatus = resolveArtistDayStatus(artist, schedule, artistAppointments); + if (!"rest".equals(artistStatus)) { + workingArtistCount++; + if ("full".equals(artistStatus)) { + fullWorkingArtistCount++; + } + } + PlanningArtistCountVO countVO = new PlanningArtistCountVO(); + countVO.setArtistId(artist.getId()); + countVO.setArtistName(artist.getName()); + countVO.setShortName(artist.getShortName()); + countVO.setColor(artist.getColor()); + countVO.setCount(count); + countVO.setStatus(artistStatus); + artistCounts.add(countVO); + } + int total = dayAppointments.size(); + boolean hasWorkingSchedule = workingArtistCount > 0; + boolean allFull = workingArtistCount > 0 && fullWorkingArtistCount == workingArtistCount; + + PlanningDaySummaryVO summary = new PlanningDaySummaryVO(); + summary.setDate(date); + summary.setTotalCount(total); + summary.setArtistCounts(artistCounts); + summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull)); + summaries.add(summary); + cursor = cursor.plusDays(1); + } + return summaries; + } + + private String resolveArtistDayStatus(PlanningArtistVO artist, ArtistScheduleDO schedule, List appointments) { + if (schedule != null && !Integer.valueOf(1).equals(schedule.getStatus())) { + return "rest"; + } + if (schedule == null || Integer.valueOf(0).equals(artist.getStatus())) { + return "rest"; + } + if (hasContinuousFreeWindow(schedule, appointments, MONTH_AVAILABLE_MINUTES)) { + return appointments.isEmpty() ? "free" : "working"; + } + return "full"; + } + + private boolean hasContinuousFreeWindow(ArtistScheduleDO schedule, List appointments, int requiredMinutes) { + if (schedule == null || schedule.getStartTime() == null || schedule.getEndTime() == null || requiredMinutes <= 0) { + return false; + } + int startMinute = schedule.getStartTime().toSecondOfDay() / 60; + int endMinute = schedule.getEndTime().toSecondOfDay() / 60; + if (endMinute - startMinute < requiredMinutes) { + return false; + } + int cursor = startMinute; + List ranges = appointments.stream() + .map(this::toTimeRange) + .filter(Objects::nonNull) + .filter(range -> range.endMinute() > startMinute && range.startMinute() < endMinute) + .map(range -> new TimeRange(Math.max(range.startMinute(), startMinute), Math.min(range.endMinute(), endMinute))) + .sorted(Comparator.comparing(TimeRange::startMinute).thenComparing(TimeRange::endMinute)) + .toList(); + for (TimeRange range : ranges) { + if (range.startMinute() - cursor >= requiredMinutes) { + return true; + } + cursor = Math.max(cursor, range.endMinute()); + } + return endMinute - cursor >= requiredMinutes; + } + + private TimeRange toTimeRange(PlanningAppointmentVO appointment) { + if (appointment == null) { + return null; + } + Integer startMinute = appointment.getStartMinute(); + Integer durationMinutes = appointment.getDurationMinutes(); + if (startMinute == null || durationMinutes == null || durationMinutes <= 0) { + return null; + } + return new TimeRange(startMinute, startMinute + durationMinutes); + } + + private record TimeRange(int startMinute, int endMinute) { + } + + private ProductDO requireActiveProduct(Long productId, Long shopId) { + if (productId == null) { + throw new RuntimeException("请选择预约作品"); + } + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete()) || !shopId.equals(product.getShopId())) { + throw new RuntimeException("预约作品不存在或不属于当前店铺"); + } + return product; + } + + private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + if (dto.getProductId() != null) { + return requireActiveProduct(dto.getProductId(), shopId); + } + return createManualAppointmentProduct(dto, shopId); + } + + private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + String title = trimToNull(dto.getManualProductTitle()); + if (!hasText(title)) { + throw new RuntimeException("请选择预约作品或填写手动作品名称"); + } + BigDecimal price = dto.getManualProductPrice(); + if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("手动作品价格不能小于0"); + } + int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); + ProductDO product = new ProductDO(); + product.setShopId(shopId); + product.setTitle(title); + product.setDescription(trimToNull(dto.getManualProductDescription())); + product.setTags(trimToNull(dto.getManualProductTags())); + product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); + product.setPrecautions(trimToNull(dto.getManualProductPrecautions())); + product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + product.setPrice(price); + product.setLikeCount(0); + product.setCollectCount(0); + product.setApproximateDuration(durationMinutes + "分钟"); + product.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId())); + product.setFrontVisible(0); + product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT); + product.setIsDelete(0); + productMapper.insert(product); + return product; + } + + private int requireAppointmentDuration(Integer durationMinutes) { + if (durationMinutes == null || durationMinutes <= 0) { + throw new RuntimeException("预约时长不能为空且必须大于0分钟"); + } + return durationMinutes; + } + + private UserDO requireActiveArtist(Long artistId, Long shopId) { + if (artistId == null) { + throw new RuntimeException("请选择美甲师"); + } + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) + || !Integer.valueOf(3).equals(artist.getType()) || !shopId.equals(artist.getShopId())) { + throw new RuntimeException("美甲师不存在或不属于当前店铺"); + } + return artist; + } + + private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) { + if (dto.getCustomerUserId() != null) { + UserDO customer = userMapper.selectById(dto.getCustomerUserId()); + if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) { + throw new RuntimeException("客户不存在"); + } + return customer; + } + if (!hasText(dto.getPhone())) { + throw new RuntimeException("客户手机号不能为空"); + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("is_delete", 0) + .and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone())) + .last("LIMIT 1"); + UserDO existing = userMapper.selectOne(wrapper); + if (existing != null) { + return existing; + } + UserDO customer = new UserDO(); + customer.setShopId(shopId); + customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone())); + customer.setPhone(dto.getPhone()); + customer.setContactPhone(dto.getPhone()); + customer.setAccount(dto.getPhone()); + customer.setPassword(ENCODED_UNSET_PASSWORD); + customer.setType(0); + customer.setStatus(1); + customer.setIsDelete(0); + userMapper.insert(customer); + return customer; + } + + private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + adminScopeHelper.ensureShopAccessible(currentUser, order.getShopId(), "无权访问其他店铺预约"); + return order; + } + + private AppointmentReservationDO findActiveReservation(Long orderItemId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("order_item_id", orderItemId) + .eq("is_delete", 0) + .in("status", ACTIVE_RESERVATION_STATUS) + .orderByDesc("id") + .last("LIMIT 1"); + return appointmentReservationMapper.selectOne(wrapper); + } + + private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) { + ShopDO shop = shopMapper.selectById(shopId); + PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours()); + LocalTime start = startTime.toLocalTime(); + LocalTime end = endTime.toLocalTime(); + if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { + throw new RuntimeException("预约时间超出店铺营业时间"); + } + } + + private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) { + if (hasText(appointmentStartTime)) { + String normalized = appointmentStartTime.trim().replace('T', ' '); + if (normalized.length() == 16) { + normalized = normalized + ":00"; + } + try { + return LocalDateTime.parse(normalized, DATE_TIME_FORMATTER); + } catch (DateTimeParseException ignored) { + return LocalDateTime.parse(appointmentStartTime.trim()); + } + } + if (!hasText(appointmentDate) || !hasText(appointmentTime)) { + throw new RuntimeException("请选择预约日期和时间"); + } + LocalDate date = LocalDate.parse(appointmentDate.trim()); + LocalTime time = LocalTime.parse(appointmentTime.trim().length() == 5 ? appointmentTime.trim() + ":00" : appointmentTime.trim()); + return LocalDateTime.of(date, time); + } + + private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) { + if (overrideMinutes != null && overrideMinutes > 0) { + return overrideMinutes; + } + return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES); + } + + private boolean isVisibleOrder(OrderDO order, Long shopId) { + return order != null + && !Integer.valueOf(1).equals(order.getIsDelete()) + && shopId.equals(order.getShopId()) + && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); + } + + private Map loadOrderItems(Set itemIds) { + if (itemIds == null || itemIds.isEmpty()) { + return Map.of(); + } + return orderItemMapper.selectBatchIds(itemIds).stream() + .collect(Collectors.toMap(OrderItemDO::getId, Function.identity(), (a, b) -> a)); + } + + private Map loadOrders(Set orderIds) { + if (orderIds == null || orderIds.isEmpty()) { + return Map.of(); + } + return orderMapper.selectBatchIds(orderIds).stream() + .collect(Collectors.toMap(OrderDO::getId, Function.identity(), (a, b) -> a)); + } + + private Map loadProducts(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return Map.of(); + } + return productMapper.selectBatchIds(productIds).stream() + .collect(Collectors.toMap(ProductDO::getId, Function.identity(), (a, b) -> a)); + } + + private Map loadUsers(Set userIds) { + if (userIds == null || userIds.isEmpty()) { + return Map.of(); + } + return userMapper.selectBatchIds(userIds).stream() + .collect(Collectors.toMap(UserDO::getId, Function.identity(), (a, b) -> a)); + } + + private String colorForArtist(Long artistId, int index) { + if (artistId == null) { + return ARTIST_COLORS.get(index % ARTIST_COLORS.size()); + } + int colorIndex = Math.abs(artistId.hashCode()) % ARTIST_COLORS.size(); + return ARTIST_COLORS.get(colorIndex); + } + + private String statusText(Integer status) { + if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(status)) { + return "已确认"; + } + if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(status)) { + return "已完成"; + } + if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status)) { + return "已取消"; + } + if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(status)) { + return "待确认"; + } + return "未知"; + } + + private String resolveOccupancyStatus(AppointmentReservationDO reservation, OrderDO order) { + if (reservation != null && hasText(reservation.getStatus())) { + return reservation.getStatus(); + } + if (order != null && Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + return RESERVATION_PENDING_QUOTE; + } + if (order != null && Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + return RESERVATION_CONFIRMED; + } + if (order != null && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { + return "CANCELLED"; + } + if (order != null && Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { + return "COMPLETED"; + } + return "UNKNOWN"; + } + + private Boolean canEditAppointment(OrderDO order, String occupancyStatus) { + return order != null + && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) + && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) + && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); + } + + private Boolean canCancelAppointment(OrderDO order, String occupancyStatus) { + return order != null + && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) + && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) + && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); + } + + private String resolveAppointmentConflictReason(String occupancyStatus) { + if (RESERVATION_PENDING_QUOTE.equals(occupancyStatus)) { + return "该时段已有待报价预约占用"; + } + if (RESERVATION_CONFIRMED.equals(occupancyStatus)) { + return "该时段已有已确认预约占用"; + } + return null; + } + + private List safeList(List list) { + return list == null ? List.of() : list; + } + + private String firstNonBlank(String... values) { + for (String value : values) { + if (hasText(value)) { + return value.trim(); + } + } + return ""; + } + + private String trimToNull(String value) { + return hasText(value) ? value.trim() : null; + } + + private boolean hasText(String value) { + return value != null && !value.trim().isEmpty(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java new file mode 100644 index 00000000..4301d134 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java @@ -0,0 +1,83 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.support; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalTime; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class PlanningCalendarSupport { + + private static final LocalTime DEFAULT_START = LocalTime.of(10, 0); + private static final LocalTime DEFAULT_END = LocalTime.of(22, 0); + private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?)"); + + private PlanningCalendarSupport() { + } + + public static String shortName(String name) { + if (name == null || name.trim().isEmpty()) { + return "?"; + } + String normalized = name.trim(); + if (normalized.startsWith("小") && normalized.length() > 1) { + return normalized.substring(1, 2); + } + if (normalized.endsWith("老师") && normalized.length() > 2) { + return normalized.substring(0, 1); + } + return normalized.substring(0, 1).toUpperCase(); + } + + public static BusinessHours parseBusinessHours(String businessHours) { + if (businessHours == null || businessHours.trim().isEmpty()) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + String[] parts = businessHours.trim().split("-"); + if (parts.length != 2) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + if (!start.isBefore(end)) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + return new BusinessHours(start, end); + } catch (RuntimeException ignored) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + } + + public static int parseDurationMinutes(String durationText, int defaultMinutes) { + if (durationText == null || durationText.trim().isEmpty()) { + return defaultMinutes; + } + Matcher matcher = NUMBER_PATTERN.matcher(durationText.trim()); + if (!matcher.find()) { + return defaultMinutes; + } + BigDecimal amount = new BigDecimal(matcher.group(1)); + if (durationText.contains("小时") || durationText.toLowerCase().contains("hour")) { + amount = amount.multiply(BigDecimal.valueOf(60)); + } + int minutes = amount.setScale(0, RoundingMode.HALF_UP).intValue(); + return minutes > 0 ? minutes : defaultMinutes; + } + + public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) { + if (!hasWorkingSchedule) { + return "rest"; + } + if (allWorkingArtistsBusy) { + return "full"; + } + if (totalCount <= 0) { + return "free"; + } + return "working"; + } + + public record BusinessHours(LocalTime start, LocalTime end) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java new file mode 100644 index 00000000..f5186a2a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class PlanningAppointmentVO { + private Long orderId; + private String orderNo; + private Long orderItemId; + private Long customerId; + private String customerName; + private String customerPhone; + private Long productId; + private String productTitle; + private Long artistId; + private String artistName; + private String artistColor; + private String date; + private String startTime; + private String endTime; + private Integer startMinute; + private Integer durationMinutes; + private Integer status; + private String statusText; + private String occupancyStatus; + private Boolean canEdit; + private Boolean canCancel; + private String conflictReason; + private BigDecimal amount; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java new file mode 100644 index 00000000..8f20d1e5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.vo; + +import lombok.Data; + +@Data +public class PlanningArtistCountVO { + private Long artistId; + private String artistName; + private String shortName; + private String color; + private Integer count; + private String status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java new file mode 100644 index 00000000..5b64ebc9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.vo; + +import lombok.Data; + +@Data +public class PlanningArtistVO { + private Long id; + private String name; + private String shortName; + private String phone; + private String avatar; + private String color; + private Integer status; + private String statusText; + private String workStartTime; + private String workEndTime; + private Integer rangeCount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java new file mode 100644 index 00000000..a91048ff --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class PlanningCalendarVO { + private String businessStartTime; + private String businessEndTime; + private Integer slotMinutes; + private List artists; + private List schedules; + private List appointments; + private List daySummaries; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java new file mode 100644 index 00000000..ca253a1f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class PlanningDaySummaryVO { + private String date; + private Integer totalCount; + private List artistCounts; + private String dayStatus; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java new file mode 100644 index 00000000..924cb55d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.modules.planning.vo; + +import lombok.Data; + +@Data +public class PlanningScheduleVO { + private Long id; + private Long artistId; + private String artistName; + private String date; + private String startTime; + private String endTime; + private Integer capacity; + private Integer status; + private String statusText; + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/EffectDiagramController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/EffectDiagramController.java new file mode 100644 index 00000000..e17bd1fd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/EffectDiagramController.java @@ -0,0 +1,111 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.EffectDiagramDTO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.EffectDiagramVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.EffectDiagramService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 商品效果图信息表 Controller + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/effect-diagram", "/api/effect-diagram"}) +@RequiredArgsConstructor +public class EffectDiagramController { + /** + * Variable `effectDiagramService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final EffectDiagramService effectDiagramService; + + /** + * 创建效果图 + * + * @param effectDiagramDTO 效果图DTO + * @return 效果图ID + */ + @PostMapping("/create") + public Result createEffectDiagram(@RequestBody EffectDiagramDTO effectDiagramDTO) { + Long id = effectDiagramService.createEffectDiagram(effectDiagramDTO); + return Result.success(id); + } + + /** + * 更新效果图 + * + * @param id 效果图ID + * @param effectDiagramDTO 效果图DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateEffectDiagram(@PathVariable Long id, @RequestBody EffectDiagramDTO effectDiagramDTO) { + boolean success = effectDiagramService.updateEffectDiagram(id, effectDiagramDTO); + return Result.success(success); + } + + /** + * 删除效果图 + * + * @param id 效果图ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteEffectDiagram(@PathVariable Long id) { + boolean success = effectDiagramService.deleteEffectDiagram(id); + return Result.success(success); + } + + /** + * 根据ID查询效果图 + * + * @param id 效果图ID + * @return 效果图VO + */ + @GetMapping("/get/{id}") + public Result getEffectDiagramById(@PathVariable Long id) { + EffectDiagramVO effectDiagramVO = effectDiagramService.getEffectDiagramById(id); + return Result.success(effectDiagramVO); + } + + /** + * 查询所有效果图 + * + * @return 效果图VO列表 + */ + @GetMapping("/list/all") + public Result> listAllEffectDiagrams() { + List effectDiagramVOs = effectDiagramService.listAllEffectDiagrams(); + return Result.success(effectDiagramVOs); + } + + /** + * 根据商品ID查询效果图 + * + * @param productId 商品ID + * @return 效果图VO列表 + */ + @GetMapping("/list/product/{productId}") + public Result> listEffectDiagramsByProductId(@PathVariable Long productId) { + List effectDiagramVOs = effectDiagramService.listEffectDiagramsByProductId(productId); + return Result.success(effectDiagramVOs); + } + + /** + * 根据类别查询效果图 + * + * @param category 类别 + * @return 效果图VO列表 + */ + @GetMapping("/list/category/{category}") + public Result> listEffectDiagramsByCategory(@PathVariable String category) { + List effectDiagramVOs = effectDiagramService.listEffectDiagramsByCategory(category); + return Result.success(effectDiagramVOs); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/ProductController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/ProductController.java new file mode 100644 index 00000000..d9aae650 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/ProductController.java @@ -0,0 +1,225 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.ProductDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.ProductService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService; +import com.xiaowang.jayucloud.artlist.core.utils.JwtUtil; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.ProductVO; +import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/product") +@RequiredArgsConstructor +/** + * ProductController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ProductController { + /** + * Purpose: AUTHORIZATION_HEADER supports ProductController.java by holding or executing the authorization header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String AUTHORIZATION_HEADER = "Authorization"; + /** + * Purpose: BEARER_PREFIX supports ProductController.java by holding or executing the bearer prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String BEARER_PREFIX = "Bearer "; + + /** + * Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductService productService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: jwtUtil supports ProductController.java by holding or executing the jwt util business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtUtil jwtUtil; + /** + * Purpose: userSessionService supports ProductController.java by holding or executing the user session service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserSessionService userSessionService; + /** + * Purpose: userShopBindingSupport supports ProductController.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + + @PostMapping("/create") + @RequirePermission("product:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); + Long id = productService.createProduct(productDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("product:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ProductVO productVO = productService.getProductById(id); + if (productVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权编辑其他店铺商品"); + Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId(); + productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); + boolean success = productService.updateProduct(id, productDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("product:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ProductVO productVO = productService.getProductById(id); + if (productVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权删除其他店铺商品"); + boolean success = productService.deleteProduct(id); + return Result.success(success); + } + + @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getProductById(@PathVariable Long id) { + ProductVO productVO = productService.getPublicProductById(id); + return Result.success(productVO); + } + + @GetMapping("/list/all") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllProducts(HttpServletRequest request) { + Long currentShopId = resolveOptionalCurrentShopId(request); + List productVOs = currentShopId == null + ? productService.listPublicProducts() + : productService.listPublicProductsByShopId(currentShopId); + return Result.success(productVOs); + } + + @GetMapping("/list/shop/{shopId}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listProductsByShopId(@PathVariable Long shopId) { + List productVOs = productService.listPublicProductsByShopId(shopId); + return Result.success(productVOs); + } + + @GetMapping("/list/tag/{tag}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listProductsByTag(HttpServletRequest request, @PathVariable String tag) { + List productVOs = productService.listProductsByTag(tag, resolveOptionalCurrentShopId(request)); + return Result.success(productVOs); + } + + @GetMapping("/list/search") + /** + * Purpose: searchProducts supports ProductController.java by holding or executing the search products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> searchProducts(HttpServletRequest request, @RequestParam("keyword") String keyword) { + List productVOs = productService.searchProducts(keyword, resolveOptionalCurrentShopId(request)); + return Result.success(productVOs); + } + + @GetMapping("/list/page") + public Result> pagePublicProducts(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String tag, + @RequestParam(required = false) String tagIds) { + return Result.success(productService.pagePublicProducts(page, size, keyword, tag, tagIds, resolveOptionalCurrentShopId(request))); + } + + /** + * Purpose: resolveOptionalCurrentShopId supports ProductController.java by holding or executing the resolve optional current shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long resolveOptionalCurrentShopId(HttpServletRequest request) { + if (request == null) { + return null; + } + String authHeader = request.getHeader(AUTHORIZATION_HEADER); + if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(BEARER_PREFIX)) { + return null; + } + String token = authHeader.substring(BEARER_PREFIX.length()); + try { + if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) { + return null; + } + Long shopId = jwtUtil.getShopIdFromToken(token); + if (shopId == null || shopId <= 0) { + return null; + } + Long userId = jwtUtil.getUserIdFromToken(token); + String sessionId = jwtUtil.getSessionIdFromToken(token); + String jti = jwtUtil.getJtiFromToken(token); + if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { + return null; + } + return userShopBindingSupport.canUserAccessShop(userId, shopId, false, null) ? shopId : null; + } catch (RuntimeException exception) { + return null; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/TagController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/TagController.java new file mode 100644 index 00000000..3d6362a8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/controller/front/TagController.java @@ -0,0 +1,161 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.TagDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.TagService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagFilterGroupVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 系统标签信息表 Controller + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping("/tag") +@RequiredArgsConstructor +public class TagController { + /** + * Variable `tagService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagService tagService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建标签 + * + * @param tagDTO 标签DTO + * @return 标签ID + */ + @PostMapping("/create") + @RequirePermission("tag:create") + public Result createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId())); + Long id = tagService.createTag(tagDTO); + return Result.success(id); + } + + /** + * 更新标签 + * + * @param id 标签ID + * @param tagDTO 标签DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + @RequirePermission("tag:edit") + public Result updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权编辑其他店铺标签"); + Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId(); + tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); + boolean success = tagService.updateTag(id, tagDTO); + return Result.success(success); + } + + /** + * 删除标签 + * + * @param id 标签ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("tag:delete") + public Result deleteTag(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权删除其他店铺标签"); + boolean success = tagService.deleteTag(id); + return Result.success(success); + } + + /** + * 根据ID查询标签 + * + * @param id 标签ID + * @return 标签VO + */ + @GetMapping("/get/{id}") + @RequirePermission("tag:view") + public Result getTagById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); + } + return Result.success(tagVO); + } + + /** + * 查询所有标签(公开接口,不需要权限) + * + * @return 标签VO列表 + */ + @GetMapping("/list/all") + public Result> listAllTags() { + List tagVOs = tagService.listAllTags(); + return Result.success(tagVOs); + } + + /** + * Purpose: listFilterOptions exposes customer-facing grouped tag filters. + * Usage: call it from public product pages, optionally passing shopId for a shop-scoped filter bar. + */ + @GetMapping("/list/filter-options") + public Result> listFilterOptions(@RequestParam(required = false) Long shopId) { + return Result.success(tagService.listFilterOptions(shopId)); + } + + /** + * 根据店铺ID查询标签 + * + * @param shopId 店铺ID + * @return 标签VO列表 + */ + @GetMapping("/list/by-shop/{shopId}") + @RequirePermission("tag:view") + public Result> listTagsByShopId(HttpServletRequest request, @PathVariable Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List tagVOs = tagService.listTagsByShopId(shopId); + return Result.success(tagVOs); + } + + /** + * 根据标签名称查询标签 + * + * @param tagName 标签名称 + * @return 标签VO + */ + @GetMapping("/get/tagName/{tagName}") + @RequirePermission("tag:view") + public Result getTagByTagName(HttpServletRequest request, @PathVariable String tagName) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagByTagName(tagName); + if (tagVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); + } + return Result.success(tagVO); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/EffectDiagramDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/EffectDiagramDTO.java new file mode 100644 index 00000000..29ab466a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/EffectDiagramDTO.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * 商品效果图信息表 DTO + * 用于效果图信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class EffectDiagramDTO { + + /** + * 所属商品ID,关联商品表主键 + */ + private Long productId; + + /** + * 效果图类别 + */ + private String category; + + /** + * 图片文件ID集合,多ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 效果图描述 + */ + private String description; + + /** + * 效果图对应服务价格 + */ + private BigDecimal price; + + /** + * 效果图对应服务耗时 + */ + private String duration; + + /** + * 效果图标签 + */ + private String tag; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/ProductDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/ProductDTO.java new file mode 100644 index 00000000..07a8f839 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/ProductDTO.java @@ -0,0 +1,91 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * 商品信息表 DTO + * 用于商品信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ProductDTO { + + /** + * 所属店铺ID,关联店铺表主键 + */ + private Long shopId; + + /** + * 商品标题 + */ + private String title; + + /** + * 商品描述 + */ + private String description; + + /** + * 适合人群说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 + */ + private String targetAudience; + + /** + * 注意事项说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 + */ + private String precautions; + + /** + * 图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 商品价格,保留2位小数 + */ + private BigDecimal price; + + /** + * 标签集合,多个标签以逗号分隔,最多5个 + */ + private String tags; + + /** + * 鍟嗗搧鐐硅禐鏁? + */ + private Integer likeCount; + + /** + * 鍟嗗搧鏀惰棌鏁? + */ + private Integer collectCount; + + /** + * 商品对应的服务大约耗时(如"30分钟") + */ + private String approximateDuration; + + /** + * 可预约的美甲师ID集合,多个ID以逗号分隔 + */ + private String bookableArtists; + + /** + * 可用的优惠券ID集合,多个ID以逗号分隔 + */ + private String availableCoupons; + + /** + * 前台是否展示:0-隐藏,1-展示 + */ + private Integer frontVisible; + + /** + * 来源类型 + */ + private String sourceType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/TagDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/TagDTO.java new file mode 100644 index 00000000..bff3fa03 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/dto/TagDTO.java @@ -0,0 +1,63 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.dto; + +import lombok.Data; + +/** + * 系统标签信息表 DTO + * 用于标签信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class TagDTO { + + /** + * 标签名称 + */ + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + private String borderColor; + + /** + * Purpose: sceneGroup groups tags into customer-facing scene filters. + * Usage: submit it from admin tag forms; empty values are treated as the default public group. + */ + private String sceneGroup; + + /** + * Purpose: displayName is the short label customers see in filters. + * Usage: submit it from admin forms; empty values fall back to tagName. + */ + private String displayName; + + /** + * Purpose: sortOrder controls this tag's ordering inside its public filter group. + * Usage: lower values are shown first; omit it to use legacy ordering. + */ + private Integer sortOrder; + + /** + * Purpose: frontVisible marks whether the tag appears in public filter options. + * Usage: send 1 to show, 0 to hide; omitted values default to visible. + */ + private Integer frontVisible; + + /** + * 店铺ID + */ + private Long shopId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/EffectDiagramDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/EffectDiagramDO.java new file mode 100644 index 00000000..b3c39e3f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/EffectDiagramDO.java @@ -0,0 +1,76 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 商品效果图信息表 DO + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_effect_diagram") +public class EffectDiagramDO extends BaseEntity { + + /** + * 所属商品ID,关联商品表主键 + */ + @TableField("product_id") + private Long productId; + + /** + * 效果图类别 + */ + @TableField("category") + private String category; + + /** + * 图片文件ID集合,多ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + /** + * 效果图描述 + */ + @TableField("description") + private String description; + + /** + * 效果图对应服务价格 + */ + @TableField("price") + private BigDecimal price; + + /** + * 效果图对应服务耗时 + */ + @TableField("duration") + private String duration; + + /** + * 效果图标签 + */ + @TableField("tag") + private String tag; + + /** + * 效果图点赞数 + */ + @TableField("like_count") + private Integer likeCount; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/ProductDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/ProductDO.java new file mode 100644 index 00000000..d41c2669 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/ProductDO.java @@ -0,0 +1,120 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 商品信息表 DO + * 对应数据库表 t_product + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_product") +public class ProductDO extends BaseEntity { + + /** + * 所属店铺ID,关联店铺表主键 + */ + @TableField("shop_id") + private Long shopId; + + /** + * 商品标题 + */ + @TableField("title") + private String title; + + /** + * 商品描述 + */ + @TableField("description") + private String description; + + /** + * 适合人群说明;后台创建或编辑作品时填写,用户详情页有值时展示。 + */ + @TableField("target_audience") + private String targetAudience; + + /** + * 注意事项说明;后台创建或编辑作品时填写,用户详情页有值时展示。 + */ + @TableField("precautions") + private String precautions; + + /** + * 图片文件ID集合,多个ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + /** + * 商品价格,保留2位小数 + */ + @TableField("price") + private BigDecimal price; + + /** + * 标签集合,多个标签以逗号分隔,最多5个 + */ + @TableField("tags") + private String tags; + + /** + * 商品点赞数 + */ + @TableField("like_count") + private Integer likeCount; + + /** + * 商品收藏数 + */ + @TableField("collect_count") + private Integer collectCount; + + /** + * 商品对应的服务大约耗时(如"30分钟") + */ + @TableField("approximate_duration") + private String approximateDuration; + + /** + * 可预约的美甲师ID集合,多个ID以逗号分隔 + */ + @TableField("bookable_artists") + private String bookableArtists; + + /** + * 可用的优惠券ID集合,多个ID以逗号分隔 + */ + @TableField("available_coupons") + private String availableCoupons; + + /** + * 前台是否展示:0-隐藏,1-展示 + */ + @TableField("front_visible") + private Integer frontVisible; + + /** + * 来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约 + */ + @TableField("source_type") + private String sourceType; + + /** + * 逻辑删除标识:0-未删除,1-已删除 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/TagDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/TagDO.java new file mode 100644 index 00000000..a3810e9d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/entity/TagDO.java @@ -0,0 +1,84 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 系统标签信息表 DO + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_tag") +public class TagDO extends BaseEntity { + + /** + * 标签名称 + */ + @TableField("tag_name") + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + @TableField("text_color") + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + @TableField("bg_color") + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + @TableField("border_color") + private String borderColor; + + /** + * Purpose: sceneGroup stores the customer-facing filter group, such as style or occasion. + * Usage: set it from admin tag forms and read it from public filter-option APIs. + */ + @TableField("scene_group") + private String sceneGroup; + + /** + * Purpose: displayName stores the shorter public label shown in scene filters. + * Usage: leave it empty to fall back to tagName in frontend and mini-program filters. + */ + @TableField("display_name") + private String displayName; + + /** + * Purpose: sortOrder controls tag order inside public filter groups. + * Usage: lower numbers appear first; null uses the default legacy ordering. + */ + @TableField("sort_order") + private Integer sortOrder; + + /** + * Purpose: frontVisible decides whether this tag is visible in public scene filters. + * Usage: set to 1 for visible tags and 0 to hide admin-only/internal tags. + */ + @TableField("front_visible") + private Integer frontVisible; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + private Integer isDelete; + + /** + * 店铺ID + */ + @TableField("shop_id") + private Long shopId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/EffectDiagramMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/EffectDiagramMapper.java new file mode 100644 index 00000000..7a6cb049 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/EffectDiagramMapper.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.EffectDiagramDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +/** + * 商品效果图信息表 Mapper + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface EffectDiagramMapper extends BaseMapper { + + @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/ProductMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/ProductMapper.java new file mode 100644 index 00000000..80a3874d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/ProductMapper.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +/** + * 商品信息表 Mapper + * 对应数据库表 t_product + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ProductMapper extends BaseMapper { + + /** + * 增加商品收藏数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET collect_count = collect_count + 1 WHERE id = #{productId}") + int incrementCollectCount(@Param("productId") Long productId); + + /** + * 减少商品收藏数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET collect_count = CASE WHEN collect_count > 0 THEN collect_count - 1 ELSE 0 END WHERE id = #{productId}") + int decrementCollectCount(@Param("productId") Long productId); + + /** + * 增加商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET like_count = like_count + 1 WHERE id = #{productId}") + int incrementLikeCount(@Param("productId") Long productId); + + /** + * 减少商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}") + int decrementLikeCount(@Param("productId") Long productId); + + @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/TagMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/TagMapper.java new file mode 100644 index 00000000..747f3d72 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/mapper/TagMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.TagDO; + +/** + * 系统标签信息表 Mapper + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface TagMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/EffectDiagramService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/EffectDiagramService.java new file mode 100644 index 00000000..65dc2278 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/EffectDiagramService.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.EffectDiagramDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.EffectDiagramDTO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.EffectDiagramVO; + +import java.util.List; + +/** + * 商品效果图信息表 Service + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface EffectDiagramService extends IService { + + /** + * 创建效果图 + * + * @param effectDiagramDTO 效果图DTO + * @return 效果图ID + */ + Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO); + + /** + * 更新效果图 + * + * @param id 效果图ID + * @param effectDiagramDTO 效果图DTO + * @return 是否更新成功 + */ + boolean updateEffectDiagram(Long id, EffectDiagramDTO effectDiagramDTO); + + /** + * 删除效果图 + * + * @param id 效果图ID + * @return 是否删除成功 + */ + boolean deleteEffectDiagram(Long id); + + /** + * 根据ID查询效果图 + * + * @param id 效果图ID + * @return 效果图VO + */ + EffectDiagramVO getEffectDiagramById(Long id); + + /** + * 查询所有效果图 + * + * @return 效果图VO列表 + */ + List listAllEffectDiagrams(); + + /** + * 根据商品ID查询效果图 + * + * @param productId 商品ID + * @return 效果图VO列表 + */ + List listEffectDiagramsByProductId(Long productId); + + /** + * 根据类别查询效果图 + * + * @param category 类别 + * @return 效果图VO列表 + */ + List listEffectDiagramsByCategory(String category); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/ProductService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/ProductService.java new file mode 100644 index 00000000..e57b27cd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/ProductService.java @@ -0,0 +1,140 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.ProductDTO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.ProductVO; + +import java.util.List; + +/** + * 商品信息表 Service + * 对应数据库表 t_product + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ProductService extends IService { + + /** + * 创建商品 + * + * @param productDTO 商品DTO + * @return 商品ID + */ + Long createProduct(ProductDTO productDTO); + + /** + * 更新商品 + * + * @param id 商品ID + * @param productDTO 商品DTO + * @return 是否更新成功 + */ + boolean updateProduct(Long id, ProductDTO productDTO); + + /** + * 增加商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + int incrementLikeCount(Long productId); + + /** + * 减少商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + int decrementLikeCount(Long productId); + + /** + * 删除商品 + * + * @param id 商品ID + * @return 是否删除成功 + */ + boolean deleteProduct(Long id); + + /** + * 根据ID查询商品 + * + * @param id 商品ID + * @return 商品VO + */ + ProductVO getProductById(Long id); + + ProductVO getPublicProductById(Long id); + + /** + * 查询所有商品 + * + * @return 商品VO列表 + */ + List listAllProducts(); + + List listPublicProducts(); + + /** + * 根据店铺ID查询商品 + * + * @param shopId 店铺ID + * @return 商品VO列表 + */ + List listProductsByShopId(Long shopId); + + List listPublicProductsByShopId(Long shopId); + + /** + * 根据标签查询商品 + * + * @param tag 标签 + * @return 商品VO列表 + */ + List listProductsByTag(String tag); + + List listProductsByTag(String tag, Long shopId); + + /** + * 前台按标题、描述、标签名搜索商品 + * + * @param keyword 搜索关键词 + * @return 商品列表 + */ + List searchProducts(String keyword); + + List searchProducts(String keyword, Long shopId); + + /** + * 分页查询商品 + * + * @param page 页码 + * @param size 每页大小 + * @param keyword 搜索关键词 + * @return 分页结果 + */ + PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId); + + PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag); + + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId); + + /** + * Purpose: pagePublicProducts filters public product pages by legacy tag text and grouped tag ids. + * Usage: pass comma/semicolon separated tagIds from scene filters; keep tag for backward-compatible name filtering. + */ + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/TagService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/TagService.java new file mode 100644 index 00000000..a4ca5ad0 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/TagService.java @@ -0,0 +1,84 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.TagDTO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagFilterGroupVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; + +import java.util.List; + +/** + * 系统标签信息表 Service + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface TagService extends IService { + + /** + * 创建标签 + * + * @param tagDTO 标签DTO + * @return 标签ID + */ + Long createTag(TagDTO tagDTO); + + /** + * 更新标签 + * + * @param id 标签ID + * @param tagDTO 标签DTO + * @return 是否更新成功 + */ + boolean updateTag(Long id, TagDTO tagDTO); + + /** + * 删除标签 + * + * @param id 标签ID + * @return 是否删除成功 + */ + boolean deleteTag(Long id); + + /** + * 根据ID查询标签 + * + * @param id 标签ID + * @return 标签VO + */ + TagVO getTagById(Long id); + + /** + * 查询所有标签 + * + * @return 标签VO列表 + */ + List listAllTags(); + + /** + * 根据标签名称查询标签 + * + * @param tagName 标签名称 + * @return 标签VO + */ + TagVO getTagByTagName(String tagName); + + /** + * 根据店铺ID查询标签 + * + * @param shopId 店铺ID + * @return 标签VO列表 + */ + List listTagsByShopId(Long shopId); + + /** + * Purpose: listFilterOptions returns public scene-filter groups for product browsing. + * Usage: call it from public Web or mini-program product pages, optionally scoped by shopId. + * + * @param shopId optional shop scope + * @return grouped public filter tags + */ + List listFilterOptions(Long shopId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/EffectDiagramServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/EffectDiagramServiceImpl.java new file mode 100644 index 00000000..4bc8a259 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/EffectDiagramServiceImpl.java @@ -0,0 +1,180 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.EffectDiagramDTO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.EffectDiagramDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.EffectDiagramService; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.EffectDiagramVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 商品效果图信息表 Service 实现 + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class EffectDiagramServiceImpl extends ServiceImpl implements EffectDiagramService { + /** + * Variable `effectDiagramMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final EffectDiagramMapper effectDiagramMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO) { + EffectDiagramDO effectDiagramDO = new EffectDiagramDO(); + effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); + effectDiagramDO.setCategory(effectDiagramDTO.getCategory()); + effectDiagramDO.setImageFileIds(effectDiagramDTO.getImageFileIds()); + effectDiagramDO.setDescription(effectDiagramDTO.getDescription()); + effectDiagramDO.setPrice(effectDiagramDTO.getPrice()); + effectDiagramDO.setDuration(effectDiagramDTO.getDuration()); + effectDiagramDO.setTag(effectDiagramDTO.getTag()); + effectDiagramDO.setIsDelete(0); + effectDiagramMapper.insert(effectDiagramDO); + return effectDiagramDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateEffectDiagram(Long id, EffectDiagramDTO effectDiagramDTO) { + EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); + if (effectDiagramDO == null) { + return false; + } + effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); + effectDiagramDO.setCategory(effectDiagramDTO.getCategory()); + effectDiagramDO.setImageFileIds(effectDiagramDTO.getImageFileIds()); + effectDiagramDO.setDescription(effectDiagramDTO.getDescription()); + effectDiagramDO.setPrice(effectDiagramDTO.getPrice()); + effectDiagramDO.setDuration(effectDiagramDTO.getDuration()); + effectDiagramDO.setTag(effectDiagramDTO.getTag()); + return effectDiagramMapper.updateById(effectDiagramDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteEffectDiagram(Long id) { + EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); + if (effectDiagramDO == null) { + return false; + } + effectDiagramDO.setIsDelete(1); + return effectDiagramMapper.updateById(effectDiagramDO) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return EffectDiagramVO result consumed by the caller or returned to the frontend + */ + public EffectDiagramVO getEffectDiagramById(Long id) { + EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); + if (effectDiagramDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param effectDiagramDO parameter `effectDiagramDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(effectDiagramDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllEffectDiagrams() { + List effectDiagramDOs = effectDiagramMapper.selectList(null); + return effectDiagramDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listEffectDiagramsByProductId(Long productId) { + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class) + .eq(EffectDiagramDO::getProductId, productId) + ); + return effectDiagramDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param category parameter `category` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listEffectDiagramsByCategory(String category) { + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class) + .eq(EffectDiagramDO::getCategory, category) + ); + return effectDiagramDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param effectDiagramDO 效果图DO + * @return 效果图VO + */ + private EffectDiagramVO convertToVO(EffectDiagramDO effectDiagramDO) { + EffectDiagramVO effectDiagramVO = new EffectDiagramVO(); + effectDiagramVO.setId(effectDiagramDO.getId()); + effectDiagramVO.setProductId(effectDiagramDO.getProductId()); + effectDiagramVO.setCategory(effectDiagramDO.getCategory()); + effectDiagramVO.setImageFileIds(effectDiagramDO.getImageFileIds()); + effectDiagramVO.setDescription(effectDiagramDO.getDescription()); + effectDiagramVO.setPrice(effectDiagramDO.getPrice()); + effectDiagramVO.setDuration(effectDiagramDO.getDuration()); + effectDiagramVO.setTag(effectDiagramDO.getTag()); + effectDiagramVO.setLikeCount(effectDiagramDO.getLikeCount()); + effectDiagramVO.setCreateTime(effectDiagramDO.getCreateTime()); + effectDiagramVO.setUpdateTime(effectDiagramDO.getUpdateTime()); + return effectDiagramVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/ProductServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/ProductServiceImpl.java new file mode 100644 index 00000000..d9aa9cc8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/ProductServiceImpl.java @@ -0,0 +1,1312 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.ProductDTO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.CouponDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.ProductService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.ProductVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagInfo; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * ProductServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ProductServiceImpl extends ServiceImpl implements ProductService { + /** + * Purpose: PRODUCT_DETAIL_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PRODUCT_DETAIL_CACHE_PREFIX = "cache:product:detail:"; + /** + * Purpose: PRODUCT_LIST_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product list cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PRODUCT_LIST_CACHE_PREFIX = "cache:product:list:"; + /** + * Purpose: PRODUCT_SEARCH_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product search cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PRODUCT_SEARCH_CACHE_PREFIX = "cache:product:search:"; + /** + * Purpose: DEFAULT_PUBLIC_PAGE_SIZE supports ProductServiceImpl.java by holding or executing the default public page size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int DEFAULT_PUBLIC_PAGE_SIZE = 10; + /** + * Purpose: MAX_PUBLIC_PAGE_SIZE supports ProductServiceImpl.java by holding or executing the max public page size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int MAX_PUBLIC_PAGE_SIZE = 30; + private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)"); + private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L; + private static final int FRONT_VISIBLE = 1; + private static final String SOURCE_TYPE_BACKEND = "BACKEND"; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponMapper couponMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BookableArtistSupport bookableArtistSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDTO parameter `productDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createProduct(ProductDTO productDTO) { + validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); + validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); + ProductDO productDO = new ProductDO(); + productDO.setShopId(productDTO.getShopId()); + productDO.setTitle(productDTO.getTitle()); + productDO.setDescription(productDTO.getDescription()); + productDO.setTargetAudience(productDTO.getTargetAudience()); + productDO.setPrecautions(productDTO.getPrecautions()); + productDO.setImageFileIds(productDTO.getImageFileIds()); + productDO.setPrice(productDTO.getPrice()); + productDO.setTags(productDTO.getTags()); + productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + productDO.setApproximateDuration(productDTO.getApproximateDuration()); + productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); + productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible())); + productDO.setSourceType(resolveSourceType(productDTO.getSourceType())); + productDO.setIsDelete(0); + productMapper.insert(productDO); + evictPublicProductCaches(productDO.getId()); + return productDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateProduct(Long id, ProductDTO productDTO) { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null) { + return false; + } + validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); + validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); + productDO.setShopId(productDTO.getShopId()); + productDO.setTitle(productDTO.getTitle()); + productDO.setDescription(productDTO.getDescription()); + productDO.setTargetAudience(productDTO.getTargetAudience()); + productDO.setPrecautions(productDTO.getPrecautions()); + productDO.setImageFileIds(productDTO.getImageFileIds()); + productDO.setPrice(productDTO.getPrice()); + productDO.setTags(productDTO.getTags()); + if (productDTO.getLikeCount() != null) { + productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + } + if (productDTO.getCollectCount() != null) { + productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + } + productDO.setApproximateDuration(productDTO.getApproximateDuration()); + productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); + productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible())); + productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); + boolean updated = productMapper.updateById(productDO) > 0; + if (updated) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(id); + } + return updated; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteProduct(Long id) { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { + return false; + } + productDO.setIsDelete(1); + boolean deleted = productMapper.updateById(productDO) > 0; + if (deleted) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(id); + } + return deleted; + } + + @Override + /** + * Run business method `incrementLikeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return int result consumed by the caller or returned to the frontend + */ + public int incrementLikeCount(Long productId) { + int updated = productMapper.incrementLikeCount(productId); + if (updated > 0) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(productId); + } + return updated; + } + + @Override + /** + * Run business method `decrementLikeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return int result consumed by the caller or returned to the frontend + */ + public int decrementLikeCount(Long productId) { + int updated = productMapper.decrementLikeCount(productId); + if (updated > 0) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(productId); + } + return updated; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ProductVO result consumed by the caller or returned to the frontend + */ + public ProductVO getProductById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); + return multiLevelCacheService.getOrLoad( + PRODUCT_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(productDO); + } + ); + } + + @Override + public ProductVO getPublicProductById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); + return multiLevelCacheService.getOrLoad( + PRODUCT_DETAIL_CACHE_PREFIX + "public:" + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null + || Integer.valueOf(1).equals(productDO.getIsDelete()) + || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible())) { + return null; + } + return convertToVO(productDO); + } + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllProducts() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> toProductVOList(productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .orderByDesc(ProductDO::getCreateTime) + )) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listProductsByShopId(Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "shop:" + shopId, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> { + List productDOs = productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getShopId, shopId) + .orderByDesc(ProductDO::getCreateTime) + ); + /** + * Run business method `toProductVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toProductVOList(productDOs); + } + ); + } + + @Override + public List listPublicProducts() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "public:all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> toProductVOList(productMapper.selectList(buildFrontQuery(null, null, null))) + ); + } + + @Override + public List listPublicProductsByShopId(Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + Long scopedShopId = normalizeShopId(shopId); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "public", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> toProductVOList(productMapper.selectList(buildFrontQuery(null, null, null, scopedShopId))) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listProductsByTag(String tag) { + return listProductsByTag(tag, null); + } + + @Override + /** + * Purpose: listProductsByTag supports ProductServiceImpl.java by holding or executing the list products by tag business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listProductsByTag(String tag, Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + String normalizedTag = normalizeOptionalKeyword(tag); + Long scopedShopId = normalizeShopId(shopId); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "tag:" + normalizedTag, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> loadProductsByTag(normalizedTag, scopedShopId) + ); + } + + @Override + /** + * Run business method `searchProducts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List searchProducts(String keyword) { + return searchProducts(keyword, null); + } + + @Override + /** + * Purpose: searchProducts supports ProductServiceImpl.java by holding or executing the search products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List searchProducts(String keyword, Long shopId) { + if (!StringUtils.hasText(keyword)) { + return new ArrayList<>(); + } + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductSearch(); + String trimmedKeyword = keyword.trim(); + Long scopedShopId = normalizeShopId(shopId); + return multiLevelCacheService.getOrLoad( + PRODUCT_SEARCH_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + trimmedKeyword.toLowerCase(Locale.ROOT), + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> searchFrontProducts(trimmedKeyword, scopedShopId) + ); + } + + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @return private ProductVO result consumed by the caller or returned to the frontend + */ + private ProductVO convertToVO(ProductDO productDO) { + if (productDO == null) { + return null; + } + return toProductVOList(Collections.singletonList(productDO)).stream() + .findFirst() + .orElse(null); + } + + /** + * Run business method `toProductVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toProductVOList(List productDOs) { + if (productDOs == null || productDOs.isEmpty()) { + return new ArrayList<>(); + } + ProductEnrichmentContext context = buildEnrichmentContext(productDOs); + return productDOs.stream() + .map(productDO -> convertToVO(productDO, context)) + .collect(Collectors.toList()); + } + + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @param context parameter `context` supplied by the caller + * @return private ProductVO result consumed by the caller or returned to the frontend + */ + private ProductVO convertToVO(ProductDO productDO, ProductEnrichmentContext context) { + ProductVO productVO = new ProductVO(); + productVO.setId(productDO.getId()); + productVO.setShopId(productDO.getShopId()); + productVO.setShopName(context.shopNames().get(productDO.getShopId())); + productVO.setTitle(productDO.getTitle()); + productVO.setDescription(productDO.getDescription()); + productVO.setTargetAudience(productDO.getTargetAudience()); + productVO.setPrecautions(productDO.getPrecautions()); + productVO.setImageFileIds(productDO.getImageFileIds()); + productVO.setPrice(productDO.getPrice()); + productVO.setTags(productDO.getTags()); + productVO.setLikeCount(productDO.getLikeCount()); + productVO.setCollectCount(productDO.getCollectCount()); + productVO.setApproximateDuration(productDO.getApproximateDuration()); + productVO.setServiceDurationMinutes(resolveServiceDurationMinutes(productDO.getApproximateDuration())); + String validBookableArtists = bookableArtistSupport.filterValidBookableArtists(productDO.getShopId(), productDO.getBookableArtists()); + productVO.setBookableArtists(productDO.getBookableArtists()); + productVO.setAvailableBookableArtistCount(countBookableArtists(validBookableArtists)); + productVO.setBookableArtistRestricted(StringUtils.hasText(productDO.getBookableArtists())); + productVO.setAvailableCoupons(productDO.getAvailableCoupons()); + productVO.setFrontVisible(productDO.getFrontVisible()); + productVO.setSourceType(productDO.getSourceType()); + productVO.setCreateTime(productDO.getCreateTime()); + productVO.setUpdateTime(productDO.getUpdateTime()); + + List tagNames = new ArrayList<>(); + List tagInfos = new ArrayList<>(); + for (Long tagId : parseDelimitedLongIds(productDO.getTags(), ";")) { + TagDO tagDO = context.tags().get(tagId); + if (tagDO == null) { + continue; + } + tagNames.add(tagDO.getTagName()); + TagInfo tagInfo = new TagInfo(); + tagInfo.setId(tagId); + tagInfo.setTagName(tagDO.getTagName()); + tagInfo.setTextColor(tagDO.getTextColor()); + tagInfo.setBgColor(tagDO.getBgColor()); + tagInfo.setBorderColor(tagDO.getBorderColor()); + tagInfos.add(tagInfo); + } + productVO.setTagList(tagNames); + productVO.setTagInfos(tagInfos); + + List imageUrls = new ArrayList<>(); + for (Long fileId : parseDelimitedLongIds(productDO.getImageFileIds(), ",")) { + ObjectStorageFileVO fileVO = context.files().get(fileId); + if (fileVO != null && StringUtils.hasText(fileVO.getFileUrl())) { + imageUrls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); + } + } + productVO.setImageUrls(imageUrls); + return productVO; + } + + private long resolveServiceDurationMinutes(String approximateDuration) { + if (!StringUtils.hasText(approximateDuration)) { + return DEFAULT_SERVICE_DURATION_MINUTES; + } + Matcher matcher = DURATION_PATTERN.matcher(approximateDuration); + if (matcher.find()) { + try { + return Math.max(1L, Long.parseLong(matcher.group(1))); + } catch (NumberFormatException ignored) { + } + } + return DEFAULT_SERVICE_DURATION_MINUTES; + } + + /** + * Run business method `buildEnrichmentContext`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return private ProductEnrichmentContext result consumed by the caller or returned to the frontend + */ + private ProductEnrichmentContext buildEnrichmentContext(List productDOs) { + Set shopIds = new LinkedHashSet<>(); + Set tagIds = new LinkedHashSet<>(); + Set fileIds = new LinkedHashSet<>(); + for (ProductDO productDO : productDOs) { + if (productDO == null) { + continue; + } + if (productDO.getShopId() != null && productDO.getShopId() > 0) { + shopIds.add(productDO.getShopId()); + } + tagIds.addAll(parseDelimitedLongIds(productDO.getTags(), ";")); + fileIds.addAll(parseDelimitedLongIds(productDO.getImageFileIds(), ",")); + } + return new ProductEnrichmentContext( + loadShopNameMap(shopIds), + loadTagMap(tagIds), + objectStorageFileService.getObjectStorageFileMapByIds(fileIds) + ); + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId) { + return pageProducts(page, size, keyword, shopId, null, null, null, null, null); + } + + @Override + /** + * Purpose: pageProducts supports ProductServiceImpl.java by holding or executing the page products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo) { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class); + wrapper.eq(ProductDO::getIsDelete, 0); + if (StringUtils.hasText(keyword)) { + wrapper.and(w -> w.like(ProductDO::getTitle, keyword) + .or().like(ProductDO::getDescription, keyword)); + } + if (shopId != null && shopId > 0) { + wrapper.eq(ProductDO::getShopId, shopId); + } + if (tagId != null) { + wrapper.like(ProductDO::getTags, String.valueOf(tagId)); + } + if (minPrice != null) { + wrapper.ge(ProductDO::getPrice, minPrice); + } + if (maxPrice != null) { + wrapper.le(ProductDO::getPrice, maxPrice); + } + LocalDateTime createdFromTime = parseDateTime(createdFrom); + LocalDateTime createdToTime = parseDateTime(createdTo); + if (createdFromTime != null) { + wrapper.ge(ProductDO::getCreateTime, createdFromTime); + } + if (createdToTime != null) { + wrapper.le(ProductDO::getCreateTime, createdToTime); + } + wrapper.orderByDesc(ProductDO::getCreateTime); + + Page productPage = productMapper.selectPage(pageParam, wrapper); + + PageResultVO result = new PageResultVO<>(); + result.setList(toProductVOList(productPage.getRecords())); + result.setTotal(productPage.getTotal()); + result.setPage(page); + result.setSize(size); + + return result; + } + + /** + * Purpose: parseDateTime supports ProductServiceImpl.java by holding or executing the parse date time business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime parseDateTime(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + try { + return LocalDateTime.parse(value.replace(" ", "T")); + } catch (Exception ignored) { + try { + return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } catch (Exception secondIgnored) { + return null; + } + } + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag) { + return pagePublicProducts(page, size, keyword, tag, null); + } + + @Override + /** + * Purpose: pagePublicProducts supports ProductServiceImpl.java by holding or executing the page public products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId) { + return pagePublicProducts(page, size, keyword, tag, null, shopId); + } + + @Override + /** + * Purpose: pagePublicProducts supports grouped tag-id filters for public product browsing. + * Usage: pass tagIds from scene filter chips while keeping tag for legacy tag-name searches. + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId) { + int normalizedPage = normalizePage(page); + int normalizedSize = normalizePageSize(size); + String normalizedKeyword = normalizeOptionalKeyword(keyword); + String normalizedTag = normalizeOptionalKeyword(tag); + String normalizedTagIds = normalizeOptionalKeyword(tagIds); + Long scopedShopId = normalizeShopId(shopId); + AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword) + ? appCacheProperties.getProductSearch() + : appCacheProperties.getProductList(); + String cacheKey = PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "page:" + normalizedPage + + ":" + normalizedSize + + ":" + normalizedKeyword.toLowerCase(Locale.ROOT) + + ":" + normalizedTag.toLowerCase(Locale.ROOT) + + ":" + normalizedTagIds.toLowerCase(Locale.ROOT); + return multiLevelCacheService.getOrLoad( + cacheKey, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, normalizedTagIds, scopedShopId) + ); + } + + /** + * Run business method `validateBookableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param bookableArtists parameter `bookableArtists` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateBookableArtists(Long shopId, String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return; + } + + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("配置可预约美甲师前必须先选择店铺"); + } + + for (String artistIdStr : bookableArtists.split(",")) { + if (!StringUtils.hasText(artistIdStr)) { + continue; + } + + Long artistId; + try { + artistId = Long.parseLong(artistIdStr.trim()); + } catch (NumberFormatException ex) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("可预约美甲师配置格式不正确"); + } + + if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效、已停用或不属于当前店铺的美甲师配置"); + } + } + } + + /** + * Run business method `validateAvailableCoupons`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateAvailableCoupons(Long shopId, String availableCoupons) { + if (!StringUtils.hasText(availableCoupons)) { + return; + } + + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("配置可用优惠券前必须先选择店铺"); + } + + for (String couponIdStr : availableCoupons.split(",")) { + if (!StringUtils.hasText(couponIdStr)) { + continue; + } + + Long couponId; + try { + couponId = Long.parseLong(couponIdStr.trim()); + } catch (NumberFormatException exception) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("可用优惠券配置格式不正确"); + } + + CouponDO couponDO = couponMapper.selectById(couponId); + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效的优惠券配置"); + } + if (!Integer.valueOf(1).equals(couponDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在已失效的优惠券配置"); + } + if (couponDO.getShopId() == null || !shopId.equals(couponDO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不可跨店铺配置可用优惠券"); + } + } + } + + /** + * Run business method `countBookableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bookableArtists parameter `bookableArtists` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int countBookableArtists(String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return 0; + } + return (int) java.util.Arrays.stream(bookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .count(); + } + + /** + * Run business method `normalizeInteractionCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param count parameter `count` supplied by the caller + * @return private Integer result consumed by the caller or returned to the frontend + */ + private Integer normalizeInteractionCount(Integer count) { + if (count == null || count < 0) { + return 0; + } + return count; + } + + /** + * Run business method `loadProductsByTag`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List loadProductsByTag(String tag, Long shopId) { + if (!StringUtils.hasText(tag)) { + return new ArrayList<>(); + } + Set matchedTagIds = findExactTagIds(tag); + if (matchedTagIds.isEmpty()) { + return new ArrayList<>(); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .orderByDesc(ProductDO::getCreateTime); + if (shopId != null) { + wrapper.eq(ProductDO::getShopId, shopId); + } + /** + * Run business method `applyTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param matchedTagIds parameter `matchedTagIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + applyTagIdConditions(wrapper, matchedTagIds); + return toProductVOList(productMapper.selectList(wrapper)); + } + + /** + * Run business method `searchFrontProducts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List searchFrontProducts(String keyword, Long shopId) { + LambdaQueryWrapper wrapper = buildFrontQuery(keyword, null, null, shopId); + return toProductVOList(productMapper.selectList(wrapper)); + } + + /** + * Run business method `buildPublicProductPage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return private PageResultVO result consumed by the caller or returned to the frontend + */ + private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, Long shopId) { + return buildPublicProductPage(page, size, keyword, tag, null, shopId); + } + + /** + * Purpose: buildPublicProductPage creates the public product page with optional grouped tag ids. + * Usage: call from cache loaders after inputs have been normalized. + */ + private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, String tagIds, Long shopId) { + Set exactTagIds = null; + if (StringUtils.hasText(tag)) { + exactTagIds = findExactTagIds(tag); + if (exactTagIds.isEmpty()) { + /** + * Run business method `buildEmptyPageResult`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildEmptyPageResult(page, size); + } + } + Set selectedTagIds = parseTagIdFilter(tagIds); + + Page pageParam = new Page<>(page, size); + Page productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, selectedTagIds, shopId)); + PageResultVO result = new PageResultVO<>(); + result.setList(toProductVOList(productPage.getRecords())); + result.setTotal(productPage.getTotal()); + result.setPage(page); + result.setSize(size); + return result; + } + + /** + * Run business method `buildFrontQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @param exactTagIds parameter `exactTagIds` supplied by the caller + * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds) { + return buildFrontQuery(keyword, tag, exactTagIds, null); + } + + /** + * Purpose: buildFrontQuery supports ProductServiceImpl.java by holding or executing the build front query business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Long shopId) { + return buildFrontQuery(keyword, tag, exactTagIds, null, shopId); + } + + /** + * Purpose: buildFrontQuery adds product search, legacy tag, grouped tag-id, and shop filters. + * Usage: pass selectedTagIds when users tap scene-filter chips. + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE); + if (shopId != null) { + wrapper.eq(ProductDO::getShopId, shopId); + } + /** + * Run business method `applyKeywordFilter`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + applyKeywordFilter(wrapper, keyword); + if (StringUtils.hasText(tag)) { + applyTagIdConditions(wrapper, exactTagIds == null ? findExactTagIds(tag) : exactTagIds); + } + if (selectedTagIds != null && !selectedTagIds.isEmpty()) { + applyTagIdConditions(wrapper, selectedTagIds); + } + wrapper.orderByDesc(ProductDO::getCreateTime); + return wrapper; + } + + private Integer resolveFrontVisible(Integer frontVisible) { + return Integer.valueOf(0).equals(frontVisible) ? 0 : FRONT_VISIBLE; + } + + private String resolveSourceType(String sourceType) { + return StringUtils.hasText(sourceType) ? sourceType.trim() : SOURCE_TYPE_BACKEND; + } + + private Integer resolveUpdateFrontVisible(Integer currentFrontVisible, Integer nextFrontVisible) { + if (nextFrontVisible != null) { + return resolveFrontVisible(nextFrontVisible); + } + return currentFrontVisible == null ? FRONT_VISIBLE : currentFrontVisible; + } + + private String resolveUpdateSourceType(String currentSourceType, String nextSourceType) { + if (StringUtils.hasText(nextSourceType)) { + return resolveSourceType(nextSourceType); + } + return StringUtils.hasText(currentSourceType) ? currentSourceType : SOURCE_TYPE_BACKEND; + } + + /** + * Run business method `applyKeywordFilter`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyKeywordFilter(LambdaQueryWrapper wrapper, String keyword) { + if (!StringUtils.hasText(keyword)) { + return; + } + Set matchedTagIds = findLikeTagIds(keyword); + wrapper.and(w -> { + w.like(ProductDO::getTitle, keyword) + .or() + .like(ProductDO::getDescription, keyword); + /** + * Run business method `appendOrTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param w parameter `w` supplied by the caller + * @param matchedTagIds parameter `matchedTagIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + appendOrTagIdConditions(w, matchedTagIds); + }); + } + + /** + * Run business method `applyTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param tagIds parameter `tagIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyTagIdConditions(LambdaQueryWrapper wrapper, Set tagIds) { + wrapper.and(w -> { + boolean appended = false; + if (tagIds != null) { + for (String tagId : tagIds) { + if (!StringUtils.hasText(tagId)) { + continue; + } + if (appended) { + w.or(); + } + w.apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagId); + appended = true; + } + } + if (!appended) { + w.apply("1 = 0"); + } + }); + } + + /** + * Run business method `appendOrTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param tagIds parameter `tagIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void appendOrTagIdConditions(LambdaQueryWrapper wrapper, Set tagIds) { + if (tagIds == null || tagIds.isEmpty()) { + return; + } + for (String tagId : tagIds) { + if (!StringUtils.hasText(tagId)) { + continue; + } + wrapper.or().apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagId); + } + } + + /** + * Run business method `loadShopNameMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadShopNameMap(Set shopIds) { + if (shopIds == null || shopIds.isEmpty()) { + return Collections.emptyMap(); + } + return shopMapper.selectBatchIds(shopIds).stream() + .filter(shopDO -> !Integer.valueOf(1).equals(shopDO.getIsDelete())) + .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (left, right) -> left, LinkedHashMap::new)); + } + + /** + * Run business method `loadTagMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagIds parameter `tagIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadTagMap(Set tagIds) { + if (tagIds == null || tagIds.isEmpty()) { + return Collections.emptyMap(); + } + return tagMapper.selectBatchIds(tagIds).stream() + .filter(tagDO -> !Integer.valueOf(1).equals(tagDO.getIsDelete())) + .collect(Collectors.toMap(TagDO::getId, tagDO -> tagDO, (left, right) -> left, LinkedHashMap::new)); + } + + /** + * Run business method `parseDelimitedLongIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param rawValue parameter `rawValue` supplied by the caller + * @param delimiter parameter `delimiter` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List parseDelimitedLongIds(String rawValue, String delimiter) { + if (!StringUtils.hasText(rawValue)) { + return Collections.emptyList(); + } + List ids = new ArrayList<>(); + for (String value : rawValue.split(java.util.regex.Pattern.quote(delimiter))) { + if (!StringUtils.hasText(value)) { + continue; + } + try { + ids.add(Long.parseLong(value.trim())); + } catch (NumberFormatException ignored) { + // Ignore malformed ids in historical data and keep the rest of the product visible. + } + } + return ids; + } + + /** + * Purpose: parseTagIdFilter converts scene-filter tag ids into a query-safe set. + * Usage: pass comma or semicolon separated frontend values; invalid chunks are ignored. + */ + private Set parseTagIdFilter(String rawValue) { + if (!StringUtils.hasText(rawValue)) { + return Collections.emptySet(); + } + return java.util.Arrays.stream(rawValue.split("[,;]")) + .map(String::trim) + .filter(StringUtils::hasText) + .filter(value -> { + try { + Long.parseLong(value); + return true; + } catch (NumberFormatException exception) { + return false; + } + }) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `findExactTagIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set findExactTagIds(String tag) { + if (!StringUtils.hasText(tag)) { + return Set.of(); + } + return tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getTagName, tag) + ).stream() + .map(TagDO::getId) + .map(String::valueOf) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * Run business method `findLikeTagIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set findLikeTagIds(String keyword) { + if (!StringUtils.hasText(keyword)) { + return Set.of(); + } + return tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .like(TagDO::getTagName, keyword) + ).stream() + .map(TagDO::getId) + .map(String::valueOf) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * Run business method `buildEmptyPageResult`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @return private PageResultVO result consumed by the caller or returned to the frontend + */ + private PageResultVO buildEmptyPageResult(int page, int size) { + PageResultVO result = new PageResultVO<>(); + result.setList(List.of()); + result.setTotal(0L); + result.setPage(page); + result.setSize(size); + return result; + } + + /** + * Run business method `normalizePage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int normalizePage(Integer page) { + return page == null || page < 1 ? 1 : page; + } + + /** + * Run business method `normalizePageSize`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param size parameter `size` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int normalizePageSize(Integer size) { + if (size == null || size < 1) { + return DEFAULT_PUBLIC_PAGE_SIZE; + } + return Math.min(size, MAX_PUBLIC_PAGE_SIZE); + } + + /** + * Run business method `normalizeOptionalKeyword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeOptionalKeyword(String value) { + return StringUtils.hasText(value) ? value.trim() : ""; + } + + /** + * Purpose: normalizeShopId supports ProductServiceImpl.java by holding or executing the normalize shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long normalizeShopId(Long shopId) { + return shopId != null && shopId > 0 ? shopId : null; + } + + /** + * Purpose: buildShopCacheSegment supports ProductServiceImpl.java by holding or executing the build shop cache segment business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildShopCacheSegment(Long shopId) { + return shopId == null ? "all:" : "shop:" + shopId + ":"; + } + + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictPublicProductCaches(Long productId) { + if (productId != null) { + multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + productId); + multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + "public:" + productId); + } + multiLevelCacheService.evictByPrefix(PRODUCT_LIST_CACHE_PREFIX); + multiLevelCacheService.evictByPrefix(PRODUCT_SEARCH_CACHE_PREFIX); + } + + /** + * Purpose: ProductEnrichmentContext supports ProductServiceImpl.java by holding or executing the product enrichment context business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + private record ProductEnrichmentContext( + Map shopNames, + Map tags, + Map files + ) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/TagServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/TagServiceImpl.java new file mode 100644 index 00000000..a428474e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/service/impl/TagServiceImpl.java @@ -0,0 +1,545 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.TagDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.service.TagService; +import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagFilterGroupVO; +import com.xiaowang.jayucloud.artlist.core.modules.product.vo.TagVO; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 系统标签信息表 Service 实现 + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class TagServiceImpl extends ServiceImpl implements TagService { + /** + * Purpose: TAG_DETAIL_CACHE_PREFIX supports TagServiceImpl.java by holding or executing the tag detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TAG_DETAIL_CACHE_PREFIX = "cache:tag:detail:"; + /** + * Purpose: TAG_LIST_CACHE_PREFIX supports TagServiceImpl.java by holding or executing the tag list cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TAG_LIST_CACHE_PREFIX = "cache:tag:list:"; + /** + * Purpose: DEFAULT_FILTER_GROUP is the public group used for legacy tags without a scene group. + * Usage: keep old tags visible in filters without requiring data migration edits. + */ + private static final String DEFAULT_FILTER_GROUP = "其他"; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDTO parameter `tagDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createTag(TagDTO tagDTO) { + String tagName = normalizeTagName(tagDTO.getTagName()); + Long shopId = requireShopId(tagDTO.getShopId()); + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureTagNameUniqueInShop(tagName, shopId, null); + + TagDO tagDO = new TagDO(); + tagDO.setTagName(tagName); + tagDO.setTextColor(tagDTO.getTextColor()); + tagDO.setBgColor(tagDTO.getBgColor()); + tagDO.setBorderColor(tagDTO.getBorderColor()); + tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); + tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); + tagDO.setSortOrder(tagDTO.getSortOrder()); + tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); + tagDO.setShopId(shopId); + tagDO.setIsDelete(0); + try { + tagMapper.insert(tagDO); + } catch (DuplicateKeyException exception) { + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return throw result consumed by the caller or returned to the frontend + */ + throw buildDuplicateTagException(tagName, shopId, null); + } + evictTagCaches(tagDO.getId(), shopId); + return tagDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param tagDTO parameter `tagDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateTag(Long id, TagDTO tagDTO) { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null) { + return false; + } + String tagName = normalizeTagName(tagDTO.getTagName()); + Long shopId = requireShopId(tagDTO.getShopId()); + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureTagNameUniqueInShop(tagName, shopId, id); + + tagDO.setTagName(tagName); + tagDO.setTextColor(tagDTO.getTextColor()); + tagDO.setBgColor(tagDTO.getBgColor()); + tagDO.setBorderColor(tagDTO.getBorderColor()); + tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); + tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); + tagDO.setSortOrder(tagDTO.getSortOrder()); + tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); + tagDO.setShopId(shopId); + try { + boolean updated = tagMapper.updateById(tagDO) > 0; + if (updated) { + /** + * Run business method `evictTagCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictTagCaches(id, shopId); + } + return updated; + } catch (DuplicateKeyException exception) { + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return throw result consumed by the caller or returned to the frontend + */ + throw buildDuplicateTagException(tagName, shopId, id); + } + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteTag(Long id) { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null) { + return false; + } + tagDO.setIsDelete(1); + boolean deleted = tagMapper.updateById(tagDO) > 0; + if (deleted) { + evictTagCaches(id, tagDO.getShopId()); + } + return deleted; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return TagVO result consumed by the caller or returned to the frontend + */ + public TagVO getTagById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null || Integer.valueOf(1).equals(tagDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDO parameter `tagDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(tagDO); + } + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllTags() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .orderByDesc(TagDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listTagsByShopId(Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "shop:" + shopId, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getShopId, shopId) + .orderByDesc(TagDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) + ); + } + + @Override + /** + * Purpose: listFilterOptions builds public scene-filter groups for customer browsing. + * Usage: call it from Web or mini-program product pages; pass shopId to limit groups to one shop. + */ + public List listFilterOptions(Long shopId) { + Long scopedShopId = shopId != null && shopId > 0 ? shopId : null; + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "filter:" + (scopedShopId == null ? "all" : scopedShopId), + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> buildFilterOptions(scopedShopId) + ); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @return TagVO result consumed by the caller or returned to the frontend + */ + public TagVO getTagByTagName(String tagName) { + TagDO tagDO = tagMapper.selectOne( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getTagName, tagName) + ); + if (tagDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDO parameter `tagDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(tagDO); + } + + /** + * 将 DO 转换为 VO + * + * @param tagDO 标签DO + * @return 标签VO + */ + private TagVO convertToVO(TagDO tagDO) { + TagVO tagVO = new TagVO(); + tagVO.setId(tagDO.getId()); + tagVO.setTagName(tagDO.getTagName()); + tagVO.setTextColor(tagDO.getTextColor()); + tagVO.setBgColor(tagDO.getBgColor()); + tagVO.setBorderColor(tagDO.getBorderColor()); + tagVO.setSceneGroup(resolveSceneGroup(tagDO.getSceneGroup())); + tagVO.setDisplayName(resolveDisplayName(tagDO)); + tagVO.setSortOrder(tagDO.getSortOrder()); + tagVO.setFrontVisible(normalizeFrontVisible(tagDO.getFrontVisible())); + tagVO.setShopId(tagDO.getShopId()); + tagVO.setShopName(resolveShopName(tagDO.getShopId())); + tagVO.setCreateTime(tagDO.getCreateTime()); + tagVO.setUpdateTime(tagDO.getUpdateTime()); + return tagVO; + } + + /** + * Run business method `normalizeTagName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTagName(String tagName) { + if (!StringUtils.hasText(tagName)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("标签名称不能为空"); + } + return tagName.trim(); + } + + /** + * Purpose: buildFilterOptions groups visible tags while preserving legacy tags in a default group. + * Usage: call it only through the cache-backed public listFilterOptions method. + */ + private List buildFilterOptions(Long shopId) { + List tags = tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(shopId != null, TagDO::getShopId, shopId) + ); + Map> groupedTags = new LinkedHashMap<>(); + tags.stream() + .filter(tagDO -> !Integer.valueOf(0).equals(tagDO.getFrontVisible())) + .sorted(Comparator + .comparing((TagDO tagDO) -> resolveSceneGroup(tagDO.getSceneGroup()).equals(DEFAULT_FILTER_GROUP) ? 1 : 0) + .thenComparing(tagDO -> resolveSceneGroup(tagDO.getSceneGroup())) + .thenComparing(tagDO -> tagDO.getSortOrder() == null ? Integer.MAX_VALUE : tagDO.getSortOrder()) + .thenComparing(TagDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(TagDO::getId, Comparator.nullsLast(Long::compareTo))) + .forEach(tagDO -> groupedTags + .computeIfAbsent(resolveSceneGroup(tagDO.getSceneGroup()), ignored -> new ArrayList<>()) + .add(convertToVO(tagDO))); + return groupedTags.entrySet().stream() + .map(entry -> { + TagFilterGroupVO groupVO = new TagFilterGroupVO(); + groupVO.setGroupName(entry.getKey()); + groupVO.setTags(entry.getValue()); + return groupVO; + }) + .collect(Collectors.toList()); + } + + /** + * Purpose: normalizeOptionalText trims optional tag metadata. + * Usage: call before persisting sceneGroup or displayName so blank strings become null. + */ + private String normalizeOptionalText(String value) { + return StringUtils.hasText(value) ? value.trim() : null; + } + + /** + * Purpose: resolveSceneGroup keeps legacy tags usable in scene filters. + * Usage: call when serializing or grouping tags for public clients. + */ + private String resolveSceneGroup(String sceneGroup) { + return StringUtils.hasText(sceneGroup) ? sceneGroup.trim() : DEFAULT_FILTER_GROUP; + } + + /** + * Purpose: resolveDisplayName decides the public label for one tag. + * Usage: call when building TagVO so clients can render displayName directly. + */ + private String resolveDisplayName(TagDO tagDO) { + if (tagDO == null) { + return null; + } + return StringUtils.hasText(tagDO.getDisplayName()) ? tagDO.getDisplayName().trim() : tagDO.getTagName(); + } + + /** + * Purpose: normalizeFrontVisible defaults old rows to visible. + * Usage: call when saving and serializing the public visibility flag. + */ + private Integer normalizeFrontVisible(Integer frontVisible) { + return frontVisible == null ? 1 : frontVisible; + } + + /** + * Run business method `requireShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long requireShopId(Long shopId) { + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择所属店铺"); + } + return shopId; + } + + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureTagNameUniqueInShop(String tagName, Long shopId, Long excludeId) { + if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前店铺已存在同名标签"); + } + } + + /** + * Run business method `findActiveTagByNameAndShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private TagDO result consumed by the caller or returned to the frontend + */ + private TagDO findActiveTagByNameAndShopId(String tagName, Long shopId, Long excludeId) { + return tagMapper.selectOne( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getShopId, shopId) + .eq(TagDO::getTagName, tagName) + .ne(excludeId != null, TagDO::getId, excludeId) + .last("LIMIT 1") + ); + } + + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private RuntimeException result consumed by the caller or returned to the frontend + */ + private RuntimeException buildDuplicateTagException(String tagName, Long shopId, Long excludeId) { + if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return new result consumed by the caller or returned to the frontend + */ + return new RuntimeException("当前店铺已存在同名标签"); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return new result consumed by the caller or returned to the frontend + */ + return new RuntimeException("数据库仍使用旧的标签全局唯一约束,请先执行本次提供的 SQL 补丁"); + } + + /** + * Run business method `resolveShopName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveShopName(Long shopId) { + if (shopId == null || shopId <= 0) { + return null; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO == null ? null : shopDO.getShopName(); + } + + /** + * Run business method `evictTagCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagId parameter `tagId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictTagCaches(Long tagId, Long shopId) { + if (tagId != null) { + multiLevelCacheService.evict(TAG_DETAIL_CACHE_PREFIX + tagId); + } + if (shopId != null) { + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "shop:" + shopId); + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:" + shopId); + } + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "all"); + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:all"); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/EffectDiagramVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/EffectDiagramVO.java new file mode 100644 index 00000000..f962107a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/EffectDiagramVO.java @@ -0,0 +1,83 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 商品效果图信息表 VO + * 用于前端展示效果图信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class EffectDiagramVO { + + /** + * 效果图唯一主键ID(雪花id) + */ + private Long id; + + /** + * 所属商品ID,关联商品表主键 + */ + private Long productId; + + /** + * 商品标题 + */ + private String productTitle; + + /** + * 效果图类别 + */ + private String category; + + /** + * 图片文件ID集合,多ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 图片URL列表 + */ + private List imageUrls; + + /** + * 效果图描述 + */ + private String description; + + /** + * 效果图对应服务价格 + */ + private BigDecimal price; + + /** + * 效果图对应服务耗时 + */ + private String duration; + + /** + * 效果图标签 + */ + private String tag; + + /** + * 效果图点赞数 + */ + private Integer likeCount; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/HotProductVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/HotProductVO.java new file mode 100644 index 00000000..20d0ea96 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/HotProductVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +/** + * HotProductVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class HotProductVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + /** + * Field `likeCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer likeCount; + /** + * Field `collectCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer collectCount; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/ProductVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/ProductVO.java new file mode 100644 index 00000000..7576786c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/ProductVO.java @@ -0,0 +1,147 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 商品信息表 VO + * 用于前端展示商品信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ProductVO { + + /** + * 商品唯一主键ID(雪花id) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 所属店铺ID,关联店铺表主键 + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 商品标题 + */ + private String title; + + /** + * 商品描述 + */ + private String description; + + /** + * 适合人群说明;作品详情接口返回后由 Web/小程序在有值时展示。 + */ + private String targetAudience; + + /** + * 注意事项说明;作品详情接口返回后由 Web/小程序在有值时展示。 + */ + private String precautions; + + /** + * 图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 图片URL列表 + */ + private List imageUrls; + + /** + * 商品价格,保留2位小数 + */ + private BigDecimal price; + + /** + * 标签集合,多个标签以逗号分隔,最多5个 + */ + private String tags; + + /** + * 标签列表 + */ + private List tagList; + + /** + * 标签详情列表(包含样式信息) + */ + private List tagInfos; + + /** + * 商品点赞数 + */ + private Integer likeCount; + + /** + * 商品收藏数 + */ + private Integer collectCount; + + /** + * 商品对应的服务大约耗时(如"30分钟") + */ + private String approximateDuration; + + /** + * 实际用于预约排期计算的服务时长(分钟) + */ + private Long serviceDurationMinutes; + + /** + * 可预约的美甲师ID集合,多个ID以逗号分隔 + */ + private String bookableArtists; + + /** + * 当前仍可预约的美甲师数量 + */ + private Integer availableBookableArtistCount; + + /** + * 商品是否配置了限定美甲师 + */ + private Boolean bookableArtistRestricted; + + /** + * 可用的优惠券ID集合,多个ID以逗号分隔 + */ + private String availableCoupons; + + /** + * 前台是否展示:0-隐藏,1-展示 + */ + private Integer frontVisible; + + /** + * 来源类型 + */ + private String sourceType; + + /** + * 商品创建时间 + */ + private LocalDateTime createTime; + + /** + * 商品信息最后更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagFilterGroupVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagFilterGroupVO.java new file mode 100644 index 00000000..29064bb8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagFilterGroupVO.java @@ -0,0 +1,26 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * Purpose: TagFilterGroupVO groups public tags for customer scene filters. + * Usage: return it from `/tag/list/filter-options` and render each group as one filter row. + */ +@Data +public class TagFilterGroupVO { + + /** + * Purpose: groupName is the customer-facing group title. + * Usage: display it above the group's tag chips. + */ + private String groupName; + + /** + * Purpose: tags holds visible tags in the current filter group. + * Usage: use each tag id for product filtering and displayName/tagName for chip text. + */ + private List tags = new ArrayList<>(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagInfo.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagInfo.java new file mode 100644 index 00000000..0231e7c2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagInfo.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.vo; + +import lombok.Data; + +/** + * 标签信息 VO + * 用于前端展示标签,包含样式信息 + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class TagInfo { + + /** + * 标签ID + */ + private Long id; + + /** + * 标签名称 + */ + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + private String borderColor; + + public TagInfo() { + } + + public TagInfo(Long id, String tagName, String textColor, String bgColor, String borderColor) { + this.id = id; + this.tagName = tagName; + this.textColor = textColor; + this.bgColor = bgColor; + this.borderColor = borderColor; + } +} \ No newline at end of file diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagVO.java new file mode 100644 index 00000000..e2f6522e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/product/vo/TagVO.java @@ -0,0 +1,85 @@ +package com.xiaowang.jayucloud.artlist.core.modules.product.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 系统标签信息表 VO + * 用于前端展示标签信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class TagVO { + + /** + * 标签唯一主键ID + */ + private Long id; + + /** + * 标签名称 + */ + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + private String borderColor; + + /** + * Purpose: sceneGroup tells clients which public filter group this tag belongs to. + * Usage: read it from tag list APIs and group filter chips by this value. + */ + private String sceneGroup; + + /** + * Purpose: displayName is the public-facing tag label. + * Usage: show this value in filters; fall back to tagName if it is empty. + */ + private String displayName; + + /** + * Purpose: sortOrder controls the public order inside a group. + * Usage: sort lower values before higher values when rendering grouped filters. + */ + private Integer sortOrder; + + /** + * Purpose: frontVisible indicates whether the tag should appear in public filters. + * Usage: public filter APIs only return visible tags; admin screens may still display it. + */ + private Integer frontVisible; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; + + /** + * 店铺ID + */ + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/controller/front/PermissionController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/controller/front/PermissionController.java new file mode 100644 index 00000000..390ac93d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/controller/front/PermissionController.java @@ -0,0 +1,190 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.PermissionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.PermissionService; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.PermissionVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 系统权限表 Controller + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@RestController +@RequestMapping({"/permission", "/api/permission"}) +@RequiredArgsConstructor +public class PermissionController { + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionService permissionService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建权限 + * + * @param permissionDTO 权限DTO + * @return 权限ID + */ + @PostMapping("/create") + @RequirePermission("permission:create") + public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + Long id = permissionService.createPermission(permissionDTO); + return Result.success(id); + } + + /** + * 更新权限 + * + * @param id 权限ID + * @param permissionDTO 权限DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + @RequirePermission("permission:edit") + public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + boolean success = permissionService.updatePermission(id, permissionDTO); + return Result.success(success); + } + + /** + * 删除权限 + * + * @param id 权限ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("permission:delete") + public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + boolean success = permissionService.deletePermission(id); + return Result.success(success); + } + + /** + * 根据ID查询权限 + * + * @param id 权限ID + * @return 权限VO + */ + @GetMapping("/get/{id}") + @RequirePermission("permission:view") + public Result getPermissionById(@PathVariable Long id) { + PermissionVO permissionVO = permissionService.getPermissionById(id); + return Result.success(permissionVO); + } + + /** + * 查询所有权限 + * + * @return 权限VO列表 + */ + @GetMapping("/list/all") + @RequirePermission("permission:view") + public Result> listAllPermissions() { + List permissionVOs = permissionService.listAllPermissions(); + return Result.success(permissionVOs); + } + + /** + * 根据权限分组查询权限 + * + * @param permissionGroup 权限分组 + * @return 权限VO列表 + */ + @GetMapping("/list/group/{permissionGroup}") + @RequirePermission("permission:view") + public Result> listPermissionsByGroup(@PathVariable String permissionGroup) { + List permissionVOs = permissionService.listPermissionsByGroup(permissionGroup); + return Result.success(permissionVOs); + } + + /** + * 查询用户的权限列表 + * + * @param userId 用户ID + * @return 权限VO列表 + */ + @GetMapping("/list/user/{userId}") + @RequirePermission("permission:view") + public Result> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + UserDO targetUser = userService.getById(userId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); + } + List permissionVOs = permissionService.listUserPermissions(userId); + return Result.success(permissionVOs); + } + + /** + * 分配权限给用户 + * + * @param userPermissionDTO 用户权限分配DTO + * @return 是否分配成功 + */ + @PostMapping("/assign") + @RequirePermission("permission:assign") + public Result assignPermissions(HttpServletRequest request, @RequestBody UserPermissionDTO userPermissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + UserDO targetUser = userService.getById(userPermissionDTO.getUserId()); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "无权给其他店铺用户分配权限"); + } + Long userId = (Long) request.getAttribute("userId"); + boolean success = permissionService.assignPermissions(userPermissionDTO, userId); + return Result.success(success); + } + + /** + * 获取当前登录用户的权限列表 + * + * @return 权限列表 + */ + @GetMapping("/list/user/current") + public Result> getCurrentUserPermissions(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + List permissions = permissionService.listUserPermissions(userId); + return Result.success(permissions); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/PermissionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/PermissionDTO.java new file mode 100644 index 00000000..6d513ab1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/PermissionDTO.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.dto; + +import lombok.Data; + +/** + * 系统权限表 DTO + * 用于权限信息的传输 + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +public class PermissionDTO { + + /** + * 权限编码(唯一标识) + */ + private String permissionCode; + + /** + * 权限名称 + */ + private String permissionName; + + /** + * 权限分组(商品管理、用户管理等) + */ + private String permissionGroup; + + /** + * 权限描述 + */ + private String description; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/ShopRoleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/ShopRoleDTO.java new file mode 100644 index 00000000..4e4f5d7e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/ShopRoleDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.util.List; + +@Data +/** + * ShopRoleDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @NotBlank(message = "角色名不能为空") + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionIds; + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/UserPermissionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/UserPermissionDTO.java new file mode 100644 index 00000000..10739670 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/dto/UserPermissionDTO.java @@ -0,0 +1,26 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 用户权限分配 DTO + * 用于给用户分配权限 + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +public class UserPermissionDTO { + + /** + * 用户ID + */ + private Long userId; + + /** + * 权限ID列表 + */ + private List permissionIds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/PermissionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/PermissionDO.java new file mode 100644 index 00000000..ae06887d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/PermissionDO.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 系统权限表 DO + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_permission") +public class PermissionDO extends BaseEntity { + + /** + * 权限编码(唯一标识) + */ + @TableField("permission_code") + private String permissionCode; + + /** + * 权限名称 + */ + @TableField("permission_name") + private String permissionName; + + /** + * 权限分组(商品管理、用户管理等) + */ + @TableField("permission_group") + private String permissionGroup; + + /** + * 权限描述 + */ + @TableField("description") + private String description; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/SecurityAuditLogDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/SecurityAuditLogDO.java new file mode 100644 index 00000000..f02b0031 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/SecurityAuditLogDO.java @@ -0,0 +1,76 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; + +@Getter +@Setter +@TableName("t_security_audit_log") +/** + * Purpose: SecurityAuditLogDO supports SecurityAuditLogDO.java by holding or executing the security audit log do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditLogDO extends BaseEntity { + + @TableField("user_id") + /** + * Purpose: userId supports SecurityAuditLogDO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + + @TableField("account") + /** + * Purpose: account supports SecurityAuditLogDO.java by holding or executing the account business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String account; + + @TableField("action") + /** + * Purpose: action supports SecurityAuditLogDO.java by holding or executing the action business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String action; + + @TableField("result") + /** + * Purpose: result supports SecurityAuditLogDO.java by holding or executing the result business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String result; + + @TableField("reason") + /** + * Purpose: reason supports SecurityAuditLogDO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + + @TableField("ip_address") + /** + * Purpose: ipAddress supports SecurityAuditLogDO.java by holding or executing the ip address business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String ipAddress; + + @TableField("device_id") + /** + * Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String deviceId; + + @TableField("operate_time") + /** + * Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime operateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/ShopRoleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/ShopRoleDO.java new file mode 100644 index 00000000..47e4dddf --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/ShopRoleDO.java @@ -0,0 +1,61 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_shop_role") +/** + * ShopRoleDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleDO extends BaseEntity { + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("role_name") + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + + @TableField("creator_id") + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/ShopRolePermissionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/ShopRolePermissionDO.java new file mode 100644 index 00000000..1e9058d5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/ShopRolePermissionDO.java @@ -0,0 +1,37 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_shop_role_permission") +/** + * ShopRolePermissionDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRolePermissionDO extends BaseEntity { + + @TableField("role_id") + /** + * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long roleId; + + @TableField("permission_id") + /** + * Field `permissionId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long permissionId; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/UserPermissionDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/UserPermissionDO.java new file mode 100644 index 00000000..a706ddf3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/UserPermissionDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 用户权限关联表 DO + * 对应数据库表 t_user_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_permission") +public class UserPermissionDO extends BaseEntity { + + /** + * 用户ID + */ + @TableField("user_id") + private Long userId; + + /** + * 权限ID + */ + @TableField("permission_id") + private Long permissionId; + + /** + * 创建人ID + */ + @TableField("create_by") + private Long createBy; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/UserShopRoleDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/UserShopRoleDO.java new file mode 100644 index 00000000..9ea09259 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/entity/UserShopRoleDO.java @@ -0,0 +1,49 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_shop_role") +/** + * UserShopRoleDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserShopRoleDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("role_id") + /** + * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long roleId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/PermissionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/PermissionMapper.java new file mode 100644 index 00000000..1b1ccd23 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/PermissionMapper.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.PermissionDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 系统权限表 Mapper + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Mapper +public interface PermissionMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/SecurityAuditLogMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/SecurityAuditLogMapper.java new file mode 100644 index 00000000..4c4202f9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/SecurityAuditLogMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.SecurityAuditLogDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: SecurityAuditLogMapper supports SecurityAuditLogMapper.java by holding or executing the security audit log mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SecurityAuditLogMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/ShopRoleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/ShopRoleMapper.java new file mode 100644 index 00000000..999cfd63 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/ShopRoleMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.ShopRoleDO; + +/** + * ShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface ShopRoleMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/ShopRolePermissionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/ShopRolePermissionMapper.java new file mode 100644 index 00000000..8a569528 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/ShopRolePermissionMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.ShopRolePermissionDO; + +/** + * ShopRolePermissionMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface ShopRolePermissionMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/UserPermissionMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/UserPermissionMapper.java new file mode 100644 index 00000000..c059821b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/UserPermissionMapper.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserPermissionDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 用户权限关联表 Mapper + * 对应数据库表 t_user_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Mapper +public interface UserPermissionMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/UserShopRoleMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/UserShopRoleMapper.java new file mode 100644 index 00000000..60746c6f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/mapper/UserShopRoleMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserShopRoleDO; + +/** + * UserShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserShopRoleMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/PermissionService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/PermissionService.java new file mode 100644 index 00000000..b12a4f2b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/PermissionService.java @@ -0,0 +1,102 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.PermissionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.PermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.PermissionVO; + +import java.util.List; + +/** + * 系统权限表 Service + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +public interface PermissionService extends IService { + + /** + * 创建权限 + * + * @param permissionDTO 权限DTO + * @return 权限ID + */ + Long createPermission(PermissionDTO permissionDTO); + + /** + * 更新权限 + * + * @param id 权限ID + * @param permissionDTO 权限DTO + * @return 是否更新成功 + */ + boolean updatePermission(Long id, PermissionDTO permissionDTO); + + /** + * 删除权限 + * + * @param id 权限ID + * @return 是否删除成功 + */ + boolean deletePermission(Long id); + + /** + * 根据ID查询权限 + * + * @param id 权限ID + * @return 权限VO + */ + PermissionVO getPermissionById(Long id); + + /** + * 查询所有权限 + * + * @return 权限VO列表 + */ + List listAllPermissions(); + + /** + * 根据权限分组查询权限 + * + * @param permissionGroup 权限分组 + * @return 权限VO列表 + */ + List listPermissionsByGroup(String permissionGroup); + + /** + * 查询用户的权限列表 + * + * @param userId 用户ID + * @return 权限VO列表 + */ + List listUserPermissions(Long userId); + + /** + * 查询当前操作人可给目标用户分配的权限ID列表 + * + * @param targetUserId 目标用户ID + * @param currentUserId 当前操作人ID + * @return 可分配的权限ID列表 + */ + List listAssignablePermissionIds(Long targetUserId, Long currentUserId); + + /** + * 给用户分配权限 + * + * @param userPermissionDTO 用户权限分配DTO + * @param currentUserId 当前操作人ID + * @return 是否分配成功 + */ + boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId); + + /** + * 检查用户是否拥有指定权限 + * + * @param userId 用户ID + * @param permissionCode 权限编码 + * @return 是否拥有权限 + */ + boolean hasPermission(Long userId, String permissionCode); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/SecurityAuditLogService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/SecurityAuditLogService.java new file mode 100644 index 00000000..ca9e1eb8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/SecurityAuditLogService.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.service; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO; + +/** + * Purpose: SecurityAuditLogService supports SecurityAuditLogService.java by holding or executing the security audit log service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SecurityAuditLogService { + + void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request); + + PageResultVO pageLogs(String account, + String action, + String result, + LocalDateTime startTime, + LocalDateTime endTime, + Integer page, + Integer size); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/ShopRoleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/ShopRoleService.java new file mode 100644 index 00000000..a2d5e6b2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/ShopRoleService.java @@ -0,0 +1,120 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.InviteCodeDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.ShopRoleDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.UserRelationUpdateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.ShopRoleDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.ShopRoleVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserRelationVO; + +import java.util.List; + +/** + * ShopRoleService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ShopRoleService extends IService { + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listRoles(UserDO currentUser, Long shopId); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createRole(UserDO currentUser, ShopRoleDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean deleteRole(UserDO currentUser, Long id); + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds); + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean assignUsers(UserDO currentUser, Long id, List userIds); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listRelationOptions(UserDO currentUser, Long shopId); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listInviteCodes(UserDO currentUser, Long shopId); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createInviteCode(UserDO currentUser, InviteCodeDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status); + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return InviteCodeVO result consumed by the caller or returned to the frontend + */ + InviteCodeVO resolveInviteCode(String code); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/PermissionServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/PermissionServiceImpl.java new file mode 100644 index 00000000..c6c1f4e7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/PermissionServiceImpl.java @@ -0,0 +1,688 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.PermissionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.PermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserPermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.ShopRolePermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.UserPermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.ShopRolePermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.PermissionService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy; +import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.PermissionVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * PermissionServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class PermissionServiceImpl extends ServiceImpl implements PermissionService { + + private static final Set SHOP_BOOTSTRAP_PERMISSION_CODES = Set.of( + "shop:view", + "shop:create" + ); + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserPermissionMapper userPermissionMapper; + /** + * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRolePermissionMapper shopRolePermissionMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createPermission(PermissionDTO permissionDTO) { + PermissionDO permissionDO = new PermissionDO(); + permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); + permissionDO.setPermissionName(permissionDTO.getPermissionName()); + permissionDO.setPermissionGroup(permissionDTO.getPermissionGroup()); + permissionDO.setDescription(permissionDTO.getDescription()); + permissionDO.setIsDelete(0); + permissionMapper.insert(permissionDO); + return permissionDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updatePermission(Long id, PermissionDTO permissionDTO) { + PermissionDO permissionDO = permissionMapper.selectById(id); + if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { + return false; + } + if (permissionDTO.getPermissionCode() != null) { + permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); + } + if (permissionDTO.getPermissionName() != null) { + permissionDO.setPermissionName(permissionDTO.getPermissionName()); + } + if (permissionDTO.getPermissionGroup() != null) { + permissionDO.setPermissionGroup(permissionDTO.getPermissionGroup()); + } + if (permissionDTO.getDescription() != null) { + permissionDO.setDescription(permissionDTO.getDescription()); + } + permissionDO.setUpdateTime(LocalDateTime.now()); + return permissionMapper.updateById(permissionDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deletePermission(Long id) { + PermissionDO permissionDO = permissionMapper.selectById(id); + if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { + return false; + } + permissionDO.setIsDelete(1); + permissionDO.setUpdateTime(LocalDateTime.now()); + return permissionMapper.updateById(permissionDO) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return PermissionVO result consumed by the caller or returned to the frontend + */ + public PermissionVO getPermissionById(Long id) { + PermissionDO permissionDO = permissionMapper.selectById(id); + if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDO parameter `permissionDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(permissionDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllPermissions() { + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionGroup parameter `permissionGroup` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listPermissionsByGroup(String permissionGroup) { + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionGroup, permissionGroup) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listUserPermissions(Long userId) { + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return List.of(); + } + if (isShopBootstrapAdmin(userDO)) { + return listAllPermissions().stream() + .filter(permission -> PermissionCatalog.isAllowedForPlatformOverview(permission.getPermissionCode())) + .collect(Collectors.toList()); + } + + List activeShopRoles = listActiveShopRoles(userId); + if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { + return listPermissionsByIds(listPermissionIdsByShopRoles(activeShopRoles)).stream() + .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) + .collect(Collectors.toList()); + } + + List userPermissions = userPermissionMapper.selectList( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + ); + if (userPermissions.isEmpty()) { + return List.of(); + } + + List permissionIds = userPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (permissionIds.isEmpty()) { + return List.of(); + } + + List permissionVOs = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getId, permissionIds) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + + return permissionVOs.stream() + .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAssignablePermissionIds(Long targetUserId, Long currentUserId) { + UserDO currentUser = userMapper.selectById(currentUserId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户不存在"); + } + + UserDO targetUser = userMapper.selectById(targetUserId); + if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + + if (!hasPermission(currentUserId, "permission:assign")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("权限不足,无法分配权限"); + } + + boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前角色不能维护该用户的权限"); + } + + if (!platformAdmin) { + if (currentUserId.equals(targetUserId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不允许给自己调整权限"); + } + if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(targetUserId, currentShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能给本店铺用户分配权限"); + } + } + + Set baseAllowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); + Set operatorPermissionCodes = platformAdmin + ? Collections.emptySet() + : listPermissionCodesByUserId(currentUserId); + Set assignablePermissionCodes = platformAdmin + ? baseAllowedPermissionCodes + : baseAllowedPermissionCodes.stream() + .filter(operatorPermissionCodes::contains) + .collect(Collectors.toSet()); + + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .filter(permission -> assignablePermissionCodes.contains(permission.getPermissionCode())) + .map(PermissionDO::getId) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userPermissionDTO parameter `userPermissionDTO` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId) { + Long userId = userPermissionDTO.getUserId(); + List permissionIds = userPermissionDTO.getPermissionIds() == null + ? Collections.emptyList() + : userPermissionDTO.getPermissionIds().stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + + UserDO currentUser = userMapper.selectById(currentUserId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户不存在"); + } + + UserDO targetUser = userMapper.selectById(userId); + if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + + if (!hasPermission(currentUserId, "permission:assign")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("权限不足,无法分配权限"); + } + + boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前角色不能维护该用户的权限"); + } + + if (!platformAdmin) { + if (currentUserId.equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不允许给自己调整权限"); + } + if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(userId, currentShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能给本店铺用户分配权限"); + } + } + + Set requestedPermissionCodes = resolvePermissionCodes(permissionIds); + Set allowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); + if (!allowedPermissionCodes.containsAll(requestedPermissionCodes)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标角色的权限配置超出允许范围"); + } + + if (!platformAdmin) { + Set operatorPermissionCodes = listPermissionCodesByUserId(currentUserId); + if (!operatorPermissionCodes.containsAll(requestedPermissionCodes)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不能分配超出自己已有的权限"); + } + } + + userPermissionMapper.delete( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + ); + + for (Long permissionId : permissionIds) { + UserPermissionDO userPermissionDO = new UserPermissionDO(); + userPermissionDO.setUserId(userId); + userPermissionDO.setPermissionId(permissionId); + userPermissionDO.setCreateBy(currentUserId); + userPermissionMapper.insert(userPermissionDO); + } + + return true; + } + + @Override + /** + * Run business method `hasPermission`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param permissionCode parameter `permissionCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean hasPermission(Long userId, String permissionCode) { + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + if (isShopBootstrapAdmin(userDO)) { + return PermissionCatalog.isAllowedForPlatformOverview(permissionCode); + } + if (!isPermissionAllowedForUserType(userDO, permissionCode)) { + return false; + } + + List activeShopRoles = listActiveShopRoles(userId); + if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { + return hasShopRolePermission(activeShopRoles, permissionCode); + } + + List userPermissions = userPermissionMapper.selectList( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + ); + if (userPermissions.isEmpty()) { + return false; + } + + List permissionIds = userPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (permissionIds.isEmpty()) { + return false; + } + + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + ); + if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) { + return false; + } + + return true; + } + + /** + * Purpose: hasShopRolePermission supports PermissionServiceImpl.java by holding or executing the has shop role permission business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean hasShopRolePermission(List activeShopRoles, String permissionCode) { + List permissionIds = listPermissionIdsByShopRoles(activeShopRoles); + if (permissionIds.isEmpty()) { + return false; + } + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + .last("limit 1")); + return permissionDO != null && permissionIds.contains(permissionDO.getId()); + } + + /** + * Run business method `resolvePermissionCodes`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set resolvePermissionCodes(List permissionIds) { + if (permissionIds == null || permissionIds.isEmpty()) { + return Collections.emptySet(); + } + + List permissionDOs = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getId, permissionIds) + .eq(PermissionDO::getIsDelete, 0) + ); + if (permissionDOs.size() != permissionIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效的权限配置"); + } + + return permissionDOs.stream() + .map(PermissionDO::getPermissionCode) + .collect(Collectors.toSet()); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set listPermissionCodesByUserId(Long userId) { + return listUserPermissions(userId).stream() + .map(PermissionVO::getPermissionCode) + .collect(Collectors.toSet()); + } + + /** + * Purpose: listActiveShopRoles supports PermissionServiceImpl.java by holding or executing the list active shop roles business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listActiveShopRoles(Long userId) { + if (userId == null) { + return List.of(); + } + + Long currentShopId = RequestShopContext.getCurrentShopId(); + List activeShopRoles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class) + .eq(UserShopRoleDO::getUserId, userId) + .eq(currentShopId != null, UserShopRoleDO::getShopId, currentShopId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1)); + if (currentShopId == null) { + return activeShopRoles; + } + return activeShopRoles.stream() + .filter(role -> Objects.equals(currentShopId, role.getShopId())) + .collect(Collectors.toList()); + } + + /** + * Purpose: listPermissionIdsByShopRoles supports PermissionServiceImpl.java by holding or executing the list permission ids by shop roles business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listPermissionIdsByShopRoles(List activeShopRoles) { + if (activeShopRoles == null || activeShopRoles.isEmpty()) { + return List.of(); + } + + List roleIds = activeShopRoles.stream() + .map(UserShopRoleDO::getRoleId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (roleIds.isEmpty()) { + return List.of(); + } + + return shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class) + .in(ShopRolePermissionDO::getRoleId, roleIds) + .eq(ShopRolePermissionDO::getIsDelete, 0)) + .stream() + .filter(permission -> roleIds.contains(permission.getRoleId())) + .map(ShopRolePermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Purpose: listPermissionsByIds supports PermissionServiceImpl.java by holding or executing the list permissions by ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listPermissionsByIds(List permissionIds) { + if (permissionIds == null || permissionIds.isEmpty()) { + return List.of(); + } + + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getId, permissionIds) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * Purpose: usesShopRoleEffectivePermissions supports PermissionServiceImpl.java by holding or executing the uses shop role effective permissions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean usesShopRoleEffectivePermissions(UserDO userDO, List activeShopRoles) { + return !isPlatformAdmin(userDO) && activeShopRoles != null && !activeShopRoles.isEmpty(); + } + + /** + * Purpose: isPermissionAllowedForUserType supports PermissionServiceImpl.java by holding or executing the is permission allowed for user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isPermissionAllowedForUserType(UserDO userDO, String permissionCode) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + if (isPlatformAdmin(userDO)) { + return true; + } + return PermissionPolicy.getDefaultPermissionCodeSet(userDO.getType()).contains(permissionCode); + } + + /** + * Purpose: isPlatformAdmin supports PermissionServiceImpl.java by holding or executing the is platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isPlatformAdmin(UserDO userDO) { + return userDO != null && Integer.valueOf(4).equals(userDO.getType()); + } + + /** + * Run business method `isShopBootstrapAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isShopBootstrapAdmin(UserDO userDO) { + return userDO != null + && Integer.valueOf(4).equals(userDO.getType()) + && RequestShopContext.getCurrentShopId() == null; + } + + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDO parameter `permissionDO` supplied by the caller + * @return private PermissionVO result consumed by the caller or returned to the frontend + */ + private PermissionVO convertToVO(PermissionDO permissionDO) { + PermissionVO permissionVO = new PermissionVO(); + permissionVO.setId(permissionDO.getId()); + permissionVO.setPermissionCode(permissionDO.getPermissionCode()); + permissionVO.setPermissionName(permissionDO.getPermissionName()); + permissionVO.setPermissionGroup(permissionDO.getPermissionGroup()); + permissionVO.setDescription(permissionDO.getDescription()); + permissionVO.setCreateTime(permissionDO.getCreateTime()); + permissionVO.setUpdateTime(permissionDO.getUpdateTime()); + return permissionVO; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java new file mode 100644 index 00000000..4dd0ef8f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java @@ -0,0 +1,135 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.SecurityAuditLogDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.SecurityAuditLogMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.SecurityAuditLogVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +/** + * Purpose: SecurityAuditLogServiceImpl supports SecurityAuditLogServiceImpl.java by holding or executing the security audit log service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { + + /** + * Purpose: auditLogMapper supports SecurityAuditLogServiceImpl.java by holding or executing the audit log mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogMapper auditLogMapper; + + @Override + /** + * Purpose: record supports SecurityAuditLogServiceImpl.java by holding or executing the record business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request) { + try { + SecurityAuditLogDO log = new SecurityAuditLogDO(); + log.setUserId(userId); + log.setAccount(limit(account, 80)); + log.setAction(limit(action, 80)); + log.setResult(limit(result, 20)); + log.setReason(limit(reason, 500)); + log.setIpAddress(limit(resolveClientIp(request), 80)); + log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120)); + log.setOperateTime(LocalDateTime.now()); + auditLogMapper.insert(log); + } catch (Exception ignored) { + // Audit failure must never block the main user flow. + } + } + + @Override + public PageResultVO pageLogs(String account, + String action, + String result, + LocalDateTime startTime, + LocalDateTime endTime, + Integer page, + Integer size) { + int pageNo = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 20 : Math.min(size, 100); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (StringUtils.hasText(account)) { + wrapper.like(SecurityAuditLogDO::getAccount, account.trim()); + } + if (StringUtils.hasText(action)) { + wrapper.eq(SecurityAuditLogDO::getAction, action.trim()); + } + if (StringUtils.hasText(result)) { + wrapper.eq(SecurityAuditLogDO::getResult, result.trim()); + } + if (startTime != null) { + wrapper.ge(SecurityAuditLogDO::getOperateTime, startTime); + } + if (endTime != null) { + wrapper.le(SecurityAuditLogDO::getOperateTime, endTime); + } + wrapper.orderByDesc(SecurityAuditLogDO::getOperateTime).orderByDesc(SecurityAuditLogDO::getId); + Page logPage = auditLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper); + + PageResultVO resultVO = new PageResultVO<>(); + resultVO.setList(logPage.getRecords().stream().map(this::toVO).toList()); + resultVO.setTotal(logPage.getTotal()); + resultVO.setPage(pageNo); + resultVO.setSize(pageSize); + return resultVO; + } + + /** + * Purpose: toVO supports SecurityAuditLogServiceImpl.java by holding or executing the to vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SecurityAuditLogVO toVO(SecurityAuditLogDO log) { + SecurityAuditLogVO vo = new SecurityAuditLogVO(); + vo.setId(log.getId()); + vo.setUserId(log.getUserId()); + vo.setAccount(log.getAccount()); + vo.setAction(log.getAction()); + vo.setResult(log.getResult()); + vo.setReason(log.getReason()); + vo.setIpAddress(log.getIpAddress()); + vo.setDeviceId(log.getDeviceId()); + vo.setOperateTime(log.getOperateTime()); + return vo; + } + + /** + * Purpose: resolveClientIp supports SecurityAuditLogServiceImpl.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return null; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); + } + + /** + * Purpose: limit supports SecurityAuditLogServiceImpl.java by holding or executing the limit business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String limit(String value, int max) { + if (value == null || value.length() <= max) { + return value; + } + return value.substring(0, max); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/ShopRoleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/ShopRoleServiceImpl.java new file mode 100644 index 00000000..91d77344 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/service/impl/ShopRoleServiceImpl.java @@ -0,0 +1,546 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.InviteCodeDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.ShopRoleDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.UserRelationUpdateDTO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.PermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.ShopRoleDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.ShopRolePermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserInviteCodeDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserRelationDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.ShopRoleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.ShopRolePermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserInviteCodeMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserRelationMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.jayucloud.artlist.core.modules.security.vo.ShopRoleVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserRelationVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.UserShopBindingDO; +@Service +@RequiredArgsConstructor +/** + * ShopRoleServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ShopRoleServiceImpl extends ServiceImpl implements ShopRoleService { + /** + * Variable `shopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleMapper shopRoleMapper; + /** + * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRolePermissionMapper shopRolePermissionMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserRelationMapper userRelationMapper; + /** + * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserInviteCodeMapper userInviteCodeMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listRoles(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return shopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(ShopRoleDO::getIsDelete, 0) + .eq(scopedShopId != null, ShopRoleDO::getShopId, scopedShopId) + .orderByAsc(ShopRoleDO::getSortOrder) + .orderByDesc(ShopRoleDO::getCreateTime)) + .stream().map(this::toVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createRole(UserDO currentUser, ShopRoleDTO dto) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); + if (shopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权创建其他店铺角色"); + ShopRoleDO role = new ShopRoleDO(); + role.setShopId(shopId); + role.setRoleName(dto.getRoleName().trim()); + role.setCreatorId(currentUser.getId()); + role.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); + role.setRemark(dto.getRemark()); + role.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + role.setIsDelete(0); + shopRoleMapper.insert(role); + syncPermissions(role.getId(), dto.getPermissionIds()); + syncUsers(role.getId(), dto.getUserIds(), shopId); + return role.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权修改其他店铺角色"); + if (StringUtils.hasText(dto.getRoleName())) { + role.setRoleName(dto.getRoleName().trim()); + } + if (dto.getStatus() != null) { + role.setStatus(dto.getStatus() == 0 ? 0 : 1); + } + if (dto.getRemark() != null) { + role.setRemark(dto.getRemark()); + } + if (dto.getSortOrder() != null) { + role.setSortOrder(dto.getSortOrder()); + } + role.setUpdateTime(LocalDateTime.now()); + shopRoleMapper.updateById(role); + if (dto.getPermissionIds() != null) { + syncPermissions(role.getId(), dto.getPermissionIds()); + } + if (dto.getUserIds() != null) { + syncUsers(role.getId(), dto.getUserIds(), role.getShopId()); + } + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean deleteRole(UserDO currentUser, Long id) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权删除其他店铺角色"); + role.setIsDelete(1); + role.setUpdateTime(LocalDateTime.now()); + shopRoleMapper.updateById(role); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权分配其他店铺角色"); + /** + * Run business method `syncPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncPermissions(id, permissionIds); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean assignUsers(UserDO currentUser, Long id, List userIds) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权绑定其他店铺员工"); + syncUsers(id, userIds, role.getShopId()); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listRelationOptions(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List users = userMapper.selectList(new LambdaQueryWrapper().eq(UserDO::getIsDelete, 0)); + if (scopedShopId != null) { + Set userIds = userShopBindingMapper.selectList(new LambdaQueryWrapper<>()) + .stream().filter(b -> Objects.equals(scopedShopId, b.getShopId()) && Integer.valueOf(1).equals(b.getStatus())) + .map(b -> b.getUserId()).collect(Collectors.toSet()); + users = users.stream().filter(u -> userIds.contains(u.getId())).collect(Collectors.toList()); + } + return users.stream().map(u -> { + UserRelationVO vo = new UserRelationVO(); + vo.setUserId(u.getId()); + vo.setShopId(scopedShopId); + vo.setParentUserId(null); + vo.setParentUserName(u.getNickname()); + vo.setParentRoleType(u.getType()); + vo.setParentRoleTypeName(typeName(u.getType())); + vo.setSourceType("MANUAL"); + vo.setSourceTypeName("手动维护"); + return vo; + }).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权修改所属关系"); + UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() + .eq(UserRelationDO::getUserId, userId) + .eq(UserRelationDO::getIsDelete, 0) + .last("limit 1")); + if (relation == null) { + relation = new UserRelationDO(); + relation.setUserId(userId); + relation.setIsDelete(0); + userRelationMapper.insert(relation); + } + relation.setShopId(dto.getShopId() == null ? user.getShopId() : dto.getShopId()); + relation.setParentUserId(dto.getParentUserId()); + relation.setParentRoleType(dto.getParentRoleType()); + relation.setSourceType(dto.getSourceType()); + relation.setCreatorId(currentUser.getId()); + relation.setUpdateTime(LocalDateTime.now()); + userRelationMapper.updateById(relation); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listInviteCodes(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return userInviteCodeMapper.selectList(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getIsDelete, 0) + .eq(scopedShopId != null, UserInviteCodeDO::getShopId, scopedShopId) + .orderByDesc(UserInviteCodeDO::getCreateTime)) + .stream().map(this::toInviteVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createInviteCode(UserDO currentUser, InviteCodeDTO dto) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); + if (shopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + UserInviteCodeDO code = new UserInviteCodeDO(); + code.setInviteCode(dto.getInviteCode().trim()); + code.setOwnerUserId(dto.getOwnerUserId()); + code.setShopId(shopId); + code.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); + code.setUseCount(dto.getUseCount() == null ? 0 : dto.getUseCount()); + code.setExpireTime(dto.getExpireTime()); + code.setIsDelete(0); + userInviteCodeMapper.insert(code); + return code.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status) { + UserInviteCodeDO code = userInviteCodeMapper.selectById(id); + if (code == null || Integer.valueOf(1).equals(code.getIsDelete())) { + return false; + } + adminScopeHelper.ensureShopAccessible(currentUser, code.getShopId(), "无权修改其他店铺邀请码"); + code.setStatus(status == null || status == 0 ? 0 : 1); + code.setUpdateTime(LocalDateTime.now()); + userInviteCodeMapper.updateById(code); + return true; + } + + @Override + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return InviteCodeVO result consumed by the caller or returned to the frontend + */ + public InviteCodeVO resolveInviteCode(String code) { + if (!StringUtils.hasText(code)) { + return null; + } + UserInviteCodeDO entity = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, code.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .last("limit 1")); + return entity == null ? null : toInviteVO(entity); + } + + /** + * Run business method `syncPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void syncPermissions(Long roleId, List permissionIds) { + // 保存角色权限时采用“先清空再重建”的方式: + // 表单里传来的 permissionIds 就是最终状态,避免残留上一次勾选的权限。 + shopRolePermissionMapper.delete(new LambdaQueryWrapper().eq(ShopRolePermissionDO::getRoleId, roleId)); + if (permissionIds == null) { + return; + } + for (Long permissionId : permissionIds.stream().filter(Objects::nonNull).distinct().toList()) { + ShopRolePermissionDO item = new ShopRolePermissionDO(); + item.setRoleId(roleId); + item.setPermissionId(permissionId); + item.setIsDelete(0); + shopRolePermissionMapper.insert(item); + } + } + + /** + * Run business method `syncUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void syncUsers(Long roleId, List userIds, Long shopId) { + userShopRoleMapper.delete(new LambdaQueryWrapper().eq(UserShopRoleDO::getRoleId, roleId)); + if (userIds == null) { + return; + } + for (Long userId : userIds.stream().filter(Objects::nonNull).distinct().toList()) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + continue; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (!Objects.equals(shopId, user.getShopId()) && bindingCount <= 0) { + continue; + } + UserShopRoleDO item = new UserShopRoleDO(); + item.setRoleId(roleId); + item.setUserId(userId); + item.setShopId(shopId); + item.setStatus(1); + item.setIsDelete(0); + userShopRoleMapper.insert(item); + } + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param role parameter `role` supplied by the caller + * @return private ShopRoleVO result consumed by the caller or returned to the frontend + */ + private ShopRoleVO toVO(ShopRoleDO role) { + ShopRoleVO vo = new ShopRoleVO(); + vo.setId(role.getId()); + vo.setShopId(role.getShopId()); + ShopDO shop = shopMapper.selectById(role.getShopId()); + vo.setShopName(shop == null ? null : shop.getShopName()); + vo.setRoleName(role.getRoleName()); + vo.setCreatorId(role.getCreatorId()); + UserDO creator = role.getCreatorId() == null ? null : userMapper.selectById(role.getCreatorId()); + vo.setCreatorName(creator == null ? null : creator.getNickname()); + vo.setStatus(role.getStatus()); + vo.setRemark(role.getRemark()); + vo.setSortOrder(role.getSortOrder()); + vo.setCreateTime(role.getCreateTime()); + vo.setUpdateTime(role.getUpdateTime()); + List permissions = shopRolePermissionMapper.selectList(new LambdaQueryWrapper() + .eq(ShopRolePermissionDO::getRoleId, role.getId()) + .eq(ShopRolePermissionDO::getIsDelete, 0)); + vo.setPermissionIds(permissions.stream().map(ShopRolePermissionDO::getPermissionId).collect(Collectors.toList())); + Set permissionIds = vo.getPermissionIds().stream().collect(Collectors.toSet()); + if (!permissionIds.isEmpty()) { + vo.setPermissionCodes(permissionMapper.selectBatchIds(permissionIds).stream().map(PermissionDO::getPermissionCode).collect(Collectors.toList())); + } else { + vo.setPermissionCodes(List.of()); + } + vo.setUserIds(userShopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getRoleId, role.getId()) + .eq(UserShopRoleDO::getIsDelete, 0)) + .stream().map(UserShopRoleDO::getUserId).collect(Collectors.toList())); + return vo; + } + + /** + * Run business method `toInviteVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return private InviteCodeVO result consumed by the caller or returned to the frontend + */ + private InviteCodeVO toInviteVO(UserInviteCodeDO code) { + InviteCodeVO vo = new InviteCodeVO(); + vo.setId(code.getId()); + vo.setInviteCode(code.getInviteCode()); + vo.setOwnerUserId(code.getOwnerUserId()); + vo.setOwnerUserName(code.getOwnerUserId() == null ? null : Optional.ofNullable(userMapper.selectById(code.getOwnerUserId())).map(UserDO::getNickname).orElse(null)); + vo.setShopId(code.getShopId()); + vo.setShopName(code.getShopId() == null ? null : Optional.ofNullable(shopMapper.selectById(code.getShopId())).map(ShopDO::getShopName).orElse(null)); + vo.setStatus(code.getStatus()); + vo.setUseCount(code.getUseCount()); + vo.setExpireTime(code.getExpireTime()); + vo.setCreateTime(code.getCreateTime()); + return vo; + } + + /** + * Run business method `requireRole`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private ShopRoleDO result consumed by the caller or returned to the frontend + */ + private ShopRoleDO requireRole(Long id) { + ShopRoleDO role = shopRoleMapper.selectById(id); + if (role == null || Integer.valueOf(1).equals(role.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("角色不存在"); + } + return role; + } + + /** + * Run business method `typeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String typeName(Integer type) { + return switch (type == null ? -1 : type) { + case 0 -> "普通用户"; + case 2 -> "店长"; + case 3 -> "美甲师"; + case 4 -> "管理员"; + default -> "未知"; + }; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/AdminScopeHelper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/AdminScopeHelper.java new file mode 100644 index 00000000..0160e008 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/AdminScopeHelper.java @@ -0,0 +1,192 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.support; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +@Component +@RequiredArgsConstructor +/** + * Purpose: AdminScopeHelper supports AdminScopeHelper.java by holding or executing the admin scope helper business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class AdminScopeHelper { + + /** + * Purpose: userService supports AdminScopeHelper.java by holding or executing the user service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserService userService; + /** + * Purpose: userShopBindingSupport supports AdminScopeHelper.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + + /** + * Purpose: getCurrentUser supports AdminScopeHelper.java by holding or executing the get current user business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public UserDO getCurrentUser(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + throw new RuntimeException("未获取到当前用户信息"); + } + + UserDO currentUser = userService.getById(userId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + throw new RuntimeException("当前用户不存在或已失效"); + } + + Long currentShopId = RequestShopContext.getCurrentShopId(request); + currentUser.setShopId(currentShopId); + + return currentUser; + } + + /** + * Purpose: isPlatformAdmin supports AdminScopeHelper.java by holding or executing the is platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isPlatformAdmin(UserDO currentUser) { + return currentUser != null && Integer.valueOf(4).equals(currentUser.getType()); + } + + /** + * Purpose: isPlatformOverviewMode supports AdminScopeHelper.java by holding or executing the is platform overview mode business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isPlatformOverviewMode(UserDO currentUser) { + return isPlatformAdmin(currentUser) + && (currentUser.getShopId() == null || currentUser.getShopId() <= 0); + } + + /** + * Purpose: requireShopContext supports AdminScopeHelper.java by holding or executing the require shop context business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requireShopContext(UserDO currentUser) { + requireShopContext(currentUser, "请先选择店铺后再管理店铺细节"); + } + + /** + * Purpose: requireShopContext supports AdminScopeHelper.java by holding or executing the require shop context business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requireShopContext(UserDO currentUser, String message) { + if (isPlatformOverviewMode(currentUser)) { + throw new RuntimeException(message); + } + if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) { + throw new RuntimeException(message); + } + } + + /** + * Purpose: getManagedShopId supports AdminScopeHelper.java by holding or executing the get managed shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long getManagedShopId(UserDO currentUser) { + if (isPlatformAdmin(currentUser)) { + return null; + } + + if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) { + throw new RuntimeException("当前账号未绑定店铺,无法访问后台业务数据"); + } + + return currentUser.getShopId(); + } + + /** + * Purpose: resolveShopScope supports AdminScopeHelper.java by holding or executing the resolve shop scope business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long resolveShopScope(UserDO currentUser, Long requestedShopId) { + Long managedShopId = getManagedShopId(currentUser); + if (managedShopId != null) { + return managedShopId; + } + if (requestedShopId != null && requestedShopId > 0) { + return requestedShopId; + } + if (currentUser != null && currentUser.getShopId() != null && currentUser.getShopId() > 0) { + return currentUser.getShopId(); + } + return null; + } + + /** + * Purpose: ensureShopAccessible supports AdminScopeHelper.java by holding or executing the ensure shop accessible business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureShopAccessible(UserDO currentUser, Long targetShopId, String message) { + Long managedShopId = getManagedShopId(currentUser); + if (managedShopId != null && !managedShopId.equals(targetShopId)) { + throw new BusinessException(403, message); + } + } + + /** + * Purpose: ensureUserAccessibleInCurrentShop supports AdminScopeHelper.java by holding or executing the ensure user accessible in current shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureUserAccessibleInCurrentShop(UserDO currentUser, Long targetUserId, String message) { + if (currentUser == null || targetUserId == null) { + throw new RuntimeException(message); + } + if (isPlatformAdmin(currentUser)) { + return; + } + Long managedShopId = getManagedShopId(currentUser); + if (!userShopBindingSupport.isUserAccessibleInShop(targetUserId, managedShopId)) { + throw new BusinessException(403, message); + } + } + + /** + * Purpose: requirePlatformAdmin supports AdminScopeHelper.java by holding or executing the require platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requirePlatformAdmin(UserDO currentUser, String message) { + if (!isPlatformAdmin(currentUser)) { + throw new RuntimeException(message); + } + } + + /** + * Purpose: ensureAssignableUserType supports AdminScopeHelper.java by holding or executing the ensure assignable user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureAssignableUserType(UserDO currentUser, Integer targetType) { + if (targetType == null) { + throw new RuntimeException("用户类型不能为空"); + } + + if (isPlatformAdmin(currentUser)) { + return; + } + + if (Integer.valueOf(2).equals(currentUser.getType())) { + if (Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType)) { + return; + } + throw new RuntimeException("店长只能创建或维护普通用户、美甲师"); + } + + if (Integer.valueOf(3).equals(currentUser.getType())) { + if (Integer.valueOf(0).equals(targetType)) { + return; + } + throw new RuntimeException("美甲师只能创建或维护普通用户"); + } + + throw new RuntimeException("当前角色无权维护后台用户"); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/PermissionCatalog.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/PermissionCatalog.java new file mode 100644 index 00000000..0e045a79 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/PermissionCatalog.java @@ -0,0 +1,313 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.support; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 权限目录是后台权限编码、中文展示文案和默认角色矩阵的唯一真源。 + */ +public final class PermissionCatalog { + + private static final Map DEFINITIONS = buildDefinitions(); + + private static final List ADMIN_DEFAULT_PERMISSION_CODES = List.of( + "home:view", + "dashboard:view", + "workbench:view", + "user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete", + "user:balance:view", "user:balance:manage", "user:vip:manage", + "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", + "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", + "shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage", + "permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign", + "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", + "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", + "comment:view", "comment:delete", + "order:view", "order:process", "order:edit", "order:delete", "order:artist-change", + "nail_artist:view", "nail_artist:edit", + "message:view", "message:create", "message:delete", + "announcement:view", "announcement:create", "announcement:delete", + "messagehub:config:manage", + "security:audit:view", + "legal_agreement:manage", + "schedule:view", "schedule:edit", + "payment:view", "payment:manage", "refund:view", "refund:manage", + "after_sale:view", "after_sale:audit", + "inventory:view", "inventory:manage", + "campaign:view", "campaign:manage", + "growth:view", "analytics:view", "performance:view" + ); + + private static final List SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of( + "home:view", + "dashboard:view", + "workbench:view", + "user:view", "user:create", "user:edit", "user:unbind", "user:reset_password", + "user:balance:view", "user:balance:manage", "user:vip:manage", + "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", + "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", + "shop:view", "shop:edit", "shop:staff:manage", + "permission:view", "permission:assign", + "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", + "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", + "comment:view", "comment:delete", + "order:view", "order:process", "order:edit", "order:delete", "order:artist-change", + "nail_artist:view", "nail_artist:edit", + "message:view", "message:create", + "announcement:view", "announcement:create", + "schedule:view", "schedule:edit", + "payment:view", "refund:view", + "after_sale:view", "after_sale:audit", + "inventory:view", "inventory:manage", + "campaign:view", "campaign:manage", + "analytics:view", "performance:view" + ); + + private static final List NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of( + "home:view", + "workbench:view", + "user:view", + "user:balance:view", + "product:view", + "shop:view", + "tag:view", + "coupon:view", + "comment:view", + "order:view", "order:process", "order:artist-change", + "schedule:view", "after_sale:view", "performance:view" + ); + + private static final Set PLATFORM_OVERVIEW_PREFIXES = Set.of( + "user:", + "shop:", + "permission:", + "message:", + "announcement:" + ); + + private static final Set PLATFORM_OVERVIEW_PERMISSIONS = Set.of( + "messagehub:config:manage", + "security:audit:view", + "legal_agreement:manage" + ); + + private static final Set MANAGED_PERMISSION_CODES = buildManagedPermissionCodes(); + + private PermissionCatalog() { + } + + /** + * Purpose: getDefaultPermissionCodes supports PermissionCatalog.java by holding or executing the get default permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static List getDefaultPermissionCodes(Integer userType) { + return switch (userType == null ? -1 : userType) { + case 4 -> ADMIN_DEFAULT_PERMISSION_CODES; + case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES; + case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES; + default -> List.of(); + }; + } + + /** + * Purpose: getDefaultPermissionCodeSet supports PermissionCatalog.java by holding or executing the get default permission code set business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getDefaultPermissionCodeSet(Integer userType) { + return Set.copyOf(getDefaultPermissionCodes(userType)); + } + + /** + * Purpose: getManagedPermissionCodes supports PermissionCatalog.java by holding or executing the get managed permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getManagedPermissionCodes() { + return MANAGED_PERMISSION_CODES; + } + + /** + * Purpose: getManagedDefinitions supports PermissionCatalog.java by holding or executing the get managed definitions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Collection getManagedDefinitions() { + return MANAGED_PERMISSION_CODES.stream() + .map(PermissionCatalog::getRequiredDefinition) + .toList(); + } + + /** + * Purpose: getDefinitionsByCode supports PermissionCatalog.java by holding or executing the get definitions by code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Map getDefinitionsByCode() { + return DEFINITIONS; + } + + /** + * Purpose: getRequiredDefinition supports PermissionCatalog.java by holding or executing the get required definition business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static PermissionDefinition getRequiredDefinition(String permissionCode) { + PermissionDefinition definition = DEFINITIONS.get(permissionCode); + if (definition == null) { + throw new IllegalArgumentException("Unknown permission code: " + permissionCode); + } + return definition; + } + + /** + * Purpose: isAllowedForPlatformOverview supports PermissionCatalog.java by holding or executing the is allowed for platform overview business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean isAllowedForPlatformOverview(String permissionCode) { + if (permissionCode == null || permissionCode.isBlank()) { + return true; + } + if ("dashboard:view".equals(permissionCode) || permissionCode.endsWith(":view")) { + return true; + } + if (PLATFORM_OVERVIEW_PERMISSIONS.contains(permissionCode)) { + return true; + } + return PLATFORM_OVERVIEW_PREFIXES.stream().anyMatch(permissionCode::startsWith); + } + + /** + * Purpose: canManageUserType supports PermissionCatalog.java by holding or executing the can manage user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean canManageUserType(Integer operatorType, Integer targetType) { + if (operatorType == null || targetType == null) { + return false; + } + + return switch (operatorType) { + case 4 -> true; + case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType); + case 3 -> Integer.valueOf(0).equals(targetType); + default -> false; + }; + } + + /** + * Purpose: buildManagedPermissionCodes supports PermissionCatalog.java by holding or executing the build managed permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static Set buildManagedPermissionCodes() { + LinkedHashSet permissionCodes = new LinkedHashSet<>(); + permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES); + permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES); + permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES); + return Set.copyOf(permissionCodes); + } + + /** + * Purpose: buildDefinitions supports PermissionCatalog.java by holding or executing the build definitions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static Map buildDefinitions() { + LinkedHashMap definitions = new LinkedHashMap<>(); + put(definitions, "home:view", "查看首页", "首页", "查看系统首页入口与概览"); + put(definitions, "dashboard:view", "查看仪表盘", "仪表盘", "查看后台仪表盘统计"); + put(definitions, "user:view", "查看用户", "用户管理", "查看用户列表与详情"); + put(definitions, "user:create", "新增用户", "用户管理", "创建用户账号"); + put(definitions, "user:edit", "编辑用户", "用户管理", "修改用户基础信息"); + put(definitions, "user:disable", "启停用户", "用户管理", "启用或禁用用户账号"); + put(definitions, "user:unbind", "解绑用户", "用户管理", "解绑用户与当前店铺的关系"); + put(definitions, "user:reset_password", "重置密码", "用户管理", "重置用户密码"); + put(definitions, "user:delete", "删除用户", "用户管理", "删除用户账号"); + put(definitions, "user:balance:view", "查看余额资产", "用户资产", "查看用户余额、累计充值与流水"); + put(definitions, "user:balance:manage", "调整余额", "用户资产", "充值、手工加减余额与关联订单"); + put(definitions, "user:vip:manage", "管理VIP", "用户资产", "手工设置VIP等级或恢复自动判级"); + put(definitions, "role:view", "查看店铺角色", "角色管理", "查看店铺自定义角色"); + put(definitions, "role:create", "新增店铺角色", "角色管理", "创建店铺自定义角色"); + put(definitions, "role:edit", "编辑店铺角色", "角色管理", "编辑角色权限和绑定员工"); + put(definitions, "role:delete", "删除店铺角色", "角色管理", "删除店铺自定义角色"); + put(definitions, "user:relation:view", "查看用户所属", "用户管理", "查看用户归属关系"); + put(definitions, "user:relation:edit", "编辑用户所属", "用户管理", "调整用户店铺和直属上级"); + put(definitions, "product:view", "查看商品", "商品管理", "查看商品列表与详情"); + put(definitions, "product:create", "新增商品", "商品管理", "创建商品"); + put(definitions, "product:edit", "编辑商品", "商品管理", "编辑商品信息"); + put(definitions, "product:delete", "删除商品", "商品管理", "删除商品"); + put(definitions, "product:category:manage", "管理商品分类", "商品管理", "维护商品分类与归类信息"); + put(definitions, "shop:view", "查看店铺", "店铺管理", "查看店铺列表与详情"); + put(definitions, "shop:create", "新增店铺", "店铺管理", "创建店铺"); + put(definitions, "shop:edit", "编辑店铺", "店铺管理", "编辑店铺信息"); + put(definitions, "shop:delete", "删除店铺", "店铺管理", "删除店铺"); + put(definitions, "shop:staff:manage", "管理员工", "店铺管理", "管理店铺员工与归属"); + put(definitions, "permission:view", "查看权限", "权限管理", "查看权限清单"); + put(definitions, "permission:create", "新增权限", "权限管理", "新增系统权限定义"); + put(definitions, "permission:edit", "编辑权限", "权限管理", "编辑系统权限定义"); + put(definitions, "permission:delete", "删除权限", "权限管理", "删除系统权限定义"); + put(definitions, "permission:assign", "分配权限", "权限管理", "给用户分配后台权限"); + put(definitions, "tag:view", "查看标签", "标签管理", "查看标签列表与详情"); + put(definitions, "tag:create", "新增标签", "标签管理", "创建标签"); + put(definitions, "tag:edit", "编辑标签", "标签管理", "编辑标签"); + put(definitions, "tag:delete", "删除标签", "标签管理", "删除标签"); + put(definitions, "tag:assign", "分配标签", "标签管理", "给商品或优惠券分配标签"); + put(definitions, "coupon:view", "查看优惠券", "优惠券管理", "查看优惠券与发放情况"); + put(definitions, "coupon:create", "新增优惠券", "优惠券管理", "创建优惠券模板"); + put(definitions, "coupon:edit", "编辑优惠券", "优惠券管理", "编辑优惠券模板"); + put(definitions, "coupon:delete", "删除优惠券", "优惠券管理", "删除优惠券模板"); + put(definitions, "coupon:assign", "发放优惠券", "优惠券管理", "向用户发放普通优惠券"); + put(definitions, "comment:view", "查看评论", "评论管理", "查看作品评论与回复"); + put(definitions, "comment:delete", "删除评论", "评论管理", "删除不合规作品评论"); + put(definitions, "order:view", "查看订单", "订单管理", "查看订单列表与详情"); + put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单"); + put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限"); + put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限"); + put(definitions, "order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请"); + put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口"); + put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息"); + put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知"); + put(definitions, "message:create", "发布消息", "消息管理", "发布站内消息"); + put(definitions, "message:delete", "撤回消息", "消息管理", "撤回已发布站内消息"); + put(definitions, "announcement:view", "查看公告", "公告管理", "查看公告列表与详情"); + put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告"); + put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告"); + put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数"); + put(definitions, "security:audit:view", "查看安全审计", "安全审计", "查看高危操作和登录安全审计日志"); + put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本"); + put(definitions, "schedule:view", "查看排班", "排班管理", "查看美甲师排班和可约时段"); + put(definitions, "schedule:edit", "编辑排班", "排班管理", "维护美甲师班次、休息日和预约容量"); + put(definitions, "payment:view", "查看支付", "支付退款", "查看订单支付状态和支付单"); + put(definitions, "payment:manage", "确认支付", "支付退款", "手工确认支付或处理支付异常"); + put(definitions, "refund:view", "查看退款", "支付退款", "查看退款申请和退款单"); + put(definitions, "refund:manage", "处理退款", "支付退款", "手工确认退款或处理退款异常"); + put(definitions, "after_sale:view", "查看售后", "售后管理", "查看订单售后和客户反馈"); + put(definitions, "after_sale:audit", "处理售后", "售后管理", "审批或驳回售后申请"); + put(definitions, "inventory:view", "查看库存", "库存管理", "查看门店耗材库存和预警"); + put(definitions, "inventory:manage", "调整库存", "库存管理", "维护耗材、入库和库存调整"); + put(definitions, "campaign:view", "查看活动", "活动管理", "查看营销活动和推荐位"); + put(definitions, "campaign:manage", "管理活动", "活动管理", "创建、编辑和发布营销活动"); + put(definitions, "growth:view", "查看成长", "用户成长", "查看用户成长值和会员权益进度"); + put(definitions, "analytics:view", "查看经营分析", "经营分析", "查看订单漏斗和经营指标"); + put(definitions, "performance:view", "查看绩效", "绩效统计", "查看门店和美甲师服务绩效"); + put(definitions, "workbench:view", "查看工作台", "门店工作台", "查看今日订单、售后待办、排班和绩效摘要"); + return Map.copyOf(definitions); + } + + /** + * Purpose: put supports PermissionCatalog.java by holding or executing the put business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static void put(Map definitions, String code, String name, String group, String description) { + definitions.put(code, new PermissionDefinition(code, name, group, description)); + } + + /** + * Purpose: PermissionDefinition supports PermissionCatalog.java by holding or executing the permission definition business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + public record PermissionDefinition( + String permissionCode, + String permissionName, + String permissionGroup, + String description + ) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/PermissionPolicy.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/PermissionPolicy.java new file mode 100644 index 00000000..da6a0065 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/PermissionPolicy.java @@ -0,0 +1,45 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.support; + +import java.util.List; +import java.util.Set; + +/** + * 后台角色默认权限与可分配策略。 + */ +public final class PermissionPolicy { + + private PermissionPolicy() { + } + + /** + * Purpose: getDefaultPermissionCodes supports PermissionPolicy.java by holding or executing the get default permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static List getDefaultPermissionCodes(Integer userType) { + return PermissionCatalog.getDefaultPermissionCodes(userType); + } + + /** + * Purpose: getDefaultPermissionCodeSet supports PermissionPolicy.java by holding or executing the get default permission code set business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getDefaultPermissionCodeSet(Integer userType) { + return PermissionCatalog.getDefaultPermissionCodeSet(userType); + } + + /** + * Purpose: getManagedDefaultPermissionCodes supports PermissionPolicy.java by holding or executing the get managed default permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getManagedDefaultPermissionCodes() { + return PermissionCatalog.getManagedPermissionCodes(); + } + + /** + * Purpose: canManageUserType supports PermissionPolicy.java by holding or executing the can manage user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean canManageUserType(Integer operatorType, Integer targetType) { + return PermissionCatalog.canManageUserType(operatorType, targetType); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/SecurityAuditActions.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/SecurityAuditActions.java new file mode 100644 index 00000000..568a8fdb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/SecurityAuditActions.java @@ -0,0 +1,113 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.support; + +/** + * Purpose: SecurityAuditActions supports SecurityAuditActions.java by holding or executing the security audit actions business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class SecurityAuditActions { + + /** + * Purpose: SUCCESS supports SecurityAuditActions.java by holding or executing the success business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String SUCCESS = "SUCCESS"; + /** + * Purpose: FAIL supports SecurityAuditActions.java by holding or executing the fail business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String FAIL = "FAIL"; + + /** + * Purpose: ORDER_PROCESS supports SecurityAuditActions.java by holding or executing the order process business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ORDER_PROCESS = "ORDER_PROCESS"; + /** + * Purpose: ARTIST_CHANGE_APPROVE supports SecurityAuditActions.java by holding or executing the artist change approve business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ARTIST_CHANGE_APPROVE = "ARTIST_CHANGE_APPROVE"; + /** + * Purpose: ARTIST_CHANGE_REJECT supports SecurityAuditActions.java by holding or executing the artist change reject business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ARTIST_CHANGE_REJECT = "ARTIST_CHANGE_REJECT"; + /** + * Purpose: SHOP_DELETE_BLOCKED supports SecurityAuditActions.java by holding or executing the shop delete blocked business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String SHOP_DELETE_BLOCKED = "SHOP_DELETE_BLOCKED"; + /** + * Purpose: SHOP_STATUS_UPDATE supports SecurityAuditActions.java by holding or executing the shop status update business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String SHOP_STATUS_UPDATE = "SHOP_STATUS_UPDATE"; + /** + * Purpose: PERMISSION_CREATE supports SecurityAuditActions.java by holding or executing the permission create business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_CREATE = "PERMISSION_CREATE"; + /** + * Purpose: PERMISSION_UPDATE supports SecurityAuditActions.java by holding or executing the permission update business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_UPDATE = "PERMISSION_UPDATE"; + /** + * Purpose: PERMISSION_DELETE supports SecurityAuditActions.java by holding or executing the permission delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_DELETE = "PERMISSION_DELETE"; + /** + * Purpose: PERMISSION_ASSIGN supports SecurityAuditActions.java by holding or executing the permission assign business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_ASSIGN = "PERMISSION_ASSIGN"; + /** + * Purpose: USER_STATUS_UPDATE supports SecurityAuditActions.java by holding or executing the user status update business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_STATUS_UPDATE = "USER_STATUS_UPDATE"; + /** + * Purpose: USER_RESET_PASSWORD supports SecurityAuditActions.java by holding or executing the user reset password business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_RESET_PASSWORD = "USER_RESET_PASSWORD"; + /** + * Purpose: USER_DELETE supports SecurityAuditActions.java by holding or executing the user delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_DELETE = "USER_DELETE"; + /** + * Purpose: USER_UNBIND supports SecurityAuditActions.java by holding or executing the user unbind business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_UNBIND = "USER_UNBIND"; + /** + * Purpose: USER_BALANCE_CHANGE supports SecurityAuditActions.java by holding or executing the user balance change business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_BALANCE_CHANGE = "USER_BALANCE_CHANGE"; + /** + * Purpose: USER_VIP_OVERRIDE supports SecurityAuditActions.java by holding or executing the user vip override business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_VIP_OVERRIDE = "USER_VIP_OVERRIDE"; + /** + * Purpose: USER_VIP_RECALCULATE supports SecurityAuditActions.java by holding or executing the user vip recalculate business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_VIP_RECALCULATE = "USER_VIP_RECALCULATE"; + public static final String SCHEDULE_UPDATE = "SCHEDULE_UPDATE"; + public static final String PAYMENT_MANUAL_CONFIRM = "PAYMENT_MANUAL_CONFIRM"; + public static final String REFUND_MANUAL_CONFIRM = "REFUND_MANUAL_CONFIRM"; + public static final String AFTER_SALE_CREATE = "AFTER_SALE_CREATE"; + public static final String AFTER_SALE_APPROVE = "AFTER_SALE_APPROVE"; + public static final String AFTER_SALE_REJECT = "AFTER_SALE_REJECT"; + public static final String INVENTORY_ADJUST = "INVENTORY_ADJUST"; + public static final String CAMPAIGN_PUBLISH = "CAMPAIGN_PUBLISH"; + public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW"; + public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW"; + + private SecurityAuditActions() { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/SecurityAuditSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/SecurityAuditSupport.java new file mode 100644 index 00000000..88aef108 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/support/SecurityAuditSupport.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.support; + +import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; + +@Component +@RequiredArgsConstructor +/** + * Purpose: SecurityAuditSupport supports SecurityAuditSupport.java by holding or executing the security audit support business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditSupport { + + /** + * Purpose: securityAuditLogService supports SecurityAuditSupport.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + /** + * Purpose: success supports SecurityAuditSupport.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void success(HttpServletRequest request, String action, String reason) { + record(request, action, SecurityAuditActions.SUCCESS, reason); + } + + /** + * Purpose: fail supports SecurityAuditSupport.java by holding or executing the fail business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void fail(HttpServletRequest request, String action, String reason) { + record(request, action, SecurityAuditActions.FAIL, reason); + } + + /** + * Purpose: record supports SecurityAuditSupport.java by holding or executing the record business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void record(HttpServletRequest request, String action, String result, String reason) { + try { + Long userId = request == null ? null : asLong(request.getAttribute("userId")); + String account = request == null ? null : asString(request.getAttribute("account")); + securityAuditLogService.record(userId, account, action, result, reason, request); + } catch (Exception ignored) { + // Audit failure must never block the guarded business operation. + } + } + + /** + * Purpose: asLong supports SecurityAuditSupport.java by holding or executing the as long business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long asLong(Object value) { + if (value instanceof Long) { + return (Long) value; + } + if (value instanceof Number) { + return ((Number) value).longValue(); + } + return null; + } + + /** + * Purpose: asString supports SecurityAuditSupport.java by holding or executing the as string business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String asString(Object value) { + return value == null ? null : String.valueOf(value); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/PermissionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/PermissionVO.java new file mode 100644 index 00000000..cc96d636 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/PermissionVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 系统权限表 VO + * 用于前端展示权限信息 + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +public class PermissionVO { + + /** + * 权限唯一主键ID + */ + private Long id; + + /** + * 权限编码(唯一标识) + */ + private String permissionCode; + + /** + * 权限名称 + */ + private String permissionName; + + /** + * 权限分组(商品管理、用户管理等) + */ + private String permissionGroup; + + /** + * 权限描述 + */ + private String description; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/SecurityAuditLogVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/SecurityAuditLogVO.java new file mode 100644 index 00000000..2ed21327 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/SecurityAuditLogVO.java @@ -0,0 +1,59 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * Purpose: SecurityAuditLogVO supports SecurityAuditLogVO.java by holding or executing the security audit log vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditLogVO { + + /** + * Purpose: id supports SecurityAuditLogVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: userId supports SecurityAuditLogVO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: account supports SecurityAuditLogVO.java by holding or executing the account business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String account; + /** + * Purpose: action supports SecurityAuditLogVO.java by holding or executing the action business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String action; + /** + * Purpose: result supports SecurityAuditLogVO.java by holding or executing the result business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String result; + /** + * Purpose: reason supports SecurityAuditLogVO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + /** + * Purpose: ipAddress supports SecurityAuditLogVO.java by holding or executing the ip address business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String ipAddress; + /** + * Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String deviceId; + /** + * Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime operateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/ShopRoleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/ShopRoleVO.java new file mode 100644 index 00000000..871f3b7f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/security/vo/ShopRoleVO.java @@ -0,0 +1,75 @@ +package com.xiaowang.jayucloud.artlist.core.modules.security.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * ShopRoleVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + /** + * Field `creatorName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String creatorName; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionIds; + /** + * Field `permissionCodes` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionCodes; + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java new file mode 100644 index 00000000..8ef3b590 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactInfoController.java @@ -0,0 +1,70 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/contact-info", "/api/contact-info"}) +/** + * ContactInfoController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ContactInfoController { + /** + * Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ContactInfoService contactInfoService; + + @GetMapping("/shop/{shopId}/manager") + /** + * Run business method `shopManager`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result shopManager(HttpServletRequest request, @PathVariable Long shopId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getShopManagerContact(userId, shopId)); + } + + @GetMapping("/product/{productId}/artist/{artistId}") + /** + * Run business method `productArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId)); + } + + @GetMapping("/order/{orderId}/artist") + /** + * Purpose: orderArtist supports ContactInfoController.java by holding or executing the order artist business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId)); + } + + @GetMapping("/platform") + /** + * Run business method `platform`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result result consumed by the caller or returned to the frontend + */ + public Result platform() { + return Result.success(contactInfoService.getPlatformContact()); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ShopController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ShopController.java new file mode 100644 index 00000000..e347aa23 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ShopController.java @@ -0,0 +1,211 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopTrustProfileVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/shop") +@RequiredArgsConstructor +/** + * ShopController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ShopController { + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopService shopService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/create") + @RequirePermission("shop:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺"); + Long id = shopService.createShop(shopDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("shop:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ShopVO shopVO = shopService.getShopById(id); + if (shopVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + shopDTO.setAuthorizationExpireTime(shopVO.getAuthorizationExpireTime()); + } + boolean success = shopService.updateShop(id, shopDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("shop:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); + boolean success = shopService.deleteShop(id); + return Result.success(success); + } + + @PutMapping("/status/{id}") + @RequirePermission("shop:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param statusRequest parameter `statusRequest` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); + boolean success = shopService.updateShopStatus(id, statusRequest.getStatus()); + return Result.success(success); + } + + @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getShopById(@PathVariable Long id) { + ShopVO shopVO = shopService.getShopById(id); + return Result.success(shopVO); + } + + @GetMapping("/trust-profile/{id}") + /** + * Purpose: getShopTrustProfile returns public confidence signals for a shop detail page. + * Usage: anonymous clients can call this endpoint; phone data remains behind contact-info APIs. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getShopTrustProfile(@PathVariable Long id) { + return Result.success(shopService.getShopTrustProfile(id)); + } + + @GetMapping("/list/all") + @RequirePermission("shop:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllShops(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List shopVOs; + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + shopVOs = shopService.listAllShopsForAdmin(); + } else { + ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser)); + shopVOs = currentShop == null ? List.of() : List.of(currentShop); + } + return Result.success(shopVOs); + } + + @GetMapping("/list/shopName/{shopName}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopName parameter `shopName` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listShopsByShopName(@PathVariable String shopName) { + List shopVOs = shopService.listShopsByShopName(shopName); + return Result.success(shopVOs); + } + + @GetMapping("/list/simple") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listShopsSimple() { + List shopVOs = shopService.listAllShops(); + List simpleVOs = shopVOs.stream() + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + return Result.success(simpleVOs); + } + + @GetMapping("/list") + /** + * Purpose: listPublicShopsCompat keeps the legacy /shop/list public catalog URL usable for anonymous clients. + * Usage: call from old Web or mini-program builds that still request /api/shop/list; new code may prefer /shop/list/public. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listPublicShopsCompat() { + return Result.success(shopService.listAllShops()); + } + + @GetMapping("/list/public") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listPublicShops() { + return Result.success(shopService.listAllShops()); + } + + @Data + /** + * Purpose: StatusRequest supports ShopController.java by holding or executing the status request business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class StatusRequest { + /** + * Purpose: status supports ShopController.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/ShopDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/ShopDTO.java new file mode 100644 index 00000000..ca1b08c6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/ShopDTO.java @@ -0,0 +1,124 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * 店铺信息表 DTO + * 用于店铺信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ShopDTO { + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 店铺描述 + */ + private String description; + + /** + * 店铺地址 + */ + private String address; + + /** + * Purpose: mapProvider supports ShopDTO.java by holding or executing the map provider business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String mapProvider; + + /** + * Purpose: longitude supports ShopDTO.java by holding or executing the longitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal longitude; + + /** + * Purpose: latitude supports ShopDTO.java by holding or executing the latitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal latitude; + + /** + * 店铺营业时间 + */ + private String businessHours; + + /** + * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 + */ + private String coverImageFileId; + + /** + * 店铺图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * Purpose: themePrimaryColor supports ShopDTO.java by holding or executing the theme primary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePrimaryColor; + + /** + * Purpose: themeSecondaryColor supports ShopDTO.java by holding or executing the theme secondary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeSecondaryColor; + + /** + * Purpose: themeAccentColor supports ShopDTO.java by holding or executing the theme accent color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeAccentColor; + + /** + * Purpose: themePageBgColor supports ShopDTO.java by holding or executing the theme page bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePageBgColor; + + /** + * Purpose: themeCardBgColor supports ShopDTO.java by holding or executing the theme card bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeCardBgColor; + + /** + * Purpose: themeBackgroundImageFileId supports ShopDTO.java by holding or executing the theme background image file id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeBackgroundImageFileId; + + /** + * 店铺状态:1-启用,0-停用 + */ + private Integer status; + + /** + * Purpose: authorizationStartDate supports ShopDTO.java by holding or executing the authorization start date business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDate authorizationStartDate; + + /** + * Purpose: authorizationDays supports ShopDTO.java by holding or executing the authorization days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer authorizationDays; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + private LocalDateTime authorizationExpireTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/entity/ShopDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/entity/ShopDO.java new file mode 100644 index 00000000..a5bbb814 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/entity/ShopDO.java @@ -0,0 +1,165 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 店铺信息表 DO + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("t_shop") +public class ShopDO extends BaseEntity { + + /** + * 店铺唯一主键ID(雪花ID) + */ + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + /** + * 店铺名称 + */ + @TableField("shop_name") + private String shopName; + + /** + * 店铺描述 + */ + @TableField("description") + private String description; + + /** + * 店铺地址 + */ + @TableField("address") + private String address; + + @TableField("map_provider") + /** + * Purpose: mapProvider supports ShopDO.java by holding or executing the map provider business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String mapProvider; + + @TableField("longitude") + /** + * Purpose: longitude supports ShopDO.java by holding or executing the longitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal longitude; + + @TableField("latitude") + /** + * Purpose: latitude supports ShopDO.java by holding or executing the latitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal latitude; + + /** + * 店铺营业时间 + */ + @TableField("business_hours") + private String businessHours; + + /** + * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 + */ + @TableField("cover_image_file_id") + private String coverImageFileId; + + /** + * 店铺图片文件ID集合,多个ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + @TableField("theme_primary_color") + /** + * Purpose: themePrimaryColor supports ShopDO.java by holding or executing the theme primary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePrimaryColor; + + @TableField("theme_secondary_color") + /** + * Purpose: themeSecondaryColor supports ShopDO.java by holding or executing the theme secondary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeSecondaryColor; + + @TableField("theme_accent_color") + /** + * Purpose: themeAccentColor supports ShopDO.java by holding or executing the theme accent color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeAccentColor; + + @TableField("theme_page_bg_color") + /** + * Purpose: themePageBgColor supports ShopDO.java by holding or executing the theme page bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePageBgColor; + + @TableField("theme_card_bg_color") + /** + * Purpose: themeCardBgColor supports ShopDO.java by holding or executing the theme card bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeCardBgColor; + + @TableField("theme_background_image_file_id") + /** + * Purpose: themeBackgroundImageFileId supports ShopDO.java by holding or executing the theme background image file id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeBackgroundImageFileId; + + /** + * 店铺状态:1-启用,0-停用 + */ + @TableField("status") + private Integer status; + + @TableField("authorization_start_date") + /** + * Purpose: authorizationStartDate supports ShopDO.java by holding or executing the authorization start date business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDate authorizationStartDate; + + @TableField("authorization_days") + /** + * Purpose: authorizationDays supports ShopDO.java by holding or executing the authorization days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer authorizationDays; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + @TableField("authorization_expire_time") + private LocalDateTime authorizationExpireTime; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/entity/UserShopBindingDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/entity/UserShopBindingDO.java new file mode 100644 index 00000000..da05dfb1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/entity/UserShopBindingDO.java @@ -0,0 +1,50 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 用户与店铺绑定关系。 + */ +@Getter +@Setter +@TableName("t_user_shop_binding") +public class UserShopBindingDO extends BaseEntity { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * 绑定状态:1-正常,0-禁用。 + */ + @TableField("status") + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/mapper/ShopMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/mapper/ShopMapper.java new file mode 100644 index 00000000..5de6a79a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/mapper/ShopMapper.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +/** + * 店铺信息表 Mapper + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ShopMapper extends BaseMapper { + + @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") + Long countPublicImageReference(@Param("fileId") Long fileId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/mapper/UserShopBindingMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/mapper/UserShopBindingMapper.java new file mode 100644 index 00000000..fb3f2ac1 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/mapper/UserShopBindingMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.UserShopBindingDO; + +/** + * UserShopBindingMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserShopBindingMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactInfoService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactInfoService.java new file mode 100644 index 00000000..987ae9c0 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactInfoService.java @@ -0,0 +1,42 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; + +/** + * ContactInfoService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ContactInfoService { + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getShopManagerContact(Long userId, Long shopId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getPlatformContact(); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ShopService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ShopService.java new file mode 100644 index 00000000..b8c66fd5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ShopService.java @@ -0,0 +1,113 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopTrustProfileVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopVO; + +import java.util.List; + +/** + * 店铺信息表 Service + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ShopService extends IService { + + /** + * 创建店铺 + * + * @param shopDTO 店铺DTO + * @return 店铺ID + */ + Long createShop(ShopDTO shopDTO); + + /** + * 更新店铺 + * + * @param id 店铺ID + * @param shopDTO 店铺DTO + * @return 是否更新成功 + */ + boolean updateShop(Long id, ShopDTO shopDTO); + + /** + * 删除店铺 + * + * @param id 店铺ID + * @return 是否删除成功 + */ + boolean deleteShop(Long id); + + /** + * 根据ID查询店铺 + * + * @param id 店铺ID + * @return 店铺VO + */ + ShopVO getShopById(Long id); + + /** + * Purpose: getShopTrustProfile aggregates public shop confidence signals. + * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. + * + * @param id shop id to inspect + * @return public trust profile or null when the shop cannot be viewed + */ + ShopTrustProfileVO getShopTrustProfile(Long id); + + /** + * 查询所有店铺 + * + * @return 店铺VO列表 + */ + List listAllShops(); + + /** + * 查询后台全部店铺(含停用,不含删除) + * + * @return 店铺列表 + */ + List listAllShopsForAdmin(); + + /** + * 根据店铺名称查询店铺 + * + * @param shopName 店铺名称 + * @return 店铺VO列表 + */ + List listShopsByShopName(String shopName); + + /** + * 分页查询店铺 + * + * @param page 页码 + * @param size 每页大小 + * @param keyword 搜索关键词 + * @return 分页结果 + */ + PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId); + + /** + * 更新店铺状态 + * + * @param id 店铺ID + * @param status 状态:1-启用,0-停用 + * @return 是否成功 + */ + boolean updateShopStatus(Long id, Integer status); + + /** + * 店铺是否已超过授权有效期。 + */ + boolean isAuthorizationExpired(Long shopId); + + /** + * 前台可用:未删除、启用、且授权未到期。 + */ + boolean isFrontendAvailable(Long shopId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java new file mode 100644 index 00000000..43ac284e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java @@ -0,0 +1,216 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +@Service +@RequiredArgsConstructor +/** + * ContactInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ContactInfoServiceImpl implements ContactInfoService { + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + /** + * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderItemMapper orderItemMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `objectStorageUrlSupport`: converts stored QR image URLs into frontend-safe signed URLs. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getShopManagerContact(Long userId, Long shopId) { + if (shopId == null || shopId <= 0) throw new RuntimeException("店铺ID不能为空"); + /** + * Run business method `ensureUserCanSeeShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureUserCanSeeShop(userId, shopId); + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 2) + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("LIMIT 1")); + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param manager parameter `manager` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toContact(manager, "店长"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId) { + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) throw new RuntimeException("作品不存在"); + if (artistId == null || artistId <= 0) throw new RuntimeException("请选择美甲师"); + ensureArtistAllowed(product.getBookableArtists(), artistId); + return toContact(userMapper.selectById(artistId), "美甲师"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || !userId.equals(order.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在或无权查看"); + } + OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getOrderId, orderId) + .eq(OrderItemDO::getIsDelete, 0) + .eq(artistId != null && artistId > 0, OrderItemDO::getArtistId, artistId) + .isNotNull(OrderItemDO::getArtistId) + .last("LIMIT 1")) + .stream() + .findFirst() + .orElseThrow(() -> new RuntimeException("订单暂无可联系美甲师")); + return toContact(userMapper.selectById(item.getArtistId()), "美甲师"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getPlatformContact() { + UserDO admin = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 4) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .isNotNull(UserDO::getPhone) + .last("LIMIT 1")); + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param admin parameter `admin` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toContact(admin, "平台客服"); + } + + /** + * Run business method `ensureUserCanSeeShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureUserCanSeeShop(Long userId, Long shopId) { + if (userId == null) return; + UserDO user = userMapper.selectById(userId); + if (user != null && shopId.equals(user.getShopId())) return; + if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { + // 店铺详情是公开入口,未绑定用户仍允许看联系方式。 + } + } + + /** + * Run business method `ensureArtistAllowed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureArtistAllowed(String rawBookableArtists, Long artistId) { + if (!StringUtils.hasText(rawBookableArtists)) return; + boolean allowed = java.util.Arrays.stream(rawBookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .anyMatch(id -> id.equals(String.valueOf(artistId))); + if (!allowed) throw new RuntimeException("该美甲师不可预约当前作品"); + } + + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param roleLabel parameter `roleLabel` supplied by the caller + * @return private ContactInfoVO result consumed by the caller or returned to the frontend + */ + private ContactInfoVO toContact(UserDO user, String roleLabel) { + ContactInfoVO vo = new ContactInfoVO(); + vo.setPlatformContactAvailable(false); + vo.setPlatformContactText("平台联系暂未接入"); + vo.setRoleLabel(roleLabel); + if (user == null) { + vo.setContactName(roleLabel); + vo.setPhoneAvailable(false); + return vo; + } + vo.setContactUserId(user.getId()); + vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone(); + vo.setPhone(contactPhone); + vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); + vo.setWechatId(user.getWechatId()); + vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); + vo.setWechatQrCode(StringUtils.hasText(user.getWechatQrCode()) + ? objectStorageUrlSupport.toAccessibleUrl(user.getWechatQrCode()) + : null); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ShopServiceImpl.java new file mode 100644 index 00000000..302cc256 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ShopServiceImpl.java @@ -0,0 +1,896 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.artlist.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MapService; +import com.xiaowang.jayucloud.artlist.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.ShopThemeSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopTrustProfileVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 店铺信息表 Service 实现 + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class ShopServiceImpl extends ServiceImpl implements ShopService { + /** + * Purpose: SHOP_DETAIL_CACHE_PREFIX supports ShopServiceImpl.java by holding or executing the shop detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:"; + /** + * Purpose: SHOP_LIST_CACHE_PREFIX supports ShopServiceImpl.java by holding or executing the shop list cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:"; + /** + * Purpose: SHOP_DELETE_DISABLED_MESSAGE supports ShopServiceImpl.java by holding or executing the shop delete disabled message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SHOP_DELETE_DISABLED_MESSAGE = "店铺删除已停用,请使用停用封存"; + /** + * Purpose: DISABLED_SHOP_ARCHIVED_MESSAGE supports ShopServiceImpl.java by holding or executing the disabled shop archived message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String DISABLED_SHOP_ARCHIVED_MESSAGE = "停用店铺已封存,仅允许重新启用"; + private static final Set FEATURED_PRODUCT_TAG_NAMES = Set.of("特色作品", "热门"); + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponService couponService; + /** + * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponMapper couponMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentMapper commentMapper; + /** + * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserCouponMapper userCouponMapper; + /** + * Variable `orderArtistReviewMapper`: Spring-injected collaborator used by this class to aggregate public shop review trust signals. + */ + private final OrderArtistReviewMapper orderArtistReviewMapper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to resolve public image URLs for trust cards. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageUrlSupport`: converts stored object URLs into frontend-accessible signed URLs. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + private final NailArtistInfoService nailArtistInfoService; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + /** + * Purpose: mapService supports ShopServiceImpl.java by holding or executing the map service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final MapService mapService; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createShop(ShopDTO shopDTO) { + ShopDO shopDO = new ShopDO(); + shopDO.setShopName(shopDTO.getShopName()); + shopDO.setDescription(shopDTO.getDescription()); + shopDO.setAddress(shopDTO.getAddress()); + shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); + shopDO.setLongitude(shopDTO.getLongitude()); + shopDO.setLatitude(shopDTO.getLatitude()); + shopDO.setBusinessHours(shopDTO.getBusinessHours()); + shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); + shopDO.setImageFileIds(shopDTO.getImageFileIds()); + applyTheme(shopDO, shopDTO); + applyAuthorization(shopDO, shopDTO); + shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); + shopDO.setIsDelete(0); + shopMapper.insert(shopDO); + couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); + evictShopCaches(shopDO.getId()); + return shopDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateShop(Long id, ShopDTO shopDTO) { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null) { + return false; + } + if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { + throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); + } + shopDO.setShopName(shopDTO.getShopName()); + shopDO.setDescription(shopDTO.getDescription()); + shopDO.setAddress(shopDTO.getAddress()); + shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); + shopDO.setLongitude(shopDTO.getLongitude()); + shopDO.setLatitude(shopDTO.getLatitude()); + shopDO.setBusinessHours(shopDTO.getBusinessHours()); + shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); + shopDO.setImageFileIds(shopDTO.getImageFileIds()); + applyTheme(shopDO, shopDTO); + applyAuthorization(shopDO, shopDTO); + if (shopDTO.getStatus() != null) { + shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); + } + boolean updated = shopMapper.updateById(shopDO) > 0; + if (updated) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictShopCaches(id); + } + return updated; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteShop(Long id) { + throw new RuntimeException(SHOP_DELETE_DISABLED_MESSAGE); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateShopStatus(Long id, Integer status) { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { + return false; + } + shopDO.setStatus(normalizeStatus(status)); + boolean updated = shopMapper.updateById(shopDO) > 0; + if (updated) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictShopCaches(id); + } + return updated; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ShopVO result consumed by the caller or returned to the frontend + */ + public ShopVO getShopById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + return multiLevelCacheService.getOrLoad( + SHOP_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(shopDO); + } + ); + } + + @Override + /** + * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. + * Usage: pass a valid shop id; the returned profile never exposes contact phone data. + */ + public ShopTrustProfileVO getShopTrustProfile(Long id) { + if (id == null || id <= 0) { + return null; + } + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { + return null; + } + + long productCount = countActiveProducts(id); + long artistCount = countShopArtists(id); + List featuredProducts = listFeaturedProducts(id); + List recentReviews = listSubmittedReviews(id, 3); + BigDecimal averageRating = calculateAverageRating(id); + long reviewCount = countSubmittedReviews(id); + + Set fileIds = new LinkedHashSet<>(); + fileIds.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); + fileIds.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); + featuredProducts.forEach(product -> fileIds.addAll(parseLongIds(product.getImageFileIds(), ","))); + recentReviews.forEach(review -> fileIds.addAll(parseLongIds(review.getImageFileIds(), ","))); + Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + + ShopTrustProfileVO profile = new ShopTrustProfileVO(); + profile.setShopId(shopDO.getId()); + profile.setShopName(shopDO.getShopName()); + profile.setBusinessHoursText(StringUtils.hasText(shopDO.getBusinessHours()) ? shopDO.getBusinessHours() : "营业时间待补充"); + profile.setBusinessStatusText(Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) ? "正常营业" : "暂不可预约"); + boolean locationAvailable = shopDO.getLatitude() != null && shopDO.getLongitude() != null; + profile.setLocationAvailable(locationAvailable); + profile.setNavigationAvailable(locationAvailable); + profile.setDistanceCapabilityText(locationAvailable ? "开启定位后可查看距离" : "门店暂未设置地图位置"); + profile.setEnvironmentImages(resolveImageUrls(fileIdsForShop(shopDO), fileMap)); + + ShopTrustProfileVO.Stats stats = new ShopTrustProfileVO.Stats(); + stats.setProductCount(productCount); + stats.setArtistCount(artistCount); + stats.setReviewCount(reviewCount); + stats.setAverageRating(averageRating); + stats.setRecentReviewCount(recentReviews.size()); + profile.setStats(stats); + + profile.setFeaturedProducts(featuredProducts.stream() + .map(product -> buildFeaturedProduct(product, fileMap)) + .collect(Collectors.toList())); + profile.setRecentReviews(recentReviews.stream() + .map(review -> buildRecentReview(review, featuredProducts, fileMap)) + .collect(Collectors.toList())); + profile.setAvailabilitySummary(buildAvailabilitySummary(shopDO, productCount)); + profile.setContactSummary(buildContactSummary()); + return profile; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllShops() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + return multiLevelCacheService.getOrLoad( + SHOP_LIST_CACHE_PREFIX + "active", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .eq(ShopDO::getStatus, 1) + .orderByDesc(ShopDO::getCreateTime) + ).stream() + .filter(this::isAuthorizationValid) + .map(this::convertToVO) + .collect(Collectors.toList()) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllShopsForAdmin() { + List shopDOs = shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .orderByDesc(ShopDO::getCreateTime) + ); + return shopDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopName parameter `shopName` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listShopsByShopName(String shopName) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + String normalizedShopName = StringUtils.hasText(shopName) ? shopName.trim() : ""; + return multiLevelCacheService.getOrLoad( + SHOP_LIST_CACHE_PREFIX + "name:" + normalizedShopName, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> { + List shopDOs = shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .eq(ShopDO::getStatus, 1) + .like(ShopDO::getShopName, normalizedShopName) + ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); + return shopDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + ); + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId) { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ShopDO.class); + wrapper.eq(ShopDO::getIsDelete, 0); + if (StringUtils.hasText(keyword)) { + wrapper.and(w -> w.like(ShopDO::getShopName, keyword) + .or().like(ShopDO::getDescription, keyword) + .or().like(ShopDO::getAddress, keyword)); + } + if (shopId != null && shopId > 0) { + wrapper.eq(ShopDO::getId, shopId); + } + wrapper.orderByDesc(ShopDO::getCreateTime); + + Page shopPage = shopMapper.selectPage(pageParam, wrapper); + + PageResultVO result = new PageResultVO<>(); + result.setList(shopPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setTotal(shopPage.getTotal()); + result.setPage(page); + result.setSize(size); + + return result; + } + + /** + * Purpose: countActiveProducts counts products that can contribute to a public shop trust profile. + * Usage: call it with a valid shop id before rendering product trust metrics. + */ + private long countActiveProducts(Long shopId) { + Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)); + return count == null ? 0L : count; + } + + private long countShopArtists(Long shopId) { + return nailArtistInfoService.getByShopId(shopId).size(); + } + + /** + * Purpose: listFeaturedProducts returns representative active products for shop detail trust cards. + * Usage: render at most three products and navigate to product detail when tapped. + */ + private List listFeaturedProducts(Long shopId) { + Set featuredTagTokens = findFeaturedProductTagTokens(shopId); + if (featuredTagTokens.isEmpty()) { + return Collections.emptyList(); + } + return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0) + .and(wrapper -> applyProductTagTokenConditions(wrapper, featuredTagTokens)) + .orderByDesc(ProductDO::getCollectCount) + .orderByDesc(ProductDO::getLikeCount) + .orderByDesc(ProductDO::getCreateTime) + .last("LIMIT 3")) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + private Set findFeaturedProductTagTokens(Long shopId) { + Set tokens = new LinkedHashSet<>(FEATURED_PRODUCT_TAG_NAMES); + List tags = tagMapper.selectList(Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .and(wrapper -> wrapper.eq(TagDO::getShopId, shopId) + .or() + .isNull(TagDO::getShopId) + .or() + .eq(TagDO::getShopId, 0L)) + .and(wrapper -> wrapper.in(TagDO::getTagName, FEATURED_PRODUCT_TAG_NAMES) + .or() + .in(TagDO::getDisplayName, FEATURED_PRODUCT_TAG_NAMES))); + tags.stream() + .map(TagDO::getId) + .filter(Objects::nonNull) + .map(String::valueOf) + .forEach(tokens::add); + return tokens.stream() + .filter(StringUtils::hasText) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + private void applyProductTagTokenConditions(LambdaQueryWrapper wrapper, Set tagTokens) { + boolean appended = false; + for (String tagToken : tagTokens) { + if (!StringUtils.hasText(tagToken)) { + continue; + } + if (appended) { + wrapper.or(); + } + wrapper.apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagToken); + appended = true; + } + if (!appended) { + wrapper.apply("1 = 0"); + } + } + + /** + * Purpose: listSubmittedReviews loads privacy-safe submitted review rows for the shop. + * Usage: only status=1 reviews should feed public trust display. + */ + private List listSubmittedReviews(Long shopId, int limit) { + return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .orderByDesc(OrderArtistReviewDO::getSubmittedAt) + .orderByDesc(OrderArtistReviewDO::getCreateTime) + .last("LIMIT " + Math.max(1, limit))) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Purpose: countSubmittedReviews counts reviews that are visible in public shop trust sections. + * Usage: render it beside average rating so customers can judge sample size. + */ + private long countSubmittedReviews(Long shopId) { + Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0)); + return count == null ? 0L : count; + } + + /** + * Purpose: calculateAverageRating derives the public average rating for a shop. + * Usage: use submitted reviews only and return zero when no rating exists. + */ + private BigDecimal calculateAverageRating(Long shopId) { + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .isNotNull(OrderArtistReviewDO::getRatingScore)); + if (reviews == null || reviews.isEmpty()) { + return BigDecimal.ZERO; + } + BigDecimal total = reviews.stream() + .map(OrderArtistReviewDO::getRatingScore) + .filter(Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add); + long count = reviews.stream().map(OrderArtistReviewDO::getRatingScore).filter(Objects::nonNull).count(); + if (count == 0) { + return BigDecimal.ZERO; + } + return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); + } + + /** + * Purpose: buildFeaturedProduct converts a product row into a compact trust card. + * Usage: keep this card small and do not include unpublished product internals. + */ + private ShopTrustProfileVO.FeaturedProduct buildFeaturedProduct(ProductDO product, Map fileMap) { + ShopTrustProfileVO.FeaturedProduct featured = new ShopTrustProfileVO.FeaturedProduct(); + featured.setId(product.getId()); + featured.setTitle(product.getTitle()); + featured.setPrice(product.getPrice()); + featured.setLikeCount(product.getLikeCount() == null ? 0 : product.getLikeCount()); + featured.setCollectCount(product.getCollectCount() == null ? 0 : product.getCollectCount()); + int artistCount = countBookableArtists(product.getBookableArtists()); + featured.setAvailableBookableArtistCount(artistCount); + featured.setBookingHint(artistCount > 0 ? artistCount + " 位美甲师可预约" : "到店后由门店安排美甲师"); + featured.setImageUrl(resolveFirstImageUrl(product.getImageFileIds(), fileMap)); + featured.setImageFileIds(product.getImageFileIds()); + return featured; + } + + /** + * Purpose: buildRecentReview converts a submitted review row into a privacy-safe card. + * Usage: never include customer phone, account, or full order identifiers here. + */ + private ShopTrustProfileVO.RecentReview buildRecentReview(OrderArtistReviewDO review, + List featuredProducts, + Map fileMap) { + ShopTrustProfileVO.RecentReview item = new ShopTrustProfileVO.RecentReview(); + item.setId(review.getId()); + item.setProductId(review.getProductId()); + item.setProductTitle(resolveProductTitle(review.getProductId(), featuredProducts)); + item.setRatingScore(review.getRatingScore()); + item.setContent(review.getContent()); + item.setSubmittedAt(review.getSubmittedAt() == null ? review.getCreateTime() : review.getSubmittedAt()); + item.setImageUrls(resolveImageUrls(parseLongIds(review.getImageFileIds(), ","), fileMap)); + return item; + } + + /** + * Purpose: buildAvailabilitySummary gives a coarse booking-readiness summary for the public page. + * Usage: clients must still rely on order creation for final schedule validation. + */ + private ShopTrustProfileVO.AvailabilitySummary buildAvailabilitySummary(ShopDO shopDO, long productCount) { + ShopTrustProfileVO.AvailabilitySummary summary = new ShopTrustProfileVO.AvailabilitySummary(); + boolean active = Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) && productCount > 0; + summary.setAvailable(active); + if (!Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus()))) { + summary.setSummaryText("门店暂不可预约"); + } else if (productCount <= 0) { + summary.setSummaryText("暂无可预约作品"); + } else { + summary.setSummaryText("当前有 " + productCount + " 个作品可预约,提交订单前会再次校验档期"); + summary.setNextSlots(buildCoarseSlotHints(shopDO.getBusinessHours())); + } + return summary; + } + + /** + * Purpose: buildContactSummary documents the explicit contact flow without public phone leakage. + * Usage: tests assert phoneExposed is false for the public trust endpoint. + */ + private ShopTrustProfileVO.ContactSummary buildContactSummary() { + ShopTrustProfileVO.ContactSummary contact = new ShopTrustProfileVO.ContactSummary(); + contact.setActionText("点击联系店长后获取联系方式"); + contact.setPhoneExposed(false); + contact.setPhone(null); + return contact; + } + + /** + * Purpose: buildCoarseSlotHints creates simple near-term booking hints from business hours. + * Usage: render these as guidance only, not as guaranteed appointment slots. + */ + private List buildCoarseSlotHints(String businessHours) { + String hours = StringUtils.hasText(businessHours) ? businessHours.trim() : "营业时间内"; + List hints = new ArrayList<>(); + hints.add("今天 " + hours); + hints.add("明天 " + hours); + hints.add("后天 " + hours); + return hints; + } + + /** + * Purpose: fileIdsForShop returns cover and environment image ids in display order. + * Usage: resolve these ids into environment image URLs for shop detail pages. + */ + private List fileIdsForShop(ShopDO shopDO) { + List ids = new ArrayList<>(); + ids.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); + ids.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); + return ids; + } + + /** + * Purpose: resolveFirstImageUrl returns the first available image URL from a delimited file id string. + * Usage: use it for compact product cards where only one thumbnail is needed. + */ + private String resolveFirstImageUrl(String fileIds, Map fileMap) { + return resolveImageUrls(parseLongIds(fileIds, ","), fileMap).stream().findFirst().orElse(null); + } + + /** + * Purpose: resolveImageUrls maps file ids to public URLs while preserving order. + * Usage: call it for shop environment, product thumbnails, and review thumbnails. + */ + private List resolveImageUrls(List fileIds, Map fileMap) { + if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { + return Collections.emptyList(); + } + List urls = new ArrayList<>(); + for (Long fileId : fileIds) { + ObjectStorageFileVO file = fileMap.get(fileId); + if (file != null && StringUtils.hasText(file.getFileUrl())) { + urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); + } + } + return urls; + } + + /** + * Purpose: resolveProductTitle returns the title for a reviewed product. + * Usage: prefer already-loaded featured products and fall back to one product lookup. + */ + private String resolveProductTitle(Long productId, List featuredProducts) { + if (productId == null) { + return null; + } + for (ProductDO product : featuredProducts) { + if (product != null && productId.equals(product.getId())) { + return product.getTitle(); + } + } + ProductDO product = productMapper.selectById(productId); + return product == null || Integer.valueOf(1).equals(product.getIsDelete()) ? null : product.getTitle(); + } + + /** + * Purpose: parseLongIds parses comma or semicolon separated numeric ids. + * Usage: feed image/product/tag id strings into batch lookup helpers. + */ + private List parseLongIds(String value, String delimiter) { + if (!StringUtils.hasText(value)) { + return Collections.emptyList(); + } + List ids = new ArrayList<>(); + String regex = ",".equals(delimiter) ? "[,;]" : delimiter; + for (String part : value.split(regex)) { + if (!StringUtils.hasText(part)) { + continue; + } + try { + ids.add(Long.parseLong(part.trim())); + } catch (NumberFormatException ignored) { + // Ignore dirty historical file id fragments instead of failing the public shop page. + } + } + return ids; + } + + /** + * Purpose: countBookableArtists counts the configured artist ids for a product. + * Usage: render a compact availability hint without validating live schedules. + */ + private int countBookableArtists(String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return 0; + } + return (int) parseLongIds(bookableArtists, ",").stream().distinct().count(); + } + + /** + * 将 DO 转换为 VO + * + * @param shopDO 店铺DO + * @return 店铺VO + */ + private ShopVO convertToVO(ShopDO shopDO) { + ShopVO shopVO = new ShopVO(); + shopVO.setId(shopDO.getId()); + shopVO.setShopName(shopDO.getShopName()); + shopVO.setDescription(shopDO.getDescription()); + shopVO.setAddress(shopDO.getAddress()); + shopVO.setMapProvider(mapService.normalizeProvider(shopDO.getMapProvider())); + shopVO.setLongitude(shopDO.getLongitude()); + shopVO.setLatitude(shopDO.getLatitude()); + shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); + shopVO.setBusinessHours(shopDO.getBusinessHours()); + shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); + shopVO.setCoverImageUrls(new java.util.ArrayList<>()); + shopVO.setImageFileIds(shopDO.getImageFileIds()); + shopVO.setImageUrls(new java.util.ArrayList<>()); + shopVO.setThemePrimaryColor(shopDO.getThemePrimaryColor()); + shopVO.setThemeSecondaryColor(shopDO.getThemeSecondaryColor()); + shopVO.setThemeAccentColor(shopDO.getThemeAccentColor()); + shopVO.setThemePageBgColor(shopDO.getThemePageBgColor()); + shopVO.setThemeCardBgColor(shopDO.getThemeCardBgColor()); + shopVO.setThemeBackgroundImageFileId(shopDO.getThemeBackgroundImageFileId()); + shopVO.setStatus(normalizeStatus(shopDO.getStatus())); + shopVO.setAuthorizationStartDate(shopDO.getAuthorizationStartDate()); + shopVO.setAuthorizationDays(shopDO.getAuthorizationDays()); + shopVO.setAuthorizationExpireTime(shopDO.getAuthorizationExpireTime()); + boolean expired = isAuthorizationExpired(shopDO); + shopVO.setAuthorizationExpired(expired); + shopVO.setAuthorizationStatusText(expired ? "已到期" : "有效"); + shopVO.setCreateTime(shopDO.getCreateTime()); + shopVO.setUpdateTime(shopDO.getUpdateTime()); + return shopVO; + } + + @Override + /** + * Run business method `isAuthorizationExpired`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isAuthorizationExpired(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + return isAuthorizationExpired(shopMapper.selectById(shopId)); + } + + @Override + /** + * Run business method `isFrontendAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isFrontendAvailable(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) + && isAuthorizationValid(shopDO); + } + + /** + * Run business method `isAuthorizationValid`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isAuthorizationValid(ShopDO shopDO) { + return !isAuthorizationExpired(shopDO); + } + + /** + * Run business method `isAuthorizationExpired`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isAuthorizationExpired(ShopDO shopDO) { + return shopDO != null + && shopDO.getAuthorizationExpireTime() != null + && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); + } + + /** + * Run business method `normalizeStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return private Integer result consumed by the caller or returned to the frontend + */ + private Integer normalizeStatus(Integer status) { + return Integer.valueOf(0).equals(status) ? 0 : 1; + } + + /** + * Purpose: applyAuthorization supports ShopServiceImpl.java by holding or executing the apply authorization business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void applyAuthorization(ShopDO shopDO, ShopDTO shopDTO) { + LocalDate startDate = shopDTO.getAuthorizationStartDate(); + Integer days = shopDTO.getAuthorizationDays(); + shopDO.setAuthorizationStartDate(startDate); + shopDO.setAuthorizationDays(days); + if (startDate != null && days != null && days > 0) { + shopDO.setAuthorizationExpireTime(startDate.plusDays(days - 1L).atTime(23, 59, 59)); + return; + } + shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime()); + } + + /** + * Purpose: applyTheme supports ShopServiceImpl.java by holding or executing the apply theme business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void applyTheme(ShopDO shopDO, ShopDTO shopDTO) { + shopDO.setThemePrimaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePrimaryColor(), "themePrimaryColor")); + shopDO.setThemeSecondaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeSecondaryColor(), "themeSecondaryColor")); + shopDO.setThemeAccentColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeAccentColor(), "themeAccentColor")); + shopDO.setThemePageBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePageBgColor(), "themePageBgColor")); + shopDO.setThemeCardBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeCardBgColor(), "themeCardBgColor")); + shopDO.setThemeBackgroundImageFileId(StringUtils.hasText(shopDTO.getThemeBackgroundImageFileId()) + ? shopDTO.getThemeBackgroundImageFileId().trim() + : null); + } + + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictShopCaches(Long shopId) { + if (shopId != null) { + multiLevelCacheService.evict(SHOP_DETAIL_CACHE_PREFIX + shopId); + } + multiLevelCacheService.evictByPrefix(SHOP_LIST_CACHE_PREFIX); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/ShopThemeSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/ShopThemeSupport.java new file mode 100644 index 00000000..ce0e3eff --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/ShopThemeSupport.java @@ -0,0 +1,32 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support; + +import org.springframework.util.StringUtils; + +import java.util.Locale; +import java.util.regex.Pattern; + +/** + * Purpose: ShopThemeSupport supports ShopThemeSupport.java by holding or executing the shop theme support business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class ShopThemeSupport { + private static final Pattern HEX_COLOR = Pattern.compile("^#[0-9a-fA-F]{6}$"); + + private ShopThemeSupport() { + } + + /** + * Purpose: normalizeColor supports ShopThemeSupport.java by holding or executing the normalize color business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String normalizeColor(String color, String fieldName) { + if (!StringUtils.hasText(color)) { + return null; + } + String value = color.trim(); + if (!HEX_COLOR.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " must be a #RRGGBB color"); + } + return value.toUpperCase(Locale.ROOT); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/UserShopBindingSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/UserShopBindingSupport.java new file mode 100644 index 00000000..c848d786 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/UserShopBindingSupport.java @@ -0,0 +1,635 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 用户-店铺绑定关系支撑类。 + */ +@Component +@RequiredArgsConstructor +public class UserShopBindingSupport { + + /** + * Purpose: userShopBindingMapper supports UserShopBindingSupport.java by holding or executing the user shop binding mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Purpose: shopMapper supports UserShopBindingSupport.java by holding or executing the shop mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ShopMapper shopMapper; + /** + * Purpose: userMapper supports UserShopBindingSupport.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + + /** + * Purpose: listBindingsByUserId supports UserShopBindingSupport.java by holding or executing the list bindings by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listBindingsByUserId(Long userId, boolean includeDeleted) { + if (userId == null) { + return List.of(); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .orderByAsc(UserShopBindingDO::getCreateTime) + .orderByAsc(UserShopBindingDO::getId); + if (!includeDeleted) { + wrapper.eq(UserShopBindingDO::getIsDelete, 0); + } + return userShopBindingMapper.selectList(wrapper); + } + + /** + * Purpose: hasBindingHistory supports UserShopBindingSupport.java by holding or executing the has binding history business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean hasBindingHistory(Long userId) { + if (userId == null) { + return false; + } + return userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId)) > 0; + } + + /** + * Purpose: listActiveBindingsByUserId supports UserShopBindingSupport.java by holding or executing the list active bindings by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listActiveBindingsByUserId(Long userId) { + return listBindingsByUserId(userId, false).stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .filter(binding -> isShopActive(binding.getShopId())) + .sorted(Comparator.comparing(UserShopBindingDO::getCreateTime, Comparator.nullsLast(LocalDateTime::compareTo)) + .thenComparing(UserShopBindingDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + /** + * Purpose: listActiveShopIdsByUserId supports UserShopBindingSupport.java by holding or executing the list active shop ids by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listActiveShopIdsByUserId(Long userId) { + return listShopIdsByUserId(userId, true, true); + } + + /** + * Purpose: listActiveShopOptionsByUserId supports UserShopBindingSupport.java by holding or executing the list active shop options by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listActiveShopOptionsByUserId(Long userId) { + return listShopOptionsByUserId(userId, true, true); + } + + /** + * Purpose: listAllActiveShopOptions supports UserShopBindingSupport.java by holding or executing the list all active shop options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listAllActiveShopOptions() { + return toShopOptions(fetchAllShopMap(true)); + } + + /** + * Purpose: listShopIdsByUserId supports UserShopBindingSupport.java by holding or executing the list shop ids by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listShopIdsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) { + return listShopOptionsByUserId(userId, onlyActiveBindings, onlyActiveShops).stream() + .map(ShopSimpleVO::getId) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Purpose: listShopOptionsByUserId supports UserShopBindingSupport.java by holding or executing the list shop options by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listShopOptionsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) { + return listShopOptionsByUserIds(List.of(userId), onlyActiveBindings, onlyActiveShops) + .getOrDefault(userId, List.of()); + } + + /** + * Purpose: hasActiveBinding supports UserShopBindingSupport.java by holding or executing the has active binding business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean hasActiveBinding(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + return listActiveBindingsByUserId(userId).stream() + .anyMatch(binding -> shopId.equals(binding.getShopId())); + } + + /** + * Purpose: hasBindingInShop supports UserShopBindingSupport.java by holding or executing the has binding in shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean hasBindingInShop(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + return userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)) > 0; + } + + /** + * Purpose: isShopActive supports UserShopBindingSupport.java by holding or executing the is shop active business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isShopActive(Long shopId) { + return isShopEnabledIgnoringAuthorization(shopId) && !isShopAuthorizationExpired(shopId); + } + + /** + * Purpose: isShopEnabledIgnoringAuthorization supports UserShopBindingSupport.java by holding or executing the is shop enabled ignoring authorization business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isShopEnabledIgnoringAuthorization(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && Integer.valueOf(1).equals(normalizeShopStatus(shopDO.getStatus())); + } + + /** + * Purpose: isShopAuthorizationExpired supports UserShopBindingSupport.java by holding or executing the is shop authorization expired business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isShopAuthorizationExpired(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && shopDO.getAuthorizationExpireTime() != null + && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); + } + + /** + * Purpose: pickPrimaryShopId supports UserShopBindingSupport.java by holding or executing the pick primary shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long pickPrimaryShopId(Long userId) { + return listActiveBindingsByUserId(userId).stream() + .map(UserShopBindingDO::getShopId) + .findFirst() + .orElse(null); + } + + /** + * Purpose: listActiveShopOptionsByUserIds supports UserShopBindingSupport.java by holding or executing the list active shop options by user ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Map> listActiveShopOptionsByUserIds(Collection userIds) { + return listShopOptionsByUserIds(userIds, true, true); + } + + public Map> listShopOptionsByUserIds( + Collection userIds, + boolean onlyActiveBindings, + boolean onlyActiveShops + ) { + if (userIds == null || userIds.isEmpty()) { + return Collections.emptyMap(); + } + List normalizedUserIds = userIds.stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (normalizedUserIds.isEmpty()) { + return Collections.emptyMap(); + } + + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .in(UserShopBindingDO::getUserId, normalizedUserIds) + .eq(UserShopBindingDO::getIsDelete, 0) + .orderByAsc(UserShopBindingDO::getCreateTime) + .orderByAsc(UserShopBindingDO::getId)); + if (bindings.isEmpty()) { + return Collections.emptyMap(); + } + + if (onlyActiveBindings) { + bindings = bindings.stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .collect(Collectors.toList()); + if (bindings.isEmpty()) { + return Collections.emptyMap(); + } + } + + Map shopMap = fetchShopMap(bindings.stream() + .map(UserShopBindingDO::getShopId) + .collect(Collectors.toSet()), onlyActiveShops); + Map> result = new LinkedHashMap<>(); + for (UserShopBindingDO binding : bindings) { + ShopDO shopDO = shopMap.get(binding.getShopId()); + if (shopDO == null) { + continue; + } + result.computeIfAbsent(binding.getUserId(), key -> new java.util.ArrayList<>()) + .add(new ShopSimpleVO(shopDO.getId(), shopDO.getShopName())); + } + return result; + } + + /** + * Purpose: listUserIdsByShopId supports UserShopBindingSupport.java by holding or executing the list user ids by shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listUserIdsByShopId(Long shopId, boolean onlyActiveBindings) { + if (shopId == null || shopId <= 0) { + return List.of(); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0); + if (onlyActiveBindings) { + wrapper.eq(UserShopBindingDO::getStatus, 1); + } + return userShopBindingMapper.selectList(wrapper).stream() + .map(UserShopBindingDO::getUserId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Purpose: countUsersByShopId supports UserShopBindingSupport.java by holding or executing the count users by shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public long countUsersByShopId(Long shopId, boolean onlyActiveBindings) { + return listUserIdsByShopId(shopId, onlyActiveBindings).size(); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: ensureUserBoundToShop supports UserShopBindingSupport.java by holding or executing the ensure user bound to shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureUserBoundToShop(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + throw new RuntimeException("店铺绑定信息不完整"); + } + if (!isShopActive(shopId)) { + throw new RuntimeException("所选店铺不存在或已停用"); + } + + UserShopBindingDO existing = userShopBindingMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .last("limit 1")); + if (existing == null) { + UserShopBindingDO binding = new UserShopBindingDO(); + binding.setUserId(userId); + binding.setShopId(shopId); + binding.setStatus(1); + binding.setIsDelete(0); + userShopBindingMapper.insert(binding); + refreshLegacyPrimaryShop(userId); + return; + } + + existing.setStatus(1); + existing.setIsDelete(0); + existing.setUpdateTime(LocalDateTime.now()); + userShopBindingMapper.updateById(existing); + refreshLegacyPrimaryShop(userId); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: syncUserShopBindings supports UserShopBindingSupport.java by holding or executing the sync user shop bindings business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void syncUserShopBindings(Long userId, Collection shopIds) { + if (userId == null) { + return; + } + + Set desiredShopIds = normalizeActiveShopIds(shopIds); + List existingBindings = listBindingsByUserId(userId, true); + Map bindingMap = existingBindings.stream() + .filter(binding -> binding.getShopId() != null) + .collect(Collectors.toMap(UserShopBindingDO::getShopId, binding -> binding, (left, right) -> right, LinkedHashMap::new)); + + for (Long shopId : desiredShopIds) { + UserShopBindingDO existing = bindingMap.remove(shopId); + if (existing == null) { + UserShopBindingDO binding = new UserShopBindingDO(); + binding.setUserId(userId); + binding.setShopId(shopId); + binding.setStatus(1); + binding.setIsDelete(0); + userShopBindingMapper.insert(binding); + continue; + } + existing.setStatus(1); + existing.setIsDelete(0); + existing.setUpdateTime(LocalDateTime.now()); + userShopBindingMapper.updateById(existing); + } + + for (UserShopBindingDO staleBinding : bindingMap.values()) { + staleBinding.setIsDelete(1); + staleBinding.setUpdateTime(LocalDateTime.now()); + userShopBindingMapper.updateById(staleBinding); + } + + refreshLegacyPrimaryShop(userId); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: updateBindingStatus supports UserShopBindingSupport.java by holding or executing the update binding status business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean updateBindingStatus(Long userId, Long shopId, Integer status) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (bindingCount <= 0) { + return false; + } + Integer normalizedStatus = Integer.valueOf(1).equals(status) ? 1 : 0; + LocalDateTime now = LocalDateTime.now(); + int updated = userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getStatus, normalizedStatus) + .set(UserShopBindingDO::getUpdateTime, now) + ); + refreshLegacyPrimaryShop(userId); + return updated > 0; + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: deleteBinding supports UserShopBindingSupport.java by holding or executing the delete binding business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean deleteBinding(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (bindingCount <= 0) { + return false; + } + LocalDateTime now = LocalDateTime.now(); + int updated = userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, now) + ); + refreshLegacyPrimaryShop(userId); + return updated > 0; + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: deleteBindingsByShopId supports UserShopBindingSupport.java by holding or executing the delete bindings by shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void deleteBindingsByShopId(Long shopId) { + if (shopId == null || shopId <= 0) { + return; + } + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (bindings.isEmpty()) { + return; + } + Set affectedUserIds = new LinkedHashSet<>(); + for (UserShopBindingDO binding : bindings) { + affectedUserIds.add(binding.getUserId()); + } + LocalDateTime now = LocalDateTime.now(); + userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, now) + ); + affectedUserIds.forEach(this::refreshLegacyPrimaryShop); + } + + /** + * Purpose: canUserAccessShop supports UserShopBindingSupport.java by holding or executing the can user access shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean canUserAccessShop(Long userId, Long shopId, boolean adminLogin, Integer userType) { + if (Integer.valueOf(4).equals(userType)) { + if (shopId == null || shopId <= 0) { + return Boolean.TRUE.equals(adminLogin); + } + return isShopSelectableForPlatformAdmin(shopId); + } + if (shopId == null || shopId <= 0) { + return false; + } + if (Boolean.TRUE.equals(adminLogin)) { + if (!isShopEnabledIgnoringAuthorization(shopId)) { + return false; + } + } else if (!isShopActive(shopId)) { + return false; + } + return hasActiveBinding(userId, shopId); + } + + /** + * Purpose: isShopSelectableForPlatformAdmin supports UserShopBindingSupport.java by holding or executing the is shop selectable for platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isShopSelectableForPlatformAdmin(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && (shopDO.getAuthorizationExpireTime() == null + || !shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now())); + } + + /** + * Purpose: isUserAccessibleInShop supports UserShopBindingSupport.java by holding or executing the is user accessible in shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isUserAccessibleInShop(Long userId, Long shopId) { + return hasActiveBinding(userId, shopId); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: deleteBindingsByUserId supports UserShopBindingSupport.java by holding or executing the delete bindings by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void deleteBindingsByUserId(Long userId) { + if (userId == null) { + return; + } + LocalDateTime now = LocalDateTime.now(); + userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, now) + ); + refreshLegacyPrimaryShop(userId); + } + + /** + * Purpose: normalizeActiveShopIds supports UserShopBindingSupport.java by holding or executing the normalize active shop ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set normalizeActiveShopIds(Collection shopIds) { + if (shopIds == null || shopIds.isEmpty()) { + return Collections.emptySet(); + } + Set normalizedShopIds = new LinkedHashSet<>(); + for (Long shopId : shopIds) { + if (shopId == null || shopId <= 0) { + continue; + } + if (!isShopActive(shopId)) { + throw new RuntimeException("所选店铺不存在或已停用"); + } + normalizedShopIds.add(shopId); + } + return normalizedShopIds; + } + + /** + * Purpose: refreshLegacyPrimaryShop supports UserShopBindingSupport.java by holding or executing the refresh legacy primary shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void refreshLegacyPrimaryShop(Long userId) { + if (userId == null) { + return; + } + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return; + } + Long primaryShopId = pickPrimaryShopId(userId); + if (Objects.equals(userDO.getShopId(), primaryShopId)) { + return; + } + LocalDateTime now = LocalDateTime.now(); + userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, userId) + .set(UserDO::getShopId, primaryShopId) + .set(UserDO::getUpdateTime, now) + ); + } + + /** + * Purpose: fetchAllShopMap supports UserShopBindingSupport.java by holding or executing the fetch all shop map business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map fetchAllShopMap(boolean onlyActiveShops) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(ShopDO::getIsDelete, 0); + if (onlyActiveShops) { + wrapper.eq(ShopDO::getStatus, 1); + } + return shopMapper.selectList(wrapper).stream() + .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) + .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); + } + + /** + * Purpose: fetchShopMap supports UserShopBindingSupport.java by holding or executing the fetch shop map business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map fetchShopMap(Collection shopIds, boolean onlyActiveShops) { + if (shopIds == null || shopIds.isEmpty()) { + return Collections.emptyMap(); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .in(ShopDO::getId, shopIds) + .eq(ShopDO::getIsDelete, 0); + if (onlyActiveShops) { + wrapper.eq(ShopDO::getStatus, 1); + } + return shopMapper.selectList(wrapper) + .stream() + .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) + .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); + } + + /** + * Purpose: toShopOptions supports UserShopBindingSupport.java by holding or executing the to shop options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List toShopOptions(Map shopMap) { + return shopMap.values().stream() + .sorted(Comparator.comparing(ShopDO::getShopName, Comparator.nullsLast(String::compareTo)) + .thenComparing(ShopDO::getId, Comparator.nullsLast(Long::compareTo))) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * Purpose: normalizeShopStatus supports UserShopBindingSupport.java by holding or executing the normalize shop status business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer normalizeShopStatus(Integer status) { + return status == null ? 1 : status; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ContactInfoVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ContactInfoVO.java new file mode 100644 index 00000000..7ffcf786 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ContactInfoVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.vo; + +import lombok.Data; + +@Data +/** + * ContactInfoVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ContactInfoVO { + /** + * Field `contactUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long contactUserId; + /** + * Field `contactName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String contactName; + /** + * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleLabel; + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + /** + * Field `phoneAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean phoneAvailable; + /** + * Field `wechatId` (String): contact WeChat ID for quick copy/open actions. + */ + private String wechatId; + /** + * Field `wechatAvailable` (Boolean): whether the contact exposes a WeChat ID. + */ + private Boolean wechatAvailable; + /** + * Field `wechatQrCode` (String): accessible WeChat QR code image URL. + */ + private String wechatQrCode; + /** + * Field `platformContactAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean platformContactAvailable; + /** + * Field `platformContactText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platformContactText; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopSimpleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopSimpleVO.java new file mode 100644 index 00000000..52da2803 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopSimpleVO.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +/** + * ShopSimpleVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopSimpleVO { + + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopTrustProfileVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopTrustProfileVO.java new file mode 100644 index 00000000..bd4c5f73 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopTrustProfileVO.java @@ -0,0 +1,290 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page. + * Usage: return this VO from /shop/trust-profile/{shopId}; clients render it without exposing phone numbers. + */ +@Data +public class ShopTrustProfileVO { + /** + * Purpose: shopId identifies the shop whose trust profile is being rendered. + * Usage: clients use it to keep the profile matched to the visible shop. + */ + private Long shopId; + + /** + * Purpose: shopName gives the profile a stable display label. + * Usage: render it in accessibility labels or fallback section titles. + */ + private String shopName; + + /** + * Purpose: businessHoursText describes when the shop says it is open. + * Usage: show it near booking and navigation actions. + */ + private String businessHoursText; + + /** + * Purpose: businessStatusText summarizes whether the shop can currently be viewed and booked. + * Usage: display this short text in trust summary chips. + */ + private String businessStatusText; + + /** + * Purpose: locationAvailable reports whether map coordinates exist. + * Usage: hide navigation/distance affordances when false. + */ + private Boolean locationAvailable; + + /** + * Purpose: distanceCapabilityText explains whether distance can be calculated on the client. + * Usage: show this text until the client has user location permission. + */ + private String distanceCapabilityText; + + /** + * Purpose: navigationAvailable reports whether navigation URLs can be offered. + * Usage: clients use it to enable map buttons. + */ + private Boolean navigationAvailable; + + /** + * Purpose: stats contains public aggregate numbers for customer confidence. + * Usage: render as compact metrics on the shop detail page. + */ + private Stats stats = new Stats(); + + /** + * Purpose: environmentImages contains public shop environment image URLs. + * Usage: render thumbnails or a carousel; it must not include contact data. + */ + private List environmentImages = new ArrayList<>(); + + /** + * Purpose: featuredProducts lists representative products from this shop. + * Usage: render as quick inspection or booking entry cards. + */ + private List featuredProducts = new ArrayList<>(); + + /** + * Purpose: recentReviews lists recent submitted reviews only. + * Usage: show social proof while keeping customer identity private. + */ + private List recentReviews = new ArrayList<>(); + + /** + * Purpose: availabilitySummary gives a safe booking summary without reserving slots. + * Usage: render it near booking actions and keep final conflict checks in order creation. + */ + private AvailabilitySummary availabilitySummary = new AvailabilitySummary(); + + /** + * Purpose: contactSummary tells clients how to request contact details without exposing phone data. + * Usage: render the action hint and fetch phone only through the explicit contact endpoint. + */ + private ContactSummary contactSummary = new ContactSummary(); + + /** + * Purpose: Stats groups aggregate shop trust metrics. + * Usage: serialize inside ShopTrustProfileVO.stats for frontend summary cards. + */ + @Data + public static class Stats { + /** + * Purpose: averageRating is the submitted-review average for this shop. + * Usage: display with one decimal place when reviewCount is greater than zero. + */ + private BigDecimal averageRating = BigDecimal.ZERO; + + /** + * Purpose: reviewCount is the number of submitted, public reviews. + * Usage: render beside averageRating to avoid showing score without sample size. + */ + private Long reviewCount = 0L; + + /** + * Purpose: productCount is the number of active products in this shop. + * Usage: render as a confidence signal and empty-state condition. + */ + private Long productCount = 0L; + + /** + * Purpose: artistCount is the number of active nail artist users bound to this shop. + * Usage: render as the staff confidence signal on shop detail pages. + */ + private Long artistCount = 0L; + + /** + * Purpose: recentReviewCount is the number of review cards included in this response. + * Usage: clients use it for section labels and empty states. + */ + private Integer recentReviewCount = 0; + } + + /** + * Purpose: FeaturedProduct is a compact public product card for shop trust display. + * Usage: render these cards on shop detail pages without fetching full product detail first. + */ + @Data + public static class FeaturedProduct { + /** + * Purpose: id identifies the product for detail navigation. + * Usage: pass it to product detail routes when the customer taps the card. + */ + private Long id; + + /** + * Purpose: title names the featured product. + * Usage: render as the card title. + */ + private String title; + + /** + * Purpose: imageUrl provides the first public product image. + * Usage: render as a thumbnail and fall back gracefully when blank. + */ + private String imageUrl; + + /** + * Purpose: imageFileIds provides product image file ids for clients that need signed image URLs. + * Usage: clients may resolve the first id into a stable thumbnail URL. + */ + private String imageFileIds; + + /** + * Purpose: price carries the current product price. + * Usage: show it as a current quote, not as historical order price. + */ + private BigDecimal price; + + /** + * Purpose: likeCount is the current like count. + * Usage: render as a lightweight popularity signal. + */ + private Integer likeCount; + + /** + * Purpose: collectCount is the current wishlist count. + * Usage: render as a lightweight popularity signal. + */ + private Integer collectCount; + + /** + * Purpose: availableBookableArtistCount tells whether this product has available artists configured. + * Usage: show concise booking hints without exposing artist schedules. + */ + private Integer availableBookableArtistCount; + + /** + * Purpose: bookingHint is a customer-facing availability hint for this product. + * Usage: display below the product title. + */ + private String bookingHint; + } + + /** + * Purpose: RecentReview is a privacy-safe submitted review summary. + * Usage: render public review snippets without customer account or phone fields. + */ + @Data + public static class RecentReview { + /** + * Purpose: id identifies the review row. + * Usage: use it as a frontend list key. + */ + private Long id; + + /** + * Purpose: productId links the review to the reviewed product. + * Usage: optionally navigate to the product detail page. + */ + private Long productId; + + /** + * Purpose: productTitle names the product reviewed. + * Usage: display as context for the review. + */ + private String productTitle; + + /** + * Purpose: ratingScore is the submitted rating. + * Usage: render with one decimal place. + */ + private BigDecimal ratingScore; + + /** + * Purpose: content stores the submitted review text. + * Usage: display a short snippet and hide the section when blank if desired. + */ + private String content; + + /** + * Purpose: imageUrls contains public review image URLs. + * Usage: render thumbnails without exposing customer identity. + */ + private List imageUrls = new ArrayList<>(); + + /** + * Purpose: submittedAt records when the review was submitted. + * Usage: render relative or formatted review time. + */ + private LocalDateTime submittedAt; + } + + /** + * Purpose: AvailabilitySummary summarizes booking readiness for the shop. + * Usage: clients render it as guidance while final validation remains server-side on order creation. + */ + @Data + public static class AvailabilitySummary { + /** + * Purpose: available states whether the shop currently has active products to book. + * Usage: enable or soften booking entry copy. + */ + private Boolean available = false; + + /** + * Purpose: summaryText gives the customer a direct booking-readiness sentence. + * Usage: render as the availability card body. + */ + private String summaryText = "暂无可预约作品"; + + /** + * Purpose: nextSlots gives coarse upcoming booking hints when available. + * Usage: render as chips; clients must not treat these as reserved slots. + */ + private List nextSlots = new ArrayList<>(); + } + + /** + * Purpose: ContactSummary describes the explicit contact action without leaking phone data. + * Usage: render the action label and call contact-info only after the user taps contact. + */ + @Data + public static class ContactSummary { + /** + * Purpose: actionText is the label for the explicit contact action. + * Usage: render on the contact button or helper text. + */ + private String actionText = "点击联系店长后获取联系方式"; + + /** + * Purpose: phoneExposed records whether this public profile includes phone data. + * Usage: assert false in tests and use contact-info endpoint for phone data. + */ + private Boolean phoneExposed = false; + + /** + * Purpose: phone is intentionally null in this public profile. + * Usage: clients must ignore it and call the explicit contact endpoint instead. + */ + private String phone; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopVO.java new file mode 100644 index 00000000..72d5743a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/ShopVO.java @@ -0,0 +1,170 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** + * 店铺信息表 VO + * 用于前端展示店铺信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ShopVO { + + /** + * 店铺唯一主键ID + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 店铺描述 + */ + private String description; + + /** + * 店铺地址 + */ + private String address; + + /** + * Purpose: mapProvider supports ShopVO.java by holding or executing the map provider business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String mapProvider; + + /** + * Purpose: longitude supports ShopVO.java by holding or executing the longitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal longitude; + + /** + * Purpose: latitude supports ShopVO.java by holding or executing the latitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal latitude; + + /** + * Purpose: navigationUrls supports ShopVO.java by holding or executing the navigation urls business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map navigationUrls; + + /** + * 店铺营业时间 + */ + private String businessHours; + + /** + * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 + */ + private String coverImageFileId; + + /** + * 店铺封面图URL列表(Banner图) + */ + private List coverImageUrls; + + /** + * 店铺图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 店铺图片URL列表 + */ + private List imageUrls; + + /** + * Purpose: themePrimaryColor supports ShopVO.java by holding or executing the theme primary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePrimaryColor; + + /** + * Purpose: themeSecondaryColor supports ShopVO.java by holding or executing the theme secondary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeSecondaryColor; + + /** + * Purpose: themeAccentColor supports ShopVO.java by holding or executing the theme accent color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeAccentColor; + + /** + * Purpose: themePageBgColor supports ShopVO.java by holding or executing the theme page bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePageBgColor; + + /** + * Purpose: themeCardBgColor supports ShopVO.java by holding or executing the theme card bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeCardBgColor; + + /** + * Purpose: themeBackgroundImageFileId supports ShopVO.java by holding or executing the theme background image file id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeBackgroundImageFileId; + + /** + * 店铺状态:1-启用,0-停用 + */ + private Integer status; + + /** + * Purpose: authorizationStartDate supports ShopVO.java by holding or executing the authorization start date business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDate authorizationStartDate; + + /** + * Purpose: authorizationDays supports ShopVO.java by holding or executing the authorization days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer authorizationDays; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + private LocalDateTime authorizationExpireTime; + + /** + * 当前时间是否已超过授权有效期。 + */ + private Boolean authorizationExpired; + + /** + * 给前端直接展示的授权状态文案。 + */ + private String authorizationStatusText; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/HealthController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/HealthController.java new file mode 100644 index 00000000..d059ee0e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/HealthController.java @@ -0,0 +1,125 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.Result; +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 健康检查控制器 + * + * @author xiaowang + * @date 2026-02-12 + */ +@RestController +@RequestMapping("/health") +@RequiredArgsConstructor +public class HealthController { + /** + * Variable `dataSource`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final DataSource dataSource; + /** + * Variable `stringRedisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Variable `discoveryClient`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final DiscoveryClient discoveryClient; + /** + * Variable `environment`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final Environment environment; + + /** + * 服务状态检查 + */ + @GetMapping("/check") + public Result check() { + return Result.success("JC-ArtList-Core is running"); + } + + @GetMapping("/diagnostics") + /** + * Run business method `diagnostics`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> diagnostics() { + Map diagnostics = new LinkedHashMap<>(); + diagnostics.put("service", environment.getProperty("spring.application.name", "jc-artlist-core")); + diagnostics.put("port", environment.getProperty("server.port", "")); + diagnostics.put("database", checkDatabase()); + diagnostics.put("redis", checkRedis()); + diagnostics.put("discovery", checkDiscovery()); + return Result.success(diagnostics); + } + + /** + * Run business method `checkDatabase`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map checkDatabase() { + Map result = new LinkedHashMap<>(); + try (Connection connection = dataSource.getConnection()) { + result.put("ok", connection.isValid(2)); + result.put("catalog", connection.getCatalog()); + result.put("product", connection.getMetaData().getDatabaseProductName()); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } + + /** + * Run business method `checkRedis`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map checkRedis() { + Map result = new LinkedHashMap<>(); + try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) { + String pong = connection.ping(); + result.put("ok", "PONG".equalsIgnoreCase(pong)); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } + + /** + * Run business method `checkDiscovery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map checkDiscovery() { + Map result = new LinkedHashMap<>(); + try { + String serviceName = environment.getProperty("spring.application.name", "jc-artlist-core"); + List instances = discoveryClient.getInstances(serviceName); + result.put("ok", !instances.isEmpty()); + result.put("service", serviceName); + result.put("instanceCount", instances.size()); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/LegalAgreementController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/LegalAgreementController.java new file mode 100644 index 00000000..83b5e315 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/LegalAgreementController.java @@ -0,0 +1,147 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.artlist.core.modules.system.vo.LegalAgreementVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAgreementConsentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/legal-agreement", "/api/legal-agreement"}) +/** + * Purpose: LegalAgreementController supports LegalAgreementController.java by holding or executing the legal agreement controller business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementController { + + /** + * Purpose: legalAgreementService supports LegalAgreementController.java by holding or executing the legal agreement service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementService legalAgreementService; + /** + * Purpose: adminScopeHelper supports LegalAgreementController.java by holding or executing the admin scope helper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: securityAuditLogService supports LegalAgreementController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + /** + * Purpose: requestThrottleService supports LegalAgreementController.java by holding or executing the request throttle service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestThrottleService requestThrottleService; + + @GetMapping("/current") + /** + * Purpose: listCurrent supports LegalAgreementController.java by holding or executing the list current business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listCurrent(HttpServletRequest request) { + requestThrottleService.checkAgreementRead(request, "ALL"); + return Result.success(legalAgreementService.listCurrentAgreements()); + } + + @GetMapping("/current/{type}") + /** + * Purpose: getCurrent supports LegalAgreementController.java by holding or executing the get current business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result getCurrent(HttpServletRequest request, @PathVariable String type) { + requestThrottleService.checkAgreementRead(request, type); + return Result.success(legalAgreementService.getCurrentAgreement(type)); + } + + @GetMapping("/admin/list") + @RequirePermission("legal_agreement:manage") + /** + * Purpose: listAdmin supports LegalAgreementController.java by holding or executing the list admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listAdmin(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(legalAgreementService.listAdminAgreements(currentUser)); + } + + @PostMapping("/admin/create") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-create", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + /** + * Purpose: create supports LegalAgreementController.java by holding or executing the create business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result create(HttpServletRequest request, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long id = legalAgreementService.createAgreement(currentUser, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_CREATE", "SUCCESS", dto.getAgreementType(), request); + return Result.success(id); + } + + @PutMapping("/admin/{id}") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-update", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + /** + * Purpose: update supports LegalAgreementController.java by holding or executing the update business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.updateAgreement(currentUser, id, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_UPDATE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/admin/{id}/publish") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-publish", ttlSeconds = 8, message = "协议发布处理中,请勿重复提交") + /** + * Purpose: publish supports LegalAgreementController.java by holding or executing the publish business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result publish(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.publishAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_PUBLISH", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/admin/{id}/disable") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-disable", ttlSeconds = 8, message = "协议停用处理中,请勿重复提交") + /** + * Purpose: disable supports LegalAgreementController.java by holding or executing the disable business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result disable(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.disableAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_DISABLE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @GetMapping("/user/agreement-consent/me") + /** + * Purpose: getMyConsent supports LegalAgreementController.java by holding or executing the get my consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result getMyConsent(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getMyConsent(userId)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/SystemParameterConfigController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/SystemParameterConfigController.java new file mode 100644 index 00000000..360919d6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/controller/front/SystemParameterConfigController.java @@ -0,0 +1,101 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.jayucloud.artlist.core.modules.system.vo.SystemParameterConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/system-parameter-config", "/api/system-parameter-config", "/admin/system-parameter-config"}) +/** + * Purpose: SystemParameterConfigController supports SystemParameterConfigController.java by holding or executing the system parameter config controller business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigController { + + /** + * Purpose: configService supports SystemParameterConfigController.java by holding or executing the config service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SystemParameterConfigService configService; + /** + * Purpose: adminScopeHelper supports SystemParameterConfigController.java by holding or executing the admin scope helper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("messagehub:config:manage") + public Result> list(HttpServletRequest request, + @RequestParam(required = false) String configGroup) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.listConfigs(currentUser, configGroup)); + } + + @PostMapping("/admin/save") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "system-parameter-config-save", ttlSeconds = 8, message = "系统参数保存处理中,请勿重复提交") + /** + * Purpose: save supports SystemParameterConfigController.java by holding or executing the save business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result save(HttpServletRequest request, @Valid @RequestBody SystemParameterConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.saveConfig(currentUser, dto)); + } + + @GetMapping("/admin/tencent-map") + /** + * Purpose: getTencentMapKey supports SystemParameterConfigController.java by holding or executing the get tencent map key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> getTencentMapKey(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); + return Result.success(result); + } + + @GetMapping("/admin/map-config") + /** + * Purpose: getMapConfig supports SystemParameterConfigController.java by holding or executing the get map config business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> getMapConfig(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + String provider = configService.getEnabledValue("MAP", "MAP_PROVIDER"); + result.put("provider", "AMAP".equalsIgnoreCase(provider) ? "AMAP" : "TENCENT"); + result.put("tencentWebKey", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); + result.put("amapWebKey", configService.getEnabledValue("MAP", "AMAP_WEB_KEY")); + result.put("amapMiniKey", configService.getEnabledValue("MAP", "AMAP_MINI_KEY")); + return Result.success(result); + } + + @GetMapping("/admin/user-default-password") + @RequirePermission("user:create") + public Result> getUserDefaultPassword(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + String configuredDefaultPassword = configService.getEnabledValue( + AdminDefaultPasswordSupport.CONFIG_GROUP, + AdminDefaultPasswordSupport.CONFIG_KEY + ); + result.put("password", AdminDefaultPasswordSupport.resolveDefaultPassword(configuredDefaultPassword)); + return Result.success(result); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/dto/LegalAgreementDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/dto/LegalAgreementDTO.java new file mode 100644 index 00000000..71a61489 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/dto/LegalAgreementDTO.java @@ -0,0 +1,44 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * Purpose: LegalAgreementDTO supports LegalAgreementDTO.java by holding or executing the legal agreement dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementDTO { + + @NotBlank(message = "协议类型不能为空") + /** + * Purpose: agreementType supports LegalAgreementDTO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + @NotBlank(message = "协议标题不能为空") + @Size(max = 100, message = "协议标题不能超过100个字符") + /** + * Purpose: title supports LegalAgreementDTO.java by holding or executing the title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String title; + + @NotBlank(message = "协议版本不能为空") + @Size(max = 40, message = "协议版本不能超过40个字符") + /** + * Purpose: version supports LegalAgreementDTO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + @NotBlank(message = "协议内容不能为空") + /** + * Purpose: content supports LegalAgreementDTO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/dto/SystemParameterConfigDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/dto/SystemParameterConfigDTO.java new file mode 100644 index 00000000..ac83d130 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/dto/SystemParameterConfigDTO.java @@ -0,0 +1,58 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * Purpose: SystemParameterConfigDTO supports SystemParameterConfigDTO.java by holding or executing the system parameter config dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigDTO { + + @NotBlank(message = "配置分组不能为空") + @Size(max = 50, message = "配置分组不能超过50个字符") + /** + * Purpose: configGroup supports SystemParameterConfigDTO.java by holding or executing the config group business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configGroup; + + @NotBlank(message = "配置键不能为空") + @Size(max = 100, message = "配置键不能超过100个字符") + /** + * Purpose: configKey supports SystemParameterConfigDTO.java by holding or executing the config key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configKey; + + @NotBlank(message = "配置名称不能为空") + @Size(max = 100, message = "配置名称不能超过100个字符") + /** + * Purpose: configName supports SystemParameterConfigDTO.java by holding or executing the config name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configName; + + @Size(max = 1000, message = "配置值不能超过1000个字符") + /** + * Purpose: configValue supports SystemParameterConfigDTO.java by holding or executing the config value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configValue; + + /** + * Purpose: enabled supports SystemParameterConfigDTO.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer enabled = 1; + + @Size(max = 255, message = "备注不能超过255个字符") + /** + * Purpose: remark supports SystemParameterConfigDTO.java by holding or executing the remark business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/entity/LegalAgreementDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/entity/LegalAgreementDO.java new file mode 100644 index 00000000..06375f56 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/entity/LegalAgreementDO.java @@ -0,0 +1,70 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_legal_agreement") +/** + * Purpose: LegalAgreementDO supports LegalAgreementDO.java by holding or executing the legal agreement do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementDO extends BaseEntity { + + @TableField("agreement_type") + /** + * Purpose: agreementType supports LegalAgreementDO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + @TableField("title") + /** + * Purpose: title supports LegalAgreementDO.java by holding or executing the title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String title; + + @TableField("version") + /** + * Purpose: version supports LegalAgreementDO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + @TableField("content") + /** + * Purpose: content supports LegalAgreementDO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + + @TableField("status") + /** + * Purpose: status supports LegalAgreementDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + + @TableField("effective_time") + /** + * Purpose: effectiveTime supports LegalAgreementDO.java by holding or executing the effective time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime effectiveTime; + + @TableField("is_delete") + @TableLogic + /** + * Purpose: isDelete supports LegalAgreementDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/entity/SystemParameterConfigDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/entity/SystemParameterConfigDO.java new file mode 100644 index 00000000..52308786 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/entity/SystemParameterConfigDO.java @@ -0,0 +1,68 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_system_parameter_config") +/** + * Purpose: SystemParameterConfigDO supports SystemParameterConfigDO.java by holding or executing the system parameter config do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigDO extends BaseEntity { + + @TableField("config_group") + /** + * Purpose: configGroup supports SystemParameterConfigDO.java by holding or executing the config group business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configGroup; + + @TableField("config_key") + /** + * Purpose: configKey supports SystemParameterConfigDO.java by holding or executing the config key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configKey; + + @TableField("config_name") + /** + * Purpose: configName supports SystemParameterConfigDO.java by holding or executing the config name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configName; + + @TableField("config_value") + /** + * Purpose: configValue supports SystemParameterConfigDO.java by holding or executing the config value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configValue; + + @TableField("enabled") + /** + * Purpose: enabled supports SystemParameterConfigDO.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer enabled; + + @TableField("remark") + /** + * Purpose: remark supports SystemParameterConfigDO.java by holding or executing the remark business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String remark; + + @TableField("is_delete") + @TableLogic + /** + * Purpose: isDelete supports SystemParameterConfigDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/mapper/LegalAgreementMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/mapper/LegalAgreementMapper.java new file mode 100644 index 00000000..0779850f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/mapper/LegalAgreementMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.system.entity.LegalAgreementDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: LegalAgreementMapper supports LegalAgreementMapper.java by holding or executing the legal agreement mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface LegalAgreementMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/mapper/SystemParameterConfigMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/mapper/SystemParameterConfigMapper.java new file mode 100644 index 00000000..1da82a67 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/mapper/SystemParameterConfigMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.system.entity.SystemParameterConfigDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: SystemParameterConfigMapper supports SystemParameterConfigMapper.java by holding or executing the system parameter config mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SystemParameterConfigMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/LegalAgreementService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/LegalAgreementService.java new file mode 100644 index 00000000..ec98fdf3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/LegalAgreementService.java @@ -0,0 +1,37 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.service; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.system.vo.LegalAgreementVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAgreementConsentVO; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * Purpose: LegalAgreementService supports LegalAgreementService.java by holding or executing the legal agreement service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface LegalAgreementService { + + List listAdminAgreements(UserDO currentUser); + + Long createAgreement(UserDO currentUser, LegalAgreementDTO dto); + + Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto); + + Boolean publishAgreement(UserDO currentUser, Long id); + + Boolean disableAgreement(UserDO currentUser, Long id); + + List listCurrentAgreements(); + + LegalAgreementVO getCurrentAgreement(String agreementType); + + UserAgreementConsentVO getMyConsent(Long userId); + + void requireAccepted(AgreementAwareRequest request); + + void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/SystemParameterConfigService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/SystemParameterConfigService.java new file mode 100644 index 00000000..cead8d50 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/SystemParameterConfigService.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.service; + +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.system.vo.SystemParameterConfigVO; + +import java.util.List; + +/** + * Purpose: SystemParameterConfigService supports SystemParameterConfigService.java by holding or executing the system parameter config service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SystemParameterConfigService { + + List listConfigs(UserDO currentUser, String configGroup); + + Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto); + + String getEnabledValue(String configGroup, String configKey); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/impl/LegalAgreementServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/impl/LegalAgreementServiceImpl.java new file mode 100644 index 00000000..6f3929fb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/impl/LegalAgreementServiceImpl.java @@ -0,0 +1,348 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.jayucloud.artlist.core.modules.system.entity.LegalAgreementDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserAgreementConsentDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.system.mapper.LegalAgreementMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserAgreementConsentMapper; +import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.artlist.core.modules.system.vo.LegalAgreementVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAgreementConsentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * Purpose: LegalAgreementServiceImpl supports LegalAgreementServiceImpl.java by holding or executing the legal agreement service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementServiceImpl implements LegalAgreementService { + + /** + * Purpose: USER_TERMS supports LegalAgreementServiceImpl.java by holding or executing the user terms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_TERMS = "USER_TERMS"; + /** + * Purpose: PRIVACY_POLICY supports LegalAgreementServiceImpl.java by holding or executing the privacy policy business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PRIVACY_POLICY = "PRIVACY_POLICY"; + + /** + * Purpose: agreementMapper supports LegalAgreementServiceImpl.java by holding or executing the agreement mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementMapper agreementMapper; + /** + * Purpose: consentMapper supports LegalAgreementServiceImpl.java by holding or executing the consent mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserAgreementConsentMapper consentMapper; + + @Override + /** + * Purpose: listAdminAgreements supports LegalAgreementServiceImpl.java by holding or executing the list admin agreements business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listAdminAgreements(UserDO currentUser) { + ensurePlatformAdmin(currentUser); + return agreementMapper.selectList(new LambdaQueryWrapper() + .eq(LegalAgreementDO::getIsDelete, 0) + .orderByDesc(LegalAgreementDO::getEffectiveTime) + .orderByDesc(LegalAgreementDO::getCreateTime)) + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: createAgreement supports LegalAgreementServiceImpl.java by holding or executing the create agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long createAgreement(UserDO currentUser, LegalAgreementDTO dto) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = new LegalAgreementDO(); + apply(agreement, dto); + agreement.setStatus(0); + agreement.setIsDelete(0); + agreementMapper.insert(agreement); + return agreement.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: updateAgreement supports LegalAgreementServiceImpl.java by holding or executing the update agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + apply(agreement, dto); + agreementMapper.updateById(agreement); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: publishAgreement supports LegalAgreementServiceImpl.java by holding or executing the publish agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean publishAgreement(UserDO currentUser, Long id) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + agreementMapper.update(null, new LambdaUpdateWrapper() + .eq(LegalAgreementDO::getAgreementType, agreement.getAgreementType()) + .eq(LegalAgreementDO::getIsDelete, 0) + .set(LegalAgreementDO::getStatus, 0)); + agreement.setStatus(1); + agreement.setEffectiveTime(LocalDateTime.now()); + agreementMapper.updateById(agreement); + return true; + } + + @Override + /** + * Purpose: disableAgreement supports LegalAgreementServiceImpl.java by holding or executing the disable agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean disableAgreement(UserDO currentUser, Long id) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + agreement.setStatus(0); + agreementMapper.updateById(agreement); + return true; + } + + @Override + /** + * Purpose: listCurrentAgreements supports LegalAgreementServiceImpl.java by holding or executing the list current agreements business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listCurrentAgreements() { + return List.of(USER_TERMS, PRIVACY_POLICY).stream() + .map(this::getCurrentAgreement) + .collect(Collectors.toList()); + } + + @Override + /** + * Purpose: getCurrentAgreement supports LegalAgreementServiceImpl.java by holding or executing the get current agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public LegalAgreementVO getCurrentAgreement(String agreementType) { + LegalAgreementDO agreement = findCurrentAgreement(normalizeType(agreementType)); + if (agreement == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + return toVO(agreement); + } + + @Override + /** + * Purpose: getMyConsent supports LegalAgreementServiceImpl.java by holding or executing the get my consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public UserAgreementConsentVO getMyConsent(Long userId) { + Map versions = consentMapper.selectList(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId)) + .stream() + .collect(Collectors.toMap(UserAgreementConsentDO::getAgreementType, UserAgreementConsentDO::getVersion, (left, right) -> right, LinkedHashMap::new)); + return new UserAgreementConsentVO(versions); + } + + @Override + /** + * Purpose: requireAccepted supports LegalAgreementServiceImpl.java by holding or executing the require accepted business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requireAccepted(AgreementAwareRequest request) { + if (request == null || !Boolean.TRUE.equals(request.getAgreementAccepted())) { + throw new RuntimeException("请先阅读并同意用户协议和隐私政策"); + } + Map versions = request.getAgreementVersions(); + requireVersion(versions, USER_TERMS); + requireVersion(versions, PRIVACY_POLICY); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: recordConsent supports LegalAgreementServiceImpl.java by holding or executing the record consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest) { + if (userId == null || request == null || request.getAgreementVersions() == null) { + return; + } + String clientType = StringUtils.hasText(request.getClientType()) ? request.getClientType().trim().toUpperCase() : "WEB"; + request.getAgreementVersions().forEach((type, version) -> upsertConsent( + userId, + normalizeType(type), + version, + entry, + clientType, + resolveClientIp(httpRequest), + httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER) + )); + } + + /** + * Purpose: requireVersion supports LegalAgreementServiceImpl.java by holding or executing the require version business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void requireVersion(Map versions, String type) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + String submittedVersion = versions == null ? null : versions.get(type); + if (!StringUtils.hasText(submittedVersion) || !current.getVersion().equals(submittedVersion.trim())) { + throw new RuntimeException("协议版本已更新,请重新阅读并同意"); + } + } + + /** + * Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) { + if (!StringUtils.hasText(version)) { + return; + } + UserAgreementConsentDO existing = consentMapper.selectOne(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId) + .eq(UserAgreementConsentDO::getAgreementType, type) + .last("limit 1")); + UserAgreementConsentDO consent = existing == null ? new UserAgreementConsentDO() : existing; + consent.setUserId(userId); + consent.setAgreementType(type); + consent.setVersion(version.trim()); + consent.setEntry(entry); + consent.setClientType(clientType); + consent.setIpAddress(ip); + consent.setDeviceId(deviceId); + consent.setConsentTime(LocalDateTime.now()); + if (existing == null) { + consentMapper.insert(consent); + } else { + consentMapper.updateById(consent); + } + } + + /** + * Purpose: findCurrentAgreement supports LegalAgreementServiceImpl.java by holding or executing the find current agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LegalAgreementDO findCurrentAgreement(String type) { + return agreementMapper.selectOne(new LambdaQueryWrapper() + .eq(LegalAgreementDO::getAgreementType, normalizeType(type)) + .eq(LegalAgreementDO::getStatus, 1) + .eq(LegalAgreementDO::getIsDelete, 0) + .orderByDesc(LegalAgreementDO::getEffectiveTime) + .last("limit 1")); + } + + /** + * Purpose: requireAgreement supports LegalAgreementServiceImpl.java by holding or executing the require agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LegalAgreementDO requireAgreement(Long id) { + LegalAgreementDO agreement = agreementMapper.selectById(id); + if (agreement == null || Integer.valueOf(1).equals(agreement.getIsDelete())) { + throw new RuntimeException("协议不存在"); + } + return agreement; + } + + /** + * Purpose: apply supports LegalAgreementServiceImpl.java by holding or executing the apply business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void apply(LegalAgreementDO agreement, LegalAgreementDTO dto) { + agreement.setAgreementType(normalizeType(dto.getAgreementType())); + agreement.setTitle(dto.getTitle().trim()); + agreement.setVersion(dto.getVersion().trim()); + agreement.setContent(dto.getContent().trim()); + } + + /** + * Purpose: normalizeType supports LegalAgreementServiceImpl.java by holding or executing the normalize type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String normalizeType(String type) { + if (!StringUtils.hasText(type)) { + throw new RuntimeException("协议类型不能为空"); + } + String normalized = type.trim().toUpperCase(); + if (!USER_TERMS.equals(normalized) && !PRIVACY_POLICY.equals(normalized)) { + throw new RuntimeException("协议类型不正确"); + } + return normalized; + } + + /** + * Purpose: ensurePlatformAdmin supports LegalAgreementServiceImpl.java by holding or executing the ensure platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理协议"); + } + } + + /** + * Purpose: resolveClientIp supports LegalAgreementServiceImpl.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return null; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); + } + + /** + * Purpose: toVO supports LegalAgreementServiceImpl.java by holding or executing the to vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LegalAgreementVO toVO(LegalAgreementDO agreement) { + LegalAgreementVO vo = new LegalAgreementVO(); + vo.setId(agreement.getId()); + vo.setAgreementType(agreement.getAgreementType()); + vo.setAgreementTypeName(USER_TERMS.equals(agreement.getAgreementType()) ? "用户协议" : "隐私政策"); + vo.setTitle(agreement.getTitle()); + vo.setVersion(agreement.getVersion()); + vo.setContent(agreement.getContent()); + vo.setStatus(agreement.getStatus()); + vo.setStatusText(Integer.valueOf(1).equals(agreement.getStatus()) ? "已发布" : "草稿/停用"); + vo.setEffectiveTime(agreement.getEffectiveTime()); + vo.setCreateTime(agreement.getCreateTime()); + vo.setUpdateTime(agreement.getUpdateTime()); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java new file mode 100644 index 00000000..aee50eae --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java @@ -0,0 +1,140 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.jayucloud.artlist.core.modules.system.entity.SystemParameterConfigDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.artlist.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.jayucloud.artlist.core.modules.system.vo.SystemParameterConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * Purpose: SystemParameterConfigServiceImpl supports SystemParameterConfigServiceImpl.java by holding or executing the system parameter config service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigServiceImpl implements SystemParameterConfigService { + + /** + * Purpose: configMapper supports SystemParameterConfigServiceImpl.java by holding or executing the config mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SystemParameterConfigMapper configMapper; + + @Override + /** + * Purpose: listConfigs supports SystemParameterConfigServiceImpl.java by holding or executing the list configs business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listConfigs(UserDO currentUser, String configGroup) { + ensurePlatformAdmin(currentUser); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getIsDelete, 0) + .orderByAsc(SystemParameterConfigDO::getConfigGroup) + .orderByAsc(SystemParameterConfigDO::getConfigKey); + if (StringUtils.hasText(configGroup)) { + wrapper.eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)); + } + return configMapper.selectList(wrapper).stream().map(this::toVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: saveConfig supports SystemParameterConfigServiceImpl.java by holding or executing the save config business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto) { + ensurePlatformAdmin(currentUser); + String group = normalize(dto.getConfigGroup()); + String key = normalize(dto.getConfigKey()); + if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) { + AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue()); + } + SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, group) + .eq(SystemParameterConfigDO::getConfigKey, key) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + if (config == null) { + config = new SystemParameterConfigDO(); + config.setConfigGroup(group); + config.setConfigKey(key); + config.setIsDelete(0); + } + config.setConfigName(dto.getConfigName().trim()); + config.setConfigValue(StringUtils.hasText(dto.getConfigValue()) ? dto.getConfigValue().trim() : ""); + config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); + config.setRemark(dto.getRemark()); + if (config.getId() == null) { + configMapper.insert(config); + } else { + configMapper.updateById(config); + } + return true; + } + + @Override + /** + * Purpose: getEnabledValue supports SystemParameterConfigServiceImpl.java by holding or executing the get enabled value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getEnabledValue(String configGroup, String configKey) { + if (!StringUtils.hasText(configGroup) || !StringUtils.hasText(configKey)) { + return ""; + } + SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)) + .eq(SystemParameterConfigDO::getConfigKey, normalize(configKey)) + .eq(SystemParameterConfigDO::getEnabled, 1) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + return config == null ? "" : config.getConfigValue(); + } + + /** + * Purpose: ensurePlatformAdmin supports SystemParameterConfigServiceImpl.java by holding or executing the ensure platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理系统参数"); + } + } + + /** + * Purpose: normalize supports SystemParameterConfigServiceImpl.java by holding or executing the normalize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String normalize(String value) { + return value.trim().toUpperCase(Locale.ROOT); + } + + /** + * Purpose: toVO supports SystemParameterConfigServiceImpl.java by holding or executing the to vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SystemParameterConfigVO toVO(SystemParameterConfigDO config) { + SystemParameterConfigVO vo = new SystemParameterConfigVO(); + vo.setId(config.getId()); + vo.setConfigGroup(config.getConfigGroup()); + vo.setConfigKey(config.getConfigKey()); + vo.setConfigName(config.getConfigName()); + vo.setConfigValue(config.getConfigValue()); + vo.setEnabled(config.getEnabled()); + vo.setRemark(config.getRemark()); + vo.setCreateTime(config.getCreateTime()); + vo.setUpdateTime(config.getUpdateTime()); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/support/AdminDefaultPasswordSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/support/AdminDefaultPasswordSupport.java new file mode 100644 index 00000000..0a786c21 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/support/AdminDefaultPasswordSupport.java @@ -0,0 +1,70 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.support; + +import org.springframework.util.StringUtils; + +import java.util.Locale; + +public final class AdminDefaultPasswordSupport { + + public static final String CONFIG_GROUP = "USER"; + public static final String CONFIG_KEY = "DEFAULT_PASSWORD"; + public static final String FALLBACK_DEFAULT_PASSWORD = "Fingertip@123"; + + private AdminDefaultPasswordSupport() { + } + + public static String resolveCreatePassword(String requestedPassword, String configuredDefaultPassword) { + String resolvedPassword = StringUtils.hasText(requestedPassword) + ? requestedPassword.trim() + : resolveDefaultPassword(configuredDefaultPassword); + validatePasswordStrength(resolvedPassword); + return resolvedPassword; + } + + public static String resolveDefaultPassword(String configuredDefaultPassword) { + if (!StringUtils.hasText(configuredDefaultPassword)) { + return FALLBACK_DEFAULT_PASSWORD; + } + String defaultPassword = configuredDefaultPassword.trim(); + validateDefaultPassword(defaultPassword); + return defaultPassword; + } + + public static void validatePasswordStrength(String password) { + validatePasswordStrength(password, "密码"); + } + + public static void validateDefaultPassword(String password) { + validatePasswordStrength(password, "默认密码"); + } + + public static boolean isDefaultPasswordConfig(String configGroup, String configKey) { + return CONFIG_GROUP.equals(normalize(configGroup)) && CONFIG_KEY.equals(normalize(configKey)); + } + + private static void validatePasswordStrength(String password, String label) { + if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { + throw new RuntimeException(label + "长度需为 8-32 位"); + } + int count = 0; + if (password.matches(".*\\d.*")) { + count++; + } + if (password.matches(".*[a-z].*")) { + count++; + } + if (password.matches(".*[A-Z].*")) { + count++; + } + if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { + count++; + } + if (count < 3) { + throw new RuntimeException(label + "需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); + } + } + + private static String normalize(String value) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/vo/LegalAgreementVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/vo/LegalAgreementVO.java new file mode 100644 index 00000000..d5f1ce92 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/vo/LegalAgreementVO.java @@ -0,0 +1,79 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * Purpose: LegalAgreementVO supports LegalAgreementVO.java by holding or executing the legal agreement vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementVO { + + /** + * Purpose: id supports LegalAgreementVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + + /** + * Purpose: agreementType supports LegalAgreementVO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + /** + * Purpose: agreementTypeName supports LegalAgreementVO.java by holding or executing the agreement type name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementTypeName; + + /** + * Purpose: title supports LegalAgreementVO.java by holding or executing the title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String title; + + /** + * Purpose: version supports LegalAgreementVO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + /** + * Purpose: content supports LegalAgreementVO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + + /** + * Purpose: status supports LegalAgreementVO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + + /** + * Purpose: statusText supports LegalAgreementVO.java by holding or executing the status text business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String statusText; + + /** + * Purpose: effectiveTime supports LegalAgreementVO.java by holding or executing the effective time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime effectiveTime; + + /** + * Purpose: createTime supports LegalAgreementVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; + + /** + * Purpose: updateTime supports LegalAgreementVO.java by holding or executing the update time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/vo/SystemParameterConfigVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/vo/SystemParameterConfigVO.java new file mode 100644 index 00000000..593711e7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/system/vo/SystemParameterConfigVO.java @@ -0,0 +1,59 @@ +package com.xiaowang.jayucloud.artlist.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * Purpose: SystemParameterConfigVO supports SystemParameterConfigVO.java by holding or executing the system parameter config vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigVO { + + /** + * Purpose: id supports SystemParameterConfigVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: configGroup supports SystemParameterConfigVO.java by holding or executing the config group business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configGroup; + /** + * Purpose: configKey supports SystemParameterConfigVO.java by holding or executing the config key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configKey; + /** + * Purpose: configName supports SystemParameterConfigVO.java by holding or executing the config name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configName; + /** + * Purpose: configValue supports SystemParameterConfigVO.java by holding or executing the config value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configValue; + /** + * Purpose: enabled supports SystemParameterConfigVO.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer enabled; + /** + * Purpose: remark supports SystemParameterConfigVO.java by holding or executing the remark business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String remark; + /** + * Purpose: createTime supports SystemParameterConfigVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; + /** + * Purpose: updateTime supports SystemParameterConfigVO.java by holding or executing the update time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime updateTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java new file mode 100644 index 00000000..c5feab86 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java @@ -0,0 +1,1069 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.controller.front; + +import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.artlist.core.annotation.OperationGuard; +import com.xiaowang.jayucloud.artlist.core.common.Result; +import com.xiaowang.jayucloud.artlist.core.common.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.content.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.ChunkUploadService; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.artlist.core.modules.file.vo.ChunkUploadSessionVO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAssetVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserRelationVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLoginResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserAssetService; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService; +import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.artlist.core.utils.AccountValidationUtils; +import com.xiaowang.jayucloud.artlist.core.support.security.OperationGuardStrategy; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import org.springframework.web.multipart.MultipartFile; +import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.FileInputStream; +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.jayucloud.artlist.core.common.dto.AgreementAwareRequest; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.BindEmailRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.BindPhoneRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.PhoneLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.RefreshTokenRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.RegisterRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.ResetPasswordRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.SendVerificationCodeRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.SwitchShopRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadCompleteRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.UserDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAgreementConsentVO; +/** + * 系统用户信息表 Controller + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping("/user") +@RequiredArgsConstructor +public class UserController { + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserAssetService userAssetService; + /** + * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PrimaryObjectStorageService primaryObjectStorageService; + /** + * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ChunkUploadService chunkUploadService; + /** + * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VerificationCodeService verificationCodeService; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `wechatMiniAuthService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniAuthService wechatMiniAuthService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RequestThrottleService requestThrottleService; + /** + * Purpose: legalAgreementService supports UserController.java by holding or executing the legal agreement service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementService legalAgreementService; + /** + * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + /** + * 创建用户 + * + * @param userDTO 用户DTO + * @return 用户ID + */ + @PostMapping("/create") + @RequirePermission("user:create") + @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + userDTO.setShopId(managedShopId); + userDTO.setShopIds(List.of(managedShopId)); + } + Long id = userService.createUser(userDTO); + return Result.success(id); + } + + /** + * 更新用户 + * + * @param id 用户ID + * @param userDTO 用户DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + @RequirePermission("user:edit") + @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权编辑其他店铺用户"); + if (userDTO.getType() != null) { + adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); + } + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + userDTO.setShopId(null); + userDTO.setShopIds(null); + } + boolean success = userService.updateUser(id, userDTO); + return Result.success(success); + } + + /** + * 删除用户 + * + * @param id 用户ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("user:delete") + @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权删除其他店铺用户"); + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许删除"); + } + boolean success = userService.deleteUser(id); + return Result.success(success); + } + + @PutMapping("/unbind/{id}") + @RequirePermission("user:unbind") + @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + /** + * Run business method `unbindUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权解绑其他店铺用户"); + adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType()); + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许解绑"); + } + boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); + return Result.success(success); + } + + @GetMapping("/asset/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyAsset(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userAssetService.getUserAsset(userId)); + } + + @GetMapping("/balance/history/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getMyBalanceHistory(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userAssetService.listBalanceHistory(userId)); + } + + /** + * 根据ID查询用户 + * + * @param id 用户ID + * @return 用户VO + */ + @GetMapping("/get/{id}") + @RequirePermission("user:view") + public Result getUserById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO userVO = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户"); + return Result.success(userVO); + } + + /** + * 查询所有用户 + * + * @return 用户VO列表 + */ + @GetMapping("/list/all") + @RequirePermission("user:view") + public Result> listAllUsers(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List userVOs = adminScopeHelper.isPlatformAdmin(currentUser) + ? userService.listAllUsers() + : userService.listUsersByShopId(adminScopeHelper.getManagedShopId(currentUser)); + return Result.success(userVOs); + } + + /** + * 根据店铺ID查询用户 + * + * @param shopId 店铺ID + * @return 用户VO列表 + */ + @GetMapping("/list/shop/{shopId}") + @RequirePermission("user:view") + public Result> listUsersByShopId(HttpServletRequest request, @PathVariable Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List userVOs = userService.listUsersByShopId(shopId); + return Result.success(userVOs); + } + + /** + * 根据用户类型查询用户 + * + * @param type 用户类型 + * @return 用户VO列表 + */ + @GetMapping("/list/type/{type}") + public Result> listUsersByType(@PathVariable Integer type) { + if (!Integer.valueOf(3).equals(type)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅支持查询可预约的美甲师列表"); + } + List userVOs = userService.listUsersByType(type).stream() + .filter(user -> Integer.valueOf(1).equals(user.getStatus())) + .map(this::sanitizePublicArtist) + .collect(Collectors.toList()); + return Result.success(userVOs); + } + + /** + * 根据账号查询用户 + * + * @param account 账号 + * @return 用户VO + */ + @GetMapping("/get/account/{account}") + @RequirePermission("user:view") + public Result getUserByAccount(HttpServletRequest request, @PathVariable String account) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO userVO = userService.getUserByAccount(AccountValidationUtils.requireValidAccount(account)); + if (userVO != null) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "无权查看其他店铺用户"); + } + return Result.success(userVO); + } + + @GetMapping("/check/account/{account}") + /** + * Run business method `checkAccountAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result checkAccountAvailability(@PathVariable String account) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(account); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + ); + boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); + String message = available ? "账号可用" : "账号已被注册"; + return Result.success(new AvailabilityVO(available, message)); + } + + @GetMapping("/check/login-account/{account}") + /** + * Run business method `checkLoginAccountAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result checkLoginAccountAvailability(@PathVariable String account) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(account); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + boolean exists = userDO != null; + String nickname = exists ? userDO.getNickname() : null; + String message = exists + ? (nickname != null && !nickname.isEmpty() ? "该账号已注册,昵称:" + nickname : "该账号已注册,可继续登录") + : "该账号不存在"; + return Result.success(new LoginAccountAvailabilityVO(exists, nickname, message)); + } + + @GetMapping("/check/login-shops/account/{account}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getLoginShopsByAccount(@PathVariable String account) { + return Result.success(userService.getLoginShopSelectionByAccount(AccountValidationUtils.requireValidAccount(account))); + } + + @GetMapping("/check/login-shops/phone/{phone}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getLoginShopsByPhone(@PathVariable String phone) { + return Result.success(userService.getLoginShopSelectionByPhone(phone)); + } + + @GetMapping("/check/phone/{phone}") + /** + * Run business method `checkPhoneAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result checkPhoneAvailability(@PathVariable String phone) { + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0) + ); + boolean available = userDO == null; + String message = available ? "手机号可用" : "该手机号已被注册"; + return Result.success(new AvailabilityVO(available, message)); + } + + /** + * 用户登录 + * + * @param loginRequestDTO 登录请求DTO + * @return 登录响应VO + */ + @PostMapping("/login") + @OperationGuard(action = "user-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { + requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); + legalAgreementService.requireAccepted(loginRequestDTO); + try { + LoginResponseVO loginResponseVO = userService.login(loginRequestDTO); + legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), loginRequestDTO, "USER_PASSWORD_LOGIN", request); + requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "USER_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(null, loginRequestDTO.getAccount(), "USER_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + /** + * 手机号验证码登录 + * + * @param phoneLoginRequestDTO 手机号验证码登录请求DTO + * @return 登录响应VO + */ + @PostMapping("/phone-login") + @OperationGuard(action = "user-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result phoneLogin(HttpServletRequest request, @RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) { + requestThrottleService.checkLogin(request, phoneLoginRequestDTO.getPhone()); + legalAgreementService.requireAccepted(phoneLoginRequestDTO); + try { + LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO); + legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO, "USER_PHONE_LOGIN", request); + requestThrottleService.clearLoginFailure(request, phoneLoginRequestDTO.getPhone()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, phoneLoginRequestDTO.getPhone()); + securityAuditLogService.record(null, phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + @PostMapping("/wechat-mini/auto-login") + @OperationGuard(action = "wechat-mini-auto-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `wechatMiniAutoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); + } + + @PostMapping("/wechat-mini/phone-login") + @OperationGuard(action = "wechat-mini-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `wechatMiniPhoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result wechatMiniPhoneLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, "wechat-mini-phone"); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.phoneLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_PHONE_LOGIN", request); + return Result.success(result); + } + + @PostMapping("/wechat-mini/confirm-login") + @OperationGuard(action = "wechat-mini-confirm-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `confirmWechatMiniLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result confirmWechatMiniLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, requestDTO.getTicket()); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.confirmLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_CONFIRM_LOGIN", request); + return Result.success(result); + } + + @PostMapping("/switch-shop") + @OperationGuard(action = "user-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); + } + + /** + * 用户注册 + * + * @param registerRequestDTO 注册请求DTO + * @return 是否注册成功 + */ + @PostMapping("/register") + @OperationGuard(action = "user-register", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result register(HttpServletRequest request, @Valid @RequestBody RegisterRequestDTO registerRequestDTO) { + requestThrottleService.checkRegister(request, registerRequestDTO.getAccount()); + legalAgreementService.requireAccepted(registerRequestDTO); + try { + boolean success = userService.register(registerRequestDTO); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO != null) { + legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request); + securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request); + } + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditLogService.record(null, registerRequestDTO.getAccount(), "USER_REGISTER", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + @GetMapping("/relation/me") + /** + * Run business method `relationMe`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result relationMe(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.getCurrentUserRelation(userId)); + } + + @GetMapping("/invite-code/resolve") + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result resolveInviteCode(@RequestParam String code) { + return Result.success(shopRoleService.resolveInviteCode(code)); + } + + /** + * 发送验证码 + * + * @param sendVerificationCodeRequestDTO 发送验证码请求DTO + * @return 是否发送成功 + */ + @PostMapping("/send-verification-code") + @OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试") + public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { + requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); + if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 1 parameter `1` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); + } + verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); + return Result.success(true); + } + + /** + * 通过手机号验证码重置密码 + * + * @param resetPasswordRequestDTO 重置密码请求DTO + * @return 是否重置成功 + */ + @PostMapping("/reset-password-by-phone") + @OperationGuard(action = "reset-password-by-phone", ttlSeconds = 8, message = "操作进行中,请勿重复点击") + public Result resetPasswordByPhone(HttpServletRequest request, @RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) { + requestThrottleService.checkResetPassword(request, resetPasswordRequestDTO.getPhone()); + boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO); + securityAuditLogService.record(null, resetPasswordRequestDTO.getPhone(), "RESET_PASSWORD_BY_PHONE", success ? "SUCCESS" : "FAIL", null, request); + return Result.success(success); + } + + /** + * 刷新Token + * + * @param refreshTokenRequestDTO 刷新Token请求DTO + * @return 新的Token + */ + @PostMapping("/refresh-token") + public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { + LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); + return Result.success(loginResponseVO); + } + + /** + * 用户登出 + * + * @return 是否登出成功 + */ + @PostMapping("/logout") + @OperationGuard(action = "user-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) + public Result logout(HttpServletRequest request) { + boolean success = userService.logout((String) request.getAttribute("sessionId")); + return Result.success(success); + } + + @GetMapping("/agreement-consent/me") + public Result getMyAgreementConsent(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getMyConsent(userId)); + } + + private void recordWechatConsentIfLoggedIn(WechatMiniLoginResultVO result, + AgreementAwareRequest dto, + String entry, + HttpServletRequest request) { + if (result != null && result.getUserInfo() != null) { + legalAgreementService.recordConsent(result.getUserInfo().getId(), dto, entry, request); + securityAuditLogService.record(result.getUserInfo().getId(), null, entry, "SUCCESS", null, request); + } + } + + /** + * 获取当前用户信息 + * + * @return 用户VO + */ + @GetMapping("/info") + public Result getCurrentUserInfo(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + UserVO userVO = userService.getUserById(userId); + return Result.success(userVO); + } + + /** + * 更新当前用户信息 + * + * @param userDTO 用户DTO + * @return 是否更新成功 + */ + @PutMapping({"/update", "/info"}) + @OperationGuard(action = "user-update-info", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateCurrentUserInfo(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.updateCurrentUserInfo(userId, userDTO); + return Result.success(success); + } + + /** + * 绑定手机号 + * + * @param bindPhoneRequestDTO 绑定手机号请求DTO + * @return 是否绑定成功 + */ + @PostMapping("/bind-phone") + @OperationGuard(action = "user-bind-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result bindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO bindPhoneRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.bindPhone(userId, bindPhoneRequestDTO); + return Result.success(success); + } + + /** + * 绑定邮箱 + * + * @param bindEmailRequestDTO 绑定邮箱请求DTO + * @return 是否绑定成功 + */ + @PostMapping("/bind-email") + @OperationGuard(action = "user-bind-email", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result bindEmail(HttpServletRequest request, @RequestBody BindEmailRequestDTO bindEmailRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.bindEmail(userId, bindEmailRequestDTO); + return Result.success(success); + } + + /** + * 上传头像 + * + * @param file 头像文件 + * @return 头像URL + */ + @PostMapping("/upload-avatar/init") + @OperationGuard(action = "user-avatar-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO)); + } + + @PostMapping("/upload-avatar/chunk") + @OperationGuard(action = "user-avatar-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadAvatarChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.uploadUserAvatarChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-avatar/complete") + @OperationGuard(action = "user-avatar-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + + String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + userService.updateUserAvatar(userId, avatarUrl); + chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("头像上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-avatar/{uploadId}") + @OperationGuard(action = "user-avatar-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Run business method `cancelAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearUserAvatarUpload(userId, uploadId); + return Result.success(true); + } + + @PostMapping("/upload-avatar") + @OperationGuard(action = "user-avatar-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Purpose: uploadAvatar supports UserController.java by holding or executing the upload avatar business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + try { + Long userId = (Long) request.getAttribute("userId"); + String originalFilename = file.getOriginalFilename(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + + String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName); + userService.updateUserAvatar(userId, avatarUrl); + + return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("头像上传失败: " + e.getMessage()); + } + } + + /** + * 重置用户密码为88888888 + * + * @param userId 目标用户ID + * @return 是否重置成功 + */ + /** + * 上传个人资料图片,不直接修改头像或资料字段。 + */ + @PostMapping("/upload-profile-image/init") + @OperationGuard(action = "user-profile-image-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(chunkUploadService.initUserProfileImageUpload(userId, requestDTO)); + } + + @PostMapping("/upload-profile-image/chunk") + @OperationGuard(action = "user-profile-image-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadProfileImageChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.uploadUserProfileImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-profile-image/complete") + @OperationGuard(action = "user-profile-image-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareUserProfileImageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = ""; + if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { + fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + } + String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("资料图片上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-profile-image/{uploadId}") + @OperationGuard(action = "user-profile-image-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result cancelProfileImageUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearUserProfileImageUpload(userId, uploadId); + return Result.success(true); + } + + @PostMapping("/upload-profile-image") + @OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + try { + if (file == null || file.isEmpty()) { + return Result.error("请选择要上传的图片"); + } + Long userId = (Long) request.getAttribute("userId"); + String originalFilename = file.getOriginalFilename(); + String fileExtension = ""; + if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { + fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + } + String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + String imageUrl = primaryObjectStorageService.uploadFile(file, objectName); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("资料图片上传失败: " + e.getMessage()); + } + } + + /** + * 重置用户密码。 + */ + @PostMapping("/reset-password/{userId}") + @RequirePermission("user:reset_password") + @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + requireAccessibleUser(currentUser, userId, "无权重置其他店铺用户密码"); + Long currentUserId = (Long) request.getAttribute("userId"); + boolean success = userService.resetPassword(userId, currentUserId); + return Result.success(success); + } + + /** + * 更新用户密码 + * + * @param request 请求对象 + * @param passwordDTO 密码DTO + * @return 是否更新成功 + */ + @PutMapping("/password") + @OperationGuard(action = "user-update-password", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updatePassword(HttpServletRequest request, @RequestBody PasswordDTO passwordDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.updatePassword(userId, passwordDTO.getPassword(), passwordDTO.getVerificationCode()); + return Result.success(success); + } + + /** + * 修改手机号 + * + * @param request 请求对象 + * @param updatePhoneDTO 修改手机号DTO + * @return 是否修改成功 + */ + @PutMapping("/phone") + @OperationGuard(action = "user-update-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updatePhone(HttpServletRequest request, @RequestBody UpdatePhoneRequestDTO updatePhoneDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.updatePhone(userId, updatePhoneDTO); + return Result.success(success); + } + + /** + * 注销账号 + * + * @param request 请求对象 + * @return 是否注销成功 + */ + @DeleteMapping("/deactivate") + @OperationGuard(action = "user-deactivate", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + public Result deactivateAccount(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + + // 获取用户信息 + UserDO userDO = userMapper.selectById(userId); + if (userDO == null) { + return Result.error("用户不存在"); + } + + // 管理员账号无法注销 + if (userDO.getType() == 4) { + return Result.error("管理员账号无法注销"); + } + + boolean success = userService.deleteUser(userId); + return Result.success(success); + } + + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ + private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) { + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message); + return targetUser; + } + + /** + * Run business method `sanitizePublicArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userVO parameter `userVO` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ + private UserVO sanitizePublicArtist(UserVO userVO) { + UserVO sanitized = new UserVO(); + sanitized.setId(userVO.getId()); + sanitized.setShopId(userVO.getShopId()); + sanitized.setShopName(userVO.getShopName()); + sanitized.setShopIds(userVO.getShopIds()); + sanitized.setShopNames(userVO.getShopNames()); + sanitized.setNickname(userVO.getNickname()); + sanitized.setAvatar(userVO.getAvatar()); + sanitized.setType(userVO.getType()); + sanitized.setStatus(userVO.getStatus()); + sanitized.setCreateTime(userVO.getCreateTime()); + sanitized.setUpdateTime(userVO.getUpdateTime()); + return sanitized; + } + + @Data + /** + * Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class PasswordDTO { + /** + * Purpose: password supports UserController.java by holding or executing the password business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String password; + /** + * Purpose: verificationCode supports UserController.java by holding or executing the verification code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String verificationCode; + } + + @Data + /** + * Purpose: AvailabilityVO supports UserController.java by holding or executing the availability vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class AvailabilityVO { + /** + * Variable `available`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final boolean available; + /** + * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String message; + } + + @Data + /** + * Purpose: LoginAccountAvailabilityVO supports UserController.java by holding or executing the login account availability vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class LoginAccountAvailabilityVO { + /** + * Variable `exists`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final boolean exists; + /** + * Variable `nickname`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String nickname; + /** + * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String message; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/AdminUserBalanceChangeDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/AdminUserBalanceChangeDTO.java new file mode 100644 index 00000000..186539bb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/AdminUserBalanceChangeDTO.java @@ -0,0 +1,38 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +/** + * AdminUserBalanceChangeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AdminUserBalanceChangeDTO { + + /** + * Field `amount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal amount; + + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/AdminUserVipOverrideDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/AdminUserVipOverrideDTO.java new file mode 100644 index 00000000..0b289c49 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/AdminUserVipOverrideDTO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.dto; + +import lombok.Data; + +@Data +/** + * AdminUserVipOverrideDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AdminUserVipOverrideDTO { + + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/InviteCodeDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/InviteCodeDTO.java new file mode 100644 index 00000000..fd2e6fac --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/InviteCodeDTO.java @@ -0,0 +1,41 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.time.LocalDateTime; + +@Data +/** + * InviteCodeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class InviteCodeDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + + @NotBlank(message = "邀请码不能为空") + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/UserDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/UserDTO.java new file mode 100644 index 00000000..0bd718c8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/UserDTO.java @@ -0,0 +1,95 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.dto; + +import com.xiaowang.jayucloud.artlist.core.utils.AccountValidationUtils; +import lombok.Data; + +import javax.validation.constraints.Pattern; +import java.time.LocalDate; +import java.util.List; + +/** + * 系统用户信息表 DTO + * 用于用户信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class UserDTO { + + /** + * 所属店铺ID,关联店铺表主键(0表示无所属店铺) + */ + private Long shopId; + + /** + * 绑定店铺ID列表 + */ + private List shopIds; + + /** + * 用户昵称 + */ + private String nickname; + + /** + * 用户账号(登录用) + */ + @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + private String account; + + /** + * 用户密码(加密存储) + */ + private String password; + + /** + * 用户头像URL + */ + private String avatar; + + /** + * 用户签名 + */ + private String signature; + + /** + * 用户等级 + */ + private String level; + + /** + * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) + */ + private Integer type; + + /** + * 关联VIP信息表主键(0表示非VIP) + */ + private Long vipId; + + /** + * 手机号 + */ + private String phone; + + /** + * 联系电话 + */ + private String contactPhone; + + /** + * 生日 + */ + private LocalDate birthday; + + /** + * 微信号 + */ + private String wechatId; + + /** + * 微信二维码 + */ + private String wechatQrCode; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/UserRelationUpdateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/UserRelationUpdateDTO.java new file mode 100644 index 00000000..fed7130a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/dto/UserRelationUpdateDTO.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.dto; + +import lombok.Data; + +@Data +/** + * UserRelationUpdateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationUpdateDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserAgreementConsentDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserAgreementConsentDO.java new file mode 100644 index 00000000..4493dfcc --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserAgreementConsentDO.java @@ -0,0 +1,75 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_user_agreement_consent") +/** + * Purpose: UserAgreementConsentDO supports UserAgreementConsentDO.java by holding or executing the user agreement consent do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UserAgreementConsentDO extends BaseEntity { + + @TableField("user_id") + /** + * Purpose: userId supports UserAgreementConsentDO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + + @TableField("agreement_type") + /** + * Purpose: agreementType supports UserAgreementConsentDO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + @TableField("version") + /** + * Purpose: version supports UserAgreementConsentDO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + @TableField("entry") + /** + * Purpose: entry supports UserAgreementConsentDO.java by holding or executing the entry business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String entry; + + @TableField("client_type") + /** + * Purpose: clientType supports UserAgreementConsentDO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; + + @TableField("ip_address") + /** + * Purpose: ipAddress supports UserAgreementConsentDO.java by holding or executing the ip address business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String ipAddress; + + @TableField("device_id") + /** + * Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String deviceId; + + @TableField("consent_time") + /** + * Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime consentTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java new file mode 100644 index 00000000..cc7940bb --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java @@ -0,0 +1,148 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; + +import java.time.LocalDate; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +/** + * 系统用户信息表 DO + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = true) +@TableName("t_user") +public class UserDO extends BaseEntity { + + /** + * 用户唯一主键ID(雪花ID) + */ + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + /** + * 所属店铺ID,关联店铺表主键(0表示无所属店铺) + */ + @TableField("shop_id") + private Long shopId; + + /** + * 用户昵称 + */ + @TableField("nickname") + private String nickname; + + /** + * 用户账号(登录用) + */ + @TableField("account") + private String account; + + /** + * 手机号 + */ + @TableField("phone") + private String phone; + + /** + * 联系电话 + */ + @TableField("contact_phone") + private String contactPhone; + + /** + * 生日 + */ + @TableField("birthday") + private LocalDate birthday; + + /** + * 微信号 + */ + @TableField("wechat_id") + private String wechatId; + + /** + * 微信二维码 + */ + @TableField("wechat_qr_code") + private String wechatQrCode; + + /** + * 邮箱 + */ + @TableField("email") + private String email; + + /** + * 手机号是否已验证:0-未验证,1-已验证 + */ + @TableField("phone_verified") + private Integer phoneVerified; + + /** + * 邮箱是否已验证:0-未验证,1-已验证 + */ + @TableField("email_verified") + private Integer emailVerified; + + /** + * 用户密码(加密存储) + */ + @TableField("password") + private String password; + + /** + * 用户头像URL + */ + @TableField("avatar") + private String avatar; + + /** + * 用户签名 + */ + @TableField("signature") + private String signature; + + /** + * 用户等级 + */ + @TableField("level") + private String level; + + /** + * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) + */ + @TableField("type") + private Integer type; + + /** + * 关联VIP信息表主键(0表示非VIP) + */ + @TableField("vip_id") + private Long vipId; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; + + /** + * 用户状态:1-正常,0-禁用 + */ + @TableField("status") + private Integer status; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserGrowthRecordDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserGrowthRecordDO.java new file mode 100644 index 00000000..86eb94c6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserGrowthRecordDO.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_growth_record") +public class UserGrowthRecordDO extends BaseEntity { + @TableField("user_id") + private Long userId; + @TableField("source_type") + private String sourceType; + @TableField("source_id") + private Long sourceId; + @TableField("growth_value") + private Integer growthValue; + @TableField("remark") + private String remark; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserInviteCodeDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserInviteCodeDO.java new file mode 100644 index 00000000..276da0b9 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserInviteCodeDO.java @@ -0,0 +1,63 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_invite_code") +/** + * UserInviteCodeDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserInviteCodeDO extends BaseEntity { + + @TableField("invite_code") + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + @TableField("owner_user_id") + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("use_count") + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + + @TableField("expire_time") + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserRelationDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserRelationDO.java new file mode 100644 index 00000000..b8aa14c4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserRelationDO.java @@ -0,0 +1,61 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_relation") +/** + * UserRelationDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("parent_user_id") + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + + @TableField("parent_role_type") + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + + @TableField("source_type") + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + + @TableField("creator_id") + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserAgreementConsentMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserAgreementConsentMapper.java new file mode 100644 index 00000000..7092e7b7 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserAgreementConsentMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserAgreementConsentDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: UserAgreementConsentMapper supports UserAgreementConsentMapper.java by holding or executing the user agreement consent mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface UserAgreementConsentMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserGrowthRecordMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserGrowthRecordMapper.java new file mode 100644 index 00000000..eeccd6d6 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserGrowthRecordMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserGrowthRecordDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface UserGrowthRecordMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserInviteCodeMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserInviteCodeMapper.java new file mode 100644 index 00000000..2f691cdf --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserInviteCodeMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserInviteCodeDO; + +/** + * UserInviteCodeMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserInviteCodeMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserMapper.java new file mode 100644 index 00000000..80693a8a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; + +/** + * 系统用户信息表 Mapper + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface UserMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserRelationMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserRelationMapper.java new file mode 100644 index 00000000..5d7518a5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/mapper/UserRelationMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserRelationDO; + +/** + * UserRelationMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserRelationMapper extends BaseMapper { +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserAssetService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserAssetService.java new file mode 100644 index 00000000..8081c653 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserAssetService.java @@ -0,0 +1,60 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.service; + +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.AdminUserBalanceChangeDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.AdminUserVipOverrideDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAssetVO; + +import java.util.List; + +/** + * UserAssetService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface UserAssetService { + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO getUserAsset(Long userId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listBalanceHistory(Long userId); + + /** + * Run business method `changeBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request); + + /** + * Run business method `overrideVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request); + + /** + * Run business method `recalculateVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO recalculateVip(Long operatorId, Long userId); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java new file mode 100644 index 00000000..950a1ad0 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java @@ -0,0 +1,397 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.BindEmailRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.BindPhoneRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.PhoneLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningManagerRegisterDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.RegisterRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.ResetPasswordRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.UserDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserStatisticsVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserRelationVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserVO; + +import java.util.List; + +/** + * UserService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface UserService extends IService { + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDTO parameter `userDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createUser(UserDTO userDTO); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUser(Long id, UserDTO userDTO); + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean deleteUser(Long id); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return UserVO result consumed by the caller or returned to the frontend + */ + UserVO getUserById(Long id); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + List listAllUsers(); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listUsersByShopId(Long shopId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listUsersByType(Integer type); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return UserVO result consumed by the caller or returned to the frontend + */ + UserVO getUserByAccount(String account); + + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO login(LoginRequestDTO loginRequestDTO); + + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO); + + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO loginByVerifiedPhone(String phone, Long shopId); + + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO loginByUserId(Long userId, Long shopId); + + /** + * Run business method `adminLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + LoginShopSelectionVO getLoginShopSelectionByAccount(String account); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + LoginShopSelectionVO getLoginShopSelectionByPhone(String phone); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + LoginShopSelectionVO getAdminLoginShopSelection(String account); + + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId); + + /** + * Run business method `switchAdminShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId); + + /** + * Run business method `syncManagedPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + void syncManagedPermissions(Long userId); + + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean register(RegisterRequestDTO registerRequestDTO); + + LoginResponseVO registerPlanningManager(PlanningManagerRegisterDTO registerDTO); + + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshToken parameter `refreshToken` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO refreshToken(String refreshToken); + + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionId parameter `sessionId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean logout(String sessionId); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return UserVO result consumed by the caller or returned to the frontend + */ + UserVO getCurrentUserInfo(); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateCurrentUserInfo(Long userId, UserDTO userDTO); + + /** + * Run business method `bindPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO); + + /** + * Run business method `bindEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO); + + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean resetPassword(Long targetUserId, Long currentUserId); + + /** + * Run business method `resetPasswordByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); + + /** + * Run business method `statisticsUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return UserStatisticsVO result consumed by the caller or returned to the frontend + */ + UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserRelationVO result consumed by the caller or returned to the frontend + */ + UserRelationVO getCurrentUserRelation(Long userId); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUserStatus(Long id, Integer status); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUserStatusInShop(Long id, Integer status, Long shopId); + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean deleteUserInShop(Long id, Long shopId); + + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean unbindUserInShop(Long id, Long shopId); + + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param operatorType parameter `operatorType` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUserAvatar(Long userId, String avatarUrl); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param password parameter `password` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updatePassword(Long userId, String password, String verificationCode); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserAssetServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserAssetServiceImpl.java new file mode 100644 index 00000000..70454679 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserAssetServiceImpl.java @@ -0,0 +1,630 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.AdminUserBalanceChangeDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.AdminUserVipOverrideDTO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceChangeDetailDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.entity.BalanceDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipBenefitDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipInfoDO; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.entity.VipRechargePlanDO; +import com.xiaowang.jayucloud.artlist.core.modules.payment.mapper.BalanceChangeDetailMapper; +import com.xiaowang.jayucloud.artlist.core.modules.payment.mapper.BalanceMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.VipBenefitMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.VipInfoMapper; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper.VipRechargePlanMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserAssetService; +import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserAssetVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.jayucloud.artlist.core.modules.marketing.service.impl.VipRechargePlanServiceImpl; +@Service +@RequiredArgsConstructor +/** + * UserAssetServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class UserAssetServiceImpl implements UserAssetService { + + /** + * Purpose: VIP_LEVEL_NORMAL supports UserAssetServiceImpl.java by holding or executing the vip level normal business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIP_LEVEL_NORMAL = "普通"; + /** + * Purpose: SCENE_RECHARGE supports UserAssetServiceImpl.java by holding or executing the scene recharge business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_RECHARGE = "RECHARGE"; + /** + * Purpose: SCENE_MANUAL_ADD supports UserAssetServiceImpl.java by holding or executing the scene manual add business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_MANUAL_ADD = "MANUAL_ADD"; + /** + * Purpose: SCENE_MANUAL_DEDUCT supports UserAssetServiceImpl.java by holding or executing the scene manual deduct business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_MANUAL_DEDUCT = "MANUAL_DEDUCT"; + /** + * Purpose: SCENE_ORDER_CONSUME supports UserAssetServiceImpl.java by holding or executing the scene order consume business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_ORDER_CONSUME = "ORDER_CONSUME"; + /** + * Purpose: SCENE_ORDER_REFUND supports UserAssetServiceImpl.java by holding or executing the scene order refund business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_ORDER_REFUND = "ORDER_REFUND"; + /** + * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceMapper balanceMapper; + /** + * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceChangeDetailMapper balanceChangeDetailMapper; + /** + * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipInfoMapper vipInfoMapper; + /** + * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipBenefitMapper vipBenefitMapper; + /** + * Purpose: vipRechargePlanMapper supports UserAssetServiceImpl.java by holding or executing the vip recharge plan mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final VipRechargePlanMapper vipRechargePlanMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO getUserAsset(Long userId) { + UserDO user = getAvailableUser(userId); + BalanceDO balance = ensureBalance(userId); + VipInfoDO vipInfo = getVipInfo(userId); + VipBenefitDO benefit = vipInfo != null && vipInfo.getBenefitId() != null + ? vipBenefitMapper.selectById(vipInfo.getBenefitId()) + : null; + /** + * Run business method `toAssetVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param balance parameter `balance` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param benefit parameter `benefit` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toAssetVO(user, balance, vipInfo, benefit); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listBalanceHistory(Long userId) { + UserDO user = getAvailableUser(userId); + return balanceChangeDetailMapper.selectList( + Wrappers.lambdaQuery(BalanceChangeDetailDO.class) + .eq(BalanceChangeDetailDO::getUserId, userId) + .orderByDesc(BalanceChangeDetailDO::getChangeTime) + .orderByDesc(BalanceChangeDetailDO::getId)) + .stream() + .map(detail -> toBalanceHistoryVO(detail, user.getNickname())) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `changeBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request) { + if (request == null || request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 0 parameter `0` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("变动金额必须大于 0"); + } + if (!StringUtils.hasText(request.getChangeScene())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("变动场景不能为空"); + } + + UserDO user = getAvailableUser(userId); + BalanceDO balance = ensureBalance(userId); + LocalDateTime now = LocalDateTime.now(); + + BigDecimal beforeBalance = defaultDecimal(balance.getAmount()); + BigDecimal delta = normalizeDelta(request.getAmount(), request.getChangeScene()); + BigDecimal afterBalance = beforeBalance.add(delta); + if (afterBalance.compareTo(BigDecimal.ZERO) < 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("余额不足,无法执行扣减"); + } + + OrderDO relatedOrder = null; + String relatedOrderNo = null; + if (request.getRelatedOrderId() != null) { + relatedOrder = orderMapper.selectById(request.getRelatedOrderId()); + if (relatedOrder == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("关联系统订单不存在"); + } + if (!userId.equals(relatedOrder.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("所选订单不属于当前用户"); + } + relatedOrderNo = relatedOrder.getOrderNo(); + } + + if (isDeductScene(request.getChangeScene()) + && relatedOrder == null + && !StringUtils.hasText(request.getExternalOrderNo())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("扣减余额时必须关联系统订单或填写外部订单号"); + } + + balance.setAmount(afterBalance); + balance.setLastUpdateTime(now); + if (SCENE_RECHARGE.equals(request.getChangeScene())) { + balance.setTotalRechargeAmount(defaultDecimal(balance.getTotalRechargeAmount()).add(request.getAmount())); + balance.setLastRechargeTime(now); + } + balanceMapper.updateById(balance); + + BalanceChangeDetailDO detail = new BalanceChangeDetailDO(); + detail.setUserId(userId); + detail.setAmount(delta); + detail.setType(request.getChangeScene()); + detail.setCurrentBalance(afterBalance); + detail.setBeforeBalance(beforeBalance); + detail.setAfterBalance(afterBalance); + detail.setChangeScene(request.getChangeScene()); + detail.setRelatedOrderId(relatedOrder != null ? relatedOrder.getId() : null); + detail.setRelatedOrderNo(relatedOrderNo); + detail.setExternalOrderNo(StringUtils.hasText(request.getExternalOrderNo()) ? request.getExternalOrderNo().trim() : null); + detail.setOperatorId(operatorId); + detail.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null); + detail.setChangeTime(now); + balanceChangeDetailMapper.insert(detail); + + if (SCENE_RECHARGE.equals(request.getChangeScene())) { + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + recalculateVipInternal(user, false); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return getUserAsset(userId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `overrideVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request) { + if (request == null || !StringUtils.hasText(request.getVipLevel())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("VIP 等级不能为空"); + } + + UserDO user = getAvailableUser(userId); + String targetLevel = request.getVipLevel().trim(); + VipInfoDO vipInfo = getOrCreateVipInfo(userId); + vipInfo.setActivationMethod("MANUAL_OVERRIDE"); + vipInfo.setManualOverride(1); + vipInfo.setStartTime(LocalDateTime.now()); + + VipBenefitDO benefit = null; + if (!VIP_LEVEL_NORMAL.equals(targetLevel)) { + benefit = vipBenefitMapper.selectOne( + Wrappers.lambdaQuery(VipBenefitDO.class) + .eq(VipBenefitDO::getRequiredVipLevel, targetLevel) + .eq(VipBenefitDO::getStatus, 1) + .last("limit 1")); + if (benefit == null && !isVipLevelAvailable(targetLevel)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标 VIP 等级未配置有效规则"); + } + vipInfo.setBenefitId(benefit != null ? benefit.getId() : null); + } else { + vipInfo.setBenefitId(null); + } + vipInfo.setVipLevel(targetLevel); + vipInfoMapper.updateById(vipInfo); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param targetLevel parameter `targetLevel` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateUserVipFields(user, vipInfo, targetLevel); + return toAssetVO(userMapper.selectById(userId), ensureBalance(userId), vipInfo, benefit); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `recalculateVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO recalculateVip(Long operatorId, Long userId) { + UserDO user = getAvailableUser(userId); + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param true parameter `true` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + recalculateVipInternal(user, true); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return getUserAsset(userId); + } + + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param clearManualOverride parameter `clearManualOverride` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void recalculateVipInternal(UserDO user, boolean clearManualOverride) { + BalanceDO balance = ensureBalance(user.getId()); + VipBenefitDO matchedBenefit = vipBenefitMapper.selectList( + Wrappers.lambdaQuery(VipBenefitDO.class) + .eq(VipBenefitDO::getStatus, 1) + .orderByAsc(VipBenefitDO::getLevelRank) + .orderByAsc(VipBenefitDO::getRechargeThreshold)) + .stream() + .filter(benefit -> defaultDecimal(balance.getTotalRechargeAmount()) + .compareTo(defaultDecimal(benefit.getRechargeThreshold())) >= 0) + .max(Comparator.comparing(VipBenefitDO::getLevelRank, Comparator.nullsLast(Integer::compareTo)) + .thenComparing(VipBenefitDO::getRechargeThreshold, Comparator.nullsLast(BigDecimal::compareTo))) + .orElse(null); + + VipInfoDO vipInfo = getVipInfo(user.getId()); + if (vipInfo != null && Integer.valueOf(1).equals(vipInfo.getManualOverride()) && !clearManualOverride) { + return; + } + if (vipInfo == null && matchedBenefit == null) { + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param VIP_LEVEL_NORMAL parameter `VIP_LEVEL_NORMAL` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateUserVipFields(user, null, VIP_LEVEL_NORMAL); + return; + } + + vipInfo = vipInfo == null ? getOrCreateVipInfo(user.getId()) : vipInfo; + vipInfo.setActivationMethod("AUTO_RECALCULATE"); + vipInfo.setManualOverride(clearManualOverride ? 0 : vipInfo.getManualOverride()); + vipInfo.setStartTime(LocalDateTime.now()); + + String targetLevel = matchedBenefit != null ? matchedBenefit.getRequiredVipLevel() : VIP_LEVEL_NORMAL; + vipInfo.setVipLevel(targetLevel); + vipInfo.setBenefitId(matchedBenefit != null ? matchedBenefit.getId() : null); + vipInfoMapper.updateById(vipInfo); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param targetLevel parameter `targetLevel` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateUserVipFields(user, vipInfo, targetLevel); + } + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void updateUserVipFields(UserDO user, VipInfoDO vipInfo, String vipLevel) { + user.setLevel(StringUtils.hasText(vipLevel) ? vipLevel : VIP_LEVEL_NORMAL); + user.setVipId(VIP_LEVEL_NORMAL.equals(user.getLevel()) || vipInfo == null ? 0L : vipInfo.getId()); + user.setUpdateTime(LocalDateTime.now()); + userMapper.updateById(user); + } + + /** + * Run business method `normalizeDelta`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param amount parameter `amount` supplied by the caller + * @param changeScene parameter `changeScene` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal normalizeDelta(BigDecimal amount, String changeScene) { + if (isDeductScene(changeScene)) { + return amount.negate(); + } + if (SCENE_RECHARGE.equals(changeScene) || SCENE_MANUAL_ADD.equals(changeScene) || SCENE_ORDER_REFUND.equals(changeScene)) { + return amount; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不支持的余额变动场景"); + } + + /** + * Run business method `isDeductScene`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param changeScene parameter `changeScene` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isDeductScene(String changeScene) { + return SCENE_MANUAL_DEDUCT.equals(changeScene) || SCENE_ORDER_CONSUME.equals(changeScene); + } + + /** + * Run business method `ensureBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private BalanceDO result consumed by the caller or returned to the frontend + */ + private BalanceDO ensureBalance(Long userId) { + BalanceDO balance = balanceMapper.selectOne( + Wrappers.lambdaQuery(BalanceDO.class) + .eq(BalanceDO::getUserId, userId) + .last("limit 1")); + if (balance != null) { + if (balance.getAmount() == null) { + balance.setAmount(BigDecimal.ZERO); + } + if (balance.getTotalRechargeAmount() == null) { + balance.setTotalRechargeAmount(BigDecimal.ZERO); + } + return balance; + } + + balance = new BalanceDO(); + balance.setUserId(userId); + balance.setAmount(BigDecimal.ZERO); + balance.setTotalRechargeAmount(BigDecimal.ZERO); + balance.setLastUpdateTime(LocalDateTime.now()); + balanceMapper.insert(balance); + return balance; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private VipInfoDO result consumed by the caller or returned to the frontend + */ + private VipInfoDO getVipInfo(Long userId) { + return vipInfoMapper.selectOne( + Wrappers.lambdaQuery(VipInfoDO.class) + .eq(VipInfoDO::getUserId, userId) + .last("limit 1")); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private VipInfoDO result consumed by the caller or returned to the frontend + */ + private VipInfoDO getOrCreateVipInfo(Long userId) { + VipInfoDO vipInfo = getVipInfo(userId); + if (vipInfo != null) { + return vipInfo; + } + vipInfo = new VipInfoDO(); + vipInfo.setUserId(userId); + vipInfo.setVipLevel(VIP_LEVEL_NORMAL); + vipInfo.setManualOverride(0); + vipInfo.setActivationMethod("INIT"); + vipInfo.setStartTime(LocalDateTime.now()); + vipInfoMapper.insert(vipInfo); + return vipInfo; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO getAvailableUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + return user; + } + + /** + * Purpose: isVipLevelAvailable supports UserAssetServiceImpl.java by holding or executing the is vip level available business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isVipLevelAvailable(String vipLevel) { + if (!StringUtils.hasText(vipLevel)) { + return false; + } + if (VipRechargePlanServiceImpl.DEFAULT_VIP_LEVELS.contains(vipLevel.trim())) { + return true; + } + Long count = vipRechargePlanMapper.selectCount( + Wrappers.lambdaQuery(VipRechargePlanDO.class) + .eq(VipRechargePlanDO::getVipLevel, vipLevel.trim()) + .eq(VipRechargePlanDO::getStatus, 1) + .eq(VipRechargePlanDO::getIsDelete, 0)); + return count != null && count > 0; + } + + /** + * Run business method `defaultDecimal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal defaultDecimal(BigDecimal value) { + return value == null ? BigDecimal.ZERO : value; + } + + /** + * Run business method `toAssetVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param balance parameter `balance` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param benefit parameter `benefit` supplied by the caller + * @return private UserAssetVO result consumed by the caller or returned to the frontend + */ + private UserAssetVO toAssetVO(UserDO user, BalanceDO balance, VipInfoDO vipInfo, VipBenefitDO benefit) { + UserAssetVO vo = new UserAssetVO(); + vo.setUserId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setBalance(defaultDecimal(balance != null ? balance.getAmount() : null)); + vo.setTotalRechargeAmount(defaultDecimal(balance != null ? balance.getTotalRechargeAmount() : null)); + vo.setLastRechargeTime(balance != null ? balance.getLastRechargeTime() : null); + vo.setVipInfoId(vipInfo != null ? vipInfo.getId() : null); + vo.setVipLevel(StringUtils.hasText(user.getLevel()) ? user.getLevel() : VIP_LEVEL_NORMAL); + vo.setBenefitId(vipInfo != null ? vipInfo.getBenefitId() : null); + vo.setBenefitInfo(benefit != null ? benefit.getBenefitInfo() : null); + vo.setManualOverride(vipInfo != null && Integer.valueOf(1).equals(vipInfo.getManualOverride())); + vo.setVipStartTime(vipInfo != null ? vipInfo.getStartTime() : null); + vo.setVipExpireTime(vipInfo != null ? vipInfo.getExpireTime() : null); + return vo; + } + + /** + * Run business method `toBalanceHistoryVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param detail parameter `detail` supplied by the caller + * @param nickname parameter `nickname` supplied by the caller + * @return private BalanceChangeDetailVO result consumed by the caller or returned to the frontend + */ + private BalanceChangeDetailVO toBalanceHistoryVO(BalanceChangeDetailDO detail, String nickname) { + BalanceChangeDetailVO vo = new BalanceChangeDetailVO(); + vo.setId(detail.getId()); + vo.setUserId(detail.getUserId()); + vo.setUserNickname(nickname); + vo.setAmount(detail.getAmount()); + vo.setType(detail.getType()); + vo.setCurrentBalance(detail.getCurrentBalance()); + vo.setBeforeBalance(detail.getBeforeBalance()); + vo.setAfterBalance(detail.getAfterBalance()); + vo.setChangeScene(detail.getChangeScene()); + vo.setRelatedOrderId(detail.getRelatedOrderId()); + vo.setRelatedOrderNo(detail.getRelatedOrderNo()); + vo.setExternalOrderNo(detail.getExternalOrderNo()); + vo.setOperatorId(detail.getOperatorId()); + vo.setRemark(detail.getRemark()); + vo.setChangeTime(detail.getChangeTime()); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java new file mode 100644 index 00000000..18d98347 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java @@ -0,0 +1,3259 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.jayucloud.artlist.core.config.BrandProperties; +import com.xiaowang.jayucloud.artlist.core.common.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.content.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.file.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.message.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.order.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.payment.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.product.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.security.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.system.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.*; +import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserPermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.PermissionDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserRelationDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserInviteCodeDO; +import com.xiaowang.jayucloud.artlist.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.UserPermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserRelationMapper; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserInviteCodeMapper; +import com.xiaowang.jayucloud.artlist.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.jayucloud.artlist.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.artlist.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.artlist.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog; +import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy; +import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.user.support.UserProfileFieldSupport; +import com.xiaowang.jayucloud.artlist.core.utils.AccountValidationUtils; +import com.xiaowang.jayucloud.artlist.core.utils.JwtUtil; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserRelationVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.vo.UserStatisticsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.BindEmailRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.BindPhoneRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.PhoneLoginRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.RegisterRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.ResetPasswordRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningManagerRegisterDTO; +import com.xiaowang.jayucloud.artlist.core.modules.user.dto.UserDTO; +/** + * 系统用户信息表 Service 实现 + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class UserServiceImpl extends ServiceImpl implements UserService { + /** + * Purpose: VIP_LEVEL_NORMAL supports UserServiceImpl.java by holding or executing the vip level normal business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIP_LEVEL_NORMAL = "普通"; + /** + * Purpose: PHONE_REGEX supports UserServiceImpl.java by holding or executing the phone regex business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; + /** + * Purpose: DEFAULT_AVATAR_URL supports UserServiceImpl.java by holding or executing the default avatar url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; + private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5); + /** + * Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String DELETED_PHONE_MARKER = "_deleted_"; + /** + * Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String LOGIN_FAIL_KEY_PREFIX = "user:login:failed:"; + /** + * Purpose: MAX_LOGIN_FAILURES supports UserServiceImpl.java by holding or executing the max login failures business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int MAX_LOGIN_FAILURES = 5; + private static final Duration LOGIN_FAIL_EXPIRE = Duration.ofDays(7); + /** + * Purpose: SYSTEM_PERMISSION_ASSIGNER_ID supports UserServiceImpl.java by holding or executing the system permission assigner id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L; + private static final Set MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes(); + private static final Map DEFAULT_PERMISSION_SEEDS = PermissionCatalog.getDefinitionsByCode(); + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + private final ShopMapper shopMapper; + /** + * Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final JwtUtil jwtUtil; + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopService shopService; + /** + * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserPermissionMapper userPermissionMapper; + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserRelationMapper userRelationMapper; + /** + * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserInviteCodeMapper userInviteCodeMapper; + private final BrandProperties brandProperties; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final NailArtistInfoService nailArtistInfoService; + private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + /** + * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VerificationCodeService verificationCodeService; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniBindingMapper wechatMiniBindingMapper; + /** + * Variable `userSessionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserSessionService userSessionService; + private final SystemParameterConfigService systemParameterConfigService; + + /** + * Run business method `synchronizeManagedDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void synchronizeManagedDefaultPermissions(Long userId, Integer userType) { + List desiredPermissionCodes = getDefaultPermissionCodes(userType); + List managedPermissions = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getIsDelete, 0) + .in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES) + ); + + if (managedPermissions.isEmpty()) { + return; + } + + Map permissionIdByCode = managedPermissions.stream() + .collect(Collectors.toMap(PermissionDO::getPermissionCode, PermissionDO::getId, (left, right) -> left)); + List managedPermissionIds = managedPermissions.stream() + .map(PermissionDO::getId) + .collect(Collectors.toList()); + Set desiredPermissionIds = desiredPermissionCodes.stream() + .map(permissionIdByCode::get) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + + List currentPermissions = userPermissionMapper.selectList( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + .in(UserPermissionDO::getPermissionId, managedPermissionIds) + ); + + Set currentPermissionIds = currentPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .collect(Collectors.toSet()); + List stalePermissionIds = currentPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .filter(permissionId -> !desiredPermissionIds.contains(permissionId)) + .distinct() + .collect(Collectors.toList()); + + if (!stalePermissionIds.isEmpty()) { + userPermissionMapper.delete( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + .in(UserPermissionDO::getPermissionId, stalePermissionIds) + ); + } + + for (Long permissionId : desiredPermissionIds) { + if (currentPermissionIds.contains(permissionId)) { + continue; + } + UserPermissionDO userPermissionDO = new UserPermissionDO(); + userPermissionDO.setUserId(userId); + userPermissionDO.setPermissionId(permissionId); + userPermissionDO.setCreateBy(SYSTEM_PERMISSION_ASSIGNER_ID); + userPermissionMapper.insert(userPermissionDO); + } + } + + /** + * Run business method `ensurePermissionDefinitions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePermissionDefinitions() { + List existingPermissions = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES) + ); + + Map existingByCode = existingPermissions.stream() + .collect(Collectors.toMap(PermissionDO::getPermissionCode, permission -> permission, (left, right) -> left)); + + for (String permissionCode : MANAGED_DEFAULT_PERMISSION_CODES) { + PermissionCatalog.PermissionDefinition permissionSeed = DEFAULT_PERMISSION_SEEDS.get(permissionCode); + if (permissionSeed == null) { + continue; + } + + PermissionDO permissionDO = existingByCode.get(permissionCode); + if (permissionDO == null) { + permissionDO = new PermissionDO(); + permissionDO.setPermissionCode(permissionCode); + permissionDO.setPermissionName(permissionSeed.permissionName()); + permissionDO.setPermissionGroup(permissionSeed.permissionGroup()); + permissionDO.setDescription(permissionSeed.description()); + permissionDO.setIsDelete(0); + permissionDO.setUpdateTime(LocalDateTime.now()); + permissionMapper.insert(permissionDO); + continue; + } + + if (isPermissionDefinitionCurrent(permissionDO, permissionSeed)) { + continue; + } + + permissionDO.setPermissionName(permissionSeed.permissionName()); + permissionDO.setPermissionGroup(permissionSeed.permissionGroup()); + permissionDO.setDescription(permissionSeed.description()); + permissionDO.setIsDelete(0); + permissionDO.setUpdateTime(LocalDateTime.now()); + permissionMapper.updateById(permissionDO); + } + } + + private boolean isPermissionDefinitionCurrent(PermissionDO permissionDO, PermissionCatalog.PermissionDefinition permissionSeed) { + return Objects.equals(permissionDO.getPermissionName(), permissionSeed.permissionName()) + && Objects.equals(permissionDO.getPermissionGroup(), permissionSeed.permissionGroup()) + && Objects.equals(permissionDO.getDescription(), permissionSeed.description()) + && Objects.equals(permissionDO.getIsDelete(), 0); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getDefaultPermissionCodes(Integer userType) { + return PermissionPolicy.getDefaultPermissionCodes(userType); + } + + /** + * Run business method `assignDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assignDefaultPermissions(Long userId, Integer userType) { + if (getDefaultPermissionCodes(userType).isEmpty()) { + return; + } + /** + * Run business method `syncDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncDefaultPermissions(userId, userType); + } + + /** + * 创建新用户 + * @param userDTO 用户数据传输对象 + * @return 新创建用户的ID + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Long createUser(UserDTO userDTO) { + String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); + // 检查账号是否已存在 + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, validatedAccount) + .eq(UserDO::getIsDelete, 0) + ); + if (existingUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已存在"); + } + + List validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); + Long validatedShopId = pickPrimaryShopId(validatedShopIds); + String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); + Integer userType = userDTO.getType(); + String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); + UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); + + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @param validatedShopIds parameter `validatedShopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopBindingRequirement(userType, validatedShopIds); + + // 创建用户实体并设置属性 + UserDO userDO = new UserDO(); + userDO.setShopId(validatedShopId); + userDO.setNickname(userDTO.getNickname()); + userDO.setAccount(validatedAccount); + String resolvedPassword = AdminDefaultPasswordSupport.resolveCreatePassword( + userDTO.getPassword(), + getConfiguredAdminDefaultPassword() + ); + validatePasswordStrength(resolvedPassword); + userDO.setPassword(passwordEncoder.encode(resolvedPassword)); + userDO.setPhone(validatedPhone); + userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); + userDO.setBirthday(userDTO.getBirthday()); + userDO.setWechatId(validatedWechatId); + userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + userDO.setSignature(userDTO.getSignature()); + userDO.setLevel(userDTO.getLevel()); + userDO.setType(userType); + userDO.setVipId(userDTO.getVipId()); + userDO.setIsDelete(0); + userDO.setStatus(1); + if (StringUtils.hasText(userDTO.getAvatar())) { + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + } else { + userDO.setAvatar(DEFAULT_AVATAR_URL); + } + + if (Integer.valueOf(0).equals(userDO.getType())) { + if (!StringUtils.hasText(userDO.getLevel())) { + userDO.setLevel(VIP_LEVEL_NORMAL); + } + if (userDO.getVipId() == null) { + userDO.setVipId(0L); + } + } + + try { + // 插入用户数据 + userMapper.insert(userDO); + } catch (Exception e) { + // 捕获重复账号异常 + if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已被使用"); + } + throw e; + } + + // 分配默认权限 + assignDefaultPermissions(userDO.getId(), userDO.getType()); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds); + + // 如果是美甲师,创建对应的美甲师信息记录 + if (userDO.getType() == 3) { + NailArtistInfoDTO nailArtistInfoDTO = new NailArtistInfoDTO(); + nailArtistInfoDTO.setUserId(userDO.getId()); + nailArtistInfoDTO.setIdentity(""); // 默认身份为空 + nailArtistInfoDTO.setExperience(0); // 默认经验为0 + nailArtistInfoDTO.setSkills(""); // 默认技能为空 + nailArtistInfoDTO.setRating(DEFAULT_NAIL_ARTIST_RATING); // 默认评分为4.5 + nailArtistInfoDTO.setStatus(1); // 默认状态为营业中 + nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空 + nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + } + + return userDO.getId(); + } + + /** + * 分配默认权限 + * @param userId 用户ID + * @param userType 用户类型 + */ + private void syncDefaultPermissions(Long userId, Integer userType) { + if (userId == null) { + return; + } + + /** + * Run business method `ensurePermissionDefinitions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + ensurePermissionDefinitions(); + /** + * Run business method `synchronizeManagedDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + synchronizeManagedDefaultPermissions(userId, userType); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `syncManagedPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + public void syncManagedPermissions(Long userId) { + if (userId == null) { + return; + } + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return; + } + syncDefaultPermissions(userDO.getId(), userDO.getType()); + } + + /** + * 更新用户信息 + * @param id 用户ID + * @param userDTO 用户数据传输对象 + * @return 更新是否成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateUser(Long id, UserDTO userDTO) { + // 查询用户是否存在 + UserDO userDO = userMapper.selectById(id); + if (userDO == null) { + return false; + } + + // 更新账号(如果提供且变更) + String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount()); + if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + ); + if (existingUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已存在"); + } + userDO.setAccount(normalizedAccount); + } + + // 更新其他字段(如果提供) + if (userDTO.getShopId() != null) { + userDO.setShopId(validateAndNormalizeShopId(userDTO.getShopId())); + } + if (userDTO.getNickname() != null) { + userDO.setNickname(userDTO.getNickname()); + } + if (userDTO.getPassword() != null) { + validatePasswordStrength(userDTO.getPassword()); + userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); + } + if (userDTO.getPhone() != null) { + userDO.setPhone(validateUserPhone(userDTO.getPhone(), id, true)); + } + if (userDTO.getContactPhone() != null) { + userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); + } + if (userDTO.getBirthday() != null) { + userDO.setBirthday(userDTO.getBirthday()); + } + if (userDTO.getWechatId() != null) { + userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); + } + if (userDTO.getWechatQrCode() != null) { + userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + } + if (userDTO.getAvatar() != null) { + if (userDTO.getAvatar().isEmpty()) { + userDO.setAvatar(null); + } else { + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + } + } + if (userDTO.getSignature() != null) { + userDO.setSignature(userDTO.getSignature()); + } + if (userDTO.getLevel() != null) { + userDO.setLevel(userDTO.getLevel()); + } + if (userDTO.getType() != null) { + userDO.setType(userDTO.getType()); + } + if (userDTO.getVipId() != null) { + userDO.setVipId(userDTO.getVipId()); + } + Integer targetUserType = userDO.getType(); + UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); + List validatedShopIds = null; + boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; + if (shopBindingChanged) { + validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserType parameter `targetUserType` supplied by the caller + * @param validatedShopIds parameter `validatedShopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopBindingRequirement(targetUserType, validatedShopIds); + userDO.setShopId(pickPrimaryShopId(validatedShopIds)); + } + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + if (shopBindingChanged) { + userShopBindingSupport.syncUserShopBindings(id, validatedShopIds); + } + if (userDTO.getPassword() != null) { + userSessionService.revokeAllUserSessions(id); + } + /** + * Run business method `syncDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param targetUserType parameter `targetUserType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncDefaultPermissions(id, targetUserType); + } + return updated; + } + + /** + * 删除用户 + * @param id 用户ID + * @return 删除是否成功 + */ + @Override + public boolean deleteUser(Long id) { + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + + clearLoginFailureCount(userDO.getAccount()); + userSessionService.revokeAllUserSessions(id); + userShopBindingSupport.deleteBindingsByUserId(id); + wechatMiniBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(WechatMiniBindingDO::getUserId, id) + .set(WechatMiniBindingDO::getStatus, 0) + .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) + ); + LocalDateTime now = LocalDateTime.now(); + return userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, id) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getAccount, buildDeletedAccount(userDO)) + .set(UserDO::getPhone, buildDeletedPhone(userDO)) + .set(UserDO::getStatus, 0) + .set(UserDO::getIsDelete, 1) + .set(UserDO::getUpdateTime, now) + ) > 0; + } + + /** + * 根据ID获取用户信息 + * @param id 用户ID + * @return 用户视图对象 + */ + @Override + public UserVO getUserById(Long id) { + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(userDO); + } + + /** + * 获取所有用户列表 + * @return 用户视图对象列表 + */ + @Override + public List listAllUsers() { + List userDOs = userMapper.selectList( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + ); + return userDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 根据店铺ID获取用户列表 + * @param shopId 店铺ID + * @return 用户视图对象列表 + */ + @Override + public List listUsersByShopId(Long shopId) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (userIds.isEmpty()) { + return List.of(); + } + List userDOs = userMapper.selectList( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + .in(UserDO::getId, userIds) + ); + return userDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 根据用户类型获取用户列表 + * @param type 用户类型 + * @return 用户视图对象列表 + */ + @Override + public List listUsersByType(Integer type) { + List userDOs = userMapper.selectList( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getType, type) + ); + return userDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 根据账号获取用户信息 + * @param account 用户账号 + * @return 用户视图对象 + */ + @Override + public UserVO getUserByAccount(String account) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(account); + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + ); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(userDO); + } + + /** + * 将 DO 转换为 VO + * @param userDO 用户DO + * @param userDO 用户DO + * @return 用户VO + */ + private UserVO convertToVO(UserDO userDO) { + UserVO userVO = new UserVO(); + userVO.setId(userDO.getId()); + List shopOptions = resolveShopOptions(userDO, true, false); + Long scopedShopId = RequestShopContext.getCurrentShopId(); + if (scopedShopId != null) { + shopOptions.stream() + .filter(shop -> Objects.equals(shop.getId(), scopedShopId)) + .findFirst() + .ifPresent(shop -> { + shopOptions.remove(shop); + shopOptions.add(0, shop); + }); + } + Long primaryShopId = !shopOptions.isEmpty() ? shopOptions.get(0).getId() : normalizeShopId(userDO.getShopId()); + String primaryShopName = !shopOptions.isEmpty() ? shopOptions.get(0).getShopName() : null; + userVO.setShopId(primaryShopId); + userVO.setShopName(primaryShopName); + userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); + userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); + userVO.setNickname(userDO.getNickname()); + userVO.setAccount(userDO.getAccount()); + userVO.setPhone(userDO.getPhone()); + userVO.setContactPhone(userDO.getContactPhone()); + userVO.setBirthday(userDO.getBirthday()); + userVO.setWechatId(userDO.getWechatId()); + userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); + userVO.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); + userVO.setSignature(userDO.getSignature()); + userVO.setLevel(userDO.getLevel()); + userVO.setType(userDO.getType()); + userVO.setTypeName(resolveUserTypeName(userDO.getType())); + userVO.setVipId(userDO.getVipId()); + userVO.setCreateTime(userDO.getCreateTime()); + userVO.setUpdateTime(userDO.getUpdateTime()); + userVO.setStatus(userDO.getStatus() != null ? userDO.getStatus() : 1); + userVO.setEmail(userDO.getEmail()); + userVO.setMaskedPhone(maskPhone(userDO.getPhone())); + userVO.setMaskedEmail(maskEmail(userDO.getEmail())); + applyRelationInfo(userVO, userDO.getId()); + return userVO; + } + + /** + * Run business method `resolveAccessibleAvatar`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveAccessibleAvatar(String avatarUrl) { + if (!StringUtils.hasText(avatarUrl)) { + return DEFAULT_AVATAR_URL; + } + return objectStorageUrlSupport.toAccessibleUrl(avatarUrl); + } + + /** + * Run business method `normalizeStoredAvatar`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeStoredAvatar(String avatarUrl) { + if (!StringUtils.hasText(avatarUrl)) { + return avatarUrl; + } + return objectStorageUrlSupport.toStoredUrl(avatarUrl); + } + + private String resolveAccessibleProfileImage(String imageUrl) { + if (!StringUtils.hasText(imageUrl)) { + return imageUrl; + } + return objectStorageUrlSupport.toAccessibleUrl(imageUrl); + } + + private String normalizeStoredProfileImage(String imageUrl) { + if (!StringUtils.hasText(imageUrl)) { + return null; + } + return objectStorageUrlSupport.toStoredUrl(imageUrl); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) { + String normalizedAccount = account == null ? "" : account.trim(); + if (!StringUtils.hasText(normalizedAccount)) { + return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺"); + } + AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO == null) { + return buildLoginShopSelection(List.of(), false, "该账号不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); + } + + if (Integer.valueOf(4).equals(userDO.getType())) { + List shops = listSelectableShopOptionsForPlatformAdmin(); + String message = shops.isEmpty() + ? "当前暂无店铺,可直接登录" + : "平台管理员可选择任意店铺作为本次登录店铺"; + return buildLoginShopSelection(shops, true, message); + } + + List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + if (!shops.isEmpty()) { + return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); + } + + if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { + return buildLoginShopSelection( + userShopBindingSupport.listAllActiveShopOptions(), + false, + "该账号首次登录,请先选择店铺" + ); + } + + return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + public LoginShopSelectionVO getLoginShopSelectionByPhone(String phone) { + String normalizedPhone = phone == null ? "" : phone.trim(); + if (!StringUtils.hasText(normalizedPhone)) { + return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺"); + } + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, normalizedPhone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO == null) { + return buildLoginShopSelection( + userShopBindingSupport.listAllActiveShopOptions(), + false, + "新手机号首次登录需要选择店铺" + ); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); + } + + if (Integer.valueOf(4).equals(userDO.getType())) { + List shops = listSelectableShopOptionsForPlatformAdmin(); + String message = shops.isEmpty() + ? "当前暂无店铺,可直接登录" + : "平台管理员可选择任意店铺作为本次登录店铺"; + return buildLoginShopSelection(shops, true, message); + } + + List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + if (!shops.isEmpty()) { + return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); + } + + if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { + return buildLoginShopSelection( + userShopBindingSupport.listAllActiveShopOptions(), + false, + "该手机号账号首次登录,请先选择店铺" + ); + } + + return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + public LoginShopSelectionVO getAdminLoginShopSelection(String account) { + String normalizedAccount = account == null ? "" : account.trim(); + if (!StringUtils.hasText(normalizedAccount)) { + return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺"); + } + AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO == null) { + return buildLoginShopSelection(List.of(), false, "该账号不存在"); + } + if (userDO.getType() == null || userDO.getType() < 2) { + return buildLoginShopSelection(List.of(), false, "该账号不是后台管理账号"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); + } + + if (Integer.valueOf(4).equals(userDO.getType())) { + List shops = listSelectableShopOptionsForPlatformAdmin(); + String message = shops.isEmpty() + ? "当前暂无可选店铺,可直接进入平台总览模式" + : "平台管理员可直接进入平台总览,也可选择任意店铺作为本次登录店铺"; + /** + * Run business method `buildLoginShopSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginShopSelection(shops, true, message); + } + + List shops = listEnabledShopOptionsForUser(userDO.getId()); + if (!shops.isEmpty()) { + return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); + } + return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系平台管理员"); + } + + @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO login(LoginRequestDTO loginRequestDTO) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + ); + + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertLoginAccountAvailable(userDO); + + // 检查是否为未设置密码的账号 + if (ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请使用手机号验证码登录,并在个人中心设置密码"); + } + + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + handleLoginPasswordFailure(userDO); + } + + Long resolvedShopId = resolveUserLoginShopId(userDO, loginRequestDTO.getShopId()); + clearLoginFailureCount(userDO.getAccount()); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + } + + @Override + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO) { + if (!verificationCodeService.verifyCode(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getVerificationCode())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码错误或已过期"); + } + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) + .eq(UserDO::getIsDelete, 0) + ); + + if (userDO == null) { + if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("首次登录需要选择店铺"); + } + userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId()); + } else { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + clearLoginFailureCount(userDO.getAccount()); + } + + Long resolvedShopId = resolveUserLoginShopId(userDO, phoneLoginRequestDTO.getShopId()); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), Boolean.TRUE.equals(phoneLoginRequestDTO.getRememberMe())); + } + + // 未设置密码的特殊标识 + @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + + if (userDO == null) { + if (shopId == null || shopId == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("首次登录需要选择店铺"); + } + userDO = registerByPhone(phone, shopId); + } else { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + clearLoginFailureCount(userDO.getAccount()); + } + + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); + } + + @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO loginByUserId(Long userId, Long shopId) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + clearLoginFailureCount(userDO.getAccount()); + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); + } + + /** + * Purpose: UNSET_PASSWORD_MARKER supports UserServiceImpl.java by holding or executing the unset password marker business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String UNSET_PASSWORD_MARKER = "__UNSET_PASSWORD__"; + /** + * Purpose: ENCODED_UNSET_PASSWORD supports UserServiceImpl.java by holding or executing the encoded unset password business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识 + + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO registerByPhone(String phone, Long shopId) { + Long validatedShopId = validateAndNormalizeShopId(shopId); + if (validatedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("首次登录需要选择店铺"); + } + UserDO userDO = new UserDO(); + userDO.setAccount(phone); + userDO.setPhone(phone); + userDO.setPhoneVerified(1); + userDO.setNickname("用户" + phone.substring(7)); + userDO.setType(0); + userDO.setLevel(VIP_LEVEL_NORMAL); + userDO.setVipId(0L); + userDO.setShopId(validatedShopId); + userDO.setIsDelete(0); + userDO.setStatus(1); + userDO.setCreateTime(LocalDateTime.now()); + userDO.setUpdateTime(LocalDateTime.now()); + userDO.setPassword(ENCODED_UNSET_PASSWORD); + + userMapper.insert(userDO); + syncDefaultPermissions(userDO.getId(), userDO.getType()); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); + return userDO; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `adminLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + ); + + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertLoginAccountAvailable(userDO); + + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + handleLoginPasswordFailure(userDO); + } + + Integer userType = userDO.getType(); + if (userType == null || userType < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号不是后台管理账号"); + } + + Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); + clearLoginFailureCount(userDO.getAccount()); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + } + + @Override + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + Integer userType = userDO.getType(); + if (userType != null && userType >= 2 && !Integer.valueOf(4).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号请使用后台切换店铺"); + } + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), previousSessionId); + } + + @Override + /** + * Run business method `switchAdminShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + Integer userType = userDO.getType(); + if (userType == null || userType < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("您没有后台管理权限"); + } + Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, resolvedShopId, false, previousSessionId); + } + + /** + * Run business method `resolveAdminLoginShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) { + Long normalizedRequestedShopId = normalizeShopId(requestedShopId); + if (Integer.valueOf(4).equals(userDO.getType())) { + if (normalizedRequestedShopId == null) { + return null; + } + boolean canSelectShop = listSelectableShopOptionsForPlatformAdmin().stream() + .map(ShopSimpleVO::getId) + .anyMatch(shopId -> Objects.equals(shopId, normalizedRequestedShopId)); + if (!canSelectShop) { + throw new RuntimeException("当前账号无权登录所选店铺"); + } + return normalizedRequestedShopId; + } + + List activeShopIds = listEnabledShopOptionsForUser(userDO.getId()).stream() + .map(ShopSimpleVO::getId) + .collect(Collectors.toList()); + if (activeShopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员"); + } + if (normalizedRequestedShopId != null) { + if (!activeShopIds.contains(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号无权登录所选店铺"); + } + return normalizedRequestedShopId; + } + if (activeShopIds.size() == 1) { + return activeShopIds.get(0); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择登录店铺"); + } + + /** + * Run business method `hasAnyShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean hasAnyShop() { + return !listEnabledShopOptionsForAdmin().isEmpty(); + } + + /** + * Run business method `normalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long normalizeShopId(Long shopId) { + return shopId != null && shopId > 0 ? shopId : null; + } + + @Override + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean register(RegisterRequestDTO registerRequestDTO) { + String validatedAccount = AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()); + if (!verificationCodeService.verifyCode(registerRequestDTO.getPhone(), registerRequestDTO.getVerificationCode())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码错误或已过期"); + } + + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, validatedAccount) + ); + + if (existingUser != null) { + if (existingUser.getIsDelete() == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已存在"); + } else { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号已被注销,请使用手机号验证码登录"); + } + } + + UserDO existingPhoneUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, registerRequestDTO.getPhone()) + .eq(UserDO::getIsDelete, 0) + ); + + if (existingPhoneUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该手机号已被注册"); + } + + Long validatedShopId = resolveRegisterShopId(registerRequestDTO.getShopId(), registerRequestDTO.getInviteCode()); + if (validatedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + UserDO userDO = new UserDO(); + userDO.setShopId(validatedShopId); + userDO.setAccount(validatedAccount); + validatePasswordStrength(registerRequestDTO.getPassword()); + userDO.setPassword(passwordEncoder.encode(registerRequestDTO.getPassword())); + userDO.setNickname(registerRequestDTO.getNickname()); + userDO.setPhone(registerRequestDTO.getPhone()); + userDO.setPhoneVerified(1); + userDO.setType(Integer.valueOf(0)); + userDO.setLevel(VIP_LEVEL_NORMAL); + userDO.setVipId(0L); + userDO.setIsDelete(Integer.valueOf(0)); + userDO.setCreateTime(LocalDateTime.now()); + userDO.setUpdateTime(LocalDateTime.now()); + + userMapper.insert(userDO); + assignDefaultPermissions(userDO.getId(), userDO.getType()); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); + createRelationForRegister(userDO.getId(), validatedShopId, registerRequestDTO.getInviteCode()); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public LoginResponseVO registerPlanningManager(PlanningManagerRegisterDTO registerDTO) { + if (registerDTO == null) { + throw new RuntimeException("注册信息不能为空"); + } + String phone = validateUserPhone(registerDTO.getPhone(), null, true); + if (!verificationCodeService.verifyCode(phone, registerDTO.getCode())) { + throw new RuntimeException("验证码错误或已过期"); + } + String password = registerDTO.getPassword(); + if (!StringUtils.hasText(password)) { + throw new RuntimeException("密码不能为空"); + } + if (!Objects.equals(password, registerDTO.getConfirmPassword())) { + throw new RuntimeException("两次密码不一致"); + } + validatePasswordStrength(password); + String shopName = registerDTO.getShopName() == null ? null : registerDTO.getShopName().trim(); + if (!StringUtils.hasText(shopName)) { + throw new RuntimeException("店铺名称不能为空"); + } + + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, phone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (existingUser != null) { + throw new RuntimeException("该手机号已注册"); + } + + ShopDO shop = new ShopDO(); + shop.setShopName(shopName); + shop.setDescription(brandProperties.getManagerRegisterShopDescription()); + shop.setBusinessHours("10:00-22:00"); + shop.setStatus(1); + shop.setAuthorizationStartDate(LocalDateTime.now().minusDays(1).toLocalDate()); + shop.setAuthorizationDays(0); + shop.setAuthorizationExpireTime(LocalDateTime.now().minusSeconds(1)); + shop.setIsDelete(0); + shopMapper.insert(shop); + + UserDO manager = new UserDO(); + manager.setShopId(shop.getId()); + manager.setNickname(shopName + "店长"); + manager.setAccount(phone); + manager.setPassword(passwordEncoder.encode(password)); + manager.setPhone(phone); + manager.setContactPhone(phone); + manager.setPhoneVerified(1); + manager.setEmailVerified(0); + manager.setType(2); + manager.setStatus(1); + manager.setIsDelete(0); + manager.setAvatar(DEFAULT_AVATAR_URL); + userMapper.insert(manager); + + syncDefaultPermissions(manager.getId(), manager.getType()); + userShopBindingSupport.syncUserShopBindings(manager.getId(), List.of(shop.getId())); + createRelationForRegister(manager.getId(), shop.getId(), null); + clearLoginFailureCount(manager.getAccount()); + return buildLoginResponse(manager, shop.getId(), false); + } + + @Override + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshToken parameter `refreshToken` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO refreshToken(String refreshToken) { + if (!jwtUtil.validateToken(refreshToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param Token parameter `Token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("刷新Token无效或已过期"); + } + + if (!jwtUtil.isRefreshToken(refreshToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param Token parameter `Token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("Token类型错误"); + } + + Long userId = jwtUtil.getUserIdFromToken(refreshToken); + String account = jwtUtil.getAccountFromToken(refreshToken); + Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); + String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); + String refreshJti = jwtUtil.getJtiFromToken(refreshToken); + if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("登录态已失效,请重新登录"); + } + + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前登录店铺已失效,请重新登录"); + } + + return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), sessionId); + } + + @Override + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionId parameter `sessionId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean logout(String sessionId) { + userSessionService.revokeSession(sessionId); + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return UserVO result consumed by the caller or returned to the frontend + */ + public UserVO getCurrentUserInfo() { + org.springframework.web.context.request.ServletRequestAttributes attributes = + (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes(); + Long userId = attributes == null ? null : (Long) attributes.getRequest().getAttribute("userId"); + return userId == null ? null : getUserById(userId); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateCurrentUserInfo(Long userId, UserDTO userDTO) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + + if (userDTO.getNickname() != null) { + userDO.setNickname(userDTO.getNickname()); + } + if (userDTO.getAvatar() != null) { + if (userDTO.getAvatar().isEmpty()) { + userDO.setAvatar(null); + } else { + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + } + } + if (userDTO.getSignature() != null) { + userDO.setSignature(userDTO.getSignature()); + } + if (userDTO.getContactPhone() != null) { + userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); + } + if (userDTO.getBirthday() != null) { + userDO.setBirthday(userDTO.getBirthday()); + } + if (userDTO.getWechatId() != null) { + userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); + } + if (userDTO.getWechatQrCode() != null) { + userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + } + UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); + + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + syncDefaultPermissions(userDO.getId(), userDO.getType()); + } + return updated; + } + + @Override + /** + * Run business method `bindPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + validateVerificationCode(bindPhoneRequestDTO.getPhone(), bindPhoneRequestDTO.getVerificationCode()); + ensurePhoneNotUsed(bindPhoneRequestDTO.getPhone(), userId); + + userDO.setPhone(bindPhoneRequestDTO.getPhone()); + userDO.setPhoneVerified(1); + userDO.setUpdateTime(LocalDateTime.now()); + + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Run business method `bindEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO) { + UserDO userDO = userMapper.selectById(userId); + if (userDO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + + userDO.setEmail(bindEmailRequestDTO.getEmail()); + userDO.setEmailVerified(1); + userDO.setUpdateTime(LocalDateTime.now()); + + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean resetPassword(Long targetUserId, Long currentUserId) { + UserDO targetUser = userMapper.selectById(targetUserId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + + UserDO currentUser = userMapper.selectById(currentUserId); + if (currentUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户不存在"); + } + + Integer currentUserType = currentUser.getType(); + Integer targetUserType = targetUser.getType(); + + if (currentUserType == null || targetUserType == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户类型错误"); + } + + if (currentUserType <= targetUserType) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("权限不足,只能重置比自己级别低的用户密码"); + } + + targetUser.setPassword(passwordEncoder.encode(resolveAdminDefaultPassword())); + targetUser.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(targetUser) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(targetUserId); + } + return updated; + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type) { + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return pageUsers(page, size, keyword, shopId, type, null, null, null, null, null, null, null, null, null); + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); + wrapper.eq(UserDO::getIsDelete, 0); + // 不再过滤普通用户,由前端根据用户角色进行过滤 + if (StringUtils.hasText(keyword)) { + wrapper.and(w -> w.like(UserDO::getAccount, keyword) + .or().like(UserDO::getNickname, keyword) + .or().like(UserDO::getPhone, keyword) + .or().like(UserDO::getContactPhone, keyword)); + } + if (shopId != null && shopId > 0) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (userIds.isEmpty()) { + PageResultVO emptyResult = new PageResultVO<>(); + emptyResult.setList(List.of()); + emptyResult.setTotal(0L); + emptyResult.setPage(page); + emptyResult.setSize(size); + return emptyResult; + } + wrapper.in(UserDO::getId, userIds); + } + Set relationFilteredIds = resolveRelationFilteredUserIds(roleId, parentUserId, sourceType); + if (relationFilteredIds != null) { + if (relationFilteredIds.isEmpty()) { + PageResultVO emptyResult = new PageResultVO<>(); + emptyResult.setList(List.of()); + emptyResult.setTotal(0L); + emptyResult.setPage(page); + emptyResult.setSize(size); + return emptyResult; + } + wrapper.in(UserDO::getId, relationFilteredIds); + } + if (type != null) { + wrapper.eq(UserDO::getType, type); + } + if (status != null) { + wrapper.eq(UserDO::getStatus, status); + } + if (StringUtils.hasText(vipLevel)) { + wrapper.eq(UserDO::getLevel, vipLevel); + } + if (StringUtils.hasText(createdFrom)) { + wrapper.ge(UserDO::getCreateTime, LocalDateTime.parse(createdFrom)); + } + if (StringUtils.hasText(createdTo)) { + wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo)); + } + if (Boolean.TRUE.equals(hasPhone)) { + wrapper.isNotNull(UserDO::getPhone); + } + if (Boolean.FALSE.equals(hasPhone)) { + wrapper.isNull(UserDO::getPhone); + } + wrapper.orderByDesc(UserDO::getCreateTime); + + Page userPage = userMapper.selectPage(pageParam, wrapper); + + PageResultVO result = new PageResultVO<>(); + result.setList(userPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setTotal(userPage.getTotal()); + result.setPage(page); + result.setSize(size); + + return result; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateUserStatus(Long id, Integer status) { + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + Integer normalizedStatus = Integer.valueOf(1).equals(status) ? 1 : 0; + boolean updated = userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, id) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getStatus, normalizedStatus) + .set(UserDO::getUpdateTime, LocalDateTime.now()) + ) > 0; + if (updated && normalizedStatus == 1) { + UserDO latestUser = userMapper.selectById(id); + if (latestUser != null) { + clearLoginFailureCount(latestUser.getAccount()); + } + } else if (updated) { + userSessionService.revokeAllUserSessions(id); + } + return updated; + } + + @Override + /** + * Run business method `statisticsUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return UserStatisticsVO result consumed by the caller or returned to the frontend + */ + public UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { + List users = pageUsers(1, Integer.MAX_VALUE, keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder).getList(); + UserStatisticsVO vo = new UserStatisticsVO(); + vo.setTotalUserCount(users.size()); + vo.setNormalUserCount(users.stream().filter(u -> Integer.valueOf(0).equals(u.getType())).count()); + vo.setEmployeeCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType()) || Integer.valueOf(3).equals(u.getType())).count()); + vo.setManagerCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType())).count()); + vo.setArtistCount(users.stream().filter(u -> Integer.valueOf(3).equals(u.getType())).count()); + vo.setVipUserCount(users.stream().filter(u -> StringUtils.hasText(u.getLevel()) && !"普通".equals(u.getLevel())).count()); + vo.setNewUserCount(users.stream().filter(u -> u.getCreateTime() != null && u.getCreateTime().isAfter(LocalDateTime.now().minusDays(7))).count()); + vo.setByShop(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopId()), Collectors.counting()))); + vo.setByRole(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopRoleName()), Collectors.counting()))); + vo.setByParent(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getParentUserName()), Collectors.counting()))); + return vo; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserRelationVO result consumed by the caller or returned to the frontend + */ + public UserRelationVO getCurrentUserRelation(Long userId) { + /** + * Run business method `buildRelationVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildRelationVO(userId); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateUserStatusInShop(Long id, Integer status, Long shopId) { + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return updateUserStatus(id, status); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteUserInShop(Long id, Long shopId) { + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return unbindUserInShop(id, shopId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean unbindUserInShop(Long id, Long shopId) { + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return unbindUserInShopWithOperator(id, shopId, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param operatorType parameter `operatorType` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType) { + Long normalizedShopId = normalizeShopId(shopId); + if (normalizedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前操作缺少店铺上下文"); + } + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + + boolean success = userShopBindingSupport.updateBindingStatus(id, normalizedShopId, 0); + if (!success) { + return false; + } + + if (Integer.valueOf(2).equals(operatorType) && Integer.valueOf(3).equals(userDO.getType())) { + userDO.setType(0); + userDO.setUpdateTime(LocalDateTime.now()); + userMapper.updateById(userDO); + syncDefaultPermissions(userDO.getId(), userDO.getType()); + } + return true; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateUserAvatar(Long userId, String avatarUrl) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + userDO.setAvatar(avatarUrl); + userDO.setUpdateTime(LocalDateTime.now()); + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param password parameter `password` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updatePassword(Long userId, String password, String verificationCode) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先绑定手机号"); + } + validateVerificationCode(userDO.getPhone(), verificationCode); + validatePasswordStrength(password); + userDO.setPassword(passwordEncoder.encode(password)); + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(userId); + } + return updated; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { + String oldPhone = updatePhoneDTO.getOldPhone(); + String newPhone = updatePhoneDTO.getNewPhone(); + String verificationCode = updatePhoneDTO.getVerificationCode(); + + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号未绑定手机号"); + } + if (!userDO.getPhone().equals(oldPhone)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("原手机号不匹配"); + } + + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param newPhone parameter `newPhone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateVerificationCode(newPhone, verificationCode); + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param newPhone parameter `newPhone` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePhoneNotUsed(newPhone, userId); + + userDO.setPhone(newPhone); + userDO.setPhoneVerified(1); + userDO.setUpdateTime(LocalDateTime.now()); + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Run business method `resetPasswordByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO) { + String phone = resetPasswordRequestDTO.getPhone(); + String verificationCode = resetPasswordRequestDTO.getVerificationCode(); + String newPassword = resetPasswordRequestDTO.getNewPassword(); + + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateVerificationCode(phone, verificationCode); + + // 根据手机号查找用户 + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); + wrapper.eq(UserDO::getPhone, phone); + wrapper.eq(UserDO::getIsDelete, 0); + UserDO userDO = userMapper.selectOne(wrapper); + + if (userDO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("未绑定手机号,请联系店员"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已被禁用"); + } + + // 更新密码 + validatePasswordStrength(newPassword); + userDO.setPassword(passwordEncoder.encode(newPassword)); + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(userDO.getId()); + } + return updated; + } + + /** + * Run business method `buildDeletedAccount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildDeletedAccount(UserDO userDO) { + String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); + String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted"; + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param suffix parameter `suffix` supplied by the caller + * @param 50 parameter `50` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); + } + + /** + * Run business method `buildDeletedPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildDeletedPhone(UserDO userDO) { + String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); + String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone"; + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param suffix parameter `suffix` supplied by the caller + * @param 50 parameter `50` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); + } + + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param maxLength parameter `maxLength` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String trimDeletedPlaceholder(String value, int maxLength) { + if (!StringUtils.hasText(value) || value.length() <= maxLength) { + return value; + } + return value.substring(value.length() - maxLength); + } + + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUserAvailable(UserDO userDO) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已被禁用"); + } + } + + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertLoginAccountAvailable(UserDO userDO) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号已被禁用"); + } + } + + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void handleLoginPasswordFailure(UserDO userDO) { + if (userDO == null || !StringUtils.hasText(userDO.getAccount())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("密码错误"); + } + String failKey = buildLoginFailKey(userDO.getAccount()); + Long failCount = redisTemplate.opsForValue().increment(failKey); + redisTemplate.expire(failKey, LOGIN_FAIL_EXPIRE); + long safeFailCount = failCount == null ? 1L : failCount; + if (safeFailCount >= MAX_LOGIN_FAILURES) { + disableUserByFailedPassword(userDO.getId()); + redisTemplate.delete(failKey); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("密码错误次数过多,账号已被禁用"); + } + long remainingAttempts = MAX_LOGIN_FAILURES - safeFailCount; + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("密码错误,还可尝试" + remainingAttempts + "次"); + } + + /** + * Run business method `disableUserByFailedPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void disableUserByFailedPassword(Long userId) { + if (userId == null) { + return; + } + userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, userId) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getStatus, 0) + .set(UserDO::getUpdateTime, LocalDateTime.now()) + ); + userSessionService.revokeAllUserSessions(userId); + } + + /** + * Run business method `clearLoginFailureCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void clearLoginFailureCount(String account) { + if (!StringUtils.hasText(account)) { + return; + } + redisTemplate.delete(buildLoginFailKey(account)); + } + + /** + * Run business method `buildLoginFailKey`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildLoginFailKey(String account) { + return LOGIN_FAIL_KEY_PREFIX + account.trim(); + } + + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateVerificationCode(String phone, String verificationCode) { + if (!StringUtils.hasText(phone) || !StringUtils.hasText(verificationCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码不能为空"); + } + if (!verificationCodeService.verifyCode(phone, verificationCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码错误或已过期"); + } + } + + /** + * Purpose: validatePasswordStrength supports UserServiceImpl.java by holding or executing the validate password strength business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void validatePasswordStrength(String password) { + if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { + throw new RuntimeException("密码长度需为 8-32 位"); + } + int count = 0; + if (password.matches(".*\\d.*")) { + count++; + } + if (password.matches(".*[a-z].*")) { + count++; + } + if (password.matches(".*[A-Z].*")) { + count++; + } + if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { + count++; + } + if (count < 3) { + throw new RuntimeException("密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); + } + } + + private String resolveAdminDefaultPassword() { + return AdminDefaultPasswordSupport.resolveDefaultPassword(getConfiguredAdminDefaultPassword()); + } + + private String getConfiguredAdminDefaultPassword() { + return systemParameterConfigService.getEnabledValue( + AdminDefaultPasswordSupport.CONFIG_GROUP, + AdminDefaultPasswordSupport.CONFIG_KEY + ); + } + + /** + * Run business method `resolveValidatedShopIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @param fallbackShopId parameter `fallbackShopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveValidatedShopIds(List shopIds, Long fallbackShopId) { + LinkedHashSet resolvedShopIds = new LinkedHashSet<>(); + if (shopIds != null) { + for (Long shopId : shopIds) { + Long validatedShopId = validateAndNormalizeShopId(shopId); + if (validatedShopId != null) { + resolvedShopIds.add(validatedShopId); + } + } + } + Long validatedFallbackShopId = validateAndNormalizeShopId(fallbackShopId); + if (validatedFallbackShopId != null) { + resolvedShopIds.add(validatedFallbackShopId); + } + return new ArrayList<>(resolvedShopIds); + } + + /** + * Run business method `pickPrimaryShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long pickPrimaryShopId(List shopIds) { + return shopIds == null || shopIds.isEmpty() ? null : shopIds.get(0); + } + + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureShopBindingRequirement(Integer userType, List shopIds) { + if (Integer.valueOf(4).equals(userType)) { + return; + } + if (shopIds == null || shopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请至少选择一个所属店铺"); + } + } + + /** + * Run business method `buildLoginShopSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + private LoginShopSelectionVO buildLoginShopSelection(List shops, boolean allowShoplessLogin, String message) { + LoginShopSelectionVO selectionVO = new LoginShopSelectionVO(); + selectionVO.setAllowShoplessLogin(allowShoplessLogin); + selectionVO.setMessage(message); + selectionVO.setShops(shops == null ? new ArrayList<>() : new ArrayList<>(shops)); + return selectionVO; + } + + /** + * Run business method `buildLoginShopMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildLoginShopMessage(List shops) { + if (shops == null || shops.isEmpty()) { + return "当前暂无可登录店铺"; + } + if (shops.size() == 1) { + return "已匹配到 1 家可登录店铺,已为您默认选中"; + } + return "该账号已绑定多家店铺,请选择本次登录店铺"; + } + + /** + * Run business method `buildAdminLoginShopMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildAdminLoginShopMessage(List shops) { + if (shops == null || shops.isEmpty()) { + return "当前暂无启用店铺,可直接进入平台总览模式"; + } + if (shops.size() == 1) { + return "平台管理员将进入平台总览模式,店铺业务默认仅可查看"; + } + return "当前已有 " + shops.size() + " 家启用店铺;平台管理员将进入平台总览模式"; + } + + /** + * Run business method `resolveUserLoginShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) { + if (Integer.valueOf(4).equals(userDO.getType())) { + return resolveAdminLoginShopId(userDO, requestedShopId); + } + Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId); + List activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()); + if (!activeShopIds.isEmpty()) { + if (normalizedRequestedShopId != null) { + if (!activeShopIds.contains(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号无权登录所选店铺"); + } + return normalizedRequestedShopId; + } + if (activeShopIds.size() == 1) { + return activeShopIds.get(0); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择登录店铺"); + } + + if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { + if (normalizedRequestedShopId != null) { + userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), normalizedRequestedShopId); + return normalizedRequestedShopId; + } + + Long legacyShopId = normalizeShopId(userDO.getShopId()); + if (legacyShopId != null && userShopBindingSupport.isShopActive(legacyShopId)) { + userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), legacyShopId); + return legacyShopId; + } + + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号没有可登录的店铺,请联系门店处理"); + } + + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @return private LoginResponseVO result consumed by the caller or returned to the frontend + */ + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) { + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, currentShopId, needSetPassword, null); + } + + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, boolean rememberMe) { + return buildLoginResponse(userDO, currentShopId, needSetPassword, null, rememberMe); + } + + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return private LoginResponseVO result consumed by the caller or returned to the frontend + */ + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId) { + return buildLoginResponse(userDO, currentShopId, needSetPassword, previousSessionId, false); + } + + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId, boolean rememberMe) { + UserSessionService.SessionIssueResult sessionIssueResult = StringUtils.hasText(previousSessionId) + ? userSessionService.rotateSession(previousSessionId, userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()) + : userSessionService.issueSession(userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()); + String accessToken = jwtUtil.generateAccessToken( + userDO.getId(), + userDO.getAccount(), + currentShopId, + sessionIssueResult.sessionId(), + sessionIssueResult.accessJti(), + jwtUtil.resolveAccessTokenExpirationSeconds(rememberMe) + ); + String refreshToken = jwtUtil.generateRefreshToken( + userDO.getId(), + userDO.getAccount(), + currentShopId, + sessionIssueResult.sessionId(), + sessionIssueResult.refreshJti() + ); + + LoginResponseVO responseVO = new LoginResponseVO(); + responseVO.setAccessToken(accessToken); + responseVO.setRefreshToken(refreshToken); + responseVO.setNeedSetPassword(needSetPassword); + responseVO.setUserInfo(buildLoginUserInfo(userDO, currentShopId)); + return responseVO; + } + + /** + * Run business method `buildLoginUserInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @return private LoginResponseVO.UserInfo result consumed by the caller or returned to the frontend + */ + private LoginResponseVO.UserInfo buildLoginUserInfo(UserDO userDO, Long currentShopId) { + boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + List activeShopOptions = resolveShopOptions(userDO, true, !adminLogin); + Long normalizedCurrentShopId = normalizeShopId(currentShopId); + String currentShopName = activeShopOptions.stream() + .filter(shop -> Objects.equals(shop.getId(), normalizedCurrentShopId)) + .map(ShopSimpleVO::getShopName) + .findFirst() + .orElseGet(() -> { + if (normalizedCurrentShopId == null) { + return null; + } + ShopVO shopVO = shopService.getShopById(normalizedCurrentShopId); + return shopVO == null ? null : shopVO.getShopName(); + }); + + LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo(); + userInfo.setId(userDO.getId()); + userInfo.setAccount(userDO.getAccount()); + userInfo.setNickname(userDO.getNickname()); + userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); + userInfo.setType(userDO.getType()); + userInfo.setShopId(normalizedCurrentShopId); + userInfo.setShopName(currentShopName); + ShopVO currentShop = normalizedCurrentShopId == null ? null : shopService.getShopById(normalizedCurrentShopId); + userInfo.setShopAuthorizationExpireTime(currentShop == null ? null : currentShop.getAuthorizationExpireTime()); + userInfo.setShopAuthorizationExpired(currentShop != null && Boolean.TRUE.equals(currentShop.getAuthorizationExpired())); + userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); + userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); + userInfo.setCreateTime(userDO.getCreateTime()); + return userInfo; + } + + /** + * Run business method `resolveShopOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param onlyActiveBindings parameter `onlyActiveBindings` supplied by the caller + * @param onlyActiveShops parameter `onlyActiveShops` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveShopOptions(UserDO userDO, boolean onlyActiveBindings, boolean onlyActiveShops) { + if (userDO == null) { + return new ArrayList<>(); + } + + List shopOptions; + if (Integer.valueOf(4).equals(userDO.getType())) { + shopOptions = new ArrayList<>(onlyActiveShops + ? userShopBindingSupport.listAllActiveShopOptions() + : listSelectableShopOptionsForPlatformAdmin()); + } else { + shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId( + userDO.getId(), + onlyActiveBindings, + onlyActiveShops + )); + } + + if (!shopOptions.isEmpty()) { + return shopOptions; + } + + if (userShopBindingSupport.hasBindingHistory(userDO.getId())) { + return shopOptions; + } + + Long legacyShopId = normalizeShopId(userDO.getShopId()); + if (legacyShopId != null) { + ShopVO legacyShop = shopService.getShopById(legacyShopId); + if (legacyShop != null && (!onlyActiveShops || Integer.valueOf(1).equals(legacyShop.getStatus()))) { + shopOptions.add(new ShopSimpleVO(legacyShop.getId(), legacyShop.getShopName())); + } + } + return shopOptions; + } + + /** + * Run business method `validateAndNormalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long validateAndNormalizeShopId(Long shopId) { + Long normalizedShopId = normalizeShopId(shopId); + if (normalizedShopId == null) { + return null; + } + if (!userShopBindingSupport.isShopActive(normalizedShopId)) { + if (userShopBindingSupport.isShopEnabledIgnoringAuthorization(normalizedShopId) + && userShopBindingSupport.isShopAuthorizationExpired(normalizedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店铺已被冻结"); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("所属店铺不存在或已失效"); + } + return normalizedShopId; + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private List result consumed by the caller or returned to the frontend + */ + private List listEnabledShopOptionsForAdmin() { + return shopService.listAllShopsForAdmin().stream() + .filter(shop -> Integer.valueOf(1).equals(shop.getStatus())) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * Purpose: listSelectableShopOptionsForPlatformAdmin supports UserServiceImpl.java by holding or executing the list selectable shop options for platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listSelectableShopOptionsForPlatformAdmin() { + return shopService.listAllShopsForAdmin().stream() + .filter(shop -> !Boolean.TRUE.equals(shop.getAuthorizationExpired())) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listEnabledShopOptionsForUser(Long userId) { + return userShopBindingSupport.listShopOptionsByUserId(userId, true, false).stream() + .filter(shop -> userShopBindingSupport.isShopEnabledIgnoringAuthorization(shop.getId())) + .collect(Collectors.toList()); + } + + /** + * Run business method `validateUserPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param required parameter `required` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String validateUserPhone(String phone, Long currentUserId, boolean required) { + String normalizedPhone = phone == null ? null : phone.trim(); + if (!StringUtils.hasText(normalizedPhone)) { + if (required) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("手机号不能为空"); + } + return null; + } + if (isDeletedPlaceholderPhone(normalizedPhone)) { + return normalizedPhone; + } + if (!normalizedPhone.matches(PHONE_REGEX)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("手机号格式不正确"); + } + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param normalizedPhone parameter `normalizedPhone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePhoneNotUsed(normalizedPhone, currentUserId); + return normalizedPhone; + } + + /** + * Run business method `isDeletedPlaceholderPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isDeletedPlaceholderPhone(String phone) { + return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER); + } + + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePhoneNotUsed(String phone, Long currentUserId) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0); + if (currentUserId != null) { + wrapper.ne(UserDO::getId, currentUserId); + } + if (userMapper.selectOne(wrapper) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("手机号已被使用"); + } + } + /** + * Run business method `buildRelationVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserRelationVO result consumed by the caller or returned to the frontend + */ + private UserRelationVO buildRelationVO(Long userId) { + if (userId == null) { + return null; + } + UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() + .eq(UserRelationDO::getUserId, userId) + .eq(UserRelationDO::getIsDelete, 0) + .last("limit 1")); + if (relation == null) { + return null; + } + UserRelationVO vo = new UserRelationVO(); + vo.setUserId(userId); + vo.setShopId(relation.getShopId()); + vo.setShopName(relation.getShopId() == null ? null : Optional.ofNullable(shopService.getShopById(relation.getShopId())).map(ShopVO::getShopName).orElse(null)); + vo.setParentUserId(relation.getParentUserId()); + vo.setParentUserName(relation.getParentUserId() == null ? null : Optional.ofNullable(userMapper.selectById(relation.getParentUserId())).map(UserDO::getNickname).orElse(null)); + vo.setParentRoleType(relation.getParentRoleType()); + vo.setParentRoleTypeName(resolveUserTypeName(relation.getParentRoleType())); + vo.setSourceType(relation.getSourceType()); + vo.setSourceTypeName(resolveSourceTypeName(relation.getSourceType())); + return vo; + } + + /** + * Run business method `applyRelationInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userVO parameter `userVO` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyRelationInfo(UserVO userVO, Long userId) { + UserRelationVO relation = buildRelationVO(userId); + if (relation != null) { + userVO.setParentUserId(relation.getParentUserId()); + userVO.setParentUserName(relation.getParentUserName()); + userVO.setParentUserTypeName(relation.getParentRoleTypeName()); + userVO.setRelationSourceType(relation.getSourceTypeName()); + } + UserShopRoleDO roleBinding = userShopRoleMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, userId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1) + .last("limit 1")); + if (roleBinding != null) { + userVO.setShopRoleId(roleBinding.getRoleId()); + } + } + + /** + * Run business method `resolveUserTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveUserTypeName(Integer type) { + return switch (type == null ? -1 : type) { + case 0 -> "普通用户"; + case 2 -> "店长"; + case 3 -> "美甲师"; + case 4 -> "管理员"; + default -> "未知"; + }; + } + + /** + * Run business method `resolveSourceTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sourceType parameter `sourceType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveSourceTypeName(String sourceType) { + if (!StringUtils.hasText(sourceType)) { + return "-"; + } + return switch (sourceType) { + case "INVITE" -> "邀请码"; + case "DEFAULT_MANAGER" -> "默认店长"; + case "MANUAL" -> "手动"; + default -> sourceType; + }; + } + + /** + * Run business method `maskPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskPhone(String phone) { + if (!StringUtils.hasText(phone) || phone.length() < 7) { + return phone; + } + return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); + } + + /** + * Run business method `maskEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param email parameter `email` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskEmail(String email) { + if (!StringUtils.hasText(email) || !email.contains("@")) { + return email; + } + int at = email.indexOf('@'); + return (at <= 1 ? "***" : email.substring(0, 1) + "***") + email.substring(at); + } + + /** + * Run business method `resolveRegisterShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @param inviteCode parameter `inviteCode` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveRegisterShopId(Long requestedShopId, String inviteCode) { + if (StringUtils.hasText(inviteCode)) { + UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .eq(UserInviteCodeDO::getStatus, 1) + .last("limit 1")); + if (code != null) { + return code.getShopId(); + } + } + Long normalized = validateAndNormalizeShopId(requestedShopId); + if (normalized != null) { + return normalized; + } + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (currentShopId != null) { + return currentShopId; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param inviteCode parameter `inviteCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void createRelationForRegister(Long userId, Long shopId, String inviteCode) { + UserRelationDO relation = new UserRelationDO(); + relation.setUserId(userId); + relation.setShopId(shopId); + relation.setCreatorId(userId); + relation.setSourceType(StringUtils.hasText(inviteCode) ? "INVITE" : "DEFAULT_MANAGER"); + relation.setIsDelete(0); + if (StringUtils.hasText(inviteCode)) { + UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .last("limit 1")); + if (code != null) { + relation.setParentUserId(code.getOwnerUserId()); + UserDO parent = userMapper.selectById(code.getOwnerUserId()); + relation.setParentRoleType(parent == null ? null : parent.getType()); + code.setUseCount((code.getUseCount() == null ? 0 : code.getUseCount()) + 1); + code.setUpdateTime(LocalDateTime.now()); + userInviteCodeMapper.updateById(code); + } + } else if (shopId != null) { + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getType, 2) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("limit 1")); + relation.setParentUserId(manager == null ? null : manager.getId()); + relation.setParentRoleType(manager == null ? null : manager.getType()); + } + userRelationMapper.insert(relation); + } + + /** + * Run business method `resolveRelationFilteredUserIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set resolveRelationFilteredUserIds(Long roleId, Long parentUserId, String sourceType) { + if (roleId == null && parentUserId == null && !StringUtils.hasText(sourceType)) { + return null; + } + List relations = userRelationMapper.selectList(new LambdaQueryWrapper() + .eq(UserRelationDO::getIsDelete, 0)); + if (roleId != null) { + Set roleUserIds = userShopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getRoleId, roleId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1)) + .stream().map(UserShopRoleDO::getUserId).filter(Objects::nonNull).collect(Collectors.toSet()); + relations = relations.stream() + .filter(r -> roleUserIds.contains(r.getParentUserId())) + .collect(Collectors.toList()); + } + if (parentUserId != null) { + relations = relations.stream() + .filter(r -> Objects.equals(parentUserId, r.getParentUserId())) + .collect(Collectors.toList()); + } + if (StringUtils.hasText(sourceType)) { + relations = relations.stream() + .filter(r -> sourceType.equals(r.getSourceType())) + .collect(Collectors.toList()); + } + return relations.stream() + .map(UserRelationDO::getUserId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java new file mode 100644 index 00000000..7be4d5a8 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/support/UserProfileFieldSupport.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.support; + +import org.springframework.util.StringUtils; + +public final class UserProfileFieldSupport { + + private UserProfileFieldSupport() { + } + + public static String normalizeOptionalText(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + return value.trim(); + } + + public static void requireWechatIdForServiceUser(Integer userType, String wechatId) { + if ((Integer.valueOf(2).equals(userType) || Integer.valueOf(3).equals(userType)) + && !StringUtils.hasText(wechatId)) { + throw new IllegalArgumentException("店长和美甲师的微信号不能为空"); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/InviteCodeVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/InviteCodeVO.java new file mode 100644 index 00000000..7a511fd5 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/InviteCodeVO.java @@ -0,0 +1,58 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * InviteCodeVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class InviteCodeVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + /** + * Field `ownerUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ownerUserName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserAgreementConsentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserAgreementConsentVO.java new file mode 100644 index 00000000..a05b3434 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserAgreementConsentVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +@Data +@NoArgsConstructor +@AllArgsConstructor +/** + * Purpose: UserAgreementConsentVO supports UserAgreementConsentVO.java by holding or executing the user agreement consent vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UserAgreementConsentVO { + + /** + * Purpose: consentVersions supports UserAgreementConsentVO.java by holding or executing the consent versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map consentVersions; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserAssetVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserAssetVO.java new file mode 100644 index 00000000..b0e7978f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserAssetVO.java @@ -0,0 +1,74 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * UserAssetVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserAssetVO { + + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + + /** + * Field `balance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal balance; + + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalRechargeAmount; + + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; + + /** + * Field `vipInfoId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long vipInfoId; + + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + /** + * Field `benefitId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long benefitId; + + /** + * Field `benefitInfo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String benefitInfo; + + /** + * Field `manualOverride` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean manualOverride; + + /** + * Field `vipStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime vipStartTime; + + /** + * Field `vipExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime vipExpireTime; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserRelationVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserRelationVO.java new file mode 100644 index 00000000..c6ee9e98 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserRelationVO.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +@Data +/** + * UserRelationVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserName; + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + /** + * Field `parentRoleTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentRoleTypeName; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + /** + * Field `sourceTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceTypeName; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserStatisticsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserStatisticsVO.java new file mode 100644 index 00000000..3d8ea2ef --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserStatisticsVO.java @@ -0,0 +1,53 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.vo; + +import lombok.Data; + +import java.util.Map; + +@Data +/** + * UserStatisticsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserStatisticsVO { + /** + * Field `totalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long totalUserCount; + /** + * Field `normalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long normalUserCount; + /** + * Field `employeeCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long employeeCount; + /** + * Field `managerCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long managerCount; + /** + * Field `artistCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long artistCount; + /** + * Field `vipUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long vipUserCount; + /** + * Field `newUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long newUserCount; + /** + * Field `byShop` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byShop; + /** + * Field `byRole` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byRole; + /** + * Field `byParent` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byParent; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserVO.java new file mode 100644 index 00000000..ae86313f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/vo/UserVO.java @@ -0,0 +1,168 @@ +package com.xiaowang.jayucloud.artlist.core.modules.user.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 系统用户信息表 VO + * 用于前端展示用户信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class UserVO { + + /** + * 用户唯一主键ID(雪花ID) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 所属店铺ID,关联店铺表主键(0表示无所属店铺) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 绑定店铺ID列表 + */ + @JsonSerialize(contentUsing = ToStringSerializer.class) + private List shopIds; + + /** + * 绑定店铺名称列表 + */ + private List shopNames; + + /** + * 用户昵称 + */ + private String nickname; + + /** + * 用户账号(登录用) + */ + private String account; + + /** + * 用户头像URL + */ + private String avatar; + + /** + * 用户签名 + */ + private String signature; + + /** + * 用户等级 + */ + private String level; + + /** + * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) + */ + private Integer type; + + /** + * 用户类型名称 + */ + private String typeName; + + /** + * 关联VIP信息表主键(0表示非VIP) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long vipId; + + /** + * VIP等级 + */ + private String vipLevel; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; + + /** + * 用户状态:1-正常,0-禁用 + */ + private Integer status; + + /** + * 手机号 + */ + private String phone; + /** + * 联系电话 + */ + private String contactPhone; + /** + * 生日 + */ + private LocalDate birthday; + /** + * 微信号 + */ + private String wechatId; + /** + * 微信二维码 + */ + private String wechatQrCode; + /** + * Field `email` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String email; + /** + * Field `maskedPhone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String maskedPhone; + /** + * Field `maskedEmail` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String maskedEmail; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopRoleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopRoleId; + /** + * Field `shopRoleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopRoleName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserName; + /** + * Field `parentUserTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserTypeName; + /** + * Field `relationSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relationSourceType; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/RequestShopContext.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/RequestShopContext.java new file mode 100644 index 00000000..e6dac543 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/RequestShopContext.java @@ -0,0 +1,67 @@ +package com.xiaowang.jayucloud.artlist.core.support; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +/** + * 当前请求中的店铺上下文。 + */ +public final class RequestShopContext { + + /** + * Purpose: CURRENT_SHOP_ID_ATTRIBUTE supports RequestShopContext.java by holding or executing the current shop id attribute business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String CURRENT_SHOP_ID_ATTRIBUTE = "currentShopId"; + + private RequestShopContext() { + } + + /** + * Purpose: getCurrentShopId supports RequestShopContext.java by holding or executing the get current shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Long getCurrentShopId() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return null; + } + return parseShopId(attributes.getRequest().getAttribute(CURRENT_SHOP_ID_ATTRIBUTE)); + } + + /** + * Purpose: getCurrentShopId supports RequestShopContext.java by holding or executing the get current shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Long getCurrentShopId(HttpServletRequest request) { + if (request == null) { + return null; + } + return parseShopId(request.getAttribute(CURRENT_SHOP_ID_ATTRIBUTE)); + } + + /** + * Purpose: parseShopId supports RequestShopContext.java by holding or executing the parse shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static Long parseShopId(Object value) { + if (value == null) { + return null; + } + if (value instanceof Number number) { + long shopId = number.longValue(); + return shopId > 0 ? shopId : null; + } + if (value instanceof String text) { + try { + long shopId = Long.parseLong(text.trim()); + return shopId > 0 ? shopId : null; + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/cache/MultiLevelCacheService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/cache/MultiLevelCacheService.java new file mode 100644 index 00000000..82d92579 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/cache/MultiLevelCacheService.java @@ -0,0 +1,324 @@ +package com.xiaowang.jayucloud.artlist.core.support.cache; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** + * 本地 + Redis 多级缓存。 + */ +@Component +@RequiredArgsConstructor +@Slf4j +public class MultiLevelCacheService { + + /** + * Purpose: NULL_SENTINEL supports MultiLevelCacheService.java by holding or executing the null sentinel business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String NULL_SENTINEL = "__CACHE_NULL__"; + + /** + * Purpose: stringRedisTemplate supports MultiLevelCacheService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: objectMapper supports MultiLevelCacheService.java by holding or executing the object mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ObjectMapper objectMapper; + /** + * Purpose: cacheProperties supports MultiLevelCacheService.java by holding or executing the cache properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AppCacheProperties cacheProperties; + + /** + * Purpose: localCache supports MultiLevelCacheService.java by holding or executing the local cache business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Cache localCache; + + /** + * Purpose: getLocalCache supports MultiLevelCacheService.java by holding or executing the get local cache business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Cache getLocalCache() { + if (localCache == null) { + localCache = Caffeine.newBuilder() + .maximumSize(Math.max(128, cacheProperties.getLocalMaxSize())) + .build(); + } + return localCache; + } + + public T getOrLoad(String key, + Duration localTtl, + Duration redisTtl, + TypeReference typeReference, + Supplier loader) { + CacheLookup lookup = get(key, localTtl, typeReference); + if (lookup.isHit()) { + return lookup.getValue(); + } + + T loaded = loader.get(); + put(key, loaded, localTtl, redisTtl); + return loaded; + } + + /** + * Purpose: get supports MultiLevelCacheService.java by holding or executing the get business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public CacheLookup get(String key, Duration localTtl, TypeReference typeReference) { + if (!StringUtils.hasText(key)) { + return CacheLookup.miss(); + } + + LocalCacheEntry localEntry = getLocalCache().getIfPresent(key); + if (localEntry != null) { + if (!localEntry.isExpired()) { + return CacheLookup.hit(readValue(localEntry.getJson(), typeReference)); + } + getLocalCache().invalidate(key); + } + + String json = readRedisValue(key); + if (!StringUtils.hasText(json)) { + return CacheLookup.miss(); + } + + putLocal(key, json, localTtl); + return CacheLookup.hit(readValue(json, typeReference)); + } + + /** + * Purpose: put supports MultiLevelCacheService.java by holding or executing the put business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void put(String key, Object value, Duration localTtl, Duration redisTtl) { + if (!StringUtils.hasText(key)) { + return; + } + String json = writeValue(value); + putLocal(key, json, localTtl); + writeRedisValue(key, json, redisTtl); + } + + /** + * Purpose: evict supports MultiLevelCacheService.java by holding or executing the evict business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void evict(String... keys) { + if (keys == null || keys.length == 0) { + return; + } + for (String key : keys) { + getLocalCache().invalidate(key); + } + deleteRedisKeys(Set.of(keys)); + } + + /** + * Purpose: evictByPrefix supports MultiLevelCacheService.java by holding or executing the evict by prefix business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void evictByPrefix(String prefix) { + if (!StringUtils.hasText(prefix)) { + return; + } + getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix)); + Set redisKeys = scanRedisKeys(prefix + "*"); + if (!CollectionUtils.isEmpty(redisKeys)) { + deleteRedisKeys(redisKeys); + } + } + + /** + * Purpose: readRedisValue supports MultiLevelCacheService.java by holding or executing the read redis value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String readRedisValue(String key) { + try { + return stringRedisTemplate.opsForValue().get(key); + } catch (Exception exception) { + log.warn("Redis cache read failed, key={}", key, exception); + return null; + } + } + + /** + * Purpose: writeRedisValue supports MultiLevelCacheService.java by holding or executing the write redis value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void writeRedisValue(String key, String json, Duration redisTtl) { + try { + stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS); + } catch (Exception exception) { + log.warn("Redis cache write failed, key={}", key, exception); + } + } + + /** + * Purpose: deleteRedisKeys supports MultiLevelCacheService.java by holding or executing the delete redis keys business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void deleteRedisKeys(Set keys) { + if (CollectionUtils.isEmpty(keys)) { + return; + } + try { + stringRedisTemplate.delete(keys); + } catch (Exception exception) { + log.warn("Redis cache delete failed, size={}", keys.size(), exception); + } + } + + /** + * Purpose: scanRedisKeys supports MultiLevelCacheService.java by holding or executing the scan redis keys business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set scanRedisKeys(String pattern) { + Set keys = new LinkedHashSet<>(); + try { + return stringRedisTemplate.execute((RedisConnection connection) -> { + Set matchedKeys = new LinkedHashSet<>(); + try (Cursor cursor = connection.scan(ScanOptions.scanOptions() + .match(pattern) + .count(500) + .build())) { + while (cursor.hasNext()) { + matchedKeys.add(new String(cursor.next(), StandardCharsets.UTF_8)); + } + } + return matchedKeys; + }); + } catch (Exception exception) { + log.warn("Redis cache scan failed, pattern={}", pattern, exception); + return keys; + } + } + + /** + * Purpose: putLocal supports MultiLevelCacheService.java by holding or executing the put local business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void putLocal(String key, String json, Duration localTtl) { + getLocalCache().put(key, new LocalCacheEntry(json, System.currentTimeMillis() + Math.max(1L, localTtl.toMillis()))); + } + + /** + * Purpose: writeValue supports MultiLevelCacheService.java by holding or executing the write value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String writeValue(Object value) { + try { + return value == null ? NULL_SENTINEL : objectMapper.writeValueAsString(value); + } catch (JsonProcessingException exception) { + throw new RuntimeException("缓存序列化失败", exception); + } + } + + /** + * Purpose: readValue supports MultiLevelCacheService.java by holding or executing the read value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private T readValue(String json, TypeReference typeReference) { + if (NULL_SENTINEL.equals(json)) { + return null; + } + try { + return objectMapper.readValue(json, typeReference); + } catch (JsonProcessingException exception) { + throw new RuntimeException("缓存反序列化失败", exception); + } + } + + @Getter + /** + * Purpose: CacheLookup supports MultiLevelCacheService.java by holding or executing the cache lookup business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final class CacheLookup { + /** + * Purpose: hit supports MultiLevelCacheService.java by holding or executing the hit business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final boolean hit; + /** + * Purpose: value supports MultiLevelCacheService.java by holding or executing the value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final T value; + + private CacheLookup(boolean hit, T value) { + this.hit = hit; + this.value = value; + } + + /** + * Purpose: hit supports MultiLevelCacheService.java by holding or executing the hit business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static CacheLookup hit(T value) { + return new CacheLookup<>(true, value); + } + + /** + * Purpose: miss supports MultiLevelCacheService.java by holding or executing the miss business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static CacheLookup miss() { + return new CacheLookup<>(false, null); + } + } + + @Getter + @RequiredArgsConstructor + /** + * Purpose: LocalCacheEntry supports MultiLevelCacheService.java by holding or executing the local cache entry business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class LocalCacheEntry { + /** + * Purpose: json supports MultiLevelCacheService.java by holding or executing the json business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final String json; + /** + * Purpose: expireAt supports MultiLevelCacheService.java by holding or executing the expire at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long expireAt; + + /** + * Purpose: isExpired supports MultiLevelCacheService.java by holding or executing the is expired business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isExpired() { + return System.currentTimeMillis() >= expireAt; + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/id/TimeOrderedSnowflakeIdGenerator.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/id/TimeOrderedSnowflakeIdGenerator.java new file mode 100644 index 00000000..9dacfdd3 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/id/TimeOrderedSnowflakeIdGenerator.java @@ -0,0 +1,275 @@ +package com.xiaowang.jayucloud.artlist.core.support.id; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.lang.management.ManagementFactory; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.nio.charset.StandardCharsets; +import java.util.Enumeration; +import java.util.Locale; + +/** + * 时间高位雪花 ID 生成器。 + * 统一为数据库主键和业务有序标识提供趋势递增的唯一 ID。 + */ +@Slf4j +@Component +public class TimeOrderedSnowflakeIdGenerator { + + /** + * Purpose: DEFAULT_EPOCH supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the default epoch business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DEFAULT_EPOCH = 1704067200000L; + /** + * Purpose: WORKER_ID_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id bits business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long WORKER_ID_BITS = 5L; + /** + * Purpose: DATACENTER_ID_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id bits business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DATACENTER_ID_BITS = 5L; + /** + * Purpose: SEQUENCE_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the sequence bits business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long SEQUENCE_BITS = 12L; + private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); + private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); + private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); + /** + * Purpose: WORKER_ID_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id shift business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; + /** + * Purpose: DATACENTER_ID_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id shift business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; + /** + * Purpose: TIMESTAMP_LEFT_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the timestamp left shift business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; + + /** + * Purpose: epoch supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the epoch business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long epoch; + /** + * Purpose: workerId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long workerId; + /** + * Purpose: datacenterId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long datacenterId; + + /** + * Purpose: sequence supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the sequence business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long sequence = 0L; + /** + * Purpose: lastTimestamp supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the last timestamp business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long lastTimestamp = -1L; + + public TimeOrderedSnowflakeIdGenerator( + @Value("${snowflake.epoch:" + DEFAULT_EPOCH + "}") long configuredEpoch, + @Value("${snowflake.worker-id:-1}") long configuredWorkerId, + @Value("${snowflake.datacenter-id:-1}") long configuredDatacenterId, + @Value("${spring.application.name:jc-artlist-core}") String applicationName + ) { + this.epoch = configuredEpoch > 0 ? configuredEpoch : DEFAULT_EPOCH; + this.datacenterId = resolveNodeId(configuredDatacenterId, MAX_DATACENTER_ID, resolveDatacenterId()); + this.workerId = resolveNodeId(configuredWorkerId, MAX_WORKER_ID, resolveWorkerId(applicationName)); + log.info("Snowflake generator ready: app={}, epoch={}, datacenterId={}, workerId={}", + applicationName, this.epoch, this.datacenterId, this.workerId); + } + + /** + * Purpose: nextId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public synchronized long nextId() { + long timestamp = currentTimeMillis(); + if (timestamp < lastTimestamp) { + timestamp = waitUntil(lastTimestamp); + } + + if (timestamp == lastTimestamp) { + sequence = (sequence + 1) & SEQUENCE_MASK; + if (sequence == 0L) { + timestamp = waitUntilNextMillis(lastTimestamp); + } + } else { + sequence = 0L; + } + + lastTimestamp = timestamp; + return ((timestamp - epoch) << TIMESTAMP_LEFT_SHIFT) + | (datacenterId << DATACENTER_ID_SHIFT) + | (workerId << WORKER_ID_SHIFT) + | sequence; + } + + /** + * Purpose: nextIdString supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next id string business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String nextIdString() { + return Long.toUnsignedString(nextId()); + } + + /** + * Purpose: nextBase36String supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next base36 string business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String nextBase36String(int width) { + String raw = Long.toUnsignedString(nextId(), 36).toUpperCase(Locale.ROOT); + if (raw.length() >= width) { + return raw.substring(raw.length() - width); + } + return "0".repeat(width - raw.length()) + raw; + } + + /** + * Purpose: currentTimeMillis supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the current time millis business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long currentTimeMillis() { + return System.currentTimeMillis(); + } + + /** + * Purpose: waitUntil supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the wait until business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long waitUntil(long targetTimestamp) { + long timestamp = currentTimeMillis(); + while (timestamp < targetTimestamp) { + Thread.yield(); + timestamp = currentTimeMillis(); + } + return timestamp; + } + + /** + * Purpose: waitUntilNextMillis supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the wait until next millis business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long waitUntilNextMillis(long currentTimestamp) { + long timestamp = currentTimeMillis(); + while (timestamp <= currentTimestamp) { + Thread.yield(); + timestamp = currentTimeMillis(); + } + return timestamp; + } + + /** + * Purpose: resolveNodeId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve node id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long resolveNodeId(long configuredValue, long maxValue, long fallbackValue) { + long candidate = configuredValue >= 0 ? configuredValue : fallbackValue; + return Math.floorMod(candidate, maxValue + 1); + } + + /** + * Purpose: resolveDatacenterId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve datacenter id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long resolveDatacenterId() { + return stableHash(resolveMachineFingerprint()); + } + + /** + * Purpose: resolveWorkerId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve worker id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long resolveWorkerId(String applicationName) { + return stableHash(applicationName + ":" + resolveProcessFingerprint()); + } + + /** + * Purpose: resolveMachineFingerprint supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve machine fingerprint business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveMachineFingerprint() { + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces != null && interfaces.hasMoreElements()) { + NetworkInterface networkInterface = interfaces.nextElement(); + if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual()) { + continue; + } + byte[] hardwareAddress = networkInterface.getHardwareAddress(); + if (hardwareAddress != null && hardwareAddress.length > 0) { + return bytesToHex(hardwareAddress); + } + } + } catch (Exception exception) { + log.warn("Unable to resolve hardware address for snowflake datacenter id", exception); + } + + try { + return InetAddress.getLocalHost().getHostAddress(); + } catch (Exception exception) { + log.warn("Unable to resolve host address for snowflake datacenter id", exception); + return "fallback-host"; + } + } + + /** + * Purpose: resolveProcessFingerprint supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve process fingerprint business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveProcessFingerprint() { + try { + return ManagementFactory.getRuntimeMXBean().getName(); + } catch (Exception exception) { + return "pid-unknown"; + } + } + + /** + * Purpose: stableHash supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the stable hash business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long stableHash(String value) { + if (value == null || value.isEmpty()) { + return 0L; + } + long hash = 1469598103934665603L; + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + for (byte currentByte : bytes) { + hash ^= currentByte; + hash *= 1099511628211L; + } + return hash & Long.MAX_VALUE; + } + + /** + * Purpose: bytesToHex supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the bytes to hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String bytesToHex(byte[] source) { + StringBuilder builder = new StringBuilder(source.length * 2); + for (byte currentByte : source) { + builder.append(String.format("%02X", currentByte)); + } + return builder.toString(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/CachedBodyHttpServletRequest.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/CachedBodyHttpServletRequest.java new file mode 100644 index 00000000..da21fc90 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/CachedBodyHttpServletRequest.java @@ -0,0 +1,87 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * 可重复读取 body 的请求包装。 + */ +public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper { + + /** + * Purpose: cachedBody supports CachedBodyHttpServletRequest.java by holding or executing the cached body business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final byte[] cachedBody; + + public CachedBodyHttpServletRequest(HttpServletRequest request, byte[] cachedBody) { + super(request); + this.cachedBody = cachedBody == null ? new byte[0] : cachedBody; + } + + @Override + /** + * Purpose: getInputStream supports CachedBodyHttpServletRequest.java by holding or executing the get input stream business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public ServletInputStream getInputStream() { + ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody); + return new ServletInputStream() { + @Override + /** + * Purpose: isFinished supports CachedBodyHttpServletRequest.java by holding or executing the is finished business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isFinished() { + return inputStream.available() == 0; + } + + @Override + /** + * Purpose: isReady supports CachedBodyHttpServletRequest.java by holding or executing the is ready business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isReady() { + return true; + } + + @Override + /** + * Purpose: setReadListener supports CachedBodyHttpServletRequest.java by holding or executing the set read listener business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void setReadListener(ReadListener readListener) { + // no-op + } + + @Override + /** + * Purpose: read supports CachedBodyHttpServletRequest.java by holding or executing the read business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public int read() { + return inputStream.read(); + } + }; + } + + @Override + /** + * Purpose: getReader supports CachedBodyHttpServletRequest.java by holding or executing the get reader business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public BufferedReader getReader() throws IOException { + Charset charset = getCharacterEncoding() == null + ? StandardCharsets.UTF_8 + : Charset.forName(getCharacterEncoding()); + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java new file mode 100644 index 00000000..89239fff --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java @@ -0,0 +1,384 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static com.xiaowang.jayucloud.artlist.core.support.security.RequestSignatureService.REQUEST_BODY_ATTRIBUTE; + +@Component +@RequiredArgsConstructor +/** + * Purpose: OperationGuardService supports OperationGuardService.java by holding or executing the operation guard service business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OperationGuardService { + + private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); + + static { + RELEASE_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) " + + "else return 0 end" + ); + RELEASE_LOCK_SCRIPT.setResultType(Long.class); + } + + private static final TypeReference> MAP_TYPE = new TypeReference<>() { + }; + + /** + * Purpose: stringRedisTemplate supports OperationGuardService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: objectMapper supports OperationGuardService.java by holding or executing the object mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ObjectMapper objectMapper; + + /** + * Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public GuardHandle tryAcquire(HttpServletRequest request, String action, Duration ttl) { + String key = buildKey(request, action); + String token = UUID.randomUUID().toString(); + Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( + key, + token, + Math.max(1L, ttl == null ? 10L : ttl.getSeconds()), + TimeUnit.SECONDS + ); + return new GuardHandle(key, token, Boolean.TRUE.equals(success)); + } + + /** + * Purpose: release supports OperationGuardService.java by holding or executing the release business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void release(GuardHandle handle) { + if (handle == null || !handle.acquired()) { + return; + } + stringRedisTemplate.execute( + RELEASE_LOCK_SCRIPT, + Collections.singletonList(handle.key()), + handle.token() + ); + } + + /** + * Purpose: buildKey supports OperationGuardService.java by holding or executing the build key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String buildKey(HttpServletRequest request, String action) { + String safeAction = sanitize(action); + String path = request == null ? "-" : sanitize(request.getRequestURI()); + Long userId = request == null ? null : parseLong(request.getAttribute("userId")); + Integer userType = request == null ? null : parseInteger(request.getAttribute("userType")); + Long shopId = request == null ? null : RequestShopContext.getCurrentShopId(request); + + if (isUploadPath(path)) { + return buildUploadKey(request, safeAction, userId); + } + + String fingerprint = buildRequestFingerprint(request, path); + if (userId != null) { + if (isAdminRequest(path, userType)) { + return String.join(":", + "op", + "admin", + String.valueOf(userId), + safeAction, + sanitize(shopId), + fingerprint + ); + } + return String.join(":", + "op", + "user", + String.valueOf(userId), + safeAction, + fingerprint + ); + } + + String subject = resolvePublicSubject(request); + return String.join(":", + "op", + "public", + safeAction, + subject, + sanitize(resolveClientIp(request)), + sanitize(resolveDeviceId(request)) + ); + } + + /** + * Purpose: buildUploadKey supports OperationGuardService.java by holding or executing the build upload key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildUploadKey(HttpServletRequest request, String action, Long userId) { + String uploadId = firstNonBlank( + request == null ? null : request.getParameter("uploadId"), + readBodyField(request, "uploadId") + ); + String chunkIndex = firstNonBlank( + request == null ? null : request.getParameter("chunkIndex"), + readBodyField(request, "chunkIndex") + ); + String suffix = StringUtils.hasText(chunkIndex) + ? sanitize(chunkIndex) + : buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); + return String.join(":", + "op", + "upload", + sanitize(userId), + action, + sanitize(uploadId), + suffix + ); + } + + /** + * Purpose: buildRequestFingerprint supports OperationGuardService.java by holding or executing the build request fingerprint business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildRequestFingerprint(HttpServletRequest request, String path) { + String canonicalParams = buildCanonicalParams(request == null ? null : request.getParameterMap()); + String bodyHash = buildBodyHash(request); + String raw = String.join("|", + sanitize(path), + sanitize(canonicalParams), + sanitize(bodyHash) + ); + return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: resolvePublicSubject supports OperationGuardService.java by holding or executing the resolve public subject business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolvePublicSubject(HttpServletRequest request) { + for (String key : new String[]{"account", "phone", "shopId", "productId", "couponId", "userId", "uploadId", "ticket"}) { + String value = firstNonBlank( + request == null ? null : request.getParameter(key), + readBodyField(request, key) + ); + if (StringUtils.hasText(value)) { + return sanitize(value); + } + } + return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); + } + + /** + * Purpose: buildBodyHash supports OperationGuardService.java by holding or executing the build body hash business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildBodyHash(HttpServletRequest request) { + if (request == null) { + return "-"; + } + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (cachedBody instanceof byte[] bytes && bytes.length > 0) { + return DigestUtils.md5DigestAsHex(bytes); + } + return DigestUtils.md5DigestAsHex( + buildCanonicalParams(request.getParameterMap()).getBytes(StandardCharsets.UTF_8) + ); + } + + /** + * Purpose: readBodyField supports OperationGuardService.java by holding or executing the read body field business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String readBodyField(HttpServletRequest request, String fieldName) { + if (request == null || !StringUtils.hasText(fieldName)) { + return null; + } + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (!(cachedBody instanceof byte[] bytes) || bytes.length == 0) { + return null; + } + try { + Map payload = objectMapper.readValue(bytes, MAP_TYPE); + Object value = payload.get(fieldName); + return value == null ? null : String.valueOf(value); + } catch (Exception ignored) { + return null; + } + } + + /** + * Purpose: buildCanonicalParams supports OperationGuardService.java by holding or executing the build canonical params business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildCanonicalParams(Map parameterMap) { + if (parameterMap == null || parameterMap.isEmpty()) { + return ""; + } + Map sorted = new LinkedHashMap<>(); + parameterMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .forEach(entry -> sorted.put(entry.getKey(), entry.getValue())); + StringBuilder builder = new StringBuilder(); + sorted.forEach((key, values) -> { + if (builder.length() > 0) { + builder.append('&'); + } + builder.append(key) + .append('=') + .append(String.join(",", sortValues(values))); + }); + return builder.toString(); + } + + /** + * Purpose: sortValues supports OperationGuardService.java by holding or executing the sort values business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String[] sortValues(String[] values) { + String[] copy = values == null ? new String[0] : values.clone(); + Arrays.sort(copy, Comparator.nullsLast(String::compareTo)); + return copy; + } + + /** + * Purpose: isUploadPath supports OperationGuardService.java by holding or executing the is upload path business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isUploadPath(String path) { + return StringUtils.hasText(path) && path.contains("/upload/"); + } + + /** + * Purpose: isAdminRequest supports OperationGuardService.java by holding or executing the is admin request business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isAdminRequest(String path, Integer userType) { + return (StringUtils.hasText(path) && (path.startsWith("/admin/") || path.startsWith("/order/admin/"))) + || (userType != null && userType >= 2); + } + + /** + * Purpose: resolveClientIp supports OperationGuardService.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return "-"; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + if (StringUtils.hasText(realIp)) { + return realIp.trim(); + } + return request.getRemoteAddr(); + } + + /** + * Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveDeviceId(HttpServletRequest request) { + if (request == null) { + return "-"; + } + return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER); + } + + /** + * Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sanitize(Object value) { + if (value == null) { + return "-"; + } + String text = String.valueOf(value).trim(); + return text.isEmpty() ? "-" : text.replace(":", "_"); + } + + /** + * Purpose: firstNonBlank supports OperationGuardService.java by holding or executing the first non blank business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String firstNonBlank(String... values) { + if (values == null) { + return null; + } + for (String value : values) { + if (StringUtils.hasText(value)) { + return value.trim(); + } + } + return null; + } + + /** + * Purpose: parseLong supports OperationGuardService.java by holding or executing the parse long business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long parseLong(Object value) { + if (value instanceof Number number) { + return number.longValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Long.parseLong(text.trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + /** + * Purpose: parseInteger supports OperationGuardService.java by holding or executing the parse integer business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer parseInteger(Object value) { + if (value instanceof Number number) { + return number.intValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Integer.parseInt(text.trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + /** + * Purpose: GuardHandle supports OperationGuardService.java by holding or executing the guard handle business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + public record GuardHandle(String key, String token, boolean acquired) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardStrategy.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardStrategy.java new file mode 100644 index 00000000..43d10a33 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardStrategy.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +/** + * Purpose: OperationGuardStrategy supports OperationGuardStrategy.java by holding or executing the operation guard strategy business role. + * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. + */ +public enum OperationGuardStrategy { + REJECT_IF_RUNNING, + NOOP_IF_DUPLICATE +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestSignatureService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestSignatureService.java new file mode 100644 index 00000000..90bf8e3e --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestSignatureService.java @@ -0,0 +1,238 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +import com.xiaowang.jayucloud.artlist.core.config.RequestSignatureProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * 已登录写接口签名校验。 + */ +@Component +@RequiredArgsConstructor +public class RequestSignatureService { + + /** + * Purpose: REQUEST_BODY_ATTRIBUTE supports RequestSignatureService.java by holding or executing the request body attribute business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String REQUEST_BODY_ATTRIBUTE = "cachedRequestBody"; + /** + * Purpose: HEADER_TIMESTAMP supports RequestSignatureService.java by holding or executing the header timestamp business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_TIMESTAMP = "X-Timestamp"; + /** + * Purpose: HEADER_NONCE supports RequestSignatureService.java by holding or executing the header nonce business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_NONCE = "X-Nonce"; + /** + * Purpose: HEADER_SIGNATURE supports RequestSignatureService.java by holding or executing the header signature business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_SIGNATURE = "X-Signature"; + /** + * Purpose: HEADER_SIGNATURE_VERSION supports RequestSignatureService.java by holding or executing the header signature version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_SIGNATURE_VERSION = "X-Sign-Version"; + + /** + * Purpose: SIGNATURE_VERSION supports RequestSignatureService.java by holding or executing the signature version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SIGNATURE_VERSION = "v1"; + /** + * Purpose: HMAC_ALGORITHM supports RequestSignatureService.java by holding or executing the hmac algorithm business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String HMAC_ALGORITHM = "HmacSHA256"; + + /** + * Purpose: properties supports RequestSignatureService.java by holding or executing the properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestSignatureProperties properties; + /** + * Purpose: stringRedisTemplate supports RequestSignatureService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + + /** + * Purpose: validateRequest supports RequestSignatureService.java by holding or executing the validate request business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validateRequest(HttpServletRequest request, String accessToken, Long userId) { + if (!properties.isEnabled() || isSafeMethod(request.getMethod())) { + return; + } + if (!StringUtils.hasText(accessToken)) { + throw new RuntimeException("请求签名缺少登录态"); + } + + String version = request.getHeader(HEADER_SIGNATURE_VERSION); + String timestamp = request.getHeader(HEADER_TIMESTAMP); + String nonce = request.getHeader(HEADER_NONCE); + String signature = request.getHeader(HEADER_SIGNATURE); + + if (!SIGNATURE_VERSION.equals(version)) { + throw new RuntimeException("请求签名版本不正确"); + } + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) { + throw new RuntimeException("请求签名缺失"); + } + + validateTimestamp(timestamp); + registerNonce(userId, nonce); + + String bodyHash = sha256Hex(resolvePayloadBytes(request)); + String canonical = request.getMethod().toUpperCase() + + "\n" + request.getRequestURI() + + "\n" + timestamp + + "\n" + nonce + + "\n" + bodyHash; + String expected = hmacSha256Hex(accessToken, canonical); + if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) { + throw new RuntimeException("请求签名无效"); + } + } + + /** + * Purpose: validateTimestamp supports RequestSignatureService.java by holding or executing the validate timestamp business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void validateTimestamp(String timestamp) { + long requestTimestamp; + try { + requestTimestamp = Long.parseLong(timestamp); + } catch (NumberFormatException exception) { + throw new RuntimeException("请求时间戳不合法"); + } + long now = Instant.now().toEpochMilli(); + long delta = Math.abs(now - requestTimestamp); + if (delta > properties.getWindowSeconds() * 1000L) { + throw new RuntimeException("请求已过期,请重试"); + } + } + + /** + * Purpose: registerNonce supports RequestSignatureService.java by holding or executing the register nonce business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void registerNonce(Long userId, String nonce) { + String nonceKey = "request:nonce:" + (userId == null ? "anon" : userId) + ":" + nonce; + Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( + nonceKey, + "1", + properties.getNonceRetentionSeconds(), + TimeUnit.SECONDS + ); + if (Boolean.FALSE.equals(success)) { + throw new RuntimeException("请求已失效,请勿重复提交"); + } + } + + /** + * Purpose: isSafeMethod supports RequestSignatureService.java by holding or executing the is safe method business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isSafeMethod(String method) { + if (!StringUtils.hasText(method)) { + return true; + } + String normalized = method.toUpperCase(); + return "GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized); + } + + /** + * Purpose: resolvePayloadBytes supports RequestSignatureService.java by holding or executing the resolve payload bytes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private byte[] resolvePayloadBytes(HttpServletRequest request) { + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (cachedBody instanceof byte[] bytes && bytes.length > 0) { + return bytes; + } + String canonicalParams = buildCanonicalParams(request.getParameterMap()); + return canonicalParams.getBytes(StandardCharsets.UTF_8); + } + + /** + * Purpose: buildCanonicalParams supports RequestSignatureService.java by holding or executing the build canonical params business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildCanonicalParams(Map parameterMap) { + if (parameterMap == null || parameterMap.isEmpty()) { + return ""; + } + return parameterMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + String.join(",", sorted(entry.getValue()))) + .reduce((left, right) -> left + "&" + right) + .orElse(""); + } + + /** + * Purpose: sorted supports RequestSignatureService.java by holding or executing the sorted business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String[] sorted(String[] values) { + String[] result = values == null ? new String[0] : values.clone(); + Arrays.sort(result, Comparator.nullsLast(String::compareTo)); + return result; + } + + /** + * Purpose: sha256Hex supports RequestSignatureService.java by holding or executing the sha256 hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sha256Hex(byte[] payload) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(payload == null ? new byte[0] : payload); + return toHex(bytes); + } catch (Exception exception) { + throw new RuntimeException("计算请求摘要失败", exception); + } + } + + /** + * Purpose: hmacSha256Hex supports RequestSignatureService.java by holding or executing the hmac sha256 hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String hmacSha256Hex(String secret, String text) { + try { + Mac mac = Mac.getInstance(HMAC_ALGORITHM); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM)); + return toHex(mac.doFinal(text.getBytes(StandardCharsets.UTF_8))); + } catch (Exception exception) { + throw new RuntimeException("计算请求签名失败", exception); + } + } + + /** + * Purpose: toHex supports RequestSignatureService.java by holding or executing the to hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String toHex(byte[] bytes) { + StringBuilder builder = new StringBuilder(bytes.length * 2); + for (byte value : bytes) { + builder.append(String.format("%02x", value)); + } + return builder.toString(); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java new file mode 100644 index 00000000..c6d0b117 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java @@ -0,0 +1,230 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +import com.xiaowang.jayucloud.artlist.core.config.LoginLockProperties; +import com.xiaowang.jayucloud.artlist.core.config.RateLimitProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +@Component +@RequiredArgsConstructor +/** + * Purpose: RequestThrottleService supports RequestThrottleService.java by holding or executing the request throttle service business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class RequestThrottleService { + + /** + * Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String DEVICE_ID_HEADER = "X-Device-Id"; + + /** + * Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: rateLimitProperties supports RequestThrottleService.java by holding or executing the rate limit properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RateLimitProperties rateLimitProperties; + /** + * Purpose: loginLockProperties supports RequestThrottleService.java by holding or executing the login lock properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LoginLockProperties loginLockProperties; + + /** + * Purpose: checkLogin supports RequestThrottleService.java by holding or executing the check login business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkLogin(HttpServletRequest request, String account) { + assertLoginNotLocked(request, account); + assertAllowed("login", request, sanitize(account), rateLimitProperties.getLogin(), "登录过于频繁,请稍后再试"); + } + + /** + * Purpose: checkRegister supports RequestThrottleService.java by holding or executing the check register business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkRegister(HttpServletRequest request, String account) { + assertAllowed("register", request, sanitize(account), rateLimitProperties.getRegister(), "注册过于频繁,请稍后再试"); + } + + /** + * Purpose: checkSendCode supports RequestThrottleService.java by holding or executing the check send code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkSendCode(HttpServletRequest request, String phone) { + assertAllowed("send-code", request, sanitize(phone), rateLimitProperties.getSendCode(), "验证码发送过于频繁,请稍后再试"); + } + + /** + * Purpose: checkResetPassword supports RequestThrottleService.java by holding or executing the check reset password business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkResetPassword(HttpServletRequest request, String phone) { + assertAllowed("reset-password", request, sanitize(phone), rateLimitProperties.getResetPassword(), "密码重置请求过于频繁,请稍后再试"); + } + + /** + * Purpose: checkWechatMiniLogin supports RequestThrottleService.java by holding or executing the check wechat mini login business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkWechatMiniLogin(HttpServletRequest request, String subject) { + assertAllowed("wechat-mini-login", request, sanitize(subject), rateLimitProperties.getWechatMiniLogin(), "微信登录过于频繁,请稍后再试"); + } + + /** + * Purpose: checkAgreementRead supports RequestThrottleService.java by holding or executing the check agreement read business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkAgreementRead(HttpServletRequest request, String agreementType) { + assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试"); + } + + /** + * Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkAuthenticatedWrite(HttpServletRequest request, Long userId) { + String path = request.getRequestURI(); + RateLimitProperties.LimitRule rule = rateLimitProperties.getAuthenticatedWrite(); + String message = "操作过于频繁,请稍后再试"; + String category = "write:" + path; + if ("/order/create".equals(path)) { + rule = rateLimitProperties.getOrderCreate(); + message = "下单过于频繁,请稍后再试"; + } + assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); + } + + /** + * Purpose: recordLoginFailure supports RequestThrottleService.java by holding or executing the record login failure business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void recordLoginFailure(HttpServletRequest request, String account) { + if (loginLockProperties.getMaxFailures() <= 0 || loginLockProperties.getWindowSeconds() <= 0) { + return; + } + String key = buildLoginFailureKey(request, account); + Long count = stringRedisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + stringRedisTemplate.expire(key, loginLockProperties.getWindowSeconds(), TimeUnit.SECONDS); + } + if (count != null && count >= loginLockProperties.getMaxFailures()) { + stringRedisTemplate.opsForValue().set(buildLoginLockKey(request, account), "1", loginLockProperties.getLockSeconds(), TimeUnit.SECONDS); + } + } + + /** + * Purpose: clearLoginFailure supports RequestThrottleService.java by holding or executing the clear login failure business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void clearLoginFailure(HttpServletRequest request, String account) { + stringRedisTemplate.delete(buildLoginFailureKey(request, account)); + stringRedisTemplate.delete(buildLoginLockKey(request, account)); + } + + private void assertAllowed(String category, + HttpServletRequest request, + String subject, + RateLimitProperties.LimitRule rule, + String message) { + if (rule == null || rule.getLimit() <= 0 || rule.getWindowSeconds() <= 0) { + return; + } + String raw = String.join("|", + category, + sanitize(resolveClientIp(request)), + sanitize(resolveDeviceId(request)), + sanitize(subject) + ); + String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + Long count = stringRedisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + stringRedisTemplate.expire(key, rule.getWindowSeconds(), TimeUnit.SECONDS); + } + if (count != null && count > rule.getLimit()) { + throw new RuntimeException(message); + } + } + + /** + * Purpose: assertLoginNotLocked supports RequestThrottleService.java by holding or executing the assert login not locked business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void assertLoginNotLocked(HttpServletRequest request, String account) { + Boolean locked = stringRedisTemplate.hasKey(buildLoginLockKey(request, account)); + if (Boolean.TRUE.equals(locked)) { + throw new RuntimeException("登录失败次数过多,请稍后再试"); + } + } + + /** + * Purpose: buildLoginFailureKey supports RequestThrottleService.java by holding or executing the build login failure key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildLoginFailureKey(HttpServletRequest request, String account) { + return "login:fail:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: buildLoginLockKey supports RequestThrottleService.java by holding or executing the build login lock key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildLoginLockKey(HttpServletRequest request, String account) { + return "login:lock:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: buildLoginLockRaw supports RequestThrottleService.java by holding or executing the build login lock raw business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildLoginLockRaw(HttpServletRequest request, String account) { + return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account)); + } + + /** + * Purpose: resolveClientIp supports RequestThrottleService.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return "-"; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + if (StringUtils.hasText(realIp)) { + return realIp.trim(); + } + return request.getRemoteAddr(); + } + + /** + * Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveDeviceId(HttpServletRequest request) { + return request == null ? null : request.getHeader(DEVICE_ID_HEADER); + } + + /** + * Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sanitize(String value) { + return StringUtils.hasText(value) ? value.trim() : "-"; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UploadSecurityValidator.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UploadSecurityValidator.java new file mode 100644 index 00000000..b9d2a869 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UploadSecurityValidator.java @@ -0,0 +1,146 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +import com.xiaowang.jayucloud.artlist.core.config.UploadSecurityProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Locale; +import java.util.Set; + +@Component +@RequiredArgsConstructor +/** + * Purpose: UploadSecurityValidator supports UploadSecurityValidator.java by holding or executing the upload security validator business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UploadSecurityValidator { + + private static final Set BLOCKED_EXTENSIONS = Set.of( + ".jsp", ".jspx", ".php", ".asp", ".aspx", ".js", ".html", ".htm", ".exe", ".bat", ".cmd", ".sh", ".jar" + ); + + private static final Set IMAGE_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".webp", ".gif"); + + private static final Set COMPATIBLE_IMAGE_MIME_TYPES = Set.of( + "image/jpeg", + "image/jpg", + "image/pjpeg", + "image/png", + "image/webp", + "image/gif" + ); + + /** + * Purpose: properties supports UploadSecurityValidator.java by holding or executing the properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UploadSecurityProperties properties; + + /** + * Purpose: validate supports UploadSecurityValidator.java by holding or executing the validate business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validate(MultipartFile file) { + if (file == null || file.isEmpty()) { + throw new RuntimeException("上传文件不能为空"); + } + if (file.getSize() > properties.getMaxSize()) { + throw new RuntimeException("上传文件过大"); + } + String filename = file.getOriginalFilename(); + String extension = resolveExtension(filename); + if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + String contentType = normalizeContentType(file.getContentType()); + if (!contentType.isEmpty() && !isAllowedMimeType(contentType)) { + throw new RuntimeException("文件 MIME 类型不允许"); + } + if (isLikelyImage(extension, contentType) && !IMAGE_EXTENSIONS.contains(extension)) { + throw new RuntimeException("图片文件扩展名不匹配"); + } + } + + /** + * Purpose: validateMetadata supports UploadSecurityValidator.java by holding or executing the validate metadata business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validateMetadata(String filename, String contentType, Long fileSize) { + if (fileSize == null || fileSize <= 0 || fileSize > properties.getMaxTotalSize()) { + throw new RuntimeException("上传文件大小不合法"); + } + String extension = resolveExtension(filename); + if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + String normalizedContentType = normalizeContentType(contentType); + if (!normalizedContentType.isEmpty() && !isAllowedMimeType(normalizedContentType)) { + throw new RuntimeException("文件 MIME 类型不允许"); + } + } + + /** + * Purpose: validateChunk supports UploadSecurityValidator.java by holding or executing the validate chunk business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validateChunk(MultipartFile chunkFile) { + if (chunkFile == null || chunkFile.isEmpty()) { + throw new RuntimeException("上传分片不能为空"); + } + if (chunkFile.getSize() > properties.getMaxSize()) { + throw new RuntimeException("上传文件过大"); + } + String filename = chunkFile.getOriginalFilename(); + String extension = resolveExtension(filename); + if (StringUtils.hasText(extension) && BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + } + + /** + * Purpose: isAllowedMimeType supports UploadSecurityValidator.java by holding or executing the is allowed mime type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isAllowedMimeType(String contentType) { + return properties.getAllowedMimeTypes().contains(contentType) || COMPATIBLE_IMAGE_MIME_TYPES.contains(contentType); + } + + /** + * Purpose: isLikelyImage supports UploadSecurityValidator.java by holding or executing the is likely image business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isLikelyImage(String extension, String contentType) { + return IMAGE_EXTENSIONS.contains(extension) || contentType.startsWith("image/"); + } + + /** + * Purpose: normalizeContentType supports UploadSecurityValidator.java by holding or executing the normalize content type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String normalizeContentType(String contentType) { + return StringUtils.hasText(contentType) ? contentType.toLowerCase(Locale.ROOT).trim() : ""; + } + + /** + * Purpose: resolveExtension supports UploadSecurityValidator.java by holding or executing the resolve extension business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveExtension(String filename) { + if (!StringUtils.hasText(filename) || !filename.contains(".")) { + return ""; + } + String normalized = filename.trim(); + int queryIndex = normalized.indexOf('?'); + if (queryIndex >= 0) { + normalized = normalized.substring(0, queryIndex); + } + int fragmentIndex = normalized.indexOf('#'); + if (fragmentIndex >= 0) { + normalized = normalized.substring(0, fragmentIndex); + } + int dotIndex = normalized.lastIndexOf("."); + return dotIndex >= 0 ? normalized.substring(dotIndex).toLowerCase(Locale.ROOT) : ""; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java new file mode 100644 index 00000000..70c3feae --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java @@ -0,0 +1,254 @@ +package com.xiaowang.jayucloud.artlist.core.support.security; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.artlist.core.config.JwtProperties; +import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * 基于 Redis 的登录会话状态。 + */ +@Component +@RequiredArgsConstructor +public class UserSessionService { + + /** + * Purpose: SESSION_KEY_PREFIX supports UserSessionService.java by holding or executing the session key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SESSION_KEY_PREFIX = "auth:session:"; + /** + * Purpose: USER_SESSION_SET_PREFIX supports UserSessionService.java by holding or executing the user session set prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:"; + + /** + * Purpose: stringRedisTemplate supports UserSessionService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: objectMapper supports UserSessionService.java by holding or executing the object mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ObjectMapper objectMapper; + /** + * Purpose: jwtProperties supports UserSessionService.java by holding or executing the jwt properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtProperties jwtProperties; + /** + * Purpose: idGenerator supports UserSessionService.java by holding or executing the id generator business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final TimeOrderedSnowflakeIdGenerator idGenerator; + + /** + * Purpose: issueSession supports UserSessionService.java by holding or executing the issue session business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public SessionIssueResult issueSession(Long userId, String account, Long shopId, Integer userType) { + String sessionId = idGenerator.nextIdString(); + String accessJti = idGenerator.nextIdString(); + String refreshJti = idGenerator.nextIdString(); + SessionState state = SessionState.builder() + .sessionId(sessionId) + .userId(userId) + .account(account) + .shopId(shopId) + .userType(userType) + .accessJti(accessJti) + .refreshJti(refreshJti) + .build(); + save(state); + return new SessionIssueResult(sessionId, accessJti, refreshJti); + } + + /** + * Purpose: rotateSession supports UserSessionService.java by holding or executing the rotate session business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public SessionIssueResult rotateSession(String previousSessionId, Long userId, String account, Long shopId, Integer userType) { + revokeSession(previousSessionId); + return issueSession(userId, account, shopId, userType); + } + + /** + * Purpose: isAccessSessionActive supports UserSessionService.java by holding or executing the is access session active business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isAccessSessionActive(Long userId, String sessionId, String accessJti) { + SessionState state = getSessionState(sessionId); + return matches(state, userId) && StringUtils.hasText(accessJti) && accessJti.equals(state.getAccessJti()); + } + + /** + * Purpose: isRefreshSessionActive supports UserSessionService.java by holding or executing the is refresh session active business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isRefreshSessionActive(Long userId, String sessionId, String refreshJti) { + SessionState state = getSessionState(sessionId); + return matches(state, userId) && StringUtils.hasText(refreshJti) && refreshJti.equals(state.getRefreshJti()); + } + + /** + * Purpose: revokeSession supports UserSessionService.java by holding or executing the revoke session business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void revokeSession(String sessionId) { + if (!StringUtils.hasText(sessionId)) { + return; + } + SessionState state = getSessionState(sessionId); + stringRedisTemplate.delete(buildSessionKey(sessionId)); + if (state != null && state.getUserId() != null) { + stringRedisTemplate.opsForSet().remove(buildUserSessionSetKey(state.getUserId()), sessionId); + } + } + + /** + * Purpose: revokeAllUserSessions supports UserSessionService.java by holding or executing the revoke all user sessions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void revokeAllUserSessions(Long userId) { + if (userId == null) { + return; + } + String setKey = buildUserSessionSetKey(userId); + Set sessionIds = stringRedisTemplate.opsForSet().members(setKey); + if (sessionIds != null) { + for (String sessionId : sessionIds) { + stringRedisTemplate.delete(buildSessionKey(sessionId)); + } + } + stringRedisTemplate.delete(setKey); + } + + /** + * Purpose: matches supports UserSessionService.java by holding or executing the matches business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean matches(SessionState state, Long userId) { + return state != null && state.getUserId() != null && state.getUserId().equals(userId); + } + + /** + * Purpose: save supports UserSessionService.java by holding or executing the save business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void save(SessionState state) { + try { + String sessionKey = buildSessionKey(state.getSessionId()); + String setKey = buildUserSessionSetKey(state.getUserId()); + Duration ttl = Duration.ofSeconds(jwtProperties.getRefreshTokenExpirationSeconds()); + String json = objectMapper.writeValueAsString(state); + stringRedisTemplate.opsForValue().set(sessionKey, json, ttl.getSeconds(), TimeUnit.SECONDS); + stringRedisTemplate.opsForSet().add(setKey, state.getSessionId()); + stringRedisTemplate.expire(setKey, ttl.getSeconds(), TimeUnit.SECONDS); + } catch (JsonProcessingException exception) { + throw new RuntimeException("写入登录会话失败", exception); + } + } + + /** + * Purpose: getSessionState supports UserSessionService.java by holding or executing the get session state business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SessionState getSessionState(String sessionId) { + if (!StringUtils.hasText(sessionId)) { + return null; + } + String json = stringRedisTemplate.opsForValue().get(buildSessionKey(sessionId)); + if (!StringUtils.hasText(json)) { + return null; + } + try { + return objectMapper.readValue(json, SessionState.class); + } catch (JsonProcessingException exception) { + stringRedisTemplate.delete(buildSessionKey(sessionId)); + return null; + } + } + + /** + * Purpose: buildSessionKey supports UserSessionService.java by holding or executing the build session key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildSessionKey(String sessionId) { + return SESSION_KEY_PREFIX + sessionId; + } + + /** + * Purpose: buildUserSessionSetKey supports UserSessionService.java by holding or executing the build user session set key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildUserSessionSetKey(Long userId) { + return USER_SESSION_SET_PREFIX + userId; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + /** + * Purpose: SessionState supports UserSessionService.java by holding or executing the session state business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class SessionState { + /** + * Purpose: sessionId supports UserSessionService.java by holding or executing the session id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sessionId; + /** + * Purpose: userId supports UserSessionService.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: account supports UserSessionService.java by holding or executing the account business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String account; + /** + * Purpose: shopId supports UserSessionService.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + /** + * Purpose: userType supports UserSessionService.java by holding or executing the user type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer userType; + /** + * Purpose: accessJti supports UserSessionService.java by holding or executing the access jti business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String accessJti; + /** + * Purpose: refreshJti supports UserSessionService.java by holding or executing the refresh jti business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String refreshJti; + } + + /** + * Purpose: SessionIssueResult supports UserSessionService.java by holding or executing the session issue result business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + public record SessionIssueResult(String sessionId, String accessJti, String refreshJti) { + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/AccountValidationUtils.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/AccountValidationUtils.java new file mode 100644 index 00000000..70296a92 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/AccountValidationUtils.java @@ -0,0 +1,66 @@ +package com.xiaowang.jayucloud.artlist.core.utils; + +import org.springframework.util.StringUtils; + +import java.util.regex.Pattern; + +/** + * Purpose: AccountValidationUtils supports AccountValidationUtils.java by holding or executing the account validation utils business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class AccountValidationUtils { + + /** + * Purpose: ACCOUNT_REGEX supports AccountValidationUtils.java by holding or executing the account regex business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ACCOUNT_REGEX = "^[A-Za-z0-9]+$"; + private static final Pattern ACCOUNT_PATTERN = Pattern.compile(ACCOUNT_REGEX); + + private AccountValidationUtils() { + } + + /** + * Purpose: normalizeAccount supports AccountValidationUtils.java by holding or executing the normalize account business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String normalizeAccount(String account) { + return account == null ? "" : account.trim(); + } + + /** + * Purpose: ensureValidAccountFormat supports AccountValidationUtils.java by holding or executing the ensure valid account format business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static void ensureValidAccountFormat(String account) { + if (!StringUtils.hasText(account)) { + throw new RuntimeException("账号不能为空"); + } + if (!ACCOUNT_PATTERN.matcher(account).matches()) { + throw new RuntimeException("账号只能包含字母和数字"); + } + } + + /** + * Purpose: requireValidAccount supports AccountValidationUtils.java by holding or executing the require valid account business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String requireValidAccount(String account) { + String normalized = normalizeAccount(account); + ensureValidAccountFormat(normalized); + return normalized; + } + + /** + * Purpose: validateOptionalAccount supports AccountValidationUtils.java by holding or executing the validate optional account business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String validateOptionalAccount(String account) { + if (account == null) { + return null; + } + String normalized = normalizeAccount(account); + ensureValidAccountFormat(normalized); + return normalized; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/JwtUtil.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/JwtUtil.java new file mode 100644 index 00000000..f226b5f4 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/JwtUtil.java @@ -0,0 +1,236 @@ +package com.xiaowang.jayucloud.artlist.core.utils; + +import com.xiaowang.jayucloud.artlist.core.config.JwtProperties; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@Component +@RequiredArgsConstructor +/** + * Purpose: JwtUtil supports JwtUtil.java by holding or executing the jwt util business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class JwtUtil { + + /** + * Purpose: jwtProperties supports JwtUtil.java by holding or executing the jwt properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtProperties jwtProperties; + + /** + * Purpose: getKey supports JwtUtil.java by holding or executing the get key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SecretKey getKey() { + return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: generateAccessToken supports JwtUtil.java by holding or executing the generate access token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { + return generateAccessToken(userId, account, currentShopId, sessionId, jti, jwtProperties.getAccessTokenExpirationSeconds()); + } + + public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti, long expirationSeconds) { + Map claims = new HashMap<>(); + claims.put("userId", userId); + claims.put("account", account); + claims.put("type", "access"); + claims.put("sessionId", sessionId); + claims.put("jti", jti); + if (currentShopId != null && currentShopId > 0) { + claims.put("shopId", currentShopId); + } + return createToken(claims, userId.toString(), expirationSeconds * 1000); + } + + public long resolveAccessTokenExpirationSeconds(boolean rememberMe) { + return rememberMe + ? jwtProperties.getRememberMeAccessTokenExpirationSeconds() + : jwtProperties.getAccessTokenExpirationSeconds(); + } + + /** + * Purpose: generateRefreshToken supports JwtUtil.java by holding or executing the generate refresh token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String generateRefreshToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { + Map claims = new HashMap<>(); + claims.put("userId", userId); + claims.put("account", account); + claims.put("type", "refresh"); + claims.put("sessionId", sessionId); + claims.put("jti", jti); + if (currentShopId != null && currentShopId > 0) { + claims.put("shopId", currentShopId); + } + return createToken(claims, userId.toString(), jwtProperties.getRefreshTokenExpirationSeconds() * 1000); + } + + /** + * Purpose: createToken supports JwtUtil.java by holding or executing the create token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String createToken(Map claims, String subject, long expiration) { + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + expiration); + + return Jwts.builder() + .setClaims(claims) + .setSubject(subject) + .setIssuer(jwtProperties.getIssuer()) + .setIssuedAt(now) + .setExpiration(expiryDate) + .signWith(getKey(), SignatureAlgorithm.HS512) + .compact(); + } + + /** + * Purpose: parseToken supports JwtUtil.java by holding or executing the parse token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Claims parseToken(String token) { + return Jwts.parserBuilder() + .setSigningKey(getKey()) + .setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds()) + .requireIssuer(jwtProperties.getIssuer()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + /** + * Purpose: getUserIdFromToken supports JwtUtil.java by holding or executing the get user id from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long getUserIdFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("userId", Long.class); + } + + /** + * Purpose: getAccountFromToken supports JwtUtil.java by holding or executing the get account from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getAccountFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("account", String.class); + } + + /** + * Purpose: getTokenType supports JwtUtil.java by holding or executing the get token type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getTokenType(String token) { + Claims claims = parseToken(token); + return claims.get("type", String.class); + } + + /** + * Purpose: getSessionIdFromToken supports JwtUtil.java by holding or executing the get session id from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getSessionIdFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("sessionId", String.class); + } + + /** + * Purpose: getJtiFromToken supports JwtUtil.java by holding or executing the get jti from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getJtiFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("jti", String.class); + } + + /** + * Purpose: getIssuerFromToken supports JwtUtil.java by holding or executing the get issuer from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getIssuerFromToken(String token) { + Claims claims = parseToken(token); + return claims.getIssuer(); + } + + /** + * Purpose: getShopIdFromToken supports JwtUtil.java by holding or executing the get shop id from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long getShopIdFromToken(String token) { + Claims claims = parseToken(token); + Object value = claims.get("shopId"); + if (value == null) { + return null; + } + if (value instanceof Integer integer) { + return integer.longValue(); + } + if (value instanceof Long longValue) { + return longValue; + } + if (value instanceof String text) { + try { + return Long.parseLong(text); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + /** + * Purpose: isTokenExpired supports JwtUtil.java by holding or executing the is token expired business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isTokenExpired(String token) { + try { + Claims claims = parseToken(token); + return claims.getExpiration().before(new Date()); + } catch (Exception e) { + return true; + } + } + + /** + * Purpose: validateToken supports JwtUtil.java by holding or executing the validate token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean validateToken(String token) { + try { + parseToken(token); + return !isTokenExpired(token); + } catch (Exception e) { + return false; + } + } + + /** + * Purpose: isAccessToken supports JwtUtil.java by holding or executing the is access token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isAccessToken(String token) { + return "access".equals(getTokenType(token)); + } + + /** + * Purpose: isRefreshToken supports JwtUtil.java by holding or executing the is refresh token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isRefreshToken(String token) { + return "refresh".equals(getTokenType(token)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/RedisUtils.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/RedisUtils.java new file mode 100644 index 00000000..c6c1b68c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/utils/RedisUtils.java @@ -0,0 +1,253 @@ +package com.xiaowang.jayucloud.artlist.core.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * Redis工具类 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Component +public class RedisUtils { + + @Autowired + /** + * Purpose: redisTemplate supports RedisUtils.java by holding or executing the redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private RedisTemplate redisTemplate; + + /** + * 指定缓存失效时间 + * @param key 键 + * @param time 时间(秒) + * @return + */ + public boolean expire(String key, long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 根据key 获取过期时间 + * @param key 键 不能为null + * @return 时间(秒) 返回0代表为永久有效 + */ + public long getExpire(String key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + /** + * 判断key是否存在 + * @param key 键 + * @return true 存在 false不存在 + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 删除缓存 + * @param key 可以传一个值 或多个 + */ + @SuppressWarnings("unchecked") + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete((Collection) CollectionUtils.arrayToList(key)); + } + } + } + + // ============================String============================= + /** + * 普通缓存获取 + * @param key 键 + * @return 值 + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 普通缓存放入 + * @param key 键 + * @param value 值 + * @return true成功 false失败 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * @param key 键 + * @param value 值 + * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 + * @return true成功 false 失败 + */ + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + // ================================Hash================================= + /** + * HashGet + * @param key 键 不能为null + * @param item 项 不能为null + * @return 值 + */ + public Object hget(String key, String item) { + return redisTemplate.opsForHash().get(key, item); + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * @param key 键 + * @param item 项 + * @param value 值 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value) { + try { + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * @param key 键 + * @param item 项 + * @param value 值 + * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value, long time) { + try { + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 获取hashKey对应的所有键值 + * @param key 键 + * @return 对应的多个键值 + */ + public Map hmget(String key) { + return redisTemplate.opsForHash().entries(key); + } + + // ============================set============================= + /** + * 根据key获取Set中的所有值 + * @param key 键 + * @return + */ + public Set sGet(String key) { + try { + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将数据放入set缓存 + * @param key 键 + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSet(String key, Object... values) { + try { + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + // ===============================list================================= + /** + * 获取list缓存的内容 + * @param key 键 + * @param start 开始 + * @param end 结束 0 到 -1代表所有值 + * @return + */ + public List lGet(String key, long start, long end) { + try { + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将list放入缓存 + * @param key 键 + * @param value 值 + * @return + */ + public boolean lSet(String key, Object value) { + try { + redisTemplate.opsForList().rightPush(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/JC-ArtList-Core/src/main/resources/application.yaml b/JC-ArtList-Core/src/main/resources/application.yaml index a5f6cc9a..d10cea30 100644 --- a/JC-ArtList-Core/src/main/resources/application.yaml +++ b/JC-ArtList-Core/src/main/resources/application.yaml @@ -1,138 +1 @@ -spring: - datasource: - url: jdbc:mysql://localhost:3306/jayucloud_artlist?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai - servlet: - multipart: - max-file-size: 5MB - max-request-size: 10MB - jackson: - time-zone: Asia/Shanghai - date-format: yyyy-MM-dd HH:mm:ss - -logging: - pattern: - console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" - -server: - servlet: - encoding: - charset: UTF-8 - force: true - enabled: true - timezone: Asia/Shanghai - -mybatis: - configuration: - map-underscore-to-camel-case: true - -fingertip-designer: - brand: - message-template-name: ${PLATFORM_MESSAGE_TEMPLATE_NAME:FingertipDesigner} - manager-register-shop-description: ${PLATFORM_MANAGER_REGISTER_SHOP_DESCRIPTION:甲屿店务注册店铺} - security: - jwt: - issuer: fingertip-designer - access-token-expiration-seconds: 7200 - remember-me-access-token-expiration-seconds: 604800 - refresh-token-expiration-seconds: 604800 - clock-skew-seconds: 30 - signature: - enabled: true - window-seconds: 300 - nonce-retention-seconds: 600 - rate-limit: - login: - limit: 10 - window-seconds: 60 - send-code: - limit: 5 - window-seconds: 60 - reset-password: - limit: 5 - window-seconds: 600 - authenticated-write: - limit: 80 - window-seconds: 60 - order-create: - limit: 10 - window-seconds: 60 - cache: - local-max-size: 2048 - product-detail: - local-ttl-seconds: 120 - redis-ttl-seconds: 900 - product-list: - local-ttl-seconds: 60 - redis-ttl-seconds: 300 - product-search: - local-ttl-seconds: 60 - redis-ttl-seconds: 300 - shop: - local-ttl-seconds: 180 - redis-ttl-seconds: 900 - tag: - local-ttl-seconds: 300 - redis-ttl-seconds: 1200 - object-storage-file: - local-ttl-seconds: 300 - redis-ttl-seconds: 1800 - dashboard: - local-ttl-seconds: 30 - redis-ttl-seconds: 90 - slow-request: - enabled: true - threshold-ms: 300 - log-response-header-request-id: true - http-client: - connect-timeout-ms: 3000 - read-timeout-ms: 5000 - connection-request-timeout-ms: 1000 - max-total-connections: 200 - max-connections-per-route: 50 - -object-storage: - provider-order: - - MINIO - - QINIU_KODO - - ALIYUN_OSS - replica-required-providers: - - MINIO - - QINIU_KODO - - ALIYUN_OSS - primary-provider: MINIO - backup-provider: QINIU_KODO,ALIYUN_OSS - signed-url-expire-minutes: 60 - backup-queue-name: fingertip-designer.file.object-storage.backup.queue - backup-exchange-name: fingertip-designer.file.object-storage.backup.exchange - backup-routing-key: fingertip-designer.file.object-storage.backup - backup-retry-batch-limit: 500 - backup-retry-cron: "0 0 2 * * ?" - -qiniu: - kodo: - access-key: ${QINIU_KODO_ACCESS_KEY:} - secret-key: ${QINIU_KODO_SECRET_KEY:} - bucket-name: ${QINIU_KODO_BUCKET_NAME:} - domain: ${QINIU_KODO_DOMAIN:} - zone: ${QINIU_KODO_ZONE:z2} - private-bucket: ${QINIU_KODO_PRIVATE_BUCKET:true} - signed-url-expire-minutes: ${QINIU_KODO_SIGNED_URL_EXPIRE_MINUTES:60} - -minio: - enabled: ${MINIO_ENABLED:false} - endpoint: ${MINIO_ENDPOINT:} - bucket-name: ${MINIO_BUCKET_NAME:} - access-key: ${MINIO_ACCESS_KEY:} - secret-key: ${MINIO_SECRET_KEY:} - private-bucket: ${MINIO_PRIVATE_BUCKET:true} - signed-url-expire-minutes: ${MINIO_SIGNED_URL_EXPIRE_MINUTES:60} - -aliyun: - oss: - enabled: ${ALIYUN_OSS_ENABLED:false} - endpoint: ${ALIYUN_OSS_ENDPOINT:} - region: ${ALIYUN_OSS_REGION:} - bucket-name: ${ALIYUN_OSS_BUCKET_NAME:} - access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID:} - access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET:} - signed-url-expire-minutes: ${ALIYUN_OSS_SIGNED_URL_EXPIRE_MINUTES:60} +# 除 bootstrap.yaml 中的 Nacos 启动引导参数外,后端运行参数统一由 Nacos 配置源管理。 diff --git a/JC-ArtList-Core/src/main/resources/bootstrap.yaml b/JC-ArtList-Core/src/main/resources/bootstrap.yaml index f3f17fd9..618b53c8 100644 --- a/JC-ArtList-Core/src/main/resources/bootstrap.yaml +++ b/JC-ArtList-Core/src/main/resources/bootstrap.yaml @@ -5,26 +5,25 @@ spring: cloud: nacos: discovery: - # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 - server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} - # Nacos 命名空间,默认指向开发环境。 + # 运行环境可覆盖 Nacos 地址;未设置时使用开发配置中心。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} + # 运行环境可覆盖 Nacos 命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 服务注册分组。 - group: DEFAULT_GROUP + group: ${NACOS_GROUP:DEFAULT_GROUP} # 注册到 Nacos 的服务名。 - service: ${spring.application.name} + service: jc-artlist-core # 是否启用服务发现。 enabled: true # 是否将当前服务注册到 Nacos。 register-enabled: true - # Nacos 认证用户名。 - username: ${NACOS_USERNAME} - # Nacos 认证密码。 - password: ${NACOS_PASSWORD} + # Nacos 认证信息可由运行环境覆盖。 + username: ${NACOS_USERNAME:jayucloud} + password: ${NACOS_PASSWORD:122503wcy....} config: - # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 - server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} - # Nacos 配置中心命名空间,默认指向开发环境。 + # Nacos 配置中心与服务发现使用同一运行环境参数。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} + # Nacos 配置中心命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 配置分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} @@ -34,18 +33,17 @@ spring: file-extension: yaml # 是否启用配置中心。 enabled: true - # Nacos 认证用户名。 - username: ${NACOS_USERNAME} - # Nacos 认证密码。 - password: ${NACOS_PASSWORD} + # Nacos 认证信息可由运行环境覆盖。 + username: ${NACOS_USERNAME:jayucloud} + password: ${NACOS_PASSWORD:122503wcy....} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: secret.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: logging.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true diff --git a/JC-ArtList-Core/src/main/resources/log4j2.xml b/JC-ArtList-Core/src/main/resources/log4j2.xml index 9563d53c..4c1317a5 100644 --- a/JC-ArtList-Core/src/main/resources/log4j2.xml +++ b/JC-ArtList-Core/src/main/resources/log4j2.xml @@ -65,7 +65,7 @@ - + diff --git a/JC-ArtList-Frontend/.env.development b/JC-ArtList-Frontend/.env.development index 0d2962f0..0470730c 100644 --- a/JC-ArtList-Frontend/.env.development +++ b/JC-ArtList-Frontend/.env.development @@ -2,7 +2,7 @@ VITE_API_BASE_URL=/api VITE_ADMIN_API_BASE_URL=/admin/api VITE_DEV_PROXY_TARGET=http://127.0.0.1:80 VITE_APP_NAME=指尖设计师 -VITE_APP_NAME_EN=Fingertip Designer -VITE_APP_TITLE=Fingertip Designer 指尖设计师 +VITE_APP_NAME_EN=JayuCloud ArtList +VITE_APP_TITLE=JayuCloud ArtList 指尖设计师 VITE_ADMIN_APP_NAME=指尖设计师管理台 VITE_APP_SHORT_NAME=YN diff --git a/JC-ArtList-Frontend/.env.production b/JC-ArtList-Frontend/.env.production index ddefe686..a36920f8 100644 --- a/JC-ArtList-Frontend/.env.production +++ b/JC-ArtList-Frontend/.env.production @@ -1,7 +1,7 @@ VITE_API_BASE_URL=https://yunail.art/api VITE_ADMIN_API_BASE_URL=https://yunail.art/admin/api VITE_APP_NAME=指尖设计师 -VITE_APP_NAME_EN=Fingertip Designer -VITE_APP_TITLE=Fingertip Designer 指尖设计师 +VITE_APP_NAME_EN=JayuCloud ArtList +VITE_APP_TITLE=JayuCloud ArtList 指尖设计师 VITE_ADMIN_APP_NAME=指尖设计师管理台 VITE_APP_SHORT_NAME=YN diff --git a/JC-ArtList-Frontend/public/fingertip-designer-icon.svg b/JC-ArtList-Frontend/public/fingertip-designer-icon.svg deleted file mode 100644 index aebebf3e..00000000 --- a/JC-ArtList-Frontend/public/fingertip-designer-icon.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/JC-ArtList-Frontend/public/jayucloud-artlist-icon.svg b/JC-ArtList-Frontend/public/jayucloud-artlist-icon.svg new file mode 100644 index 00000000..585b398a --- /dev/null +++ b/JC-ArtList-Frontend/public/jayucloud-artlist-icon.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/JC-ArtList-Frontend/src/App.vue b/JC-ArtList-Frontend/src/App.vue index bca95544..01e36eb8 100644 --- a/JC-ArtList-Frontend/src/App.vue +++ b/JC-ArtList-Frontend/src/App.vue @@ -2,7 +2,7 @@
-
+
@@ -170,8 +170,8 @@ const showPopupMessage = (item: SystemMessageVO) => { icon: null, centered: true, width: 560, - class: 'fingertip-designer-system-message-dialog', - wrapClassName: 'fingertip-designer-system-message-wrap', + class: 'jayucloud-artlist-system-message-dialog', + wrapClassName: 'jayucloud-artlist-system-message-wrap', content: h(SystemMessageCard, { title: item.title || '系统消息', content: item.content || '', @@ -267,47 +267,47 @@ onUnmounted(() => { padding-bottom: 0; } -.fingertip-designer-date-picker-panel { +.jayucloud-artlist-date-picker-panel { padding: 6px; } -.fingertip-designer-date-picker-panel .ant-picker-panel-container { +.jayucloud-artlist-date-picker-panel .ant-picker-panel-container { overflow: hidden; border-radius: 12px; box-shadow: 0 18px 44px rgba(34, 40, 49, 0.18); } -.fingertip-designer-date-picker-panel .ant-picker-panel { +.jayucloud-artlist-date-picker-panel .ant-picker-panel { border: 0; } -.fingertip-designer-date-picker-panel .ant-picker-header { +.jayucloud-artlist-date-picker-panel .ant-picker-header { padding: 8px 12px; border-bottom-color: var(--theme-border); } -.fingertip-designer-date-picker-panel .ant-picker-header button { +.jayucloud-artlist-date-picker-panel .ant-picker-header button { min-width: 34px; height: 34px; border-radius: 8px; } -.fingertip-designer-date-picker-panel .ant-picker-header-view { +.jayucloud-artlist-date-picker-panel .ant-picker-header-view { line-height: 34px; font-weight: 700; } -.fingertip-designer-date-picker-panel .ant-picker-content th { +.jayucloud-artlist-date-picker-panel .ant-picker-content th { height: 34px; color: var(--text-secondary); font-weight: 600; } -.fingertip-designer-date-picker-panel .ant-picker-cell { +.jayucloud-artlist-date-picker-panel .ant-picker-cell { padding: 4px 0; } -.fingertip-designer-date-picker-panel .ant-picker-cell-inner { +.jayucloud-artlist-date-picker-panel .ant-picker-cell-inner { min-width: 34px; height: 34px !important; line-height: 34px !important; @@ -315,44 +315,44 @@ onUnmounted(() => { transition: background .18s ease, color .18s ease, transform .18s ease; } -.fingertip-designer-date-picker-panel .ant-picker-cell:hover .ant-picker-cell-inner { +.jayucloud-artlist-date-picker-panel .ant-picker-cell:hover .ant-picker-cell-inner { background: var(--theme-primary-soft); transform: translateY(-1px); } -.fingertip-designer-date-picker-panel .ant-picker-cell-selected .ant-picker-cell-inner, -.fingertip-designer-date-picker-panel .ant-picker-cell-range-start .ant-picker-cell-inner, -.fingertip-designer-date-picker-panel .ant-picker-cell-range-end .ant-picker-cell-inner { +.jayucloud-artlist-date-picker-panel .ant-picker-cell-selected .ant-picker-cell-inner, +.jayucloud-artlist-date-picker-panel .ant-picker-cell-range-start .ant-picker-cell-inner, +.jayucloud-artlist-date-picker-panel .ant-picker-cell-range-end .ant-picker-cell-inner { background: var(--theme-primary); color: #fff; font-weight: 700; } -.fingertip-designer-date-picker-panel .ant-picker-footer { +.jayucloud-artlist-date-picker-panel .ant-picker-footer { border-top-color: var(--theme-border); } -.fingertip-designer-date-time-panel .ant-picker-time-panel, -.fingertip-designer-time-panel .ant-picker-time-panel { +.jayucloud-artlist-date-time-panel .ant-picker-time-panel, +.jayucloud-artlist-time-panel .ant-picker-time-panel { min-width: 150px; } -.fingertip-designer-date-time-panel .ant-picker-time-panel-column, -.fingertip-designer-time-panel .ant-picker-time-panel-column { +.jayucloud-artlist-date-time-panel .ant-picker-time-panel-column, +.jayucloud-artlist-time-panel .ant-picker-time-panel-column { width: 76px; padding: 8px 6px; } -.fingertip-designer-date-time-panel .ant-picker-time-panel-cell-inner, -.fingertip-designer-time-panel .ant-picker-time-panel-cell-inner { +.jayucloud-artlist-date-time-panel .ant-picker-time-panel-cell-inner, +.jayucloud-artlist-time-panel .ant-picker-time-panel-cell-inner { height: 34px !important; line-height: 34px !important; border-radius: 8px !important; text-align: center; } -.fingertip-designer-date-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner, -.fingertip-designer-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner { +.jayucloud-artlist-date-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner, +.jayucloud-artlist-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner { background: var(--theme-primary-soft); color: var(--theme-primary); font-weight: 700; @@ -368,11 +368,11 @@ onUnmounted(() => { box-shadow: var(--theme-focus-shadow); } -.fingertip-designer-system-message-wrap .ant-modal { +.jayucloud-artlist-system-message-wrap .ant-modal { max-width: calc(100vw - 32px); } -.fingertip-designer-system-message-dialog .ant-modal-content { +.jayucloud-artlist-system-message-dialog .ant-modal-content { overflow: hidden; padding: 0; border-radius: 8px; @@ -380,21 +380,21 @@ onUnmounted(() => { box-shadow: 0 24px 70px rgba(38, 31, 36, 0.32); } -.fingertip-designer-system-message-dialog .ant-modal-confirm-body-wrapper { +.jayucloud-artlist-system-message-dialog .ant-modal-confirm-body-wrapper { margin: 0; } -.fingertip-designer-system-message-dialog .ant-modal-confirm-body { +.jayucloud-artlist-system-message-dialog .ant-modal-confirm-body { display: block; } -.fingertip-designer-system-message-dialog .ant-modal-confirm-content { +.jayucloud-artlist-system-message-dialog .ant-modal-confirm-content { max-width: none; margin: 0 !important; color: inherit; } -.fingertip-designer-system-message-dialog .ant-modal-confirm-btns { +.jayucloud-artlist-system-message-dialog .ant-modal-confirm-btns { display: flex; justify-content: stretch; margin: 0; @@ -402,7 +402,7 @@ onUnmounted(() => { background: var(--theme-card-bg); } -.fingertip-designer-system-message-dialog .popup-message-ok-button { +.jayucloud-artlist-system-message-dialog .popup-message-ok-button { width: 100%; height: 44px; border: 0; @@ -413,8 +413,8 @@ onUnmounted(() => { box-shadow: var(--theme-button-shadow); } -.fingertip-designer-system-message-dialog .popup-message-ok-button:hover, -.fingertip-designer-system-message-dialog .popup-message-ok-button:focus { +.jayucloud-artlist-system-message-dialog .popup-message-ok-button:hover, +.jayucloud-artlist-system-message-dialog .popup-message-ok-button:focus { color: #ffffff; background: linear-gradient(135deg, var(--theme-accent) 0%, var(--theme-secondary) 100%); } @@ -426,11 +426,11 @@ onUnmounted(() => { } @media (max-width: 640px) { - .fingertip-designer-system-message-dialog .ant-modal-content { + .jayucloud-artlist-system-message-dialog .ant-modal-content { border-radius: 8px; } - .fingertip-designer-system-message-dialog .popup-message-ok-button { + .jayucloud-artlist-system-message-dialog .popup-message-ok-button { width: 100%; } } diff --git a/JC-ArtList-Frontend/src/api/auth-free-paths.ts b/JC-ArtList-Frontend/src/api/auth-free-paths.ts index 3399ad81..e88ace4d 100644 --- a/JC-ArtList-Frontend/src/api/auth-free-paths.ts +++ b/JC-ArtList-Frontend/src/api/auth-free-paths.ts @@ -36,7 +36,7 @@ const normalizePathname = (url?: string) => { const withoutHash = raw.split('#')[0] || '' const withoutQuery = withoutHash.split('?')[0] || '' try { - return new URL(withoutQuery, 'http://fingertipdesigner.local').pathname + return new URL(withoutQuery, 'http://jayucloud-artlist.local').pathname } catch { return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}` } diff --git a/JC-ArtList-Frontend/src/components/BottomNav.vue b/JC-ArtList-Frontend/src/components/BottomNav.vue index 7bab1be2..55563242 100644 --- a/JC-ArtList-Frontend/src/components/BottomNav.vue +++ b/JC-ArtList-Frontend/src/components/BottomNav.vue @@ -259,7 +259,7 @@ const handleNavClick = (tab: string) => { diff --git a/JC-Salon-Frontend/src/views/admin/UsersView.vue b/JC-Salon-Frontend/src/views/admin/UsersView.vue index d46416ca..f8ec06a2 100644 --- a/JC-Salon-Frontend/src/views/admin/UsersView.vue +++ b/JC-Salon-Frontend/src/views/admin/UsersView.vue @@ -1,10 +1,10 @@