feat(admin): 联动用户、预约、排班和部门统计的只读预览
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
// Local, synthetic scheduling ledger. No transport, database or business writes.
|
||||
// IDs are deterministic for a calendar slot; appointment status is evaluated at snapshot time.
|
||||
const statusNames = {
|
||||
registered: '已挂号',
|
||||
completed: '已完成',
|
||||
canceled: '已取消',
|
||||
expired: '已过号'
|
||||
}
|
||||
const pad = (n) => String(n).padStart(2, '0')
|
||||
const iso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
const minuteOf = (s) => Number(s.slice(0, 2)) * 60 + Number(s.slice(3, 5))
|
||||
const asTime = (m) => `${pad(Math.floor(m / 60))}:${pad(m % 60)}`
|
||||
export function makeAppointments({ doctors, slots, patients, assistants, now }) {
|
||||
const rows = [],
|
||||
occupied = new Set(),
|
||||
today = iso(now),
|
||||
minute = now.getHours() * 60 + now.getMinutes()
|
||||
const byDoctor = new Map(doctors.map((d) => [d.id, d]))
|
||||
for (const slot of slots) {
|
||||
if (slot.status !== 1) continue
|
||||
const doc = byDoctor.get(slot.doctor_id),
|
||||
team = assistants.filter((a) => a.dept_id === doc.dept_id)
|
||||
const capacity = Math.min(
|
||||
slot.quota || Infinity,
|
||||
Math.floor((minuteOf(slot.end_time) - minuteOf(slot.start_time)) / slot.slot_minutes)
|
||||
)
|
||||
const n = Math.min(capacity, 2 + ((slot.id + doc.id) % 7))
|
||||
for (let i = 0; i < n; i++) {
|
||||
const id = slot.id * 16 + i,
|
||||
start = minuteOf(slot.start_time) + i * slot.slot_minutes
|
||||
const future = slot.date > today || (slot.date === today && start >= minute)
|
||||
const status =
|
||||
id % 11 === 0
|
||||
? 'canceled'
|
||||
: future
|
||||
? 'registered'
|
||||
: id % 9 === 0
|
||||
? 'expired'
|
||||
: 'completed'
|
||||
let pi = (Math.floor(slot.id / 100) + doc.id * 7 + i * 5) % patients.length
|
||||
const occupiedKey = (p) => `${slot.date}/${start}/${p.id}`
|
||||
for (let j = 0; j < patients.length && occupied.has(occupiedKey(patients[pi])); j++)
|
||||
pi = (pi + 1) % patients.length
|
||||
const patient = patients[pi]
|
||||
if (status !== 'canceled') {
|
||||
if (occupied.has(occupiedKey(patient))) continue
|
||||
occupied.add(occupiedKey(patient))
|
||||
slot.booked_count++
|
||||
}
|
||||
rows.push({
|
||||
id,
|
||||
booking_no: `YY-${slot.date.replaceAll('-', '')}-${doc.id}-${pad(Math.floor(start / slot.slot_minutes))}`,
|
||||
slot_id: slot.id,
|
||||
doctor_id: doc.id,
|
||||
dept_id: doc.dept_id,
|
||||
assistant_id: team[(i + doc.id) % team.length].id,
|
||||
patient_id: patient.id,
|
||||
date: slot.date,
|
||||
time: asTime(start),
|
||||
status,
|
||||
visit_type: i % 3 ? '复诊' : '初诊'
|
||||
})
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
export function resolveAppointments(pathname, q, snapshot, memberIdForPatient) {
|
||||
if (pathname !== '/adminapi/local.preview/appointments' || q.export != null) return null
|
||||
const { appointments, departments, doctors, assistants, patients, slots, orders, now } =
|
||||
snapshot
|
||||
const map = (a, id = 'id') => new Map(a.map((v) => [v[id], v]))
|
||||
const [ds, dr, as, ps, ss] = [
|
||||
map(departments, 'dept_id'),
|
||||
map(doctors),
|
||||
map(assistants),
|
||||
map(patients),
|
||||
map(slots)
|
||||
]
|
||||
const counts = new Map()
|
||||
for (const o of orders)
|
||||
if (o.patient_id) counts.set(o.patient_id, 1 + (counts.get(o.patient_id) || 0))
|
||||
const kw = String(q.keyword || '')
|
||||
.trim()
|
||||
.toLowerCase(),
|
||||
today = iso(now)
|
||||
let matches = appointments.filter(
|
||||
(a) =>
|
||||
(!q.dept_id || a.dept_id === Number(q.dept_id)) &&
|
||||
(!q.patient_id || a.patient_id === Number(q.patient_id)) &&
|
||||
(!q.start_date || a.date >= q.start_date) &&
|
||||
(!q.end_date || a.date <= q.end_date) &&
|
||||
(!kw ||
|
||||
[
|
||||
a.booking_no,
|
||||
ps.get(a.patient_id).patient_name,
|
||||
dr.get(a.doctor_id).name,
|
||||
as.get(a.assistant_id).name
|
||||
].some((s) => s.toLowerCase().includes(kw)))
|
||||
)
|
||||
const all = matches.length,
|
||||
summary = Object.fromEntries(
|
||||
Object.keys(statusNames).map((s) => [s, matches.filter((r) => r.status === s).length])
|
||||
)
|
||||
if (q.status) matches = matches.filter((a) => a.status === q.status)
|
||||
// Today's bookings first, then upcoming earliest first, then history most recent first.
|
||||
const group = (a) => (a.date === today ? 0 : a.date > today ? 1 : 2)
|
||||
matches.sort(
|
||||
(a, b) =>
|
||||
group(a) - group(b) ||
|
||||
(group(a) === 2 ? b.date.localeCompare(a.date) : a.date.localeCompare(b.date)) ||
|
||||
a.time.localeCompare(b.time) ||
|
||||
a.id - b.id
|
||||
)
|
||||
const size = Math.min(100, Math.max(1, parseInt(q.page_size, 10) || 15)),
|
||||
page = Math.max(1, parseInt(q.page_no, 10) || 1)
|
||||
const lists = matches
|
||||
.slice((page - 1) * size, page * size)
|
||||
.map((a) => ({
|
||||
...a,
|
||||
member_id: memberIdForPatient(a.patient_id),
|
||||
patient_name: ps.get(a.patient_id).patient_name,
|
||||
doctor_name: dr.get(a.doctor_id).name,
|
||||
dept_name: ds.get(a.dept_id).dept_name,
|
||||
assistant_name: as.get(a.assistant_id).name,
|
||||
status_name: statusNames[a.status],
|
||||
start_time: ss.get(a.slot_id).start_time,
|
||||
end_time: ss.get(a.slot_id).end_time,
|
||||
patient_order_count: counts.get(a.patient_id) || 0
|
||||
}))
|
||||
return {
|
||||
code: 1,
|
||||
data: {
|
||||
lists,
|
||||
count: matches.length,
|
||||
all,
|
||||
summary,
|
||||
departments,
|
||||
today,
|
||||
patient_name: ps.get(Number(q.patient_id))?.patient_name || ''
|
||||
},
|
||||
show: 0,
|
||||
msg: ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createPreviewSnapshot } from '../fixtures.mjs'
|
||||
import { memberIdForPatient, resolvePeople } from './people.mjs'
|
||||
import { resolveDeptStats } from './dept-stats.mjs'
|
||||
import { resolveAppointments } from './appointments.mjs'
|
||||
const snap = (d) => createPreviewSnapshot(new Date(d))
|
||||
const bookings = (s, q = {}) =>
|
||||
resolveAppointments('/adminapi/local.preview/appointments', q, s, memberIdForPatient).data
|
||||
for (const local of ['2026-12-01T10:00:00', '2027-01-01T08:00:00', '2028-02-29T22:00:00']) {
|
||||
test(`关联完整、排班容量和唯一性:${local}`, () => {
|
||||
const s = snap(local),
|
||||
slots = new Map(s.slots.map((v) => [v.id, v])),
|
||||
occupied = new Map(),
|
||||
times = new Set(),
|
||||
nos = new Set()
|
||||
for (const b of s.appointments) {
|
||||
const sl = slots.get(b.slot_id),
|
||||
d = s.doctors.find((v) => v.id === b.doctor_id),
|
||||
a = s.assistants.find((v) => v.id === b.assistant_id)
|
||||
assert.ok(sl && d && a && s.patients.some((v) => v.id === b.patient_id))
|
||||
assert.equal(d.dept_id, a.dept_id)
|
||||
assert.equal(b.dept_id, a.dept_id)
|
||||
assert.equal(b.date, sl.date)
|
||||
assert.equal(sl.status, 1)
|
||||
assert.equal(sl.doctor_id, d.id)
|
||||
assert.ok(sl.start_time <= b.time && b.time < sl.end_time)
|
||||
assert.ok(!nos.has(b.booking_no))
|
||||
nos.add(b.booking_no)
|
||||
if (b.status !== 'canceled') {
|
||||
const key = [b.patient_id, b.date, b.time].join('/')
|
||||
assert.ok(!times.has(key))
|
||||
times.add(key)
|
||||
occupied.set(sl.id, 1 + (occupied.get(sl.id) || 0))
|
||||
}
|
||||
}
|
||||
const min = (t) => Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
|
||||
for (const v of s.slots) {
|
||||
assert.equal(v.booked_count, occupied.get(v.id) || 0)
|
||||
assert.ok(
|
||||
v.booked_count <=
|
||||
Math.min(
|
||||
v.quota || Infinity,
|
||||
(min(v.end_time) - min(v.start_time)) / v.slot_minutes
|
||||
)
|
||||
)
|
||||
}
|
||||
assert.deepEqual(
|
||||
new Set(s.appointments.map((v) => v.status)),
|
||||
new Set(['registered', 'completed', 'expired', 'canceled'])
|
||||
)
|
||||
})
|
||||
}
|
||||
test('三个统计周期按部门下钻;状态分布与明细精确一致', () => {
|
||||
const s = snap('2026-12-01T14:30:00')
|
||||
for (const time_type of ['today', 'week', 'month']) {
|
||||
const stats = resolveDeptStats('/adminapi/doctor.statistics/deptLists', { time_type }, s)
|
||||
.data.lists
|
||||
assert.ok(stats.length)
|
||||
for (const r of stats) {
|
||||
const data = bookings(s, {
|
||||
dept_id: r.dept_id,
|
||||
start_date: r.start_date,
|
||||
end_date: r.end_date
|
||||
})
|
||||
assert.equal(data.all, r.total_count)
|
||||
for (const [k, n] of Object.entries(data.summary)) assert.equal(n, r[k + '_count'])
|
||||
}
|
||||
}
|
||||
})
|
||||
test('预约、账号、订单同人关联;按预约号检索与分页一致', () => {
|
||||
const s = snap('2026-12-01T14:30:00'),
|
||||
one = bookings(s).lists[0]
|
||||
const person = resolvePeople('/adminapi/user.user/detail', { id: one.member_id }, s).data
|
||||
assert.equal(person.patient_id, one.patient_id)
|
||||
assert.equal(bookings(s, { patient_id: one.patient_id }).count, person.appointment_count)
|
||||
assert.equal(person.order_count, one.patient_order_count)
|
||||
assert.equal(bookings(s, { keyword: one.booking_no }).count, 1)
|
||||
assert.equal(bookings(s, { keyword: '某条不存在的演示预约' }).count, 0)
|
||||
const next = bookings(s, { page_no: 2 }).lists
|
||||
assert.ok(next.every((b) => !bookings(s).lists.some((r) => b.id === r.id)))
|
||||
assert.equal(
|
||||
resolveAppointments(
|
||||
'/adminapi/local.preview/appointments',
|
||||
{ export: 2 },
|
||||
s,
|
||||
memberIdForPatient
|
||||
),
|
||||
null
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
// Mirrors StatisticsLists::getDeptStatistics; this module reads only the provided local snapshot.
|
||||
const ok = data => ({ code: 1, data, show: 0, msg: '' })
|
||||
|
||||
function dateAt(now, offset) {
|
||||
const date = new Date(now)
|
||||
date.setDate(date.getDate() + offset)
|
||||
return [date.getFullYear(), String(date.getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0')].join('-')
|
||||
}
|
||||
function period(q, now) {
|
||||
const end = dateAt(now, 0)
|
||||
if (q.time_type === 'custom' && q.start_date && q.end_date) {
|
||||
return [q.start_date, q.end_date, `自定义 (${q.start_date} 至 ${q.end_date})`]
|
||||
}
|
||||
if (q.time_type === 'week' || q.time_type === 'month') {
|
||||
const days = q.time_type === 'week' ? 7 : 30
|
||||
const start = dateAt(now, 1 - days)
|
||||
return [start, end, `最近${days}天 (${start} 至 ${end})`]
|
||||
}
|
||||
return [end, end, `今天 (${end})`]
|
||||
}
|
||||
|
||||
export function resolveDeptStats(pathname, params, snapshot) {
|
||||
if (pathname === '/adminapi/dept.dept/all') {
|
||||
return ok(snapshot.departments.map(d => ({ id: d.dept_id, name: d.dept_name, children: [] })))
|
||||
}
|
||||
if (pathname !== '/adminapi/doctor.statistics/deptLists') return null
|
||||
|
||||
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
|
||||
const [start_date, end_date, time_range] = period(q, snapshot.now)
|
||||
const assistants = new Map(snapshot.assistants.map(a => [a.id, a.dept_id]))
|
||||
const groups = new Map(snapshot.departments.filter(d => !q.dept_id || d.dept_id === Number(q.dept_id)).map(d => [d.dept_id, {
|
||||
dept_id: d.dept_id, dept_name: d.dept_name, total_count: 0, registered_count: 0, completed_count: 0,
|
||||
canceled_count: 0, expired_count: 0, completion_rate: 0, start_date, end_date, time_range
|
||||
}]))
|
||||
for (const a of snapshot.appointments) {
|
||||
if (a.date < start_date || a.date > end_date) continue
|
||||
const row = groups.get(assistants.get(a.assistant_id))
|
||||
if (!row) continue
|
||||
row.total_count += 1
|
||||
// Total is COUNT(*) on the server; the four named statuses get separate subtotals.
|
||||
if (['registered', 'completed', 'canceled', 'expired'].includes(a.status)) row[a.status + '_count'] += 1
|
||||
}
|
||||
// SQL GROUP BY does not manufacture zero-count rows when a department has no activity.
|
||||
const lists = [...groups.values()].filter(r => r.total_count)
|
||||
for (const row of lists) row.completion_rate = Number((100 * row.completed_count / row.total_count).toFixed(2))
|
||||
return ok({ lists, count: lists.length, page_no: Number(q.page_no) || 1, page_size: Number(q.page_size) || 15, extend: [] })
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { resolveDeptStats } from './dept-stats.mjs'
|
||||
|
||||
const snapshot = {
|
||||
now: new Date(2026, 2, 1, 1, 0),
|
||||
departments: [{ dept_id: 1, dept_name: '演示一组' }, { dept_id: 2, dept_name: '演示二组' }, { dept_id: 3, dept_name: '无预约组' }],
|
||||
assistants: [{ id: 101, dept_id: 1 }, { id: 102, dept_id: 2 }],
|
||||
// Deliberately different from the assistant: StatisticsLists groups by assistant, not doctor.
|
||||
doctors: [{ id: 401, dept_id: 2 }], patients: [], slots: [],
|
||||
appointments: [
|
||||
['2026-03-01', 'completed', 101], ['2026-03-01', 'registered', 101], ['2026-03-01', 'expired', 101],
|
||||
['2026-03-01', 'canceled', 102], ['2026-02-23', 'completed', 101], ['2026-02-22', 'canceled', 102],
|
||||
['2026-01-31', 'completed', 102], ['2026-01-30', 'registered', 101], ['2026-03-02', 'registered', 102],
|
||||
['2026-03-01', 'completed', 999]
|
||||
].map(([date, status, assistant_id], i) => ({ id: i + 1, doctor_id: 401, date, status, assistant_id }))
|
||||
}
|
||||
const path = '/adminapi/doctor.statistics/deptLists'
|
||||
const rows = (query = {}) => resolveDeptStats(path, query, snapshot).data.lists
|
||||
|
||||
test('department options, query format, strict route allowlist', () => {
|
||||
assert.deepEqual(resolveDeptStats('/adminapi/dept.dept/all', {}, snapshot).data.map(d => [d.id, d.name]), [[1, '演示一组'], [2, '演示二组'], [3, '无预约组']])
|
||||
assert.equal(resolveDeptStats('/adminapi/dept.dept/edit', {}, snapshot), null)
|
||||
const reply = resolveDeptStats(path, new URLSearchParams({ dept_id: '1' }), snapshot)
|
||||
assert.deepEqual([reply.code, reply.show, reply.msg, reply.data.count], [1, 0, '', 1])
|
||||
assert.equal(reply.data.lists[0].dept_id, 1)
|
||||
})
|
||||
|
||||
test('today: joins via assistant, status counts reconcile, rates use total, no padded empty department', () => {
|
||||
assert.deepEqual(rows(), [
|
||||
{ dept_id: 1, dept_name: '演示一组', registered_count: 1, completed_count: 1, canceled_count: 0, expired_count: 1, total_count: 3, completion_rate: 33.33, time_range: '今天 (2026-03-01)', start_date: '2026-03-01', end_date: '2026-03-01' },
|
||||
{ dept_id: 2, dept_name: '演示二组', registered_count: 0, completed_count: 0, canceled_count: 1, expired_count: 0, total_count: 1, completion_rate: 0, time_range: '今天 (2026-03-01)', start_date: '2026-03-01', end_date: '2026-03-01' }
|
||||
])
|
||||
})
|
||||
|
||||
test('week/month include today and 6/29 previous calendar dates across a month boundary', () => {
|
||||
for (const [time_type, start, expected] of [['week', '2026-02-23', [4, 1]], ['month', '2026-01-31', [4, 3]]]) {
|
||||
const result = rows({ time_type })
|
||||
assert.deepEqual(result.map(r => r.total_count), expected)
|
||||
assert.ok(result.every(r => r.start_date === start && r.end_date === '2026-03-01'))
|
||||
}
|
||||
})
|
||||
|
||||
test('custom dates and department narrow together; links reconcile to the matching appointments', () => {
|
||||
const [row] = rows({ time_type: 'custom', start_date: '2026-02-22', end_date: '2026-03-01', dept_id: '2' })
|
||||
const members = snapshot.assistants.filter(a => a.dept_id === row.dept_id).map(a => a.id)
|
||||
const detail = snapshot.appointments.filter(a => members.includes(a.assistant_id) && a.date >= row.start_date && a.date <= row.end_date)
|
||||
assert.equal(row.time_range, '自定义 (2026-02-22 至 2026-03-01)')
|
||||
assert.equal(row.total_count, 2)
|
||||
assert.equal(detail.length, row.total_count)
|
||||
for (const status of ['registered', 'completed', 'canceled', 'expired']) {
|
||||
assert.equal(row[status + '_count'], detail.filter(r => r.status === status).length)
|
||||
}
|
||||
})
|
||||
|
||||
test('no matching dates, no matching appointments or unknown department returns an empty list', () => {
|
||||
assert.deepEqual(rows({ time_type: 'custom', start_date: '2000-01-01', end_date: '2000-12-31' }), [])
|
||||
assert.deepEqual(rows({ dept_id: '3' }), [])
|
||||
assert.deepEqual(rows({ dept_id: '999' }), [])
|
||||
assert.deepEqual(rows({ time_type: 'custom' }), rows())
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
// Synthetic *accounts*, not patients. Only this local adapter knows about the demo cross-links.
|
||||
const channels = ['微信小程序', '微信公众号', '手机H5', '电脑PC', '苹果APP', '安卓APP']
|
||||
const aliases = ['青竹', '晴川', '听雨', '小满', '晨光', '山月', '晚舟']
|
||||
const ok = data => ({ code: 1, msg: '', show: 0, data })
|
||||
|
||||
export function memberIdForPatient(patientId) {
|
||||
if (!['number', 'string'].includes(typeof patientId) || !/^\d+$/.test(String(patientId))) return null
|
||||
const id = Number(patientId)
|
||||
return id > 0 && Number.isSafeInteger(70000 + id) ? 70000 + id : null
|
||||
}
|
||||
|
||||
function positiveInt(raw, fallback, max = Number.MAX_SAFE_INTEGER) {
|
||||
const n = Number(raw)
|
||||
return Number.isSafeInteger(n) && n > 0 ? Math.min(n, max) : fallback
|
||||
}
|
||||
|
||||
function dateBefore(day, offset) {
|
||||
const date = new Date(day + 'T00:00:00Z')
|
||||
date.setUTCDate(date.getUTCDate() - offset)
|
||||
return date.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function accounts({ patients, orders, appointments = [] }) {
|
||||
// The order snapshot carries the fixed local demo day; never call out for identity or avatar data.
|
||||
const anchor = orders[0]?.create_time.slice(0, 10) || '2026-01-31'
|
||||
const orderCounts = new Map()
|
||||
for (const order of orders) orderCounts.set(order.patient_id, (orderCounts.get(order.patient_id) || 0) + 1)
|
||||
const appointmentCounts = new Map()
|
||||
for (const appt of appointments) appointmentCounts.set(appt.patient_id, (appointmentCounts.get(appt.patient_id) || 0) + 1)
|
||||
return patients.map((patient, i) => {
|
||||
const ordinal = String(i + 1).padStart(2, '0')
|
||||
const id = memberIdForPatient(patient.id)
|
||||
return {
|
||||
id, sn: 'U-DEMO-' + patient.id, nickname: aliases[i % aliases.length] + '·示例' + ordinal,
|
||||
avatar: '', account: 'demo_user_' + ordinal, mobile: patient.phone,
|
||||
channel: channels[i % channels.length], sex: ['未知', '女', '男'][i % 3],
|
||||
create_time: dateBefore(anchor, patients.length + 10 - i) + ' 08:30:00',
|
||||
login_time: dateBefore(anchor, i % 5 + 1) + ' 09:15:00',
|
||||
real_name: i % 4 ? '模拟姓名' + ordinal : '', user_money: (i % 4 * 15.5).toFixed(2),
|
||||
// Preview-only navigation context. Account balances are not derived from patient orders.
|
||||
patient_id: patient.id, patient_name: patient.patient_name,
|
||||
order_count: orderCounts.get(patient.id) || 0, appointment_count: appointmentCounts.get(patient.id) || 0
|
||||
}
|
||||
}).sort((a, b) => b.id - a.id)
|
||||
}
|
||||
|
||||
export function resolvePeople(pathname, params, snapshot) {
|
||||
if (!['/adminapi/user.user/lists', '/adminapi/user.user/detail'].includes(pathname)) return null
|
||||
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
|
||||
if (q.export != null) return null
|
||||
const members = accounts(snapshot)
|
||||
if (pathname === '/adminapi/user.user/detail') {
|
||||
const row = members.find(u => u.id === Number(q.id))
|
||||
return row ? ok(row) : { code: 0, data: null, show: 1, msg: '未找到该演示账号' }
|
||||
}
|
||||
const term = String(q.keyword ?? '').trim().toLowerCase()
|
||||
const end = q.create_time_end?.length === 10 ? q.create_time_end + ' 23:59:59' : q.create_time_end
|
||||
const rows = members.filter(u =>
|
||||
(!term || [u.sn, u.account, u.nickname, u.mobile].some(s => s.toLowerCase().includes(term))) &&
|
||||
(!q.channel || u.channel === channels[Number(q.channel) - 1]) &&
|
||||
(!q.create_time_start || u.create_time >= q.create_time_start) &&
|
||||
(!end || u.create_time <= end)
|
||||
)
|
||||
const size = positiveInt(q.page_size, 15, 100), page = positiveInt(q.page_no, 1)
|
||||
const lists = rows.slice((page - 1) * size, page * size).map(({ id, sn, nickname, sex, avatar, account, mobile, channel, create_time }) =>
|
||||
({ id, sn, nickname, sex, avatar, account, mobile, channel, create_time }))
|
||||
return ok({ count: rows.length, lists, extend: {} })
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { memberIdForPatient, resolvePeople } from './people.mjs'
|
||||
|
||||
const patients = Array.from({ length: 20 }, (_, i) => Object.freeze({
|
||||
id: 501 + i, patient_name: '演示患者' + (i + 1), phone: '000****' + (1000 + i)
|
||||
}))
|
||||
const snapshot = Object.freeze({
|
||||
patients: Object.freeze(patients),
|
||||
appointments: Object.freeze([{ patient_id: 501 }, { patient_id: 501 }]),
|
||||
orders: Object.freeze([{ id: 10101, patient_id: 501, create_time: '2026-12-01 08:00:00' }])
|
||||
})
|
||||
const read = (name, params = {}) => resolvePeople('/adminapi/user.user/' + name, params, snapshot)
|
||||
|
||||
test('同一批账号支持分页、编号、账号、昵称、电话、来源和注册区间筛选', () => {
|
||||
const first = read('lists'), second = read('lists', new URLSearchParams('page_no=2&page_size=15'))
|
||||
assert.deepEqual([first.code, first.msg, first.show, first.data.count, first.data.lists.length], [1, '', 0, 20, 15])
|
||||
assert.equal(second.data.lists.length, 5)
|
||||
assert.equal(new Set([...first.data.lists, ...second.data.lists].map(u => u.id)).size, 20)
|
||||
const [row] = second.data.lists
|
||||
for (const keyword of [row.account.toUpperCase(), row.nickname, row.mobile, row.sn]) {
|
||||
assert.deepEqual(read('lists', { keyword }).data.lists, [row])
|
||||
}
|
||||
const filtered = read('lists', { channel: 1 }).data.lists
|
||||
assert.ok(filtered.length && filtered.every(r => r.channel === '微信小程序'))
|
||||
assert.deepEqual(read('lists', { create_time_start: row.create_time, create_time_end: row.create_time }).data.lists, [row])
|
||||
assert.equal(read('lists', { keyword: '无此账号' }).data.count, 0)
|
||||
assert.equal(read('lists', { create_time_start: '2100-01-01' }).data.count, 0)
|
||||
})
|
||||
|
||||
test('凭账号 ID 读详情,账号、预约档案和订单的键不混用', () => {
|
||||
const id = memberIdForPatient(501)
|
||||
const { data: member } = read('detail', { id })
|
||||
assert.notEqual(id, 501)
|
||||
assert.deepEqual([member.id, member.patient_id, member.patient_name, member.order_count], [id, 501, '演示患者1', 1])
|
||||
assert.equal(member.appointment_count, 2)
|
||||
assert.notEqual(member.nickname, member.patient_name)
|
||||
assert.deepEqual(read('lists', { keyword: member.account }).data.lists.map(r => r.id), [id])
|
||||
assert.equal(read('detail', { id: memberIdForPatient(520) }).data.order_count, 0)
|
||||
assert.match(member.mobile, /^000\*{4}\d{4}$/)
|
||||
for (const value of [0, '', null, true, '1.5', 'x']) assert.equal(memberIdForPatient(value), null)
|
||||
assert.equal(read('detail', { id: 501 }).code, 0)
|
||||
})
|
||||
|
||||
test('用户端点仅限读,不承接写操作、导出或未知路径', () => {
|
||||
for (const path of ['edit', 'adjustMoney', 'export', 'arbitrary']) assert.equal(read(path), null)
|
||||
for (const mode of ['1', '2']) assert.equal(read('lists', { export: mode }), null)
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
// The seed is a local calendar date (not a UTC timestamp). Overlapping weeks keep
|
||||
// identical IDs and shifts even when the shared preview snapshot rolls forward.
|
||||
const names = ['林衡', '沈知禾', '许亦安', '顾清和', '赵元宁', '叶嘉言']
|
||||
const dayTimes = [
|
||||
['08:30', '11:30', 'day'], ['14:00', '17:00', 'day'], ['18:00', '21:00', 'night']
|
||||
]
|
||||
const isoDate = d => d.toISOString().slice(0, 10)
|
||||
const ok = data => ({ code: 1, data, show: 0, msg: '' })
|
||||
const list = (lists, count = lists.length) => ok({ lists, count, extend: {} })
|
||||
|
||||
export function makeRosterSnapshot(departments, now) {
|
||||
if (!departments.length) return { doctors: [], slots: [] }
|
||||
const doctors = names.map((name, i) => ({
|
||||
id: 201 + i, name: name + '(演示)', dept_id: departments[i % departments.length].dept_id
|
||||
}))
|
||||
const monday = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()))
|
||||
monday.setUTCDate(monday.getUTCDate() - (monday.getUTCDay() + 6) % 7)
|
||||
const slots = []
|
||||
// Five weeks before and two weeks after this Monday also cover the recent-30-day views.
|
||||
for (let offset = -35; offset < 21; offset++) {
|
||||
const d = new Date(monday)
|
||||
d.setUTCDate(d.getUTCDate() + offset)
|
||||
const date = isoDate(d), ordinal = Math.floor(d.getTime() / 86400000)
|
||||
doctors.forEach((doctor, i) => {
|
||||
const phase = (ordinal + i * 2) % 9
|
||||
if (phase === 1 || phase === 6) return // No segment ≠ cancelled/closed shift.
|
||||
const status = phase === 4 ? 2 : phase === 5 ? 4 : phase === 7 && i % 2 ? 3 : 1
|
||||
const shifts = status === 1 && phase === 0 ? [0, 1] : [phase === 2 ? 2 : phase % 2]
|
||||
for (const j of shifts) {
|
||||
const [start_time, end_time, shift_type] = dayTimes[j]
|
||||
const quota = status === 1 ? (phase % 3 === 0 ? 0 : 8 + i % 5) : 0
|
||||
slots.push({
|
||||
id: Number(date.replaceAll('-', '')) * 100 + i * 10 + j, doctor_id: doctor.id,
|
||||
date, period: 'segment', start_time, end_time, shift_type, slot_minutes: 15,
|
||||
status, quota, max_patients: 0, booked_count: 0, remark: ''
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
slots.sort((a, b) => a.date.localeCompare(b.date) || a.start_time.localeCompare(b.start_time) || a.id - b.id)
|
||||
return { doctors, slots }
|
||||
}
|
||||
|
||||
export function resolveRoster(pathname, params, snapshot) {
|
||||
const q = params instanceof URLSearchParams ? Object.fromEntries(params) : params || {}
|
||||
if (q.export != null) return null
|
||||
if (pathname === '/adminapi/auth.admin/lists') {
|
||||
// Never turn the general account-management API into an unscoped preview endpoint.
|
||||
if (String(q.role_id) !== '1' || String(q.exclude_disabled) !== '1') return null
|
||||
const rows = snapshot.doctors.filter(d => !q.name || d.name.includes(String(q.name).trim()))
|
||||
const positive = (n, fallback) => Number.isSafeInteger(+n) && +n > 0 ? +n : fallback
|
||||
const page = positive(q.page_no, 1), size = Math.min(1000, positive(q.page_size, 15))
|
||||
return list(rows.slice((page - 1) * size, page * size).map(d => ({
|
||||
...d, dept_id: [d.dept_id], dept_name: snapshot.departments.find(dep => dep.dept_id === d.dept_id)?.dept_name || ''
|
||||
})), rows.length)
|
||||
}
|
||||
if (pathname !== '/adminapi/doctor.roster/lists') return null
|
||||
const matches = snapshot.slots.filter(s =>
|
||||
(!q.start_date || s.date >= q.start_date) && (!q.end_date || s.date <= q.end_date) &&
|
||||
(!q.doctor_id || s.doctor_id === Number(q.doctor_id)) &&
|
||||
(!q.status || s.status === Number(q.status)) && (!q.period || s.period === q.period)
|
||||
)
|
||||
// Production RosterLists returns all matching segments for the displayed week, without pagination.
|
||||
return list(matches)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { makeRosterSnapshot, resolveRoster } from './roster.mjs'
|
||||
|
||||
// Deliberately not contiguous: no logic may use a department ID as an array index.
|
||||
const departments = [{ dept_id: 17, dept_name: '预览一组' }, { dept_id: 39, dept_name: '预览二组' }]
|
||||
const seed = new Date(2027, 0, 1, 9, 17)
|
||||
const snapshot = { ...makeRosterSnapshot(departments, seed), departments }
|
||||
const doctorPath = '/adminapi/auth.admin/lists', rosterPath = '/adminapi/doctor.roster/lists'
|
||||
const doctorQuery = { role_id: '1', exclude_disabled: '1' }
|
||||
const read = (path, q) => {
|
||||
const response = resolveRoster(path, q, snapshot)
|
||||
assert.deepEqual([response.code, response.show, response.msg], [1, 0, ''])
|
||||
return response.data
|
||||
}
|
||||
|
||||
test('相邻周跨年、同日期排班不漂移、每段有合法医生部门关系', () => {
|
||||
const { slots, doctors } = snapshot
|
||||
assert.ok(slots.length > 0)
|
||||
assert.equal(new Set(slots.map(s => s.id)).size, slots.length)
|
||||
assert.ok(doctors.every(d => departments.some(dep => dep.dept_id === d.dept_id)))
|
||||
assert.ok(slots.every(s => doctors.some(d => d.id === s.doctor_id) && s.start_time < s.end_time))
|
||||
assert.deepEqual(new Set(slots.map(s => s.status)), new Set([1, 2, 3, 4]))
|
||||
for (const [start, end] of [['2026-12-21','2026-12-27'],['2026-12-28','2027-01-03'],['2027-01-04','2027-01-10']]) {
|
||||
const week = read(rosterPath, { start_date: start, end_date: end })
|
||||
assert.equal(week.count, week.lists.length)
|
||||
assert.equal(new Set(week.lists.map(s => s.date)).size, 7)
|
||||
assert.ok(week.lists.every(s => s.date >= start && s.date <= end))
|
||||
}
|
||||
const next = makeRosterSnapshot(departments, new Date(2027, 0, 4))
|
||||
const interval = s => s.date >= '2026-12-28' && s.date <= '2027-01-10'
|
||||
assert.deepEqual(slots.filter(interval), next.slots.filter(interval))
|
||||
assert.deepEqual(makeRosterSnapshot([], seed), { doctors: [], slots: [] })
|
||||
})
|
||||
|
||||
test('医生列表限制角色、部门和分页;排班按日期、医生与状态合并过滤', () => {
|
||||
const all = read(doctorPath, new URLSearchParams(doctorQuery))
|
||||
assert.equal(all.count, snapshot.doctors.length)
|
||||
const d = all.lists[0]
|
||||
assert.deepEqual(d.dept_id, [17])
|
||||
assert.equal(d.dept_name, departments[0].dept_name)
|
||||
assert.deepEqual(read(doctorPath, { ...doctorQuery, name: d.name }).lists, [d])
|
||||
assert.deepEqual(read(doctorPath, { ...doctorQuery, page_no: 2, page_size: 1 }).lists, [all.lists[1]])
|
||||
const slot = snapshot.slots.find(s => s.doctor_id === d.id && s.status === 1)
|
||||
const matches = read(rosterPath, { start_date: slot.date, end_date: slot.date, doctor_id: String(d.id), status: '1', period: 'segment' })
|
||||
assert.ok(matches.lists.some(s => s.id === slot.id))
|
||||
assert.ok(matches.lists.every(s => s.doctor_id === d.id && s.status === 1 && s.date === slot.date))
|
||||
assert.equal(read(rosterPath, { doctor_id: -1 }).count, 0)
|
||||
})
|
||||
|
||||
test('通用账号、导出、写入和未开放路由均不模拟', () => {
|
||||
for (const q of [{}, { role_id: 1 }, { ...doctorQuery, role_id: 2 }, { ...doctorQuery, export: 1 }]) {
|
||||
assert.equal(resolveRoster(doctorPath, q, snapshot), null)
|
||||
}
|
||||
for (const action of ['save', 'delete', 'batchSave', 'copy', 'detail']) {
|
||||
assert.equal(resolveRoster('/adminapi/doctor.roster/' + action, {}, snapshot), null)
|
||||
}
|
||||
assert.equal(resolveRoster(rosterPath, { export: 2 }, snapshot), null)
|
||||
})
|
||||
Reference in New Issue
Block a user