Merge branch 'main' into develop

# Conflicts:
#	backend/app/api/key_visits.py
#	backend/app/api/mini_business.py
#	backend/app/api/visits.py
#	backend/app/api/work_plans.py
#	backend/app/main.py
#	backend/app/models/__init__.py
#	backend/app/schemas/key_visit.py
#	backend/app/schemas/mini_business.py
#	backend/app/schemas/work_plan.py
#	backend/app/services/light_board.py
#	frontend/src/components/DesktopLayout.vue
#	frontend/src/stores/theme.ts
#	frontend/src/views/desktop/ManagerWorkspace.vue
#	frontend/src/views/desktop/WorkPlans.vue
#	frontend/src/views/mobile/KeyVisitForm.vue
#	frontend/src/views/mobile/LeaveForm.vue
#	frontend/src/views/mobile/PlansList.vue
#	frontend/src/views/mobile/VisitForm.vue
#	frontend/src/views/mobile/WorkPlanForm.vue
This commit is contained in:
2026-08-17 09:31:12 +08:00
46 changed files with 2682 additions and 213 deletions
@@ -0,0 +1,454 @@
# 暗黑模式 Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task.
**Goal:** 为企迹系统新增双选暗黑模式:用户在设置页分别选择亮色/暗色偏好主题,顶部栏一键切换亮↔暗。
**Architecture:** 扩展 theme store 支持 mode(light/dark) + lightTheme + darkTheme 三字段,新增 minimal-dark/tech-dark 两套 CSS 变量,Element Plus 通过 `html.dark` class 适配暗色。
**Tech Stack:** Vue 3 + Pinia + TypeScript + Element Plus + CSS Custom Properties
## Global Constraints
- 四大主题: editorial(已有), light(已有), minimal-dark(新增), tech-dark(新增)
- localStorage 持久化: mode, lightTheme, darkTheme 三项
- 暗色模式时 `<html>` 同时设置 `data-theme``class="dark"`
- 移动端暂不加主题切换(仅 PC 端顶部栏按钮)
- 保持现有 editorial/light 的 CSS 变量不变
---
### Task 1: 改造 Theme Store
**Files:**
- Modify: `frontend/src/stores/theme.ts`
**Interfaces:**
- Produces: `useThemeStore()` with `mode`, `lightTheme`, `darkTheme`, `effectiveTheme`, `toggleMode()`, `setLightTheme(t)`, `setDarkTheme(t)`, `applyTheme(t)`
- Theme type: `'editorial' | 'light' | 'minimal-dark' | 'tech-dark'`
- [ ] **Step 1: 重写 theme store**
```typescript
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export type Theme = 'editorial' | 'light' | 'minimal-dark' | 'tech-dark'
type Mode = 'light' | 'dark'
export const themeLabels: Record<Theme, string> = {
editorial: '编辑风',
light: '极简亮色',
'minimal-dark': '极简深色',
'tech-dark': '科技深色',
}
export const lightThemes: Theme[] = ['editorial', 'light']
export const darkThemes: Theme[] = ['minimal-dark', 'tech-dark']
export const useThemeStore = defineStore('theme', () => {
const mode = ref<Mode>((localStorage.getItem('theme-mode') as Mode) || 'light')
const lightTheme = ref<Theme>((localStorage.getItem('theme-light') as Theme) || 'editorial')
const darkTheme = ref<Theme>((localStorage.getItem('theme-dark') as Theme) || 'tech-dark')
const effectiveTheme = computed<Theme>(() => {
return mode.value === 'light' ? lightTheme.value : darkTheme.value
})
function applyTheme(theme: Theme, isDark: boolean) {
document.documentElement.setAttribute('data-theme', theme)
if (isDark) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
}
function apply() {
applyTheme(effectiveTheme.value, mode.value === 'dark')
}
function setLightTheme(theme: Theme) {
lightTheme.value = theme
localStorage.setItem('theme-light', theme)
if (mode.value === 'light') apply()
}
function setDarkTheme(theme: Theme) {
darkTheme.value = theme
localStorage.setItem('theme-dark', theme)
if (mode.value === 'dark') apply()
}
function toggleMode() {
mode.value = mode.value === 'light' ? 'dark' : 'light'
localStorage.setItem('theme-mode', mode.value)
apply()
}
// Apply on init
apply()
return { mode, lightTheme, darkTheme, effectiveTheme, setLightTheme, setDarkTheme, toggleMode }
})
```
- [ ] **Step 2: Commit**
```bash
git add frontend/src/stores/theme.ts
git commit -m "feat: 改造 theme store 支持暗黑模式双选架构"
```
---
### Task 2: 新增两套暗色 CSS 变量
**Files:**
- Modify: `frontend/src/App.vue` (在 `:root[data-theme="light"]` 块之后添加两个新块)
**Interfaces:**
- Consumes: Theme type `'minimal-dark'`, `'tech-dark'` from store
- Produces: CSS variables for both dark themes + Element Plus dark overrides
- [ ] **Step 1: 添加 minimal-dark 主题 CSS**
`:root[data-theme="light"]` 块结束后(第178行 `}` 之后),插入:
```css
/* ═══════════════════════════════════════════════════════════
THEME: Minimal Dark — 极简深色
═══════════════════════════════════════════════════════════ */
:root[data-theme="minimal-dark"] {
/* ── Core palette ── */
--ink: #E5E5E5;
--ink-light: #CCCCCC;
--ink-dark: #FFFFFF;
--vermilion: #F87171;
--vermilion-light: #FCA5A5;
--vermilion-dark: #EF4444;
--gold: #A78BFA;
--gold-light: #C4B5FD;
--gold-dark: #8B5CF6;
--paper: #1A1A1A;
--paper-dark: #141414;
--surface: #2D2D2D;
--sage: #4ADE80;
--amber: #FBBF24;
--warm-gray: #999999;
--warm-border: #3A3A3A;
/* ── Semantic tokens ── */
--c-primary: var(--ink);
--c-primary-light: var(--ink-light);
--c-primary-bg: #262626;
--c-accent: var(--vermilion);
--c-accent-light: var(--vermilion-light);
--c-gold: var(--gold);
--c-success: var(--sage);
--c-warning: var(--amber);
--c-danger: var(--vermilion);
--c-info: #60A5FA;
--c-text: #E5E5E5;
--c-text-secondary: #999999;
--c-text-muted: #666666;
--c-bg: var(--paper);
--c-bg-card: var(--surface);
--c-border: var(--warm-border);
/* ── Effects ── */
--shadow-sm: 0 1px 2px rgba(0,0,0,0.20);
--shadow: 0 1px 3px rgba(0,0,0,0.30);
--shadow-md: 0 2px 6px rgba(0,0,0,0.40);
--shadow-lg: 0 4px 12px rgba(0,0,0,0.50);
--radius: 0px;
--radius-sm: 0px;
--radius-xs: 0px;
--transition: 0.18s cubic-bezier(0.4, 0, 0.2, 1);
/* ── Sidebar — dark minimal ── */
--sidebar-bg: #141414;
--sidebar-color: #E5E5E5;
--sidebar-accent: var(--gold);
--sidebar-nav-text: #777777;
--sidebar-nav-text-hover: #CCCCCC;
--sidebar-nav-text-active: #FFFFFF;
--sidebar-nav-bg-hover: rgba(255,255,255,0.04);
--sidebar-nav-bg-active: rgba(255,255,255,0.06);
--sidebar-nav-border-active: var(--gold);
--sidebar-divider: #2A2A2A;
--sidebar-brand-color: #FFFFFF;
--sidebar-brand-sub-color: #666666;
--sidebar-group-label-color: #555555;
--sidebar-footer-role-color: var(--gold);
--sidebar-footer-name-color: #999999;
/* ── Mobile page accent ── */
--page-accent-color: rgba(167,139,250,0.06);
/* ── Manager chip tags ── */
--mgr-chip-text: #E5E5E5;
/* ── Fonts — sans-serif minimal ── */
--font-body: 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--font-heading: 'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
}
```
- [ ] **Step 2: 添加 tech-dark 主题 CSS**
在 minimal-dark 块之后插入:
```css
/* ═══════════════════════════════════════════════════════════
THEME: Tech Dark — 科技深色 (编辑风暗色版)
═══════════════════════════════════════════════════════════ */
:root[data-theme="tech-dark"] {
/* ── Core palette ── */
--ink: #C8D6E5;
--ink-light: #A0B4CC;
--ink-dark: #E8EEF4;
--vermilion: #F26B6B;
--vermilion-light: #F59898;
--vermilion-dark: #E55555;
--gold: #5B8DEF;
--gold-light: #7BA5F5;
--gold-dark: #4070D0;
--paper: #0B1120;
--paper-dark: #080C18;
--surface: #111B2E;
--sage: #4EC9B0;
--amber: #E5C07B;
--warm-gray: #6B7A8D;
--warm-border: #1E2D45;
/* ── Semantic tokens ── */
--c-primary: var(--ink);
--c-primary-light: var(--ink-light);
--c-primary-bg: #131D30;
--c-accent: var(--vermilion);
--c-accent-light: var(--vermilion-light);
--c-gold: var(--gold);
--c-success: var(--sage);
--c-warning: var(--amber);
--c-danger: var(--vermilion);
--c-info: #5B8DEF;
--c-text: #C8D6E5;
--c-text-secondary: #6B7A8D;
--c-text-muted: #455570;
--c-bg: var(--paper);
--c-bg-card: var(--surface);
--c-border: var(--warm-border);
/* ── Effects ── */
--shadow-sm: 0 1px 2px rgba(0,0,0,0.25);
--shadow: 0 2px 6px rgba(0,0,0,0.35);
--shadow-md: 0 6px 18px rgba(0,0,0,0.45);
--shadow-lg: 0 12px 36px rgba(0,0,0,0.55);
--radius: 2px;
--radius-sm: 2px;
--radius-xs: 2px;
--transition: 0.22s cubic-bezier(0.4, 0, 0.2, 1);
/* ── Sidebar — dark tech ── */
--sidebar-bg: #070D1A;
--sidebar-color: #C8D6E5;
--sidebar-accent: var(--gold);
--sidebar-nav-text: rgba(200,214,229,0.45);
--sidebar-nav-text-hover: rgba(200,214,229,0.80);
--sidebar-nav-text-active: #FFFFFF;
--sidebar-nav-bg-hover: rgba(91,141,239,0.06);
--sidebar-nav-bg-active: rgba(91,141,239,0.10);
--sidebar-nav-border-active: var(--gold);
--sidebar-divider: rgba(200,214,229,0.06);
--sidebar-brand-color: #FFFFFF;
--sidebar-brand-sub-color: rgba(200,214,229,0.35);
--sidebar-group-label-color: rgba(200,214,229,0.20);
--sidebar-footer-role-color: var(--gold);
--sidebar-footer-name-color: rgba(200,214,229,0.65);
/* ── Mobile page accent ── */
--page-accent-color: rgba(91,141,239,0.06);
/* ── Manager chip tags ── */
--mgr-chip-text: #C8D6E5;
/* ── Fonts — editorial Chinese ── */
--font-body: 'Noto Serif SC', STSong, Songti SC, '宋体', serif;
--font-heading: 'ZCOOL XiaoWei', STSong, Songti SC, serif;
--font-mono: 'JetBrains Mono', 'SF Mono', monospace;
}
```
- [ ] **Step 3: Commit**
```bash
git add frontend/src/App.vue
git commit -m "feat: 新增 minimal-dark 和 tech-dark 两套暗色 CSS 变量"
```
---
### Task 3: 改造 DesktopLayout 顶部栏按钮
**Files:**
- Modify: `frontend/src/components/DesktopLayout.vue` (script 和 template 中的主题切换按钮)
**Interfaces:**
- Consumes: `useThemeStore()``mode`, `toggleMode()`
- [ ] **Step 1: 替换主题按钮为亮/暗切换**
`cycleTheme` 函数替换为 `toggleMode`,按钮改为 sun/moon 图标切换:
```typescript
// 替换 cycleTheme 函数:
function toggleDarkMode() {
themeStore.toggleMode()
}
```
Template 中替换按钮:
```html
<button
class="topbar-btn"
@click="toggleDarkMode"
:title="themeStore.mode === 'light' ? '切换至暗色模式' : '切换至亮色模式'"
>
<!-- Sun icon (light mode) -->
<svg v-if="themeStore.mode === 'light'" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="5"></circle>
<line x1="12" y1="1" x2="12" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="23"></line>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
<line x1="1" y1="12" x2="3" y2="12"></line>
<line x1="21" y1="12" x2="23" y2="12"></line>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
</svg>
<!-- Moon icon (dark mode) -->
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
</svg>
</button>
```
- [ ] **Step 2: 触发构建验证**
```bash
cd frontend && npm run build -- --emptyOutDir
```
- [ ] **Step 3: Commit**
```bash
git add frontend/src/components/DesktopLayout.vue
git commit -m "feat: 桌面端顶部栏改为亮/暗模式切换按钮"
```
---
### Task 4: 改造设置页面主题面板
**Files:**
- Modify: `frontend/src/views/desktop/Settings.vue` (替换 Theme 卡片为双选下拉)
**Interfaces:**
- Consumes: `useThemeStore()``lightTheme`, `darkTheme`, `mode`, `setLightTheme()`, `setDarkTheme()`
- [ ] **Step 1: 替换主题选择区域**
Replace the el-card template section (lines 158-173) and the `themeLabels` import:
**Script 部分修改 import:**
```typescript
import { useThemeStore, themeLabels, lightThemes, darkThemes, type Theme } from '@/stores/theme'
```
**Template 部分替换主题卡片:**
```html
<!-- Theme -->
<el-card class="setting-card">
<template #header>
<div class="card-header-title">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:6px; color: var(--gold)">
<circle cx="12" cy="12" r="5"></circle><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"></path>
</svg>
界面主题
</div>
</template>
<div class="theme-config">
<div class="theme-row">
<span class="theme-label">☀️ 亮色模式主题</span>
<el-select :model-value="themeStore.lightTheme" @update:model-value="themeStore.setLightTheme($event as Theme)" style="width:200px">
<el-option v-for="t in lightThemes" :key="t" :label="themeLabels[t]" :value="t" />
</el-select>
<span v-if="themeStore.mode === 'light'" class="theme-badge theme-badge--active">当前</span>
</div>
<div class="theme-row">
<span class="theme-label">🌙 暗色模式主题</span>
<el-select :model-value="themeStore.darkTheme" @update:model-value="themeStore.setDarkTheme($event as Theme)" style="width:200px">
<el-option v-for="t in darkThemes" :key="t" :label="themeLabels[t]" :value="t" />
</el-select>
<span v-if="themeStore.mode === 'dark'" class="theme-badge theme-badge--active">当前</span>
</div>
</div>
</el-card>
```
**Style 部分替换 `.theme-options` 样式:**
```css
/* ── Theme Config ── */
.theme-config { display: flex; flex-direction: column; gap: 12px; }
.theme-row { display: flex; align-items: center; gap: 12px; }
.theme-label { font-family: var(--font-body); font-size: 14px; color: var(--c-text); min-width: 140px; }
.theme-badge { font-size: 11px; padding: 2px 8px; border-radius: 2px; font-family: var(--font-mono); }
.theme-badge--active { background: var(--c-primary); color: #fff; }
```
- [ ] **Step 2: 触发构建验证**
```bash
cd frontend && npm run build -- --emptyOutDir
```
- [ ] **Step 3: Commit**
```bash
git add frontend/src/views/desktop/Settings.vue
git commit -m "feat: 设置页改为亮/暗双选主题配置面板"
```
---
### Task 5: 验证与收尾
- [ ] **Step 1: 完整构建**
```bash
cd frontend && npm run build
```
- [ ] **Step 2: 检查 localStorage 兼容性**
验证旧 `localStorage.setItem('theme', ...)` 数据不会导致新系统崩溃。在 theme store 的 `apply()` 中已有兜底逻辑。
- [ ] **Step 3: 快速手动测试检查清单**
- [ ] 默认加载为 editorial 亮色
- [ ] 点击顶部栏 ☀️→🌙 切换到 tech-dark
- [ ] 设置页切换亮色主题为 light,暗色主题为 minimal-dark
- [ ] 点击顶部栏按钮在两主题间切换
- [ ] 刷新页面偏好保持
- [ ] Element Plus 组件(表格/对话框/按钮)在暗色下正常
- [ ] **Step 4: Commit**
```bash
git add -A
git commit -m "chore: 暗黑模式最终验证通过"
```
@@ -0,0 +1,130 @@
# 商机跟单优化 — 跟进记录子表 — 设计文档
> 日期:2026-07-12 | 状态:已确认
## 一、需求概述
当前商机跟单只有一条静态记录(产品+金额+跟进内容文本+状态),缺少"持续跟进"的时间线感。新增跟进记录子表,将每个商机从"快照"变为"持续跟单"。
## 二、核心决策
| 决策项 | 结论 |
|--------|------|
| 方案 | 新增 `mini_business_logs` 子表 |
| 跟进方式 | 电话/微信/上门/邮件/其他(chip 按钮选择) |
| 原 follow_up_detail | 保留,含义改为"商机概述/背景" |
| 状态 | 不变(跟进中/已签约/已流失) |
## 三、新增表 `mini_business_logs`
```sql
CREATE TABLE mini_business_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES mini_business(id) ON DELETE CASCADE,
log_date DATE NOT NULL,
method VARCHAR(20) NOT NULL DEFAULT '电话',
content TEXT NOT NULL DEFAULT '',
created_by UUID NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX idx_mbl_business_id ON mini_business_logs(business_id);
CREATE INDEX idx_mbl_log_date ON mini_business_logs(log_date);
```
### SQLAlchemy 模型
```python
class MiniBusinessLog(Base):
__tablename__ = "mini_business_logs"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
business_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("mini_business.id", ondelete="CASCADE"), index=True)
log_date: Mapped[date] = mapped_column(Date)
method: Mapped[str] = mapped_column(String(20), default="电话")
content: Mapped[str] = mapped_column(Text, default="")
created_by: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
```
### MiniBusiness 模型添加 relationship
```python
logs: Mapped[list["MiniBusinessLog"]] = relationship(back_populates="business", cascade="all, delete-orphan")
```
## 四、商机主体字段调整
| 字段 | 变更 | 前端 label |
|------|------|-----------|
| `follow_up_detail` | 保留,含义改为商机概述 | "商机概述" |
| 其他字段 | 不变 | |
## 五、API
### 子路由
| 方法 | 路径 | 说明 | 权限 |
|------|------|------|------|
| `GET` | `/mini-business/{id}/logs` | 获取跟进记录列表(date DESC) | 经理仅看自己 |
| `POST` | `/mini-business/{id}/logs` | 新增跟进记录 | 经理本人或支局长/领导 |
| `PUT` | `/mini-business/logs/{log_id}` | 编辑跟进记录 | 创建人或支局长/领导 |
| `DELETE` | `/mini-business/logs/{log_id}` | 删除跟进记录 | 创建人或支局长/领导 |
### 请求体 (POST/PUT)
```json
{
"log_date": "2026-07-12",
"method": "电话",
"content": "客户反馈价格偏高,需进一步沟通方案"
}
```
### 跟进方式枚举
`["电话", "微信", "上门", "邮件", "其他"]`
## 六、前端
### PC 端 — 商机列表页增强
- 表格新增「最近跟进」列(最近一次跟进日期 + 跟进次数 badge)
- 点击客户名打开详情弹窗(替代直接编辑)
- 详情弹窗:上部=商机基本信息(客户/产品/金额/状态/概述)+ 编辑按钮,下部=跟进时间线 + 新增跟进入口
### PC 端 — 跟进时间线组件
```
📞 07-10 电话 — 客户反馈价格偏高,需进一步沟通 [编辑] [删除]
🏢 07-05 上门 — 现场演示产品功能,客户初步认可 [编辑] [删除]
📧 07-01 邮件 — 发送报价方案 [编辑] [删除]
```
- 按日期倒序,最新在上
- 每条显示:方式图标 + 日期 + 内容 + 操作按钮
- 底部「新增跟进」按钮展开内联表单(日期+方式 chip+内容 textarea
### 移动端 — 商机表单页改为详情页
- 现有新建表单保留
- 新增商机详情页(路由 `/m/mini-biz/:id`
- 上部:商机信息卡片(可点击编辑)
- 下部:跟进时间线 + 底部固定「新增跟进」按钮
### 移动端 — 首页入口
- Home.vue 的「商机跟单」chip 改为跳转商机列表(需新增 `/m/mini-biz` 路由)
## 七、文件变更
| 类型 | 文件 | 说明 |
|------|------|------|
| 新增 | `models/mini_business_log.py` | Log 模型 |
| 新增 | `schemas/mini_business_log.py` | Log Schema |
| 新增 | `api/mini_business_logs.py` | Log CRUD API |
| 修改 | `models/mini_business.py` | 添加 logs relationship |
| 修改 | `models/__init__.py` | 注册新模型 |
| 修改 | `main.py` | lifespan 自动建表 |
| 修改 | `MiniBusiness.vue` (PC) | 详情弹窗 + 时间线 |
| 修改 | `MiniBusinessForm.vue` (mobile) | 改为详情页模式 |
| 新增 | `frontend/src/api/miniBusiness.ts` | 追加 logs API |
| 新增 | 移动端商机列表页 | `/m/mini-biz` |
@@ -0,0 +1,122 @@
# 工作计划状态自动流转 — 设计文档
> 日期:2026-07-12 | 状态:已确认
## 一、需求概述
工作计划目前有三种状态(计划中/已完成/已取消),完全依赖手动切换。利用已有的拜访记录数据,实现状态的自动流转,减少客户经理手动操作。
## 二、核心决策
| 决策项 | 结论 |
|--------|------|
| 匹配精度 | 仅匹配 `customer_id`(任何人拜访该客户即触发,与现有逻辑一致) |
| 增强范围 | 创建/更新触发完成 + 逾期自动取消 + Excel 导入联动 |
| 删除回退 | 不做(边缘场景少,复杂度高) |
## 三、现状
- `POST /visits/` 已有自动完成逻辑:同一 `customer_id` + `plan_date <= visit_date` → 标记"已完成"
- 该逻辑嵌在 API 层,不可复用
- 更新拜访、Excel 导入均不触发自动完成
- 逾期计划(`plan_date < today`)只发企微提醒,不自动取消
## 四、设计
### 4.1 抽取可复用函数
**文件:** `backend/app/services/visits.py`(如不存在则新建,如已有则追加)
```python
async def auto_complete_work_plans(
db: AsyncSession,
customer_id: UUID,
visit_date: date,
editor_name: str,
reason: str = "拜访自动完成",
) -> int:
"""将匹配的工作计划自动标记为已完成。返回完成数量。"""
from app.models.work_plan import WorkPlan
from app.utils.edit_log import append_entry as append_edit_log
plans_result = await db.execute(
select(WorkPlan).where(
WorkPlan.customer_id == customer_id,
WorkPlan.status == "计划中",
WorkPlan.plan_date <= visit_date,
)
)
count = 0
for plan in plans_result.scalars().all():
plan.status = "已完成"
append_edit_log(plan, editor_name, [{
"field": "status", "from": "计划中", "to": "已完成",
"reason": reason,
}])
count += 1
return count
```
### 4.2 三处调用点
| 调用点 | 文件 | 触发时机 | reason 参数 |
|--------|------|---------|------------|
| POST /visits/ | `api/visits.py` | 创建拜访后 | `"拜访自动完成"` |
| PUT /visits/{id} | `api/visits.py` | 更新拜访后 | `"拜访更新自动完成"` |
| excel_import.py | `services/excel_import.py` | 导入每条拜访后 | `"旧周报导入自动完成"` |
### 4.3 逾期计划自动取消
**文件:** `backend/app/services/scheduler.py``check_overdue_plans` 函数
在现有「发送企微提醒」逻辑后新增:
```python
# 自动取消:逾期且无匹配拜访记录的计划
for plan in overdue:
has_visit = await db.execute(
select(Visit.id).where(
Visit.customer_id == plan.customer_id,
Visit.visit_date >= plan.plan_date,
)
)
if not has_visit.scalar():
plan.status = "已取消"
append_edit_log(plan, "系统", [{
"field": "status", "from": "计划中", "to": "已取消",
"reason": "逾期自动取消",
}])
```
每日 09:00 执行,与现有逾期检查共用一个调度任务。
### 4.4 状态流转总图
```
计划中 ──┬── 拜访创建/更新/导入(customer_id + plan_date <= visit_date)──→ 已完成
└── 每日 09:00 调度(plan_date < today 且无匹配拜访)───────────→ 已取消
```
## 五、文件变更
### 后端新增/修改
| 文件 | 变更 |
|------|------|
| `backend/app/services/visits.py` | 新增 `auto_complete_work_plans()` 函数 |
| `backend/app/api/visits.py` | POST 重构为调用 service 函数;PUT 新增调用 |
| `backend/app/services/excel_import.py` | 导入拜访后调用自动完成 |
| `backend/app/services/scheduler.py` | `check_overdue_plans` 新增自动取消逻辑 |
### 前端
无需改动。
## 六、验证要点
1. 创建拜访 → 匹配的计划自动变为"已完成"edit_log 有记录
2. 更新拜访日期 → 匹配的计划自动完成
3. 导入旧周报 → 导入的拜访触发计划自动完成
4. 逾期且无拜访的计划 → 每日 09:00 自动变为"已取消"
5. 逾期但有拜访的计划 → 保持"计划中"(已有拜访覆盖,不算僵尸)