初始化:连锁餐饮数字化运营管理平台

This commit is contained in:
freedakgmail
2026-07-26 22:48:08 +08:00
commit a7874d79b5
67 changed files with 14391 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
import pg from 'pg'
const { Pool } = pg
const pool = new Pool({
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432'),
database: process.env.DB_NAME || 'bill_query',
user: process.env.DB_USER || 'freedak',
password: process.env.DB_PASSWORD || '',
max: parseInt(process.env.DB_POOL_MAX || '10'),
})
pool.on('error', (err) => {
console.error('Unexpected error on idle client', err)
})
export interface QueryResult<T = any> {
rows: T[]
rowCount: number | null
}
export async function query<T = any>(text: string, params?: any[]): Promise<QueryResult<T>> {
const start = Date.now()
const res = await pool.query(text, params)
const duration = Date.now() - start
if (duration > 500) {
console.warn(`Slow query (${duration}ms):`, text.substring(0, 100))
}
return res
}
export async function withTransaction<T>(callback: (client: pg.PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect()
try {
await client.query('BEGIN')
const result = await callback(client)
await client.query('COMMIT')
return result
} catch (err) {
await client.query('ROLLBACK')
throw err
} finally {
client.release()
}
}
export default pool
+42
View File
@@ -0,0 +1,42 @@
import 'dotenv/config'
import express from 'express'
import cors from 'cors'
import { authMiddleware, AuthRequest } from './middleware/auth.js'
import { errorHandler, notFoundHandler } from './middleware/error.js'
import authRoutes from './routes/auth.js'
import dataRoutes from './routes/data.js'
import taskRoutes from './routes/tasks.js'
const app = express()
const PORT = parseInt(process.env.PORT || '3001')
app.use(cors({
origin: process.env.CLIENT_URL || 'http://localhost:5173',
credentials: true,
}))
app.use(express.json())
app.get('/api/health', (req, res) => {
res.json({ success: true, data: { status: 'ok', time: new Date().toISOString() } })
})
app.use('/api/auth', authRoutes)
app.use((req, res, next) => {
if (req.path === '/api/health' || req.path.startsWith('/api/auth')) {
return next()
}
authMiddleware(req as AuthRequest, res, next)
})
app.use('/api', dataRoutes)
app.use('/api/tasks', taskRoutes)
app.use(notFoundHandler)
app.use(errorHandler)
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`)
})
export default app
+63
View File
@@ -0,0 +1,63 @@
import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import type { AuthUser, ApiResponse } from '../types/index.js'
const JWT_SECRET = process.env.JWT_SECRET || 'default-secret'
export interface AuthRequest extends Request {
user?: AuthUser
}
export function generateToken(user: AuthUser): string {
return jwt.sign(user, JWT_SECRET, { expiresIn: '7d' })
}
export function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization
if (!authHeader || !authHeader.startsWith('Bearer ')) {
const response: ApiResponse = { success: false, data: null, error: 'No token provided' }
return res.status(401).json(response)
}
const token = authHeader.substring(7)
try {
const decoded = jwt.verify(token, JWT_SECRET) as AuthUser
req.user = decoded
next()
} catch {
const response: ApiResponse = { success: false, data: null, error: 'Invalid or expired token' }
return res.status(401).json(response)
}
}
export function requireRole(...roles: string[]) {
return (req: AuthRequest, res: Response, next: NextFunction) => {
if (!req.user) {
const response: ApiResponse = { success: false, data: null, error: 'Not authenticated' }
return res.status(401).json(response)
}
if (!roles.includes(req.user.role)) {
const response: ApiResponse = { success: false, data: null, error: 'Insufficient permissions' }
return res.status(403).json(response)
}
next()
}
}
export function requireStoreAccess(req: AuthRequest, res: Response, next: NextFunction) {
if (!req.user) {
const response: ApiResponse = { success: false, data: null, error: 'Not authenticated' }
return res.status(401).json(response)
}
if (req.user.role === 'hq' || req.user.role === 'dept') {
return next()
}
if (req.user.role === 'store') {
const storeCode = req.params.code || req.params.storeCode || req.body.store_code
if (storeCode && storeCode !== req.user.storeCode) {
const response: ApiResponse = { success: false, data: null, error: 'Access denied to this store' }
return res.status(403).json(response)
}
}
next()
}
+43
View File
@@ -0,0 +1,43 @@
import { Request, Response, NextFunction } from 'express'
import type { ApiResponse } from '../types/index.js'
export function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) {
console.error('Error:', err.message)
const response: ApiResponse = {
success: false,
data: null,
error: err.message || 'Internal server error',
}
res.status(500).json(response)
}
export function notFoundHandler(req: Request, res: Response) {
const response: ApiResponse = {
success: false,
data: null,
error: `Route not found: ${req.method} ${req.path}`,
}
res.status(404).json(response)
}
export function sendSuccess<T>(res: Response, data: T, meta?: any) {
const response: ApiResponse<T> = { success: true, data, meta }
res.json(response)
}
export function sendError(res: Response, error: string, status = 400) {
const response: ApiResponse = { success: false, data: null, error }
res.status(status).json(response)
}
export function parseMonth(req: Request): string {
const month = (req.query.month as string) || '2026-04'
return month.length === 7 ? `${month}-01` : month
}
export function parsePagination(req: Request) {
const page = parseInt((req.query.page as string) || '1')
const pageSize = parseInt((req.query.page_size as string) || '50')
const offset = (page - 1) * pageSize
return { page, pageSize, offset }
}
+36
View File
@@ -0,0 +1,36 @@
import { Router } from 'express'
import { query } from '../config/database.js'
import { sendSuccess, sendError } from '../middleware/error.js'
import { generateToken } from '../middleware/auth.js'
import type { AuthUser } from '../types/index.js'
const router = Router()
const mockUsers: AuthUser[] = [
{ id: '1', role: 'hq', name: '总部管理员' },
{ id: '2', role: 'regional', name: '区域经理', region: '北京' },
{ id: '3', role: 'store', name: '潘家园店长', storeCode: '0026' },
{ id: '4', role: 'dept', name: '商品部', dept: 'product' },
]
router.post('/login', async (req, res) => {
const { username, password } = req.body
if (!username || !password) {
return sendError(res, 'Username and password required')
}
const user = mockUsers.find((u) => u.name === username || u.id === username)
if (!user) {
return sendError(res, 'Invalid credentials', 401)
}
const token = generateToken(user)
sendSuccess(res, { token, user })
})
router.get('/me', async (req: any, res) => {
if (!req.user) {
return sendError(res, 'Not authenticated', 401)
}
sendSuccess(res, req.user)
})
export default router
+376
View File
@@ -0,0 +1,376 @@
import { Router } from 'express'
import { query } from '../config/database.js'
import { sendSuccess, sendError, parseMonth, parsePagination } from '../middleware/error.js'
import type { AuthRequest } from '../middleware/auth.js'
const router = Router()
router.get('/overview', async (req: AuthRequest, res) => {
try {
const month = parseMonth(req)
const sql = `
SELECT count(*) AS bill_count,
round(sum(received_total), 2) AS received,
round(sum(received_total) / count(*), 2) AS avg_bill_value,
round(sum(discount_total) / nullif(sum(consumption), 0) * 100, 2) AS discount_rate_pct,
round(sum(theoretical_profit) / nullif(sum(received_total), 0) * 100, 2) AS theoretical_margin_pct,
count(*) FILTER (WHERE member_id IS NOT NULL) AS member_bills,
round(count(*) FILTER (WHERE member_id IS NOT NULL)::numeric / count(*) * 100, 2) AS member_share_pct
FROM analytics.bill_fact
WHERE closed_at >= $1::date
AND closed_at < ($1::date + interval '1 month')
AND closed_at IS NOT NULL
`
const result = await query(sql, [month])
sendSuccess(res, result.rows[0])
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/overview/daily', async (req: AuthRequest, res) => {
try {
const month = parseMonth(req)
const sql = `
SELECT closed_at::date AS business_date,
count(*) AS bill_count,
round(sum(received_total), 2) AS received,
round(sum(received_total) / count(*), 2) AS avg_bill_value,
round(sum(discount_total) / nullif(sum(consumption), 0) * 100, 2) AS discount_rate_pct
FROM analytics.bill_fact
WHERE closed_at >= $1::date
AND closed_at < ($1::date + interval '1 month')
AND closed_at IS NOT NULL
GROUP BY closed_at::date
ORDER BY business_date
`
const result = await query(sql, [month])
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores', async (req: AuthRequest, res) => {
try {
const { page, pageSize, offset } = parsePagination(req)
const riskLevel = req.query.risk_level as string
const quadrant = req.query.quadrant as string
let sql = `SELECT * FROM analytics.v_store_scorecard`
const params: any[] = []
const conditions: string[] = []
if (riskLevel) {
sql = `SELECT s.* FROM analytics.v_store_scorecard s
JOIN analytics.v_store_risk_rating r ON s.store_code = r.store_code
WHERE r.risk_level = $1`
params.push(riskLevel)
}
if (quadrant) {
if (params.length > 0) {
conditions.push(`b.management_quadrant = $${params.length + 1}`)
sql = sql.replace('FROM analytics.v_store_scorecard s', 'FROM analytics.v_store_scorecard s JOIN analytics.v_store_benchmark b ON s.store_code = b.store_code')
} else {
sql = `SELECT s.* FROM analytics.v_store_scorecard s
JOIN analytics.v_store_benchmark b ON s.store_code = b.store_code
WHERE b.management_quadrant = $1`
params.push(quadrant)
}
}
sql += ` ORDER BY received DESC NULLS LAST`
const countResult = await query(`SELECT count(*) AS total FROM (${sql}) t`, params)
sql += ` LIMIT $${params.length + 1} OFFSET $${params.length + 2}`
params.push(pageSize, offset)
const result = await query(sql, params)
sendSuccess(res, result.rows, { total: parseInt(countResult.rows[0].total), page, page_size: pageSize })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores/risk', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_risk_rating ORDER BY risk_level, received DESC`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores/priority', async (req: AuthRequest, res) => {
try {
const result = await query(`
SELECT store_code, store_name, action_priority, problem_count, problem_combination,
received, scale_tier, business_type
FROM analytics.cache_store_priority
ORDER BY CASE action_priority
WHEN 'P0-修复数据口径' THEN 1
WHEN 'P0-综合专项整改' THEN 2
WHEN 'P1-重点整改' THEN 3
WHEN 'P2-单项改善' THEN 4
WHEN '标杆候选' THEN 5
ELSE 6
END, received DESC
`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores/quadrant', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_benchmark ORDER BY management_quadrant, avg_daily_received DESC`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores/:code', async (req: AuthRequest, res) => {
try {
const code = req.params.code
const scorecard = await query(`SELECT * FROM analytics.v_store_scorecard WHERE store_code = $1`, [code])
const risk = await query(`SELECT * FROM analytics.v_store_risk_rating WHERE store_code = $1`, [code])
const platform = await query(`SELECT * FROM analytics.v_store_platform_economics WHERE store_code = $1`, [code])
const benchmark = await query(`SELECT * FROM analytics.v_store_benchmark WHERE store_code = $1`, [code])
const action = await query(`SELECT * FROM analytics.v_store_action_list WHERE store_code = $1`, [code])
const execution = await query(`SELECT * FROM analytics.v_store_execution_priority WHERE store_code = $1`, [code])
if (scorecard.rows.length === 0) {
return sendError(res, 'Store not found', 404)
}
sendSuccess(res, {
scorecard: scorecard.rows[0],
risk: risk.rows[0],
platform: platform.rows[0],
benchmark: benchmark.rows[0],
action: action.rows[0],
execution: execution.rows[0],
})
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores/:code/daily', async (req: AuthRequest, res) => {
try {
const code = req.params.code
const month = parseMonth(req)
const result = await query(`
SELECT closed_at::date AS business_date,
count(*) AS bill_count,
round(sum(received_total), 2) AS received,
round(sum(received_total) / count(*), 2) AS avg_bill_value,
round(sum(discount_total) / nullif(sum(consumption), 0) * 100, 2) AS discount_rate_pct
FROM analytics.bill_fact
WHERE store_code = $1
AND closed_at >= $2::date
AND closed_at < ($2::date + interval '1 month')
AND closed_at IS NOT NULL
GROUP BY closed_at::date
ORDER BY business_date
`, [code, month])
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/cost/comparison', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_theoretical_actual_cost_april ORDER BY variance_to_theoretical_pct DESC NULLS LAST`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/cost/category-benchmark', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_category_cost_benchmark_april ORDER BY store_code`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/cost/inventory', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_inventory_efficiency_april ORDER BY estimated_inventory_days DESC NULLS LAST`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/platform/economics', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_platform_economics ORDER BY meituan_received DESC NULLS LAST`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/member/comparison', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_member_comparison`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/member/repeat', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_repeat_summary_monthly ORDER BY repeat_rate_pct DESC NULLS LAST`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/sku/abc', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_dish_sku_abc_april ORDER BY cumulative_revenue_share`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/sku/category', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.category_summary ORDER BY amount DESC`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/sku/attach', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.dish_pair_summary_april ORDER BY pair_count DESC LIMIT 50`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/risk/anomaly', async (req: AuthRequest, res) => {
try {
const { page, pageSize, offset } = parsePagination(req)
const countResult = await query(`SELECT count(*) AS total FROM analytics.v_anomaly_bills`)
const result = await query(`SELECT * FROM analytics.v_anomaly_bills ORDER BY closed_at DESC LIMIT $1 OFFSET $2`, [pageSize, offset])
sendSuccess(res, result.rows, { total: parseInt(countResult.rows[0].total), page, page_size: pageSize })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/risk/zero-received', async (req: AuthRequest, res) => {
try {
const storeCode = req.query.store_code as string
let sql = `SELECT * FROM analytics.v_zero_received_detail`
const params: any[] = []
if (storeCode) {
sql += ` WHERE store_code = $1`
params.push(storeCode)
}
sql += ` ORDER BY closed_at DESC LIMIT 200`
const result = await query(sql, params)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/risk/cashier', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_cashier_risk ORDER BY anomaly_rate_pct DESC NULLS LAST`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/marketing/plans', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_marketing_plan_summary ORDER BY received DESC`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/benchmark/composite', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_benchmark_composite ORDER BY benchmark_score DESC`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/time/weekday', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_weekday_summary ORDER BY weekday_no`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/time/hourly', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_hourly_summary ORDER BY closing_hour`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/channel', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_channel_daily ORDER BY business_date`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/data-quality', async (req: AuthRequest, res) => {
try {
const billStats = await query(`
SELECT
count(*) AS total_bills,
count(*) FILTER (WHERE bill_no IS NULL OR bill_no = '') AS missing_bill_no,
count(*) FILTER (WHERE store_code IS NULL OR store_code = '') AS missing_store_code,
count(*) FILTER (WHERE consumption = 0 OR consumption IS NULL) AS zero_consumption,
count(*) FILTER (WHERE received_total < 0) AS negative_received,
count(DISTINCT store_code) AS store_count,
min(closed_at)::text AS min_date,
max(closed_at)::text AS max_date
FROM analytics.bill_fact
`)
const dishStats = await query(`
SELECT
count(*) AS total_dish_records,
count(*) FILTER (WHERE store_code IS NULL OR store_code = '') AS dish_missing_store,
count(*) FILTER (WHERE dish_name IS NULL OR dish_name = '') AS dish_missing_dish
FROM public.dish_sales_details
`)
const result = { ...billStats.rows[0], ...dishStats.rows[0] }
sendSuccess(res, result)
} catch (err: any) {
sendError(res, err.message)
}
})
export default router
+571
View File
@@ -0,0 +1,571 @@
import { Router } from 'express'
import { query, withTransaction } from '../config/database.js'
import { sendSuccess, sendError, parseMonth, parsePagination } from '../middleware/error.js'
import type { AuthRequest } from '../middleware/auth.js'
const router = Router()
// ============================================================
// 固定路径路由(必须在 /:id 之前定义)
// ============================================================
router.get('/', async (req: AuthRequest, res) => {
try {
const { page, pageSize, offset } = parsePagination(req)
const month = parseMonth(req)
const priority = req.query.priority as string
const status = req.query.status as string
const storeCode = req.query.store_code as string
const conditions: string[] = [`plan_month = $1`]
const params: any[] = [month]
let paramIdx = 2
if (priority) {
conditions.push(`priority = $${paramIdx++}`)
params.push(priority)
}
if (status) {
conditions.push(`status = $${paramIdx++}`)
params.push(status)
}
if (storeCode) {
conditions.push(`store_code = $${paramIdx++}`)
params.push(storeCode)
}
const where = conditions.join(' AND ')
const countResult = await query(`SELECT count(*) AS total FROM analytics.store_task WHERE ${where}`, params)
const result = await query(
`SELECT * FROM analytics.store_task WHERE ${where} ORDER BY
CASE priority WHEN 'P0-修复数据口径' THEN 1 WHEN 'P0-综合专项整改' THEN 2 WHEN 'P1' THEN 3 WHEN 'P2' THEN 4 ELSE 5 END,
deadline ASC
LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
[...params, pageSize, offset]
)
sendSuccess(res, result.rows, { total: parseInt(countResult.rows[0].total), page, page_size: pageSize })
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/', async (req: AuthRequest, res) => {
try {
const b = req.body
const result = await withTransaction(async (client) => {
const taskResult = await client.query(`
INSERT INTO analytics.store_task
(plan_month, store_code, store_name, priority, problem_indicator,
current_value, benchmark_value, target_value, problem_description,
action_required, owner, collaborators, deadline,
verification_indicator)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
RETURNING task_id
`, [b.plan_month, b.store_code, b.store_name, b.priority, b.problem_indicator,
b.current_value, b.benchmark_value, b.target_value, b.problem_description,
b.action_required, b.owner, b.collaborators, b.deadline, b.verification_indicator])
const taskId = taskResult.rows[0].task_id
await client.query(`
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
VALUES ($1, '创建', '待启动', $2, $3)
`, [taskId, req.user?.name || 'system', b.problem_description])
return taskId
})
sendSuccess(res, { task_id: result })
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/auto-generate', async (req: AuthRequest, res) => {
try {
const month = req.body.month ? (req.body.month.length === 7 ? `${req.body.month}-01` : req.body.month) : '2026-05-01'
const result = await query(`SELECT * FROM analytics.f_generate_store_tasks($1)`, [month])
sendSuccess(res, result.rows[0] || { generated: 0, message: 'No tasks generated' })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/weekly-check', async (req: AuthRequest, res) => {
try {
const month = parseMonth(req)
const result = await query(`SELECT * FROM analytics.v_task_weekly_check WHERE plan_month = $1 ORDER BY consecutive_no_improve_weeks DESC, store_code`, [month])
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/monthly-review', async (req: AuthRequest, res) => {
try {
const month = parseMonth(req)
const result = await query(`SELECT * FROM analytics.v_task_monthly_review WHERE plan_month = $1 ORDER BY store_code`, [month])
const summary = {
total: result.rows.length,
passed: result.rows.filter((r: any) => r.review_result === '达标').length,
improving: result.rows.filter((r: any) => r.review_result === '改善中').length,
failed: result.rows.filter((r: any) => r.review_result === '未改善').length,
}
sendSuccess(res, { summary, details: result.rows })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/followup', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_store_monthly_followup ORDER BY priority, store_code`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/grade-change', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.store_grade_change ORDER BY change_month DESC, store_code`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/practices', async (req: AuthRequest, res) => {
try {
const mod = req.query.module as string
const status = req.query.status as string
let sql = `SELECT * FROM analytics.standardized_practice`
const params: any[] = []
const conditions: string[] = []
if (mod) {
conditions.push(`practice_module = $${params.length + 1}`)
params.push(mod)
}
if (status) {
conditions.push(`status = $${params.length + 1}`)
params.push(status)
}
if (conditions.length > 0) {
sql += ` WHERE ` + conditions.join(' AND ')
}
sql += ` ORDER BY created_at DESC`
const result = await query(sql, params)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/practices', async (req: AuthRequest, res) => {
try {
const b = req.body
const result = await query(`
INSERT INTO analytics.standardized_practice
(practice_module, benchmark_store_code, benchmark_store_name, key_actions, verification_indicators)
VALUES ($1, $2, $3, $4, $5) RETURNING id
`, [b.practice_module, b.benchmark_store_code, b.benchmark_store_name, b.key_actions, b.verification_indicators])
sendSuccess(res, { id: result.rows[0].id })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/practices/:id/replication-result', async (req: AuthRequest, res) => {
try {
const practiceId = parseInt(req.params.id)
const result = await query(`SELECT * FROM analytics.practice_replication WHERE practice_id = $1 ORDER BY id`, [practiceId])
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/practices/:id/replicate', async (req: AuthRequest, res) => {
try {
const practiceId = parseInt(req.params.id)
const b = req.body
const result = await query(`
INSERT INTO analytics.practice_replication
(practice_id, trial_store_code, trial_store_name, observation_weeks, before_value, status)
VALUES ($1, $2, $3, $4, $5, '观察中') RETURNING id
`, [practiceId, b.trial_store_code, b.trial_store_name, b.observation_weeks || 4, b.before_value])
sendSuccess(res, { id: result.rows[0].id })
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/practices/:id/promote', async (req: AuthRequest, res) => {
try {
const practiceId = parseInt(req.params.id)
await query(`UPDATE analytics.standardized_practice SET status = '已推广' WHERE id = $1`, [practiceId])
sendSuccess(res, { id: practiceId, status: '已推广' })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/indicators', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.indicator_dictionary ORDER BY id`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/indicators', async (req: AuthRequest, res) => {
try {
const b = req.body
const result = await query(`
INSERT INTO analytics.indicator_dictionary
(indicator_name, business_definition, formula, data_source, update_frequency,
owner, scope, yellow_threshold, red_threshold, version_date)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (indicator_name) DO UPDATE SET
business_definition = EXCLUDED.business_definition,
formula = EXCLUDED.formula,
data_source = EXCLUDED.data_source,
update_frequency = EXCLUDED.update_frequency,
owner = EXCLUDED.owner,
scope = EXCLUDED.scope,
yellow_threshold = EXCLUDED.yellow_threshold,
red_threshold = EXCLUDED.red_threshold,
version_date = EXCLUDED.version_date
RETURNING id
`, [b.indicator_name, b.business_definition, b.formula, b.data_source,
b.update_frequency, b.owner, b.scope, b.yellow_threshold, b.red_threshold,
b.version_date || new Date().toISOString().substring(0, 10)])
sendSuccess(res, { id: result.rows[0].id })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/loop-health', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.v_loop_health`)
sendSuccess(res, result.rows[0] || {
task_generation_rate: 0,
store_execution_rate: 0,
weekly_check_rate: 0,
monthly_review_rate: 0,
practice_promotion_rate: 0,
})
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/notifications/dispatch', async (req: AuthRequest, res) => {
try {
const result = await query(`SELECT * FROM analytics.f_dispatch_daily_notifications()`)
sendSuccess(res, result.rows[0] || { dispatched: 0 })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/stores/:code/daily-card', async (req: AuthRequest, res) => {
try {
const code = req.params.code
const result = await query(`SELECT * FROM analytics.v_store_daily_card WHERE store_code = $1 ORDER BY module`, [code])
const tasks = await query(`
SELECT t.* FROM analytics.store_task t
WHERE t.store_code = $1 AND t.status IN ('待启动', '进行中')
ORDER BY t.priority LIMIT 3
`, [code])
sendSuccess(res, { anomalies: result.rows, todos: tasks.rows })
} catch (err: any) {
sendError(res, err.message)
}
})
// ============================================================
// 动态路径路由 /:id(必须在所有固定路径之后)
// ============================================================
router.get('/:id', async (req: AuthRequest, res) => {
try {
const id = parseInt(req.params.id)
if (isNaN(id)) {
return sendError(res, 'Invalid task id', 400)
}
const result = await query(`SELECT * FROM analytics.store_task WHERE task_id = $1`, [id])
if (result.rows.length === 0) {
return sendError(res, 'Task not found', 404)
}
const logs = await query(`SELECT * FROM analytics.store_task_log WHERE task_id = $1 ORDER BY created_at`, [id])
sendSuccess(res, { task: result.rows[0], logs: logs.rows })
} catch (err: any) {
sendError(res, err.message)
}
})
router.put('/:id', async (req: AuthRequest, res) => {
try {
const id = parseInt(req.params.id)
const b = req.body
const fields = ['status', 'process_evidence', 'verification_result', 'incomplete_reason', 'next_step', 'owner', 'collaborators', 'deadline', 'action_required']
const updates: string[] = []
const params: any[] = []
let idx = 1
for (const f of fields) {
if (b[f] !== undefined) {
updates.push(`${f} = $${idx++}`)
params.push(b[f])
}
}
if (updates.length === 0) {
return sendError(res, 'No fields to update')
}
updates.push(`updated_at = NOW()`)
params.push(id)
await query(`UPDATE analytics.store_task SET ${updates.join(', ')} WHERE task_id = $${idx}`, params)
await query(`
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
VALUES ($1, '更新', $2, $3, $4)
`, [id, b.status || null, req.user?.name || 'system', b.next_step || null])
sendSuccess(res, { task_id: id })
} catch (err: any) {
sendError(res, err.message)
}
})
router.put('/:id/execute', async (req: AuthRequest, res) => {
try {
const id = parseInt(req.params.id)
const b = req.body
await withTransaction(async (client) => {
await client.query(`
UPDATE analytics.store_task
SET status = '进行中', process_evidence = $1, action_required = $2,
incomplete_reason = $3, next_step = $4, updated_at = NOW()
WHERE task_id = $5
`, [b.process_evidence, b.action_required, b.incomplete_reason, b.next_step, id])
await client.query(`
INSERT INTO analytics.store_task_log (task_id, action, old_status, new_status, operator, comment)
VALUES ($1, '执行反馈', '待启动', '进行中', $2, $3)
`, [id, req.user?.name || 'store', b.process_evidence])
})
sendSuccess(res, { task_id: id })
} catch (err: any) {
sendError(res, err.message)
}
})
router.put('/:id/weekly-check', async (req: AuthRequest, res) => {
try {
const id = parseInt(req.params.id)
const b = req.body
await withTransaction(async (client) => {
await client.query(`
UPDATE analytics.store_task
SET process_evidence = COALESCE($1, process_evidence),
next_step = $2, updated_at = NOW()
WHERE task_id = $3
`, [b.check_evidence, b.next_step, id])
await client.query(`
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
VALUES ($1, '周度检查', NULL, $2, $3)
`, [id, req.user?.name || 'regional', b.check_comment])
const task = await client.query(`SELECT store_code, store_name, problem_indicator, plan_month FROM analytics.store_task WHERE task_id = $1`, [id])
if (task.rows.length > 0) {
const t = task.rows[0]
await client.query(`
INSERT INTO analytics.task_weekly_check
(task_id, store_code, store_name, problem_indicator, iso_week,
this_week_value, last_week_value, change_direction,
consecutive_no_improve_weeks, check_comment, checked_by)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
`, [id, t.store_code, t.store_name, t.problem_indicator, b.iso_week,
b.this_week_value, b.last_week_value, b.change_direction,
b.consecutive_no_improve_weeks || 0, b.check_comment, req.user?.name])
}
})
sendSuccess(res, { task_id: id })
} catch (err: any) {
sendError(res, err.message)
}
})
router.put('/:id/verify', async (req: AuthRequest, res) => {
try {
const id = parseInt(req.params.id)
const b = req.body
const reviewResult = b.review_result || '改善中'
await withTransaction(async (client) => {
await client.query(`
UPDATE analytics.store_task
SET status = CASE WHEN $1 = '达标' THEN '已验收'
WHEN $1 = '未改善' THEN '已验收'
ELSE '进行中' END,
verification_result = $1,
verification_indicator = $2,
incomplete_reason = $3,
next_step = $4,
updated_at = NOW()
WHERE task_id = $5
`, [reviewResult, b.verification_indicator, b.incomplete_reason, b.next_step, id])
await client.query(`
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
VALUES ($1, '月度验收', $2, $3, $4)
`, [id, reviewResult, req.user?.name || 'hq', JSON.stringify({
revenue_stable: b.revenue_stable,
margin_improved: b.margin_improved,
customer_stable: b.customer_stable,
anomaly_decreased: b.anomaly_decreased,
})])
const task = await client.query(`SELECT store_code, store_name, problem_indicator, plan_month, baseline_value, target_value FROM analytics.store_task WHERE task_id = $1`, [id])
if (task.rows.length > 0) {
const t = task.rows[0]
await client.query(`
INSERT INTO analytics.task_monthly_review
(task_id, store_code, store_name, plan_month, problem_indicator,
baseline_value, target_value, actual_value, review_result,
revenue_stable, margin_improved, customer_stable, anomaly_decreased)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
`, [id, t.store_code, t.store_name, t.plan_month, t.problem_indicator,
t.baseline_value, t.target_value, b.actual_value, reviewResult,
b.revenue_stable || false, b.margin_improved || false,
b.customer_stable || false, b.anomaly_decreased || false])
}
})
sendSuccess(res, { task_id: id, review_result: reviewResult })
} catch (err: any) {
sendError(res, err.message)
}
})
router.post('/:id/rollback', async (req: AuthRequest, res) => {
try {
const id = parseInt(req.params.id)
const reason = req.body.reason
await withTransaction(async (client) => {
await client.query(`
UPDATE analytics.store_task SET status = '已回滚', incomplete_reason = $1, updated_at = NOW()
WHERE task_id = $2
`, [reason, id])
await client.query(`
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
VALUES ($1, '回滚', '已回滚', $2, $3)
`, [id, req.user?.name || 'hq', reason])
})
sendSuccess(res, { task_id: id })
} catch (err: any) {
sendError(res, err.message)
}
})
// ============================================================
// 本体标准 (Ontology Standard)
// ============================================================
router.get('/ontology/overview', async (req: AuthRequest, res) => {
try {
const dims = await query(`
SELECT table_name,
(SELECT count(*) FROM information_schema.columns WHERE table_schema='analytics' AND table_name=t.table_name) AS column_count,
(SELECT reltuples::bigint FROM pg_class WHERE relname=t.table_name) AS row_count
FROM information_schema.tables t
WHERE t.table_schema='analytics' AND t.table_name LIKE 'dim\_%'
ORDER BY t.table_name
`)
const facts = await query(`
SELECT table_name,
(SELECT count(*) FROM information_schema.columns WHERE table_schema='analytics' AND table_name=t.table_name) AS column_count,
(SELECT reltuples::bigint FROM pg_class WHERE relname=t.table_name) AS row_count
FROM information_schema.tables t
WHERE t.table_schema='analytics' AND t.table_name LIKE 'fact\_%'
ORDER BY t.table_name
`)
const enums = await query(`
SELECT table_name,
(SELECT count(*) FROM information_schema.columns WHERE table_schema='analytics' AND table_name=t.table_name) AS column_count,
(SELECT reltuples::bigint FROM pg_class WHERE relname=t.table_name) AS row_count
FROM information_schema.tables t
WHERE t.table_schema='analytics' AND t.table_name LIKE 'enum\_%'
ORDER BY t.table_name
`)
const metrics = await query(`
SELECT count(*) AS total,
count(*) FILTER (WHERE metric_category IS NOT NULL) AS standardized,
count(*) FILTER (WHERE is_active = true) AS active
FROM analytics.indicator_dictionary
`)
sendSuccess(res, {
dimensions: dims.rows,
facts: facts.rows,
enums: enums.rows,
metrics: metrics.rows[0],
})
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/ontology/dim/:table', async (req: AuthRequest, res) => {
try {
const tableName = req.params.table
if (!/^dim_\w+$/.test(tableName)) { sendError(res, 'Invalid table name'); return }
const cols = await query(`
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema='analytics' AND table_name=$1
ORDER BY ordinal_position
`, [tableName])
const rows = await query(`SELECT * FROM analytics.${tableName} LIMIT 100`)
sendSuccess(res, { columns: cols.rows, rows: rows.rows })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/ontology/fact/:table', async (req: AuthRequest, res) => {
try {
const tableName = req.params.table
if (!/^fact_\w+$/.test(tableName)) { sendError(res, 'Invalid table name'); return }
const cols = await query(`
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema='analytics' AND table_name=$1
ORDER BY ordinal_position
`, [tableName])
const count = await query(`SELECT count(*) AS cnt FROM analytics.${tableName}`)
sendSuccess(res, { columns: cols.rows, total: count.rows[0].cnt })
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/ontology/enum/:table', async (req: AuthRequest, res) => {
try {
const tableName = req.params.table
if (!/^enum_\w+$/.test(tableName)) { sendError(res, 'Invalid table name'); return }
const rows = await query(`SELECT * FROM analytics.${tableName} ORDER BY sort_order`)
sendSuccess(res, rows.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
router.get('/ontology/metrics', async (req: AuthRequest, res) => {
try {
const result = await query(`
SELECT * FROM analytics.indicator_dictionary
ORDER BY metric_category NULLS LAST, indicator_name
`)
sendSuccess(res, result.rows)
} catch (err: any) {
sendError(res, err.message)
}
})
export default router
+154
View File
@@ -0,0 +1,154 @@
export type UserRole = 'hq' | 'regional' | 'store' | 'dept'
export interface AuthUser {
id: string
role: UserRole
storeCode?: string
region?: string
dept?: string
name: string
}
export interface ApiResponse<T = any> {
success: boolean
data: T
meta?: {
total?: number
page?: number
page_size?: number
}
error?: string
}
export interface StoreScorecard {
store_code: string
store_name: string
bill_count: number
active_days: number
received: number
avg_daily_received: number
avg_bill_value: number
avg_guest_value: number
discount_rate_pct: number
theoretical_margin_pct: number
member_bill_share_pct: number
}
export interface StoreRiskRating extends StoreScorecard {
anomaly_rate_pct: number
risk_level: string
primary_issue: string
}
export interface StorePriority {
store_code: string
store_name: string
action_priority: string
problem_count: number
problem_combination: string
received: number
scale_tier: string
business_type: string
}
export interface StoreTask {
task_id: number
plan_month: string
store_code: string
store_name: string
priority: string
problem_indicator: string
current_value: number | null
benchmark_value: number | null
target_value: number | null
problem_description: string | null
action_required: string | null
owner: string
collaborators: string | null
deadline: string
status: string
process_evidence: string | null
verification_indicator: string | null
verification_result: string | null
incomplete_reason: string | null
next_step: string | null
created_at: string
updated_at: string
}
export interface WeeklyCheck {
task_id: number
store_code: string
store_name: string
iso_week: number
this_week_value: number | null
last_week_value: number | null
change_direction: string
consecutive_no_improve_weeks: number
check_comment: string | null
checked_by: string | null
checked_at: string | null
}
export interface MonthlyReview {
task_id: number
store_code: string
store_name: string
priority: string
problem_indicator: string
baseline_value: number | null
target_value: number | null
actual_value: number | null
review_result: string
revenue_stable: boolean
margin_improved: boolean
customer_stable: boolean
anomaly_decreased: boolean
}
export interface LoopHealth {
task_generation_rate: number
store_execution_rate: number
weekly_check_rate: number
monthly_review_rate: number
practice_promotion_rate: number
}
export interface IndicatorDict {
id: number
indicator_name: string
business_definition: string
formula: string
data_source: string
update_frequency: string
owner: string
scope: string
yellow_threshold: number | null
red_threshold: number | null
version_date: string
}
export interface StandardizedPractice {
id: number
practice_module: string
benchmark_store_code: string
benchmark_store_name: string
key_actions: string
verification_indicators: string
status: string
created_at: string
}
export interface PracticeReplication {
id: number
practice_id: number
trial_store_code: string
trial_store_name: string
observation_weeks: number
before_value: number | null
after_value: number | null
revenue_impacted: boolean
customer_impacted: boolean
inventory_impacted: boolean
status: string
}