create table `autoflow-demo`.aldebaran_alembic_version
(
    version_num varchar(32) not null
        primary key
);

create table `autoflow-demo`.alembic_version
(
    version_num varchar(32) not null
        primary key
);

create table `autoflow-demo`.auth_roles
(
    id          int auto_increment
        primary key,
    create_time datetime   default CURRENT_TIMESTAMP null,
    update_time datetime   default CURRENT_TIMESTAMP null,
    code        varchar(100)                         not null,
    name        varchar(100)                         not null,
    description varchar(255)                         null,
    is_system   tinyint(1) default 0                 not null,
    permissions json                                 null,
    constraint code
        unique (code),
    constraint ix_auth_roles_code
        unique (code)
);

create table `autoflow-demo`.auth_user_roles
(
    id          int auto_increment
        primary key,
    create_time datetime default CURRENT_TIMESTAMP null,
    update_time datetime default CURRENT_TIMESTAMP null,
    user_id     char(36)                           not null,
    role_id     int                                not null,
    crm_user_id varchar(100)                       null,
    constraint fk_1
        foreign key (role_id) references `autoflow-demo`.auth_roles (id)
);

create index ix_auth_user_roles_crm_user_id
    on `autoflow-demo`.auth_user_roles (crm_user_id);

create index ix_auth_user_roles_user_id
    on `autoflow-demo`.auth_user_roles (user_id);

create table `autoflow-demo`.bi_reports
(
    id                        int auto_increment
        primary key,
    report_id                 varchar(255)                          not null comment '报告ID',
    plan_id                   varchar(255)                          null comment '执行计划ID',
    execution_id              varchar(255)                          not null comment '执行ID, naming convention: <plan_id>_<version>',
    report_type               varchar(64)                           not null comment '报告类型，例如: previsit, postvisit, quarterly, etc.',
    report_name               varchar(255)                          null comment '报告名称',
    report_status             varchar(32) default 'published'       null comment '报告状态: draft, published, archived',
    report_content            mediumtext                            null comment '报告内容，包含所有分析结果',
    report_content_en         mediumtext                            null comment '报告内容英文',
    report_content_multi_lang mediumtext                            null comment '报告内容(多语言)',
    report_metadata           text                                  null comment '报告元数据，例如生成参数、来源等',
    version                   int         default 1                 null comment '报告版本号',
    created_by                varchar(64)                           null comment '创建人',
    updated_by                varchar(64)                           null comment '更新人',
    created_at                datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    account_id                varchar(255)                          null comment '关联客户唯一ID，用于避免报告查询时解析report_content',
    constraint execution_id
        unique (execution_id)
)
    comment '销售报告表';

create index idx_bi_reports_type_account_created
    on `autoflow-demo`.bi_reports (report_type, account_id, created_at);

create index idx_created_at
    on `autoflow-demo`.bi_reports (created_at);

create index idx_execution_id
    on `autoflow-demo`.bi_reports (execution_id);

create index idx_report_id
    on `autoflow-demo`.bi_reports (report_id);

create index idx_report_type
    on `autoflow-demo`.bi_reports (report_type);

create table `autoflow-demo`.corporation
(
    id                 bigint auto_increment comment '主键ID（自增序列）'
        primary key,
    corp_name          varchar(255)                         not null comment '企业全称',
    group_id           varchar(255)                         null comment '集团名称',
    social_credit_code varchar(18)                          null comment '统一社会信用代码（18位国家标准）',
    registered_country varchar(255)                         null comment '企业注册国家/地区',
    tenant_key         varchar(128)                         null comment '飞书租户唯一标识',
    app_id             varchar(64)                          null comment '飞书应用ID',
    app_secret         varchar(256)                         null comment '飞书应用密钥',
    business_status    varchar(20)                          null comment '经营状态（如存续、吊销等）',
    creator            varchar(255)                         null comment '创建者',
    create_time        datetime   default CURRENT_TIMESTAMP null comment '创建时间',
    updater            varchar(255)                         null comment '更新者',
    update_time        datetime   default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP comment '最后更新时间',
    version            int        default 1                 null comment '数据版本',
    delete_flag        tinyint(1) default 0                 null comment '删除标识, 1已删除',
    corp_en_name       varchar(255)                         not null comment '企业en名称',
    extra_info         json                                 null comment '扩展信息'
);

create table `autoflow-demo`.crm_account_assessment
(
    id                        int auto_increment
        primary key,
    unique_id                 varchar(255)                       not null comment '唯一性ID（必填）',
    assessment_date           date                               not null comment '日期',
    account_id                varchar(255)                       null comment '客户ID',
    account_name              varchar(255)                       null comment '客户名称',
    customer_type             varchar(50)                        null comment '客户类型(end_customer/partner)',
    account_level             varchar(255)                       null comment '客户等级',
    is_first_visit            tinyint(1)                         null comment '是否首次拜访',
    assessment_flag           text                               null comment '评估结果(red/yellow/green)',
    assessment_description    text                               null comment '评估描述',
    assessment_description_en text                               null comment '评估描述英文',
    opportunity_ids           text                               null comment '商机UniqueID列表, json Array格式',
    opportunity_names         text                               null comment '商机名称列表, json Array格式',
    follow_up_note            text                               null comment '销售跟进记录',
    follow_up_note_en         text                               null comment '销售跟进记录(英文)',
    follow_up_next_step       text                               null comment '销售跟进下一步',
    follow_up_next_step_en    text                               null comment '销售跟进下一步(英文)',
    correlation_id            varchar(255)                       null comment '关联ID，用于链接到CRMDailyAccountStatistics',
    create_time               datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time               datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at                datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '客户评估表';

create table `autoflow-demo`.crm_account_opportunity_assessment
(
    id                        int auto_increment
        primary key,
    unique_id                 varchar(255)                       not null comment '唯一性ID（必填）',
    assessment_date           date                               not null comment '评估日期',
    account_id                varchar(255)                       null comment '客户ID',
    account_name              varchar(255)                       null comment '客户名称',
    opportunity_id            varchar(255)                       null comment '商机ID（NULL表示未关联商机）',
    opportunity_name          varchar(255)                       null comment '商机名称（NULL表示未关联商机）',
    assessment_flag           text                               null comment '评估结果(red/yellow/green)',
    assessment_description    text                               null comment '评估描述',
    assessment_description_en text                               null comment '评估描述(英文)',
    customer_type             varchar(50)                        null comment '客户类型(end_customer/partner)',
    account_level             varchar(255)                       null comment '客户等级',
    is_first_visit            tinyint(1)                         null comment '是否首次拜访',
    follow_up_note            text                               null comment '销售跟进记录',
    follow_up_note_en         text                               null comment '销售跟进记录(英文)',
    follow_up_next_step       text                               null comment '销售跟进下一步',
    follow_up_next_step_en    text                               null comment '销售跟进下一步(英文)',
    correlation_id            varchar(255)                       null comment '关联ID，用于链接到部门/公司汇总',
    create_time               datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time               datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at                datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '客户商机评估表';

create index idx_account_opportunity_date
    on `autoflow-demo`.crm_account_opportunity_assessment (account_id, opportunity_id, assessment_date);

create index idx_assessment_date
    on `autoflow-demo`.crm_account_opportunity_assessment (assessment_date);

create index idx_correlation_id
    on `autoflow-demo`.crm_account_opportunity_assessment (correlation_id);

create index idx_opportunity_id
    on `autoflow-demo`.crm_account_opportunity_assessment (opportunity_id);

create table `autoflow-demo`.crm_account_review_execution_index
(
    id                  int auto_increment
        primary key,
    account_id          varchar(255)                       not null comment '客户唯一性ID',
    execution_id        varchar(255)                       not null comment '最新review2报告的execution_id',
    report_id           varchar(255)                       null comment '报告ID',
    plan_id             varchar(255)                       null comment '执行计划ID',
    report_created_time datetime                           not null comment '报告创建时间',
    last_updated_time   datetime default CURRENT_TIMESTAMP not null comment '索引最后更新时间',
    create_time         datetime default CURRENT_TIMESTAMP not null comment '索引创建时间',
    created_at          datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at          datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint account_id
        unique (account_id)
)
    comment '客户复盘执行索引表';

create index idx_execution_id
    on `autoflow-demo`.crm_account_review_execution_index (execution_id);

create index idx_report_created_time
    on `autoflow-demo`.crm_account_review_execution_index (report_created_time);

create table `autoflow-demo`.crm_accounts
(
    id                    int auto_increment comment '主键ID'
        primary key,
    unique_id             varchar(255) null comment '唯一性ID（必填）',
    customer_name         varchar(255) null comment '客户名称（必填）',
    customer_source       varchar(255) null comment '客户来源（必填）',
    person_in_charge      varchar(255) null comment '负责人',
    department            varchar(255) null comment '负责人主属部门',
    customer_level        varchar(255) null comment '客户等级',
    industry              varchar(255) null comment '客户行业（必填）',
    phone                 varchar(255) null comment '电话',
    website               text         null comment '网址',
    email                 varchar(255) null comment '邮件',
    remarks               text         null comment '备注',
    allocation_status     varchar(255) null comment '分配状态',
    deal_status           varchar(255) null comment '成交状态',
    last_follow_up        datetime     null comment '最后跟进时间',
    last_deal_time        datetime     null comment '最后一次成交时间',
    allocation_time       datetime     null comment '领取/分配时间',
    business_type         varchar(255) null comment '业务类型（必填）',
    life_status           varchar(255) null comment '生命状态',
    belonging_department  varchar(255) null comment '归属部门',
    creator               varchar(255) null comment '创建人',
    creation_time         datetime     null comment '创建时间',
    last_modifier         varchar(255) null comment '最后修改人',
    last_modified_time    datetime     null comment '最后修改时间',
    customer_identifier   varchar(255) null comment '客户标识',
    customer_code         varchar(255) null comment '客户编号',
    earliest_deal_date    datetime     null comment '最早成交日期',
    latest_deal_date      datetime     null comment '最新成交日期',
    customer_abbreviation varchar(255) null comment '客户简称',
    customer_attribute    varchar(255) null comment '客户属性',
    partner               varchar(255) null comment '合作伙伴',
    belonging_pool        varchar(255) null comment '所属公海',
    legal_representative  varchar(255) null comment '法定代表人',
    country               varchar(255) null comment '国家',
    province              varchar(255) null comment '省',
    city                  varchar(255) null comment '市',
    district              varchar(255) null comment '区',
    address               varchar(512) null comment '详细地址',
    customer_scale_new    varchar(255) null comment '客户规模-新',
    first_deal_date       varchar(255) null comment '最早成交日期（归档日期）',
    account_level         varchar(255) null comment 'Name Account 分级',
    key_actions           text         null comment 'top 3 key action',
    daily_followup        text         null comment '客户日常跟进',
    account_type          varchar(255) null comment '实体类型',
    delete_flag           tinyint(1)   null comment '删除标识（0-正常，1-已删除）',
    extra                 json         null comment '扩展内容',
    support_person        json         null comment '辅助人员列表，JSON格式存储多个辅助人员的userid和name',
    status                varchar(255) null comment '客户状态（"未生效"、"审核中"、"活跃"、"已废弃"）',
    person_in_charge_id   varchar(255) null comment '负责人ID（对应crm_user.user_id）',
    constraint uq_crm_accounts_unique_id
        unique (unique_id)
)
    comment '客户表';

create table `autoflow-demo`.crm_accounts_snapshot
(
    id                    int auto_increment comment '主键ID'
        primary key,
    unique_id             varchar(255) null comment '唯一性ID（必填）',
    customer_name         varchar(255) null comment '客户名称（必填）',
    customer_source       varchar(255) null comment '客户来源（必填）',
    person_in_charge      varchar(255) null comment '负责人',
    department            varchar(255) null comment '负责人主属部门',
    customer_level        varchar(255) null comment '客户等级',
    industry              varchar(255) null comment '客户行业（必填）',
    phone                 varchar(255) null comment '电话',
    website               text         null comment '网址',
    email                 varchar(255) null comment '邮件',
    remarks               text         null comment '备注',
    allocation_status     varchar(255) null comment '分配状态',
    deal_status           varchar(255) null comment '成交状态',
    last_follow_up        datetime     null comment '最后跟进时间',
    last_deal_time        datetime     null comment '最后一次成交时间',
    allocation_time       datetime     null comment '领取/分配时间',
    business_type         varchar(255) null comment '业务类型（必填）',
    life_status           varchar(255) null comment '生命状态',
    belonging_department  varchar(255) null comment '归属部门',
    creator               varchar(255) null comment '创建人',
    creation_time         datetime     null comment '创建时间',
    last_modifier         varchar(255) null comment '最后修改人',
    last_modified_time    datetime     null comment '最后修改时间',
    customer_identifier   varchar(255) null comment '客户标识',
    customer_code         varchar(255) null comment '客户编号',
    earliest_deal_date    datetime     null comment '最早成交日期',
    latest_deal_date      datetime     null comment '最新成交日期',
    customer_abbreviation varchar(255) null comment '客户简称',
    customer_attribute    varchar(255) null comment '客户属性',
    partner               varchar(255) null comment '合作伙伴',
    belonging_pool        varchar(255) null comment '所属公海',
    legal_representative  varchar(255) null comment '法定代表人',
    country               varchar(255) null comment '国家',
    province              varchar(255) null comment '省',
    city                  varchar(255) null comment '市',
    district              varchar(255) null comment '区',
    address               varchar(512) null comment '详细地址',
    customer_scale_new    varchar(255) null comment '客户规模-新',
    first_deal_date       varchar(255) null comment '最早成交日期（归档日期）',
    account_level         varchar(255) null comment 'Name Account 分级',
    key_actions           text         null comment 'top 3 key action',
    daily_followup        text         null comment '客户日常跟进',
    snapshot_date         date         null comment '快照日期',
    account_type          varchar(255) null comment '实体类型',
    delete_flag           tinyint(1)   null comment '删除标识（0-正常，1-已删除）',
    extra                 json         null comment '扩展内容',
    support_person        json         null comment '辅助人员列表，JSON格式存储多个辅助人员的userid和name',
    status                varchar(255) null comment '客户状态（"未生效"、"审核中"、"活跃"、"已废弃"）',
    person_in_charge_id   varchar(255) null comment '负责人ID（对应crm_user.user_id）',
    constraint uq_snapshot_unique_id_snapshot_date
        unique (unique_id, snapshot_date)
)
    comment '客户表快照';

create table `autoflow-demo`.crm_achievement_timeseries
(
    id               bigint auto_increment
        primary key,
    period_type      varchar(10)          not null comment 'yearly, quarterly, monthly',
    period varchar (20) not null comment 'FY26, FY26Q1, 2025-04',
    scope_type       varchar(20)          not null comment 'company, department, owner',
    scope_id         varchar(100)         null comment 'department_id or owner_id; NULL for company',
    scope_name       varchar(200)         null comment 'department or owner name; NULL for company',
    granularity      varchar(10)          not null comment 'daily or weekly',
    point_date       date                 not null comment 'date this data point represents',
    target           decimal(18, 2)       null comment 'target line',
    cum_closed       decimal(18, 2)       null comment 'Closed Won by close_date ≤ point_date',
    cum_commit_sales decimal(18, 2)       null comment 'cum_closed + sales Commit projected',
    cum_commit_ai    decimal(18, 2)       null comment 'cum_closed + AI Commit projected',
    cum_upside_sales decimal(18, 2)       null comment 'cum_closed + Commit + Upside projected',
    version          int        default 1 not null,
    is_active        tinyint(1) default 1 not null comment '1=active, 0=superseded',
    superseded_at    datetime             null,
    superseded_by    varchar(100)         null,
    as_of_date       date                 not null comment 'run_date when this snapshot was computed',
    data_cutoff_date date                 null comment 'Data cut-off (inclusive). When NULL, treat as_of_date as cut-off.',
    computed_at      datetime             not null,
    execution_id     varchar(100)         null
)
    comment 'Pre-computed cumulative achievement time-series for line chart';

create index idx_ts_as_of
    on `autoflow-demo`.crm_achievement_timeseries (as_of_date, is_active);

create index idx_ts_lookup
    on `autoflow-demo`.crm_achievement_timeseries (period_type, period, scope_type, scope_id, granularity, as_of_date,
                                                   point_date, is_active);

create index idx_ts_version
    on `autoflow-demo`.crm_achievement_timeseries (period, version, is_active);

create table `autoflow-demo`.crm_acv_targets
(
    id          int auto_increment
        primary key,
    fiscal_year varchar(9)                         not null comment '财年（如2026/2027）',
    quarter     varchar(8)                         null comment '季度（如Q1、Q2、Q3、Q4，NULL表示全年）',
    category    varchar(255)                       null comment '类别(FCST/FCST_NE)',
    department  varchar(255)                       null comment '部门',
    owner       varchar(255)                       null comment '负责人',
    target_acv  decimal(18, 2)                     not null comment 'ACV目标',
    notes       text                               null comment '备注',
    create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    biz_key     varchar(16) as (null) comment '业务主键（如FY26Q1，全年为FY26）',
    created_at  datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at  datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '按财年/季度保存ACV目标（quarter为NULL表示全年）';

create table `autoflow-demo`.crm_alembic_version
(
    version_num varchar(32) not null
        primary key
);

create table `autoflow-demo`.crm_api_clients
(
    id                        int auto_increment comment '主键ID'
        primary key,
    client_id                 varchar(255) null comment '客户端ID',
    client_secret_hash        varchar(255) null comment '客户端密钥哈希',
    client_name               varchar(255) null comment '客户端名称',
    is_active                 tinyint(1)   null comment '是否激活',
    access_token_expiry_hours int          null comment '访问令牌过期时间（小时）',
    refresh_token_expiry_days int          null comment '刷新令牌过期时间（天）',
    created_at                timestamp    null comment '创建时间',
    updated_at                timestamp    null comment '更新时间'
)
    comment 'CRM API 客户端';

create table `autoflow-demo`.crm_api_refresh_tokens
(
    id         int auto_increment comment '主键ID'
        primary key,
    client_id  varchar(255) null comment '客户端ID',
    token_hash varchar(255) null comment '令牌哈希',
    expires_at timestamp    not null comment '过期时间',
    is_revoked tinyint(1)   null comment '是否撤销',
    created_at timestamp    null comment '创建时间'
)
    comment 'CRM API 刷新令牌';

create table `autoflow-demo`.crm_charge_audit
(
    id                       int auto_increment
        primary key,
    execution_id             varchar(255)                          not null comment '工作流执行ID',
    plan_id                  varchar(255)                          not null comment '执行计划ID',
    report_id                varchar(255)                          null comment '报告ID',
    version                  int                                   null comment '执行版本',
    step_id                  varchar(255)                          null comment '产生计费项的步骤ID',
    charge_item_type         varchar(100)                          not null comment '计费项类型',
    business_object_type     varchar(100)                          not null comment '业务对象类型，如account/opportunity',
    business_object_id       varchar(255)                          not null comment '业务对象ID',
    business_object_name     varchar(255)                          null comment '业务对象名称',
    trace_id                 varchar(100)                          not null comment '外部计费trace_id',
    operator                 varchar(100)                          not null comment '操作人',
    item_url                 varchar(500)                          null comment '计费项结果URL',
    review_detail            varchar(500)                          not null comment '计费明细链接或引用',
    ai_module_key            varchar(100)                          not null comment 'AI模块key',
    status                   varchar(50) default 'pending'         not null comment 'pending/sent/failed/skipped',
    external_usage_record_id varchar(255)                          null comment '外部用量记录ID',
    external_sync_status     varchar(100)                          null comment '外部同步状态',
    charge_request           json                                  null comment '发送给外部计费服务的请求',
    charge_response          json                                  null comment '外部计费服务响应',
    error_message            text                                  null comment '错误信息',
    created_at               datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at               datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    charged_at               datetime                              null comment '发送计费时间',
    constraint uq_crm_charge_audit_business_item
        unique (execution_id, ai_module_key, business_object_type, business_object_id),
    constraint uq_crm_charge_audit_trace_id
        unique (trace_id)
)
    comment 'AI计费审计表';

create index idx_crm_charge_audit_business_object
    on `autoflow-demo`.crm_charge_audit (business_object_type, business_object_id);

create index idx_crm_charge_audit_execution
    on `autoflow-demo`.crm_charge_audit (execution_id, plan_id);

create index idx_crm_charge_audit_status
    on `autoflow-demo`.crm_charge_audit (status);

create table `autoflow-demo`.crm_contacts
(
    id                     int auto_increment comment '主键ID'
        primary key,
    unique_id              varchar(255) not null comment '唯一性ID（必填）',
    name                   varchar(255) not null comment '联系人姓名（必填）',
    customer_id            varchar(255) null comment '客户名称_唯一性ID',
    customer_name          varchar(255) null comment '客户名称',
    department1            varchar(255) null comment '部门1',
    position1              varchar(255) null comment '职务1',
    gender                 varchar(10)  null comment '性别',
    birthday               date         null comment '生日',
    key_decision_maker     varchar(255) null comment '关键决策人',
    mobile1                varchar(255) null comment '手机',
    phone1                 varchar(255) null comment '电话',
    email                  varchar(255) null comment '邮件',
    address                varchar(255) null comment '联系地址',
    responsible_person     varchar(255) not null comment '负责人（必填）',
    responsible_department varchar(255) null comment '负责人主属部门',
    affiliate_department   varchar(255) null comment '归属部门',
    attitude               varchar(255) null comment '态度',
    status                 varchar(255) null comment '状态',
    department             varchar(255) null comment '部门',
    position               varchar(255) null comment '职务',
    email_account          varchar(255) null comment '邮箱账号',
    wechat                 varchar(255) null comment '微信',
    position_id            varchar(255) null comment '联系人职务_唯一性ID',
    position_name          varchar(255) null comment '联系人职务',
    source                 varchar(255) null comment '来源',
    direct_superior        varchar(255) null comment '直属上级',
    direct_superior_id     varchar(255) null comment '直属上级_唯一性ID',
    last_modified_time     datetime     null comment '最后修改时间',
    delete_flag            tinyint(1)   null comment '删除标识（0-正常，1-已删除）',
    extra                  json         null comment '扩展内容',
    constraint uq_crm_contacts_unique_id
        unique (unique_id)
)
    comment '联系人信息表';

create table `autoflow-demo`.crm_daily_account_statistics
(
    id                             int auto_increment
        primary key,
    unique_id                      varchar(255)                       not null comment '唯一性ID',
    report_date                    date                               not null comment '日期',
    sales_id                       varchar(255)                       null comment '销售ID',
    sales_name                     varchar(255)                       null comment '销售名字',
    department_id                  varchar(255)                       null comment '部门ID',
    department_name                varchar(255)                       null comment '部门名字',
    assessment_red_count           int                                null comment '评估为red的次数',
    assessment_yellow_count        int                                null comment '评估为yellow的次数',
    assessment_green_count         int                                null comment '评估为green的次数',
    end_customer_total_follow_up   int                                null comment '总跟进最终客户数',
    end_customer_total_first_visit int                                null comment '总首次拜访最终客户数',
    end_customer_total_multi_visit int                                null comment '总多次拜访最终客户数',
    partner_total_follow_up        int                                null comment '总跟进合作伙伴数',
    partner_total_first_visit      int                                null comment '总首次拜访合作伙伴数',
    partner_total_multi_visit      int                                null comment '总多次拜访合作伙伴数',
    create_time                    datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time                    datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at                     datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                     datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '客户日报统计表';

create table `autoflow-demo`.crm_data_authority
(
    id          bigint auto_increment comment '主键ID（自增序列）'
        primary key,
    data_id     varchar(255) null comment '数据id',
    user_id     varchar(255) null comment '用户id',
    crm_id      varchar(255) null comment 'CRM用户id',
    type        varchar(255) null comment '数据类型',
    create_time datetime     null comment '创建时间',
    update_time datetime     null comment '最后更新时间',
    delete_flag tinyint(1)   null comment '删除标识, True已删除',
    constraint uq_crm_data_authority
        unique (data_id, crm_id, type)
)
    comment 'crm数据权限表';

create index idx_crm_data_authority_crm_id
    on `autoflow-demo`.crm_data_authority (crm_id);

create index idx_crm_data_authority_data_id
    on `autoflow-demo`.crm_data_authority (data_id);

create index idx_crm_data_authority_type
    on `autoflow-demo`.crm_data_authority (type);

create index idx_crm_data_authority_user_id
    on `autoflow-demo`.crm_data_authority (user_id);

create table `autoflow-demo`.crm_data_quality_warnings
(
    id                int auto_increment
        primary key,
    unique_id         varchar(255)                          not null comment '唯一性ID',
    scan_id           varchar(255)                          not null comment '扫描ID',
    rule_id           varchar(255)                          not null comment '规则ID',
    severity          varchar(50) default 'warning'         not null comment '严重级别',
    status            varchar(50) default 'active'          not null comment '状态(active/resolved)',
    identity_hash     varchar(64)                           not null comment '规则发现项身份哈希',
    source_table      varchar(255)                          not null comment '源表',
    source_field      varchar(255)                          null comment '源字段',
    source_value      varchar(255)                          null comment '源字段值',
    handbook_id       varchar(64)                           null comment 'Playbook handbook_id',
    affected_count    int         default 0                 not null comment '影响记录数',
    sample_entity_ids text                                  null comment '样例实体ID(JSON)',
    details           text                                  null comment '规则上下文(JSON)',
    first_seen_at     datetime    default CURRENT_TIMESTAMP not null comment '首次发现时间',
    last_seen_at      datetime    default CURRENT_TIMESTAMP not null comment '最近发现时间',
    resolved_at       datetime                              null comment '解决时间',
    created_at        datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at        datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_dq_warning_identity_status
        unique (identity_hash, status)
)
    comment '数据质量告警表';

create index idx_dq_warning_last_seen
    on `autoflow-demo`.crm_data_quality_warnings (last_seen_at);

create index idx_dq_warning_rule_status
    on `autoflow-demo`.crm_data_quality_warnings (rule_id, status);

create index idx_dq_warning_severity_status
    on `autoflow-demo`.crm_data_quality_warnings (severity, status);

create table `autoflow-demo`.crm_department
(
    id                   int auto_increment comment '主键ID（自增）'
        primary key,
    unique_id            varchar(255)         not null comment '部门唯一标识',
    department_name      varchar(255)         not null comment '部门名称',
    parent_department_id varchar(255)         null comment '父部门ID',
    description          text                 null comment '部门描述',
    is_active            tinyint(1) default 1 null comment '是否启用',
    creator              varchar(255)         null comment '创建人',
    creation_time        datetime             null comment '创建时间',
    last_modifier        varchar(255)         null comment '最后修改人',
    last_modified_time   datetime             null comment '最后修改时间',
    delete_flag          tinyint(1)           null comment '删除标识（0-正常，1-已删除）',
    extra                json                 null comment '扩展内容',
    constraint uq_crm_department_unique_id
        unique (unique_id)
)
    comment 'CRM 部门表';

create table `autoflow-demo`.crm_department_daily_summary
(
    id                                      int auto_increment
        primary key,
    unique_id                               varchar(255)                       not null comment '唯一性ID（必填）',
    report_date                             date                               not null comment '日期',
    summary_type                            varchar(50)                        not null comment '汇总类型(department/company)',
    department_id                           varchar(255)                       null comment '部门ID（仅当summary_type=department时）',
    department_name                         varchar(255)                       null comment '部门名称（仅当summary_type=department时）',
    assessment_red_count                    int      default 0                 null comment '评估为red的次数',
    assessment_yellow_count                 int      default 0                 null comment '评估为yellow的次数',
    assessment_green_count                  int      default 0                 null comment '评估为green的次数',
    total_assessments                       int      default 0                 null comment '总评估数',
    total_first_visit                       int      default 0                 null comment '总首次拜访数',
    total_multi_visit                       int      default 0                 null comment '总多次拜访数',
    end_customer_total_red_count            int      default 0                 null comment '最终客户总计评估为red的次数',
    end_customer_total_yellow_count         int      default 0                 null comment '最终客户总计评估为yellow的次数',
    end_customer_total_green_count          int      default 0                 null comment '最终客户总计评估为green的次数',
    end_customer_total_count                int      default 0                 null comment '最终客户总计数量',
    end_customer_first_visit_red_count      int      default 0                 null comment '最终客户首次跟进评估为red的次数',
    end_customer_first_visit_yellow_count   int      default 0                 null comment '最终客户首次跟进评估为yellow的次数',
    end_customer_first_visit_green_count    int      default 0                 null comment '最终客户首次跟进评估为green的次数',
    end_customer_first_visit_count          int      default 0                 null comment '最终客户首次跟进数量',
    end_customer_regular_visit_red_count    int      default 0                 null comment '最终客户多次跟进评估为red的次数',
    end_customer_regular_visit_yellow_count int      default 0                 null comment '最终客户多次跟进评估为yellow的次数',
    end_customer_regular_visit_green_count  int      default 0                 null comment '最终客户多次跟进评估为green的次数',
    end_customer_regular_visit_count        int      default 0                 null comment '最终客户多次跟进数量',
    partner_total_count                     int      default 0                 null comment '合作伙伴总计数量',
    partner_first_visit_count               int      default 0                 null comment '合作伙伴首次跟进数量',
    partner_regular_visit_count             int      default 0                 null comment '合作伙伴多次跟进数量',
    partner_red_count                       int      default 0                 null comment '合作伙伴评估为red的次数',
    partner_yellow_count                    int      default 0                 null comment '合作伙伴评估为yellow的次数',
    partner_green_count                     int      default 0                 null comment '合作伙伴评估为green的次数',
    summary_content                         text                               null comment '汇总内容（中文）',
    summary_content_en                      text                               null comment '汇总内容（英文）',
    summary_first_visit                     text                               null comment '首次拜访汇总内容（中文）',
    summary_regular_visit                   text                               null comment '多次拜访汇总内容（中文）',
    key_highlights                          text                               null comment '关键亮点（JSON格式）',
    key_concerns                            text                               null comment '关键关注点（JSON格式）',
    create_time                             datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time                             datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    summary_red                             text                               null comment '红灯评估汇总（中文；【首次跟进】与【多次跟进】分段）',
    summary_yellow                          text                               null comment '黄灯评估汇总（中文；【首次跟进】与【多次跟进】分段）',
    summary_green                           text                               null comment '绿灯评估汇总（中文；【首次跟进】与【多次跟进】分段）',
    created_at                              datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                              datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '部门/公司日报汇总表';

create index idx_department_date
    on `autoflow-demo`.crm_department_daily_summary (department_id, report_date);

create index idx_report_date_type
    on `autoflow-demo`.crm_department_daily_summary (report_date, summary_type);

create index idx_unique_id
    on `autoflow-demo`.crm_department_daily_summary (unique_id);

create table `autoflow-demo`.crm_eval_metrics
(
    id                     int auto_increment
        primary key,
    unique_id              varchar(255)                         not null comment '唯一性ID',
    metric_name            varchar(255)                         not null comment '指标名称',
    metric_type            varchar(255)                         not null comment '指标类型',
    account_id             varchar(255)                         null comment '客户ID',
    opportunity_id         varchar(255)                         null comment '商机ID',
    metric_value           float                                null comment '指标值',
    metric_content         text                                 null comment '指标内容',
    metric_unit            varchar(255)                         null comment '指标单位',
    metric_description     text                                 null comment '指标描述',
    eval_time              datetime                             null comment '评估时间',
    is_active              tinyint(1) default 1                 null comment '是否为当前有效评估',
    owner                  varchar(255)                         null comment '负责人姓名（用于owner级别KPI）',
    owner_id               varchar(255)                         null comment '负责人唯一性ID（用于owner级别KPI）',
    department             varchar(255)                         null comment '部门名称（用于department级别KPI）',
    department_id          varchar(255)                         null comment '部门唯一性ID（用于department级别KPI）',
    time_period            varchar(50)                          null comment '时间周期（如Q1+Q2+Q3+Q4，用于Review 1s）',
    report_date            date                                 null comment '报告日期（报告生成的日期）',
    report_datetime        datetime                             null comment '报告精确时间',
    report_week_of_year    int                                  null comment '年内周数(1-53)',
    report_month_of_year   int                                  null comment '年内月份(1-12)',
    report_quarter_of_year int                                  null comment '年内季度(1-4)',
    report_year            int                                  null comment '报告年份',
    execution_id           varchar(255)                         null comment '工作流执行ID（关联到报告）',
    create_time            datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time            datetime   default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at             datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at             datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '评估指标表';

create index idx_execution_id
    on `autoflow-demo`.crm_eval_metrics (execution_id);

create index idx_owner_dept_period
    on `autoflow-demo`.crm_eval_metrics (owner, department, time_period);

create index idx_owner_id_dept_id
    on `autoflow-demo`.crm_eval_metrics (owner_id, department_id);

create index idx_report_date
    on `autoflow-demo`.crm_eval_metrics (report_date);

create index idx_report_year_month
    on `autoflow-demo`.crm_eval_metrics (report_year, report_month_of_year);

create index idx_report_year_quarter
    on `autoflow-demo`.crm_eval_metrics (report_year, report_quarter_of_year);

create index idx_report_year_week
    on `autoflow-demo`.crm_eval_metrics (report_year, report_week_of_year);

create table `autoflow-demo`.crm_external_ingest_audit
(
    id          bigint auto_increment comment '主键ID（自增）'
        primary key,
    table_name  varchar(64)                        not null comment '表名',
    unique_id   varchar(255)                       not null comment '唯一ID',
    action      varchar(16)                        not null comment '动作：insert/update',
    ingested_at datetime default CURRENT_TIMESTAMP not null comment '写入时间'
);

create index idx_crm_audit_table_time
    on `autoflow-demo`.crm_external_ingest_audit (table_name, ingested_at);

create index idx_crm_audit_table_uid_time
    on `autoflow-demo`.crm_external_ingest_audit (table_name, unique_id, ingested_at);

create table `autoflow-demo`.crm_forecast_type_mappings
(
    id              int auto_increment
        primary key,
    internal_type   varchar(50)                          not null comment '内部类型键 (e.g. commit, closed_won, upside, pipeline, lost_cancel)',
    customer_values text                                 not null comment '客户侧文本值列表（JSON数组，不区分大小写匹配）',
    display_order   int                                  not null comment '前端展示顺序（数字越小越靠前）',
    is_active       tinyint(1) default 1                 not null comment '是否启用',
    description     text                                 null comment '配置描述',
    create_time     datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time     datetime   default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at      datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at      datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_crm_ftm_internal_type
        unique (internal_type)
)
    comment 'Forecast type 标准映射表';

create index idx_crm_ftm_display_order
    on `autoflow-demo`.crm_forecast_type_mappings (display_order);

create index idx_crm_ftm_is_active
    on `autoflow-demo`.crm_forecast_type_mappings (is_active);

create table `autoflow-demo`.crm_ingest_push_audit
(
    id            bigint auto_increment
        primary key,
    push_key      varchar(128)                        null,
    table_name    varchar(64)                         not null,
    status        varchar(16)                         not null,
    inserted      int       default 0                 not null,
    updated       int       default 0                 not null,
    skipped       int       default 0                 not null,
    error_message text                                null,
    detail_json   json                                null,
    created_at    timestamp default CURRENT_TIMESTAMP not null,
    updated_at    timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
)
    charset = utf8mb4;

create index idx_created_at
    on `autoflow-demo`.crm_ingest_push_audit (created_at);

create index idx_push_key
    on `autoflow-demo`.crm_ingest_push_audit (push_key);

create index idx_status
    on `autoflow-demo`.crm_ingest_push_audit (status);

create index idx_table_name
    on `autoflow-demo`.crm_ingest_push_audit (table_name);

create table `autoflow-demo`.crm_ka_accounts
(
    id           int auto_increment
        primary key,
    account_id   varchar(255)                       not null comment '客户唯一性ID',
    account_name varchar(255)                       not null comment '客户名称',
    create_time  datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    status       varchar(20)                        null comment '状态: active, inactive',
    flag         varchar(255)                       null comment '标志位,区分不同类别的KA客户',
    created_at   datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at   datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment 'KA客户表';

create index idx_account
    on `autoflow-demo`.crm_ka_accounts (account_id);

create table `autoflow-demo`.crm_key_opportunities
(
    id                       int auto_increment
        primary key,
    opportunity_id           varchar(255)                          not null comment '商机唯一性ID',
    opportunity_name         varchar(255)                          not null comment '商机名称',
    account_id               varchar(255)                          not null comment '客户唯一性ID',
    account_name             varchar(255)                          not null comment '客户名称',
    opportunity_stage        varchar(255)                          null comment '商机阶段',
    expected_closing_quarter varchar(50)                           null comment '预期成交季度',
    create_time              datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    status                   varchar(20) default 'active'          null comment '状态: active, inactive',
    flag                     varchar(255)                          null comment '标志位,区分不同用途的关键商机',
    created_at               datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at               datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '关键商机表';

create index idx_account_id
    on `autoflow-demo`.crm_key_opportunities (account_id);

create index idx_expected_closing_quarter
    on `autoflow-demo`.crm_key_opportunities (expected_closing_quarter);

create index idx_flag
    on `autoflow-demo`.crm_key_opportunities (flag);

create index idx_opportunity_id
    on `autoflow-demo`.crm_key_opportunities (opportunity_id);

create index idx_status
    on `autoflow-demo`.crm_key_opportunities (status);

create table `autoflow-demo`.crm_log_processing_status
(
    id                   int auto_increment
        primary key,
    unique_id            varchar(255)                          not null comment '唯一性ID（必填）',
    source_table         varchar(255)                          null comment '源数据表名',
    source_field_name    varchar(255)                          null comment '源字段名称',
    source_id            int                                   null comment '源数据ID',
    source_unique_id     varchar(255)                          null comment '源数据唯一性ID',
    processing_status    varchar(50) default 'PENDING'         not null comment '处理状态（PENDING/PROCESSING/PROCESSED/FAILED）',
    processing_stage     varchar(50)                           null comment '处理阶段（如：INITIAL/EXTRACT/TRANSFORM/LOAD）',
    processing_attempts  int         default 0                 not null comment '处理尝试次数',
    last_processing_time datetime                              null comment '最后处理时间',
    processing_error     text                                  null comment '处理错误信息',
    processing_mode      varchar(50)                           null comment '处理模式（APPEND/CREATE）',
    flag                 varchar(255)                          null comment '标志位,标记该数据被处理的任务',
    source_data_hash     varchar(64)                           null comment '源数据哈希值（用于检测变更）',
    created_at           datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at           datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '日志处理状态跟踪表';

create index idx_log_processing_flag_status_source
    on `autoflow-demo`.crm_log_processing_status (flag, processing_status, source_unique_id);

create index idx_log_processing_source_unique_id
    on `autoflow-demo`.crm_log_processing_status (source_unique_id);

create index idx_processing_status
    on `autoflow-demo`.crm_log_processing_status (processing_status);

create index idx_source_id
    on `autoflow-demo`.crm_log_processing_status (source_id);

create index idx_source_table
    on `autoflow-demo`.crm_log_processing_status (source_table);

create table `autoflow-demo`.crm_message_dispatch_logs
(
    id            int auto_increment
        primary key,
    message_id    varchar(255)                       not null comment 'Message ID',
    work_item_id  varchar(255)                       null comment 'Work item ID',
    event_type    varchar(100)                       not null comment 'Dispatch event type',
    detail        json                               null comment 'Event detail',
    error_message text                               null comment 'Error message',
    created_at    datetime default CURRENT_TIMESTAMP not null comment 'Create time'
)
    comment 'Internal message dispatch logs';

create index idx_message_dispatch_logs_message
    on `autoflow-demo`.crm_message_dispatch_logs (message_id);

create index idx_message_dispatch_logs_work_item
    on `autoflow-demo`.crm_message_dispatch_logs (work_item_id);

create table `autoflow-demo`.crm_message_inbox
(
    id               int auto_increment
        primary key,
    message_id       varchar(255)                          not null comment 'Message public ID',
    message_type     varchar(100)                          not null comment 'Message type, e.g. crm.visit_record.saved',
    source_system    varchar(100)                          not null comment 'Source system',
    source_table     varchar(255)                          null comment 'Source table',
    source_unique_id varchar(255)                          null comment 'Source unique ID',
    dedupe_key       varchar(512)                          not null comment 'Idempotency key',
    payload_hash     varchar(64)                           not null comment 'Canonical payload SHA-256 hash',
    payload          json                                  not null comment 'Raw message payload',
    status           varchar(50) default 'RECEIVED'        not null comment 'Message status',
    priority         int         default 0                 not null comment 'Higher value is claimed first',
    available_at     datetime    default CURRENT_TIMESTAMP not null comment 'Earliest dispatch time',
    received_at      datetime    default CURRENT_TIMESTAMP not null comment 'Message receipt time',
    orchestrated_at  datetime                              null comment 'Work item orchestration time',
    completed_at     datetime                              null comment 'Terminal completion time',
    attempt_count    int         default 0                 not null comment 'Orchestration attempts',
    last_error       text                                  null comment 'Last orchestration error',
    trace_id         varchar(255)                          null comment 'Upstream trace ID',
    created_at       datetime    default CURRENT_TIMESTAMP not null comment 'Create time',
    updated_at       datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment 'Update time',
    constraint dedupe_key
        unique (dedupe_key),
    constraint message_id
        unique (message_id)
)
    comment 'Internal message inbox';

create index idx_message_inbox_source
    on `autoflow-demo`.crm_message_inbox (source_table, source_unique_id);

create index idx_message_inbox_status_available
    on `autoflow-demo`.crm_message_inbox (status, available_at, priority);

create table `autoflow-demo`.crm_message_work_item_deps
(
    work_item_id            varchar(255)                          not null comment 'Dependent work item ID',
    depends_on_work_item_id varchar(255)                          not null comment 'Prerequisite work item ID',
    dependency_type         varchar(50) default 'SUCCESS'         not null comment 'SUCCESS/COMPLETION/OUTPUT_EXISTS',
    output_condition        json                                  null comment 'Optional output condition',
    created_at              datetime    default CURRENT_TIMESTAMP not null comment 'Create time',
    primary key (work_item_id, depends_on_work_item_id)
)
    comment 'Internal message work item dependencies';

create index idx_message_work_item_deps_depends_on
    on `autoflow-demo`.crm_message_work_item_deps (depends_on_work_item_id);

create table `autoflow-demo`.crm_message_work_items
(
    id               int auto_increment
        primary key,
    work_item_id     varchar(255)                             not null comment 'Work item public ID',
    message_id       varchar(255)                             not null comment 'Parent message ID',
    work_type        varchar(100) default 'workflow_plan'     not null comment 'Work item type',
    queue_name       varchar(100) default 'workflow_parallel' not null comment 'Logical queue name',
    priority         int          default 0                   not null comment 'Higher value is claimed first',
    plan_id          varchar(255)                             null comment 'Workflow plan ID',
    execution_id     varchar(255)                             null comment 'Workflow execution ID',
    report_id        varchar(255)                             null comment 'Workflow report ID',
    bootstrap_inputs json                                     null comment 'Workflow bootstrap inputs',
    status           varchar(50)  default 'PENDING'           not null comment 'Work item status',
    attempt_count    int          default 0                   not null comment 'Dispatch attempts',
    max_attempts     int          default 3                   not null comment 'Max dispatch attempts',
    available_at     datetime     default CURRENT_TIMESTAMP   not null comment 'Earliest dispatch time',
    claimed_by       varchar(255)                             null comment 'Dispatcher identity',
    claimed_at       datetime                                 null comment 'Claim time',
    started_at       datetime                                 null comment 'Start time',
    submitted_at     datetime                                 null comment 'Celery submission time',
    finished_at      datetime                                 null comment 'Terminal time',
    last_error       text                                     null comment 'Last error',
    output_ref       json                                     null comment 'Output references or guard results',
    created_at       datetime     default CURRENT_TIMESTAMP   not null comment 'Create time',
    updated_at       datetime     default CURRENT_TIMESTAMP   not null on update CURRENT_TIMESTAMP comment 'Update time',
    constraint work_item_id
        unique (work_item_id)
)
    comment 'Internal message work items';

create index idx_message_work_items_execution
    on `autoflow-demo`.crm_message_work_items (execution_id);

create index idx_message_work_items_message
    on `autoflow-demo`.crm_message_work_items (message_id);

create index idx_message_work_items_ready
    on `autoflow-demo`.crm_message_work_items (status, queue_name, available_at, priority);

create table `autoflow-demo`.crm_opportunities
(
    id                                      int auto_increment comment '主键ID'
        primary key,
    unique_id                               varchar(255) null comment '唯一性ID（必填）',
    opportunity_name                        varchar(255) null comment '商机名称（必填）',
    competitor_name                         varchar(255) null comment '友商名称',
    former_name                             varchar(255) null comment '曾用名',
    partner_opportunity_filing_id_unique_id varchar(255) null comment '合作伙伴商机报备编号_唯一性ID',
    partner_opportunity_filing_number       varchar(255) null comment '合作伙伴商机报备编号',
    filing_opportunity_number               varchar(255) null comment '报备商机编号',
    call_high_notes                         text         null comment 'Call high 情况',
    department                              varchar(255) null comment '归属部门',
    current_year_service_forecast           float        null comment '当财年 Service 收入预测金额（不含税）',
    customer_budget_status                  text         null comment '客户预算情况',
    todo_and_followup                       text         null comment 'Todo & follow up',
    is_framework_quote                      varchar(255) null comment '是否框架协议报价商机',
    customer_id                             varchar(255) null comment '客户名称_唯一性ID（必填）',
    customer_name                           varchar(255) null comment '客户名称（必填）',
    customer_type                           varchar(255) null comment '客户属性',
    owner                                   varchar(255) null comment '负责人（必填）',
    customer_business_scenario              varchar(255) null comment '客户业务场景',
    forecast_type                           varchar(255) null comment '预测类型',
    estimated_tcv                           int          null comment '预估 TCV',
    estimated_acv                           int          null comment '预估 ACV',
    expected_closing_date                   varchar(255) null comment '预计成交日期',
    expected_closing_quarter                varchar(255) null comment '预计成交季度',
    opportunity_type                        varchar(255) null comment '商机类型',
    signing_type                            varchar(255) null comment '签约类型',
    general_agent                           varchar(255) null comment '总代理',
    presales_owner                          varchar(255) null comment '售前负责人',
    opportunity_source                      varchar(255) null comment '商机来源',
    ppl_product_type                        varchar(255) null comment 'PPL 产品类型',
    latest_followup_date_new                varchar(255) null comment '最近跟进日期-新',
    remarks                                 text         null comment '备注说明',
    quotation_status                        varchar(255) null comment '报价单状态',
    create_time                             varchar(255) null comment '创建时间',
    last_modifier                           varchar(255) null comment '最后修改人',
    opportunity_stage                       varchar(255) null comment '商机阶段（必填）',
    stage_status                            varchar(255) null comment '阶段状态',
    stage_change_time                       varchar(255) null comment '阶段变更时间',
    last_modified_time                      datetime     null comment '最后修改时间',
    business_type                           varchar(255) null comment '业务类型（必填）',
    last_followup_time                      varchar(255) null comment '最后跟进时间',
    owner_main_department                   varchar(255) null comment '负责人主属部门',
    weekly_update                           text         null comment 'Weekly Update',
    sl_pull_in                              varchar(255) null comment 'SL Pull IN',
    lost_reason                             varchar(255) null comment '丢标原因',
    bidding_time                            varchar(255) null comment '招标时间',
    renew_risk_level                        varchar(255) null comment 'Renew 风险度',
    customer_category                       varchar(255) null comment '客户分类',
    quotation_order_status                  varchar(255) null comment '报价/下单状态',
    source                                  varchar(255) null comment '来源',
    project_contribution                    text         null comment '立项贡献（立项报告的内容）',
    project_date                            varchar(255) null comment '立项日期',
    budget_approval_status                  varchar(255) null comment '预算审批是否完成',
    sales_order_archive_status              varchar(255) null comment '销售订单归档状态',
    is_channel_reported_opportunity         varchar(255) null comment '是否渠道报备商机（必填）',
    is_project_approved                     varchar(255) null comment '是否立项',
    ops_cd_project_retrospective_schedule   text         null comment 'ops cd 项目进展倒排时间表',
    ops_cd_critical_issues                  text         null comment 'ops cd 重大问题卡点',
    ops_cd_business_progress                text         null comment 'ops cd 商务进展',
    kd_closure_milestone                    text         null comment 'KD-关单节点',
    kd_decision_chain                       text         null comment 'KD-决策链条',
    kd_competitor_strategy                  text         null comment 'KD-友商策略和动态',
    kd_breakthrough_basis                   text         null comment 'KD-突破单依据',
    key_deal_tag                            varchar(255) null comment 'key deal 标签',
    product_capability_needs                text         null comment 'KD-急需产品能力（售前更新）',
    kp_deal_flag_operations                 varchar(255) null comment 'KP deal 标记（运营）',
    next_stage                              text         null comment '下一阶段解决策略及资源需求',
    is_poc                                  varchar(255) null comment '是否进行poc',
    poc_status                              varchar(255) null comment 'PoC 状态',
    sales_order_review_status               varchar(255) null comment '销售订单审核状态',
    delete_flag                             tinyint(1)   null comment '删除标识（0-正常，1-已删除）',
    extra                                   json         null comment '扩展内容',
    support_person                          json         null comment '辅助人员列表，JSON格式存储多个辅助人员的userid和name',
    expected_closing_month                  varchar(255) null comment '预计成交月份（如"2025-01"格式）',
    eu_sales                                varchar(255) null comment 'EU销售人员',
    project_delivery_date                   varchar(255) null comment '项目交付日期',
    payment_received_date                   varchar(255) null comment '回款时间',
    invoice_date                            varchar(255) null comment '开票时间',
    belonging_department                    varchar(255) null comment '归属部门（默认用ETL填写owner部门）',
    department_percentage                   varchar(255) null comment '部门百分比（默认填写"100%"）',
    owner_id                                varchar(255) null comment '负责人ID（对应crm_user.user_id）',
    expected_closing_year                   int          null comment '业绩归属年度',
    owner_department_id                     varchar(255) null comment '负责人部门ID（关联crm_user.department_id）',
    owner_department_name                   varchar(255) null comment '负责人部门名称（来自crm_user.department）',
    derived_close_date                      date         null comment 'APTSell derived close date (when CRM close_date is missing)',
    close_date                              date         null comment '实际成单日期（Closed Won）',
    constraint uq_crm_opportunities_unique_id
        unique (unique_id)
)
    comment '商机表';

create table `autoflow-demo`.crm_opportunities_snapshot
(
    id                                      int auto_increment comment '主键ID'
        primary key,
    unique_id                               varchar(255) null comment '唯一性ID（必填）',
    opportunity_name                        varchar(255) null comment '商机名称（必填）',
    competitor_name                         varchar(255) null comment '友商名称',
    former_name                             varchar(255) null comment '曾用名',
    partner_opportunity_filing_id_unique_id varchar(255) null comment '合作伙伴商机报备编号_唯一性ID',
    partner_opportunity_filing_number       varchar(255) null comment '合作伙伴商机报备编号',
    filing_opportunity_number               varchar(255) null comment '报备商机编号',
    call_high_notes                         text         null comment 'Call high 情况',
    department                              varchar(255) null comment '归属部门',
    current_year_service_forecast           float        null comment '当财年 Service 收入预测金额（不含税）',
    customer_budget_status                  text         null comment '客户预算情况',
    todo_and_followup                       text         null comment 'Todo & follow up',
    is_framework_quote                      varchar(255) null comment '是否框架协议报价商机',
    customer_id                             varchar(255) null comment '客户名称_唯一性ID（必填）',
    customer_name                           varchar(255) null comment '客户名称（必填）',
    customer_type                           varchar(255) null comment '客户属性',
    owner                                   varchar(255) null comment '负责人（必填）',
    customer_business_scenario              varchar(255) null comment '客户业务场景',
    forecast_type                           varchar(255) null comment '预测类型',
    estimated_tcv                           int          null comment '预估 TCV',
    estimated_acv                           int          null comment '预估 ACV',
    expected_closing_date                   varchar(255) null comment '预计成交日期',
    expected_closing_quarter                varchar(255) null comment '预计成交季度',
    opportunity_type                        varchar(255) null comment '商机类型',
    signing_type                            varchar(255) null comment '签约类型',
    general_agent                           varchar(255) null comment '总代理',
    presales_owner                          varchar(255) null comment '售前负责人',
    opportunity_source                      varchar(255) null comment '商机来源',
    ppl_product_type                        varchar(255) null comment 'PPL 产品类型',
    latest_followup_date_new                varchar(255) null comment '最近跟进日期-新',
    remarks                                 text         null comment '备注说明',
    quotation_status                        varchar(255) null comment '报价单状态',
    create_time                             varchar(255) null comment '创建时间',
    last_modifier                           varchar(255) null comment '最后修改人',
    opportunity_stage                       varchar(255) null comment '商机阶段（必填）',
    stage_status                            varchar(255) null comment '阶段状态',
    stage_change_time                       varchar(255) null comment '阶段变更时间',
    last_modified_time                      datetime     null comment '最后修改时间',
    business_type                           varchar(255) null comment '业务类型（必填）',
    last_followup_time                      varchar(255) null comment '最后跟进时间',
    owner_main_department                   varchar(255) null comment '负责人主属部门',
    weekly_update                           text         null comment 'Weekly Update',
    sl_pull_in                              varchar(255) null comment 'SL Pull IN',
    lost_reason                             varchar(255) null comment '丢标原因',
    bidding_time                            varchar(255) null comment '招标时间',
    renew_risk_level                        varchar(255) null comment 'Renew 风险度',
    customer_category                       varchar(255) null comment '客户分类',
    quotation_order_status                  varchar(255) null comment '报价/下单状态',
    source                                  varchar(255) null comment '来源',
    project_contribution                    text         null comment '立项贡献（立项报告的内容）',
    project_date                            varchar(255) null comment '立项日期',
    budget_approval_status                  varchar(255) null comment '预算审批是否完成',
    sales_order_archive_status              varchar(255) null comment '销售订单归档状态',
    is_channel_reported_opportunity         varchar(255) null comment '是否渠道报备商机（必填）',
    is_project_approved                     varchar(255) null comment '是否立项',
    ops_cd_project_retrospective_schedule   text         null comment 'ops cd 项目进展倒排时间表',
    ops_cd_critical_issues                  text         null comment 'ops cd 重大问题卡点',
    ops_cd_business_progress                text         null comment 'ops cd 商务进展',
    kd_closure_milestone                    text         null comment 'KD-关单节点',
    kd_decision_chain                       text         null comment 'KD-决策链条',
    kd_competitor_strategy                  text         null comment 'KD-友商策略和动态',
    kd_breakthrough_basis                   text         null comment 'KD-突破单依据',
    key_deal_tag                            varchar(255) null comment 'key deal 标签',
    product_capability_needs                text         null comment 'KD-急需产品能力（售前更新）',
    snapshot_date                           date         null comment '快照日期',
    kp_deal_flag_operations                 varchar(255) null comment 'KP deal 标记（运营）',
    next_stage                              text         null comment '下一阶段解决策略及资源需求',
    is_poc                                  varchar(255) null comment '是否进行poc',
    poc_status                              varchar(255) null comment 'PoC 状态',
    sales_order_review_status               varchar(255) null comment '销售订单审核状态',
    delete_flag                             tinyint(1)   null comment '删除标识（0-正常，1-已删除）',
    extra                                   json         null comment '扩展内容',
    support_person                          json         null comment '辅助人员列表，JSON格式存储多个辅助人员的userid和name',
    expected_closing_month                  varchar(255) null comment '预计成交月份（如"2025-01"格式）',
    eu_sales                                varchar(255) null comment 'EU销售人员',
    project_delivery_date                   varchar(255) null comment '项目交付日期',
    payment_received_date                   varchar(255) null comment '回款时间',
    invoice_date                            varchar(255) null comment '开票时间',
    belonging_department                    varchar(255) null comment '归属部门（默认用ETL填写owner部门）',
    department_percentage                   varchar(255) null comment '部门百分比（默认填写"100%"）',
    owner_id                                varchar(255) null comment '负责人ID（对应crm_user.user_id）',
    expected_closing_year                   int          null comment '业绩归属年度',
    owner_department_id                     varchar(255) null comment '负责人部门ID（关联crm_user.department_id）',
    owner_department_name                   varchar(255) null comment '负责人部门名称（来自crm_user.department）',
    derived_close_date                      date         null comment 'APTSell derived close date (when CRM close_date is missing)',
    close_date                              date         null comment '实际成单日期（快照）',
    constraint uq_snapshot_unique_id_snapshot_date
        unique (unique_id, snapshot_date)
)
    comment '商机表快照';

create index idx_opportunity_snapshot_date_stage_owner
    on `autoflow-demo`.crm_opportunities_snapshot (snapshot_date, opportunity_stage, unique_id, owner_id);

create index idx_snapshot_date
    on `autoflow-demo`.crm_opportunities_snapshot (snapshot_date);

create table `autoflow-demo`.crm_opportunity_review_execution_index
(
    id                  int auto_increment
        primary key,
    opportunity_id      varchar(255)                       not null comment '商机唯一性ID',
    execution_id        varchar(255)                       not null comment '关联账户的最新review2报告的execution_id',
    account_id          varchar(255)                       null comment '关联的账户ID',
    report_id           varchar(255)                       null comment '报告ID',
    plan_id             varchar(255)                       null comment '执行计划ID',
    report_created_time datetime                           not null comment '报告创建时间',
    last_updated_time   datetime default CURRENT_TIMESTAMP not null comment '索引最后更新时间',
    create_time         datetime default CURRENT_TIMESTAMP not null comment '索引创建时间',
    created_at          datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at          datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint opportunity_id
        unique (opportunity_id)
)
    comment '商机复盘执行索引表';

create index idx_account_id
    on `autoflow-demo`.crm_opportunity_review_execution_index (account_id);

create index idx_execution_id
    on `autoflow-demo`.crm_opportunity_review_execution_index (execution_id);

create index idx_report_created_time
    on `autoflow-demo`.crm_opportunity_review_execution_index (report_created_time);

create table `autoflow-demo`.crm_opportunity_stage_stay_bucket
(
    opportunity_id    varchar(255)                       not null comment 'Opportunity id (crm_opportunities.unique_id)',
    opportunity_stage varchar(255)                       not null comment 'Stage name (non-closed stages only)',
    stay_days         int      default 0                 not null comment 'Cumulative days in this stage (bucket count)',
    updated_at        datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    created_at        datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    primary key (opportunity_id, opportunity_stage)
)
    comment '商机阶段停留时间汇总表';

create index idx_updated_at
    on `autoflow-demo`.crm_opportunity_stage_stay_bucket (updated_at);

create table `autoflow-demo`.crm_opportunity_stage_stay_daily
(
    opportunity_id    varchar(255) not null comment 'Opportunity id (crm_opportunities.unique_id)',
    opportunity_stage varchar(255) not null comment 'Stage name (non-closed stages only)',
    snapshot_date     date         not null comment 'Date this (opp, stage) was observed in snapshot',
    primary key (opportunity_id, opportunity_stage, snapshot_date)
)
    comment 'FR-ST-1: Idempotent daily ledger for stage stay; bucket is derived from this table';

create index idx_snapshot_date
    on `autoflow-demo`.crm_opportunity_stage_stay_daily (snapshot_date);

create table `autoflow-demo`.crm_orders
(
    id                                          bigint auto_increment comment '主键ID（自增序列）'
        primary key,
    signing_date                                datetime       null comment '签约日期',
    service_duration_months                     varchar(255)   null comment '服务时长/月（订阅/维保）',
    total_margin_percentage                     varchar(255)   null comment 'Margin%(总代+经销）',
    customer_name                               varchar(255)   null comment '客户名称',
    arr                                         varchar(255)   null comment 'ARR',
    maintenance_ratio                           varchar(255)   null comment '维保比例',
    renew_arr                                   varchar(255)   null comment 'Renew ARR',
    customer_id                                 varchar(255)   null comment '客户id',
    sales_type                                  varchar(255)   null comment '销售类型',
    product_subscription_amount                 decimal(18, 2) null comment '产品订阅金额',
    shipping_status                             varchar(255)   null comment '发货状态',
    shipping_address                            varchar(255)   null comment '收货地址',
    sales_order_amount                          decimal(18, 2) null comment '销售订单金额',
    third_level_distributor                     varchar(255)   null comment '经销商三级',
    planned_payment_amount                      decimal(18, 2) null comment '已计划回款金额',
    created_by                                  varchar(1024)  null comment '创建人',
    service_end_date_subscription_maintenance   datetime       null comment '服务结束日期（订阅/维保）',
    outsourcing_cost                            decimal(18, 2) null comment '外采（外包）成本',
    performance_accounting_sales_department     varchar(1024)  null comment '业绩核算销售所在部门',
    project_name                                varchar(255)   null comment '项目名称',
    expected_renewal_time_fy                    varchar(255)   null comment '应续约时间(FY)',
    new_arr                                     varchar(255)   null comment 'New ARR',
    owner                                       varchar(1024)  null comment '负责人',
    product_perpetual_license_amount            decimal(18, 2) null comment '产品永久授权金额',
    split_ratio                                 varchar(255)   null comment '拆分比例',
    contract_archiving_status                   varchar(255)   null comment '合同归档状态',
    pending_payment_amount                      varchar(512)   null comment '待回款金额',
    invoice_status                              varchar(512)   null comment '开票状态',
    order_type                                  varchar(255)   null comment '订单类型',
    is_general_agent                            varchar(512)   null comment '是否总代理',
    source                                      varchar(255)   null comment '数据来源',
    contract_type                               varchar(255)   null comment '合同类型',
    reported_partner_name                       varchar(255)   null comment '报备合作伙伴名称',
    commission_info                             varchar(255)   null comment '提成信息',
    has_sub_agents                              varchar(255)   null comment '是否有下级代理商',
    man_day_service_amount                      decimal(18, 2) null comment '人天服务金额',
    old_service_end_date                        datetime       null comment '服务结束日期（旧）',
    owning_department                           varchar(1024)  null comment '归属部门',
    unique_id                                   varchar(255)   null comment '唯一性ID（必填）',
    maintenance_service_amount                  decimal(18, 2) null comment '维保服务金额',
    partner_id                                  varchar(255)   null comment '合作伙伴',
    payment_status                              varchar(512)   null comment '回款状态',
    sales_order_amount_excluding_tax            varchar(255)   null comment '销售订单金额（不含税）',
    arr_excluding_tax                           varchar(255)   null comment 'ARR（不含税）',
    settle_type                                 varchar(255)   null comment '结算方式',
    contract_name                               varchar(255)   null comment '合同名称',
    second_level_distributor                    varchar(255)   null comment '经销商二级',
    opportunity_id                              varchar(255)   null comment '商机id',
    quote_id                                    varchar(255)   null comment '报价单编号',
    total_payment_amount                        decimal(18, 2) null comment '累计回款金额',
    is_framework_order                          varchar(255)   null comment '是否框架下订单',
    first_level_distributor                     varchar(255)   null comment '经销商一级',
    service_start_date_subscription_maintenance datetime       null comment '服务开始日期（订阅/维保）',
    previous_name                               varchar(255)   null comment '曾用名',
    owner_department                            varchar(255)   null comment '负责人主属部门',
    creation_time                               datetime       null comment '创建时间',
    sales_order_number                          varchar(255)   null comment '销售订单编号',
    invoice_completion_status                   varchar(255)   null comment '开票完成状态',
    contracting_party                           varchar(255)   null comment '签约主体',
    delivery_acceptance_progress                text           null comment '交付/验收进展',
    product_type                                varchar(255)   null comment '产品类型',
    renewal_type                                varchar(1024)  null comment '续约类型',
    delivery_comment                            varchar(255)   null comment '发货备注',
    profit_statement                            varchar(1024)  null comment '利润表',
    opportunity_number                          varchar(255)   null comment '商机编号',
    last_modified_time                          datetime       null comment '最后修改时间',
    life_status                                 varchar(255)   null comment '生命状态',
    framework_agreement_id                      varchar(255)   null comment '框架协议名称',
    acv                                         varchar(255)   null comment 'ACV',
    contracting_partner                         varchar(255)   null comment '合作伙伴（签约方）',
    renewal_status                              varchar(255)   null comment '续约状态',
    resource                                    varchar(255)   null comment '来源',
    contract_attribute                          varchar(255)   null comment '合同属性',
    remark                                      text           null comment '备注',
    last_modified_by                            varchar(1024)  null comment '最后修改人',
    delivery_time                               datetime       null comment '发货时间',
    opportunity_name                            varchar(255)   null comment '商机名称',
    sales_organization                          varchar(255)   null comment '销售组织',
    delete_flag                                 tinyint(1)     null comment '删除标识（0-正常，1-已删除）',
    extra                                       json           null comment '扩展内容'
)
    comment '订单表';

create table `autoflow-demo`.crm_payment_plans
(
    id                                 bigint auto_increment comment '主键ID（自增序列）'
        primary key,
    actual_payment_fiscal_quarter      varchar(512)   null comment '实际回款日期-财年&季度',
    lock_rule                          text           null comment '锁定规则',
    action_tag                         varchar(1024)  null comment 'Action tag-多选',
    extend_obj_data_id                 varchar(255)   null comment 'extend_obj_data_id',
    remind_time                        varchar(255)   null comment '提前几日提醒',
    life_status_before_invalid         varchar(255)   null comment '作废前生命状态',
    order_amount                       varchar(255)   null comment '销售订单金额',
    contract_party                     varchar(255)   null comment '签约方',
    plan_payment_status                varchar(255)   null comment '状态',
    owner_department                   varchar(255)   null comment '负责人所在部门',
    latest_plan_payment_fiscal_quarter varchar(512)   null comment '最新计划回款日期-财年&季度',
    plan_payment_method                varchar(255)   null comment '计划回款方式',
    plan_payment_amount                decimal(18, 2) null comment '计划回款金额（元）',
    pending_payment_amount             varchar(512)   null comment '待回款金额',
    plan_payment_ratio                 varchar(512)   null comment '计划回款占比',
    lock_status                        varchar(255)   null comment '锁定状态',
    first_plan_payment_fiscal_quarter  varchar(512)   null comment '首次计划回款日期-财年&季度',
    create_time                        datetime       null comment '创建时间',
    booking_fiscal_year                varchar(512)   null comment 'Booking财年',
    version                            varchar(255)   null comment 'version',
    created_by                         varchar(1024)  null comment '创建人',
    relevant_team                      varchar(1024)  null comment '相关团队',
    data_own_department                varchar(1024)  null comment '归属部门',
    next_plan_description              text           null comment '下一步计划说明',
    name                               varchar(255)   null comment '回款计划编号',
    unique_id                          varchar(255)   null comment '唯一性ID（必填）',
    order_id                           varchar(255)   null comment '销售订单编号',
    data_refresh_flag                  varchar(255)   null comment '刷数据',
    first_payment_overdue_days         varchar(512)   null comment '首次回款计划-逾期天数-后台计算',
    approve_employee_id                varchar(1024)  null comment '当前审批人',
    remark                             text           null comment '备注',
    contract_date                      varchar(512)   null comment '签约日期',
    origin_source                      varchar(255)   null comment '数据来源',
    lock_user                          varchar(1024)  null comment '加锁人',
    actual_payment_date                datetime       null comment '实际回款日期',
    partner_id                         varchar(255)   null comment '合作伙伴',
    overdue_reason                     varchar(1024)  null comment '逾期归因',
    is_deleted                         tinyint(1)     null comment 'is_deleted',
    attachment                         varchar(1024)  null comment '附件',
    actual_payment_amount              decimal(18, 2) null comment '实际回款金额（元）',
    overdue_payment_reason             text           null comment '逾期回款原因',
    latest_payment_overdue_days        varchar(512)   null comment '最新回款计划-逾期天数',
    latest_plan_payment_date           datetime       null comment '最新计划回款日期',
    backend_process_status             varchar(255)   null comment '后台处理状态',
    next_plan                          varchar(255)   null comment '下一步计划',
    out_owner                          varchar(1024)  null comment '外部负责人',
    out_resources                      varchar(255)   null comment '外部来源',
    owner                              varchar(1024)  null comment '负责人',
    last_modified_time                 datetime       null comment '最后修改时间',
    life_status                        varchar(255)   null comment '生命状态',
    last_modified_by                   varchar(1024)  null comment '最后修改人',
    out_tenant_id                      varchar(255)   null comment '外部企业',
    record_type                        varchar(255)   null comment '业务类型',
    overdue_description_and_next_plan  varchar(2048)  null comment '逾期说明及下一步计划-刷数据至下一步计划说明',
    account_id                         varchar(255)   null comment '客户id',
    plan_payment_time                  datetime       null comment '首次计划回款日期',
    target_payment_date                datetime       null comment 'Target 回款日期',
    order_by                           varchar(255)   null comment 'order_by',
    first_plan_overdue_month           varchar(512)   null comment '首次计划回款-逾期月份',
    contract_entity                    varchar(255)   null comment '签约主体',
    account_name                       varchar(255)   null comment '客户名称',
    delete_flag                        tinyint(1)     null comment '删除标识（0-正常，1-已删除）',
    extra                              json           null comment '扩展内容'
)
    comment '回款计划表';

create table `autoflow-demo`.crm_playbook
(
    id          int auto_increment
        primary key,
    handbook_id varchar(64)                          not null comment '销售手册ID',
    name        varchar(255)                         not null comment '销售手册名称',
    description text                                 null comment '描述',
    is_active   tinyint(1) default 1                 null comment '是否启用',
    is_default  tinyint(1) default 0                 null comment '是否默认销售手册',
    created_by  varchar(255)                         null comment '创建人',
    updated_by  varchar(255)                         null comment '更新人',
    created_at  datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at  datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_crm_playbook_handbook_id
        unique (handbook_id)
)
    comment 'Playbook元数据表';

create index idx_crm_playbook_active
    on `autoflow-demo`.crm_playbook (is_active);

create index idx_crm_playbook_default
    on `autoflow-demo`.crm_playbook (is_default);

create table `autoflow-demo`.crm_playbook_mapping
(
    id          int auto_increment
        primary key,
    field_name  varchar(100)                       not null comment '字段名 (e.g., business_type, opportunity_stage)',
    field_value varchar(255)                       not null comment '字段值 (e.g., 新签, Discovery)',
    handbook_id varchar(64)                        not null comment '关联的playbook handbook_id',
    description text                               null comment '描述',
    is_active   tinyint(1)                         null comment '是否启用',
    priority    int                                null comment '优先级，高优先级优先匹配',
    created_by  varchar(255)                       null comment '创建人',
    updated_by  varchar(255)                       null comment '更新人',
    created_at  datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at  datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_field_mapping
        unique (field_name, field_value)
)
    comment 'Playbook字段映射表';

create index idx_handbook_id
    on `autoflow-demo`.crm_playbook_mapping (handbook_id);

create index idx_is_active_priority
    on `autoflow-demo`.crm_playbook_mapping (is_active, priority);

create table `autoflow-demo`.crm_playbook_stage_metrics
(
    id                       int auto_increment
        primary key,
    unique_id                varchar(255)                          not null comment '唯一性ID（UUID）',
    handbook_id              varchar(64)                           not null comment '销售手册ID，关联diagnostic_playbook',
    sales_stage              varchar(255)                          not null comment '销售阶段名称',
    stage_sequence           int                                   null comment '阶段顺序，用于计算剩余阶段所需时间',
    avg_stay_days            int         default 0                 not null comment '平均停留天数（初始为固定值，后续从历史数据计算）',
    median_stay_days         int                                   null comment '中位数停留天数（可选）',
    min_stay_days            int                                   null comment '最小停留天数（可选）',
    max_stay_days            int                                   null comment '最大停留天数（可选）',
    sample_size              int                                   null comment '计算平均值所用的样本数量',
    data_source              varchar(50) default 'fixed'           null comment '数据来源：fixed(固定值)/calculated(历史计算)/manual(人工设置)',
    calculation_period_start date                                  null comment '计算时间段起始（仅data_source=calculated时有效）',
    calculation_period_end   date                                  null comment '计算时间段结束',
    is_active                tinyint(1)  default 1                 null comment '是否启用',
    version                  varchar(32) default '1.0'             null comment '配置版本',
    description              text                                  null comment '备注说明',
    created_by               varchar(255)                          null comment '创建人',
    updated_by               varchar(255)                          null comment '更新人',
    created_at               datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at               datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_handbook_stage
        unique (handbook_id, sales_stage)
)
    comment '销售阶段平均停留时间表，用于AI FCST评估';

create index idx_handbook_active
    on `autoflow-demo`.crm_playbook_stage_metrics (handbook_id, is_active);

create index idx_handbook_sequence
    on `autoflow-demo`.crm_playbook_stage_metrics (handbook_id, stage_sequence);

create index idx_unique_id
    on `autoflow-demo`.crm_playbook_stage_metrics (unique_id);

create table `autoflow-demo`.crm_poc
(
    id                 int auto_increment comment '主键ID（自增序列）'
        primary key,
    unique_id          varchar(255)                       not null comment '唯一标识ID',
    account_id         varchar(255)                       null comment '客户ID',
    account_name       varchar(255)                       null comment '客户名称',
    opportunity_name   varchar(255)                       null comment '商机名称',
    opportunity_id     varchar(255)                       null comment '商机ID',
    owner              varchar(255)                       null comment '负责人',
    is_poc             varchar(10)                        null comment '是否POC',
    poc_status         varchar(20)                        null comment 'POC状态',
    poc_result         varchar(20)                        null comment 'POC结果',
    poc_end_date       date                               null comment 'POC结束日期',
    created_by         varchar(255)                       null comment '创建人',
    created_time       datetime default CURRENT_TIMESTAMP null comment '创建时间',
    last_modified_by   varchar(255)                       null comment '最后修改人',
    last_modified_time datetime default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP comment '最后修改时间',
    is_deleted         tinyint(1)                         null comment '删除标记',
    client_id          varchar(255)                       null comment '客户端ID',
    owner_id           varchar(255)                       null comment '负责人ID（对应crm_user.user_id）',
    constraint uq_crm_poc_unique_id
        unique (unique_id)
)
    comment 'POC管理表';

create table `autoflow-demo`.crm_push_notification
(
    id                     int auto_increment
        primary key,
    unique_id              varchar(255)                       not null comment '唯一性ID（必填）',
    title                  varchar(255)                       not null comment '通知标题',
    content                text                               null comment '通知内容',
    notification_type      varchar(50)                        not null comment '通知类型（workflow_complete/workflow_started/workflow_failed/custom）',
    priority               varchar(20)                        null comment '优先级（high/medium/low）',
    plan_id                varchar(255)                       null comment '关联的工作流计划ID',
    execution_id           varchar(255)                       null comment '关联的工作流执行ID',
    report_id              varchar(255)                       null comment '关联的报告ID',
    tenant_id              varchar(255)                       not null comment '租户ID',
    correlation_id         varchar(255)                       null comment '关联ID，用于追踪相关联的业务实体',
    status                 varchar(50)                        not null comment '通知状态（pending/scheduled/sent/failed/cancelled）',
    scheduled_time         datetime                           null comment '计划发送时间',
    trigger_condition      varchar(100)                       null comment '触发条件（immediate/workflow_complete/delay/custom）',
    delay_minutes          int                                null comment '延迟发送分钟数',
    target_service         varchar(100)                       null comment '目标第三方服务名称（webhook/email/sms/slack/dingtalk等）',
    api_endpoint           varchar(500)                       null comment '第三方服务API端点',
    http_method            varchar(10)                        null comment 'HTTP方法（GET/POST/PUT等）',
    request_payload        text                               null comment '发送给第三方服务的完整请求载荷（JSON格式）',
    request_headers        text                               null comment 'HTTP请求头（JSON格式）',
    auth_config            text                               null comment '认证配置（JSON格式，支持Bearer Token/API Key等）',
    max_retry_attempts     int                                null comment '最大重试次数',
    current_retry_count    int                                null comment '当前重试次数',
    retry_interval_minutes int                                null comment '重试间隔（分钟）',
    next_retry_time        datetime                           null comment '下次重试时间',
    last_sent_time         datetime                           null comment '最后发送时间',
    response_status_code   int                                null comment '第三方服务响应状态码',
    response_body          text                               null comment '第三方服务响应内容',
    error_message          text                               null comment '错误信息',
    linked_account_ids     text                               null comment '关联的客户ID列表（JSON格式）',
    linked_opportunity_ids text                               null comment '关联的商机ID列表（JSON格式）',
    business_context       text                               null comment '业务上下文信息（JSON格式，用于动态生成通知内容）',
    created_by             varchar(255)                       null comment '创建人',
    created_by_id          varchar(255)                       null comment '创建人ID',
    tags                   varchar(255)                       null comment '标签（逗号分隔）',
    notes                  text                               null comment '备注信息',
    create_time            datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time            datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    completed_time         datetime                           null comment '完成时间',
    expired_time           datetime                           null comment '过期时间',
    created_at             datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at             datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '推送通知配置表';

create table `autoflow-demo`.crm_report_index
(
    id                     int auto_increment
        primary key,
    unique_id              varchar(255)                       not null comment '唯一性ID',
    report_id              int                                not null comment '报告ID, 对应CRMReport表的id',
    report_id_code         varchar(255)                       not null comment '报告ID编码, 对应CRMReport表的report_id',
    execution_id           varchar(255)                       not null comment '执行ID',
    plan_id                varchar(255)                       not null comment '计划ID',
    report_type            varchar(64)                        not null comment '报告类型: review1/review1s/review2/review5/previsit/daily',
    report_calendar_type   varchar(64)                        not null comment '报告周期类型: daily/weekly/monthly/quarterly/yearly',
    report_status          varchar(32)                        not null comment '报告状态: draft/published/archived',
    report_date            date                               not null comment '报告日期',
    report_datetime        datetime                           not null comment '报告精确时间',
    report_week_of_year    int                                not null comment '年内周数(1-53)',
    report_month_of_year   int                                not null comment '年内月份(1-12)',
    report_quarter_of_year int                                not null comment '年内季度(1-4)',
    report_year            int                                not null comment '报告年份',
    created_by             varchar(255)                       null comment '创建人',
    department_id          varchar(255)                       null comment '部门ID',
    department_name        varchar(255)                       null comment '部门名字',
    create_time            datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time            datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at             datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at             datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '报告索引表';

create index idx_execution_id
    on `autoflow-demo`.crm_report_index (execution_id);

create index idx_report_id
    on `autoflow-demo`.crm_report_index (report_id);

create index idx_report_type_date
    on `autoflow-demo`.crm_report_index (report_type, report_date);

create index idx_unique_id
    on `autoflow-demo`.crm_report_index (unique_id);

create table `autoflow-demo`.crm_review_achievement_change_analysis
(
    id               bigint auto_increment
        primary key,
    unique_id        varchar(255)                       not null,
    session_id       varchar(255)                       not null,
    calc_phase       varchar(16)                        not null,
    snapshot_period  varchar(32)                        not null,
    report_date      date                               null,
    analysis_content mediumtext                         not null,
    created_at       datetime default CURRENT_TIMESTAMP not null,
    updated_at       datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
)
    comment '复盘业绩变化分析（JSON单表存储）';

create index idx_review_change_analysis_session_phase
    on `autoflow-demo`.crm_review_achievement_change_analysis (session_id, calc_phase);

create index idx_review_change_analysis_snapshot_period
    on `autoflow-demo`.crm_review_achievement_change_analysis (snapshot_period, calc_phase);

create table `autoflow-demo`.crm_review_attendee
(
    id                 int auto_increment
        primary key,
    unique_id          varchar(255)                         not null comment 'Unique identifier',
    session_id         varchar(255)                         not null comment 'FK → crm_review_session.unique_id',
    user_id            varchar(255)                         not null comment 'User ID',
    crm_user_id        varchar(255)                         not null comment 'CRM user ID (matches opportunity.owner_id)',
    user_name          varchar(255)                         null comment 'User name',
    department_id      varchar(255)                         null comment 'Department ID',
    department_name    varchar(255)                         null comment 'Department name',
    is_leader          tinyint(1)                           null comment 'Is department lead',
    is_primary_dept    tinyint(1)                           null comment 'Is primary department',
    has_submitted      tinyint(1) default 0                 null,
    submitted_at       datetime                             null,
    submission_count   int        default 0                 null,
    modification_count int        default 0                 null,
    last_modified_at   datetime                             null,
    created_at         datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at         datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_session_user
        unique (session_id, user_id)
)
    comment '复盘参与者表';

create index idx_crm_user_id
    on `autoflow-demo`.crm_review_attendee (crm_user_id);

create index idx_has_submitted
    on `autoflow-demo`.crm_review_attendee (has_submitted);

create index idx_session_id
    on `autoflow-demo`.crm_review_attendee (session_id);

create table `autoflow-demo`.crm_review_attendee_todo_stats
(
    id                                     int auto_increment
        primary key,
    unique_id                              varchar(255)                       not null comment '唯一性ID',
    session_id                             varchar(255)                       not null comment 'FK → crm_review_session.unique_id',
    owner_id                               varchar(255)                       not null comment 'Attendee CRM user ID (matches crm_review_attendee.crm_user_id)',
    owner_name                             varchar(255)                       null comment 'Attendee display name',
    department_id                          varchar(255)                       null comment 'Attendee department ID',
    department_name                        varchar(255)                       null comment 'Attendee department name',
    period varchar (32) not null comment 'Review period (e.g., 2026-W11)',
    report_date                            date                               not null comment 'Workflow report date (used as "today" for overdue calc)',
    calc_phase                             varchar(32)                        not null comment 'first | second',
    total_this_week                        int      default 0                 not null comment '本周任务总数：due_date在本周区间的任务数',
    completed_this_week                    int      default 0                 not null comment '本周任务已完成：本周任务中ai_status=COMPLETED的数量',
    incomplete_this_week                   int      default 0                 not null comment '本周未完成：本周任务中未完成的数量',
    historical_overdue_completed_this_week int      default 0                 not null comment '历史逾期本周完成：due_date早于本周但在本周完成的任务数',
    current_total_overdue                  int      default 0                 not null comment '当前总逾期：due_date早于report_date且未完成/未取消的任务数',
    created_at                             datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                             datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint uk_review_attendee_todo_stats
        unique (session_id, owner_id, calc_phase)
)
    comment '复盘参与者任务统计表';

create index idx_review_attendee_todo_stats_owner
    on `autoflow-demo`.crm_review_attendee_todo_stats (owner_id);

create index idx_review_attendee_todo_stats_session
    on `autoflow-demo`.crm_review_attendee_todo_stats (session_id);

create table `autoflow-demo`.crm_review_department
(
    id                      int auto_increment
        primary key,
    unique_id               varchar(255)                         not null comment '唯一性ID（必填）',
    department_id           varchar(255)                         not null comment 'FK → crm_department.unique_id',
    department_name         varchar(255)                         null comment 'Department name (denormalized)',
    parent_department_id    varchar(255)                         null comment 'Parent department ID',
    is_active               tinyint(1) default 1                 null comment 'Whether review is enabled for this dept',
    review_frequency        varchar(32)                          null comment 'weekly/monthly/quarterly',
    include_sub_departments tinyint(1) default 1                 null comment 'Whether to include sub-depts in review',
    created_at              datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at              datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    created_by              varchar(255)                         null comment 'User who added this dept to review list'
)
    comment '复盘部门配置表';

create index idx_active
    on `autoflow-demo`.crm_review_department (is_active);

create index idx_department_id
    on `autoflow-demo`.crm_review_department (department_id);

create index idx_parent_id
    on `autoflow-demo`.crm_review_department (parent_department_id);

create table `autoflow-demo`.crm_review_kpi_metric_opp_link
(
    id                   int auto_increment
        primary key,
    kpi_metric_unique_id varchar(255)                       not null comment 'Logical FK -> crm_review_kpi_metrics.unique_id',
    snapshot_unique_id   varchar(255)                       not null comment 'Logical FK -> crm_review_opp_branch_snapshot.unique_id',
    session_id           varchar(255)                       not null comment 'Redundant for filter',
    opportunity_id       varchar(255)                       not null comment 'Redundant for filter',
    snapshot_period      varchar(32)                        not null comment 'Redundant for filter (e.g., 2026-W15)',
    scope_type           varchar(32)                        not null comment 'owner | department | company',
    scope_id             varchar(255)                       null comment 'Owner/department id; null for company',
    metric_name          varchar(255)                       not null comment 'closed | commit_sales | commit_ai | upside_sales',
    calc_phase           varchar(32)                        not null comment 'first | second',
    create_time          datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time          datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at           datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at           datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint uniq_kpi_snapshot
        unique (kpi_metric_unique_id, snapshot_unique_id)
)
    comment '复盘KPI指标与商机快照关联表（用于UI下钻）';

create index idx_kpi_metric_unique_id
    on `autoflow-demo`.crm_review_kpi_metric_opp_link (kpi_metric_unique_id);

create index idx_opportunity_period
    on `autoflow-demo`.crm_review_kpi_metric_opp_link (opportunity_id, snapshot_period);

create index idx_session_metric
    on `autoflow-demo`.crm_review_kpi_metric_opp_link (session_id, metric_name);

create table `autoflow-demo`.crm_review_kpi_metrics
(
    id                  int auto_increment
        primary key,
    unique_id           varchar(255)                       not null,
    session_id          varchar(255)                       not null,
    scope_type          varchar(32)                        not null,
    scope_id            varchar(255)                       null,
    scope_name          varchar(255)                       null,
    parent_scope_id     varchar(255)                       null,
    metric_category     varchar(64)                        not null,
    metric_name         varchar(255)                       not null,
    metric_value        decimal(18, 4)                     null comment 'Current period value',
    metric_value_prev   decimal(18, 4)                     null comment 'Previous period value',
    metric_delta        decimal(18, 4)                     null comment 'Change value',
    metric_rate         decimal(8, 4)                      null comment 'Rate 0-1 (e.g., 0.288 = 28.8%)',
    metric_unit         varchar(32)                        null,
    metric_content      text                               null,
    metric_content_en   text                               null,
    calc_phase          varchar(32)                        null,
    period_type         varchar(32)                        null,
    period varchar (32) null,
    report_date         date                               null,
    report_year         int                                null,
    report_week_of_year int                                null,
    create_time         datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time         datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at          datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at          datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '复盘KPI指标表';

create index idx_period_scope_metric
    on `autoflow-demo`.crm_review_kpi_metrics (period, scope_type, metric_name);

create index idx_session_scope_cat
    on `autoflow-demo`.crm_review_kpi_metrics (session_id, scope_type, metric_category);

create index idx_session_scope_metric
    on `autoflow-demo`.crm_review_kpi_metrics (session_id, scope_id, metric_name);

create table `autoflow-demo`.crm_review_opp_audit_log
(
    id            char(32)                              not null
        primary key,
    session_id    varchar(255)                          not null comment 'FK → crm_review_session.unique_id',
    change_scope  varchar(64)                           not null comment 'Field name that was changed',
    old_value     text                                  null comment 'Previous value (string representation)',
    new_value     text                                  null comment 'New value (string representation)',
    change_type   varchar(32) default 'UPDATE'          not null comment 'Type: UPDATE',
    edit_phase    varchar(32)                           null comment 'initial/meeting - which phase the change was made',
    updated_by    varchar(255)                          not null comment 'User name who made the change',
    updated_by_id varchar(255)                          not null comment 'User ID who made the change',
    created_at    datetime    default CURRENT_TIMESTAMP null,
    updated_at    datetime    default CURRENT_TIMESTAMP null
)
    comment 'Audit log for branch snapshot modifications';

create index idx_session_id
    on `autoflow-demo`.crm_review_opp_audit_log (session_id);

create index idx_updated_at
    on `autoflow-demo`.crm_review_opp_audit_log (updated_at);

create index idx_updated_by_id
    on `autoflow-demo`.crm_review_opp_audit_log (updated_by_id);

create table `autoflow-demo`.crm_review_opp_branch_snapshot
(
    id                                int auto_increment
        primary key,
    unique_id                         varchar(255)                       not null comment 'Unique record ID',
    opportunity_id                    varchar(255)                       not null,
    owner_id                          varchar(255)                       null comment 'Owner crm_user_id',
    owner_name                        varchar(255)                       null,
    owner_department_id               varchar(255)                       null,
    owner_department_name             varchar(255)                       null,
    snapshot_period                   varchar(32)                        not null comment 'Period (e.g., 2026-W10)',
    snapshot_date                     date                               not null,
    account_id                        varchar(255)                       null,
    account_name                      varchar(255)                       null,
    opportunity_name                  varchar(255)                       null,
    forecast_type                     varchar(255)                       null,
    forecast_amount                   decimal(18, 2)                     null,
    forecast_amount_source            varchar(64)                        null,
    opportunity_stage                 varchar(255)                       null,
    expected_closing_date             varchar(255)                       null,
    baseline_forecast_type            varchar(255)                       null,
    baseline_forecast_amount          decimal(18, 2)                     null,
    baseline_forecast_amount_source   varchar(64)                        null,
    baseline_opportunity_stage        varchar(255)                       null,
    baseline_expected_closing_date    varchar(255)                       null,
    baseline_frozen_at                datetime                           null,
    crm_forecast_type                 varchar(255)                       null,
    crm_forecast_amount               decimal(18, 2)                     null,
    crm_forecast_amount_source        varchar(64)                        null,
    crm_opportunity_stage             varchar(255)                       null,
    crm_expected_closing_date         varchar(255)                       null,
    ai_commit_1st                     varchar(32)                        null,
    ai_stage_1st                      varchar(255)                       null,
    ai_expected_closing_date_1st      varchar(255)                       null,
    ai_evaluated_1st_at               datetime                           null,
    ai_commit_2nd                     varchar(32)                        null,
    ai_stage_2nd                      varchar(255)                       null,
    ai_expected_closing_date_2nd      varchar(255)                       null,
    ai_evaluated_2nd_at               datetime                           null,
    ai_commit                         varchar(32)                        null comment 'Latest AI commit assessment (Commit/NotCommit)',
    ai_stage                          varchar(255)                       null comment 'Latest AI stage assessment',
    ai_expected_closing_date          varchar(255)                       null comment 'Latest AI expected closing date',
    ai_evaluated_at                   datetime                           null comment 'Timestamp of latest AI evaluation',
    ai_eval_source                    varchar(10)                        null comment 'Source of AI eval: 1st or 2nd',
    stage_stay                        int                                null comment 'Days in current stage (from crm_opportunity_stage_stay_bucket)',
    expected_closing_quarter          varchar(50)                        null,
    close_date                        date                               null,
    is_closed                         tinyint(1)                         null,
    customer_type                     varchar(255)                       null,
    was_changed_to_commit             tinyint(1)                         null,
    was_modified                      tinyint(1)                         null,
    last_modified_by                  varchar(255)                       null,
    last_modified_by_id               varchar(255)                       null,
    modification_count                int      default 0                 null,
    initial_edit_modification_count   int                                null,
    meeting_edit_modification_count   int                                null,
    create_time                       datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time                       datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    opp_create_time                   datetime                           null comment '商机创建时间（来源CRM）',
    baseline_expected_closing_quarter varchar(50)                        null,
    crm_expected_closing_quarter      varchar(50)                        null,
    crm_opportunity_type              varchar(255)                       null comment 'CRM original opportunity type',
    expected_closing_month            varchar(50)                        null comment '标准化预计成交月（如FY26M02）',
    baseline_expected_closing_month   varchar(50)                        null comment '冻结基线预计成交月（如FY26M02）',
    crm_expected_closing_month        varchar(50)                        null comment 'CRM原始预计成交月标准化值（如FY26M02）',
    created_at                        datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                        datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_opp_period
        unique (opportunity_id, snapshot_period)
)
    comment '复盘商机快照表';

create index idx_ai_commit
    on `autoflow-demo`.crm_review_opp_branch_snapshot (ai_commit);

create index idx_owner_period
    on `autoflow-demo`.crm_review_opp_branch_snapshot (owner_id, snapshot_period);

create index idx_snapshot_period
    on `autoflow-demo`.crm_review_opp_branch_snapshot (snapshot_period);

create index idx_stage_stay
    on `autoflow-demo`.crm_review_opp_branch_snapshot (stage_stay);

create index idx_was_changed
    on `autoflow-demo`.crm_review_opp_branch_snapshot (was_changed_to_commit);

create table `autoflow-demo`.crm_review_opp_branch_snapshot_cache
(
    id                                int auto_increment
        primary key,
    unique_id                         varchar(255)                       not null comment 'Unique record ID',
    opportunity_id                    varchar(255)                       not null,
    owner_id                          varchar(255)                       null comment 'Owner crm_user_id',
    owner_name                        varchar(255)                       null,
    owner_department_id               varchar(255)                       null,
    owner_department_name             varchar(255)                       null,
    snapshot_period                   varchar(32)                        not null comment 'Period (e.g., 2026-W10)',
    snapshot_date                     date                               not null,
    account_id                        varchar(255)                       null,
    account_name                      varchar(255)                       null,
    opportunity_name                  varchar(255)                       null,
    forecast_type                     varchar(255)                       null,
    forecast_amount                   decimal(18, 2)                     null,
    forecast_amount_source            varchar(64)                        null,
    opportunity_stage                 varchar(255)                       null,
    expected_closing_date             varchar(255)                       null,
    baseline_forecast_type            varchar(255)                       null,
    baseline_forecast_amount          decimal(18, 2)                     null,
    baseline_forecast_amount_source   varchar(64)                        null,
    baseline_opportunity_stage        varchar(255)                       null,
    baseline_expected_closing_date    varchar(255)                       null,
    baseline_expected_closing_quarter varchar(50)                        null,
    baseline_frozen_at                datetime                           null,
    crm_forecast_type                 varchar(255)                       null,
    crm_forecast_amount               decimal(18, 2)                     null,
    crm_forecast_amount_source        varchar(64)                        null,
    crm_opportunity_stage             varchar(255)                       null,
    crm_expected_closing_date         varchar(255)                       null,
    crm_expected_closing_quarter      varchar(50)                        null,
    ai_commit_1st                     varchar(32)                        null,
    ai_stage_1st                      varchar(255)                       null,
    ai_expected_closing_date_1st      varchar(255)                       null,
    ai_evaluated_1st_at               datetime                           null,
    ai_commit_2nd                     varchar(32)                        null,
    ai_stage_2nd                      varchar(255)                       null,
    ai_expected_closing_date_2nd      varchar(255)                       null,
    ai_evaluated_2nd_at               datetime                           null,
    ai_commit                         varchar(32)                        null comment 'Latest AI commit assessment (Commit/NotCommit)',
    ai_stage                          varchar(255)                       null comment 'Latest AI stage assessment',
    ai_expected_closing_date          varchar(255)                       null comment 'Latest AI expected closing date',
    ai_evaluated_at                   datetime                           null comment 'Timestamp of latest AI evaluation',
    ai_eval_source                    varchar(10)                        null comment 'Source of AI eval: 1st or 2nd',
    stage_stay                        int                                null comment 'Days in current stage (from crm_opportunity_stage_stay_bucket)',
    expected_closing_quarter          varchar(50)                        null,
    close_date                        date                               null,
    is_closed                         tinyint(1)                         null,
    customer_type                     varchar(255)                       null,
    was_changed_to_commit             tinyint(1)                         null,
    was_modified                      tinyint(1)                         null,
    last_modified_by                  varchar(255)                       null,
    last_modified_by_id               varchar(255)                       null,
    modification_count                int      default 0                 null,
    initial_edit_modification_count   int                                null,
    meeting_edit_modification_count   int                                null,
    opp_create_time                   datetime                           null comment '商机创建时间（来源CRM）',
    create_time                       datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time                       datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    crm_opportunity_type              varchar(255)                       null comment 'CRM original opportunity type',
    expected_closing_month            varchar(50)                        null comment '标准化预计成交月（如FY26M02）',
    baseline_expected_closing_month   varchar(50)                        null comment '冻结基线预计成交月（如FY26M02）',
    crm_expected_closing_month        varchar(50)                        null comment 'CRM原始预计成交月标准化值（如FY26M02）',
    created_at                        datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                        datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint idx_opp_period_cache
        unique (opportunity_id, snapshot_period)
)
    comment '复盘商机快照缓存表（T1初始化时同步生成，由第三方服务负责后续同步）';

create index idx_ai_commit_cache
    on `autoflow-demo`.crm_review_opp_branch_snapshot_cache (ai_commit);

create index idx_owner_period_cache
    on `autoflow-demo`.crm_review_opp_branch_snapshot_cache (owner_id, snapshot_period);

create index idx_snapshot_period_cache
    on `autoflow-demo`.crm_review_opp_branch_snapshot_cache (snapshot_period);

create index idx_stage_stay_cache
    on `autoflow-demo`.crm_review_opp_branch_snapshot_cache (stage_stay);

create index idx_was_changed_cache
    on `autoflow-demo`.crm_review_opp_branch_snapshot_cache (was_changed_to_commit);

create table `autoflow-demo`.crm_review_opp_comment
(
    id                bigint auto_increment
        primary key,
    unique_id         varchar(255)                         not null comment 'Stable comment UUID',
    session_id        varchar(255)                         not null comment 'FK → crm_review_session.unique_id',
    opportunity_id    varchar(255)                         not null comment 'CRM opportunity ID',
    content           text                                 not null comment 'Comment body text',
    created_at        datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at        datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    target_type       varchar(64)                          null comment 'RiskProgressType value: RISK | PROGRESS | OPP_SUMMARY | OPP_REQS_INSIGHT; NULL = general opp comment',
    target_id         varchar(255)                         null comment 'CRMReviewOppRiskProgress.unique_id of the anchored entity',
    parent_id         varchar(255)                         null comment 'CRMReviewOppComment.unique_id of parent comment; NULL = top-level',
    is_deleted        tinyint(1) default 0                 not null comment 'Soft-delete flag; content is blanked on delete',
    is_edited         tinyint(1) default 0                 not null comment 'Set to True on first edit; UI shows "(edited)" badge',
    submitted_by      varchar(255)                         not null comment 'CRM user ID of the submitter',
    submitted_by_name varchar(255)                         not null comment 'Display name at submit time',
    constraint uk_opp_comment_unique_id
        unique (unique_id)
)
    comment '复盘商机评论表（含回复树与目标锚定）';

create index idx_opp_comment_parent
    on `autoflow-demo`.crm_review_opp_comment (parent_id);

create index idx_opp_comment_session_opp
    on `autoflow-demo`.crm_review_opp_comment (session_id, opportunity_id);

create index idx_opp_comment_submitter
    on `autoflow-demo`.crm_review_opp_comment (submitted_by);

create index idx_opp_comment_target
    on `autoflow-demo`.crm_review_opp_comment (target_type, target_id);

create table `autoflow-demo`.crm_review_opp_risk_progress
(
    id                 bigint auto_increment
        primary key,
    unique_id          varchar(255)                       not null,
    session_id         varchar(255)                       not null,
    scope_type         varchar(32)                        not null,
    scope_id           varchar(255)                       null,
    department_id      varchar(255)                       null,
    snapshot_id        varchar(255)                       null,
    opportunity_id     varchar(255)                       null,
    owner_id           varchar(255)                       null,
    record_type        varchar(32)                        not null,
    type_code          varchar(64)                        not null,
    type_name          varchar(128)                       not null,
    category           varchar(64)                        null,
    level              varchar(32)                        null,
    severity           varchar(16)                        null,
    source             varchar(128)                       null,
    metric_name        varchar(64)                        null,
    ai_assessment      varchar(255)                       null,
    sales_assessment   varchar(255)                       null,
    judgment_rule      text                               null,
    gap_description    text                               null,
    detail_description text                               null,
    solution           text                               null,
    evidence           json                               null,
    financial_impact   decimal(18, 2)                     null,
    previous_value     decimal(18, 2)                     null,
    current_value      decimal(18, 2)                     null,
    rate_of_change     decimal(8, 4)                      null,
    status             varchar(32)                        null,
    detected_at        datetime default CURRENT_TIMESTAMP not null,
    resolved_at        datetime                           null,
    resolved_by        varchar(255)                       null,
    resolution_type    varchar(32)                        null,
    resolution_note    text                               null,
    calc_phase         varchar(16)                        not null,
    snapshot_period    varchar(32)                        not null,
    metadata           json                               null,
    created_at         datetime default CURRENT_TIMESTAMP not null,
    updated_at         datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    created_by         varchar(255)                       null,
    updated_by         varchar(255)                       null,
    summary            text                               null,
    parent_id          varchar(255)                       null comment '父风险记录的 unique_id，NULL 表示根级别风险',
    part_key           varchar(64)                        null comment '在父卡片内的逻辑分区标识，如 commit_risk / upside_fill / pipeline',
    display_order      smallint                           null comment '在父卡片内的渲染顺序',
    constraint uk_risk_part
        unique (parent_id, part_key),
    constraint uk_session_scope_type_period
        unique (session_id, scope_type, scope_id, type_code, snapshot_period, calc_phase)
)
    comment '风险与进展追踪表';

create index idx_department
    on `autoflow-demo`.crm_review_opp_risk_progress (department_id);

create index idx_detected_at
    on `autoflow-demo`.crm_review_opp_risk_progress (detected_at);

create index idx_opportunity
    on `autoflow-demo`.crm_review_opp_risk_progress (opportunity_id);

create index idx_owner
    on `autoflow-demo`.crm_review_opp_risk_progress (owner_id);

create index idx_parent_id
    on `autoflow-demo`.crm_review_opp_risk_progress (parent_id);

create index idx_record_type
    on `autoflow-demo`.crm_review_opp_risk_progress (record_type);

create index idx_session_scope
    on `autoflow-demo`.crm_review_opp_risk_progress (session_id, scope_type, scope_id);

create index idx_snapshot_period
    on `autoflow-demo`.crm_review_opp_risk_progress (snapshot_period);

create index idx_status
    on `autoflow-demo`.crm_review_opp_risk_progress (status);

create index idx_type_code
    on `autoflow-demo`.crm_review_opp_risk_progress (type_code);

create table `autoflow-demo`.crm_review_progress_category
(
    id               bigint auto_increment
        primary key,
    unique_id        varchar(255)                       not null,
    code             varchar(64)                        not null,
    name_zh          varchar(128)                       not null,
    name_en          varchar(128)                       null,
    category_group   varchar(64)                        null,
    default_level    varchar(32)                        null,
    detection_source varchar(64)                        null,
    detection_rules  json                               null,
    is_active        tinyint(1)                         null,
    sort_order       int                                null,
    created_at       datetime default CURRENT_TIMESTAMP not null,
    updated_at       datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    constraint code
        unique (code)
)
    comment '进展类别配置表';

create index idx_is_active
    on `autoflow-demo`.crm_review_progress_category (is_active);

create table `autoflow-demo`.crm_review_progress_threshold
(
    id              bigint auto_increment
        primary key,
    unique_id       varchar(255)                         not null,
    scope_type      varchar(32)                          not null comment '范围类型：department/company',
    scope_id        varchar(255)                         not null comment '范围ID：部门ID或company',
    progress_code   varchar(64)                          not null comment '进展编码，例如 MAJOR_NEW_ORDER',
    threshold_value decimal(18, 2)                       not null comment '阈值金额',
    description     text                                 null comment '阈值说明',
    is_active       tinyint(1) default 1                 null comment '是否启用',
    created_at      datetime   default CURRENT_TIMESTAMP not null,
    updated_at      datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    constraint uk_scope_progress_code
        unique (scope_type, scope_id, progress_code)
)
    comment '商机进展阈值配置表';

create index idx_progress_code_active
    on `autoflow-demo`.crm_review_progress_threshold (progress_code, is_active);

create index idx_scope_type_scope_id
    on `autoflow-demo`.crm_review_progress_threshold (scope_type, scope_id);

create table `autoflow-demo`.crm_review_risk_aggregation
(
    id                    bigint auto_increment
        primary key,
    unique_id             varchar(255)                       not null,
    session_id            varchar(255)                       not null,
    scope_type            varchar(32)                        not null,
    scope_id              varchar(255)                       not null,
    scope_name            varchar(255)                       null,
    snapshot_period       varchar(32)                        not null,
    calc_phase            varchar(16)                        not null,
    total_risks           int                                null,
    total_progress        int                                null,
    critical_risks        int                                null,
    high_risks            int                                null,
    medium_risks          int                                null,
    low_risks             int                                null,
    open_risks            int                                null,
    resolved_risks        int                                null,
    total_risk_amount     decimal(18, 2)                     null,
    total_progress_amount decimal(18, 2)                     null,
    risk_breakdown        json                               null,
    progress_breakdown    json                               null,
    previous_period_risks int                                null,
    risk_trend            varchar(16)                        null,
    computed_at           datetime default CURRENT_TIMESTAMP not null,
    created_at            datetime default CURRENT_TIMESTAMP not null,
    updated_at            datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    constraint uk_session_scope_period
        unique (session_id, scope_type, scope_id, snapshot_period, calc_phase)
)
    comment '风险聚合汇总表';

create index idx_computed_at
    on `autoflow-demo`.crm_review_risk_aggregation (computed_at);

create index idx_period_phase
    on `autoflow-demo`.crm_review_risk_aggregation (snapshot_period, calc_phase);

create index idx_session_scope
    on `autoflow-demo`.crm_review_risk_aggregation (session_id, scope_type, scope_id);

create table `autoflow-demo`.crm_review_risk_category
(
    id                      bigint auto_increment
        primary key,
    unique_id               varchar(255)                       not null,
    code                    varchar(64)                        not null,
    name_zh                 varchar(128)                       not null,
    name_en                 varchar(128)                       null,
    category_group          varchar(64)                        null,
    default_level           varchar(32)                        null,
    default_severity        varchar(16)                        null,
    detection_source        varchar(64)                        null,
    detection_rules         text                               null,
    auto_resolve            tinyint(1)                         null,
    requires_acknowledgment tinyint(1)                         null,
    is_active               tinyint(1)                         null,
    sort_order              int                                null,
    created_at              datetime default CURRENT_TIMESTAMP not null,
    updated_at              datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    solution                text                               null,
    constraint code
        unique (code)
)
    comment '风险类别配置表';

create index idx_category_group
    on `autoflow-demo`.crm_review_risk_category (category_group);

create index idx_is_active
    on `autoflow-demo`.crm_review_risk_category (is_active);

create table `autoflow-demo`.crm_review_risk_opportunity_relation
(
    id              bigint auto_increment
        primary key,
    unique_id       varchar(255)                       not null,
    risk_unique_id  varchar(255)                       not null comment '关联 crm_review_opp_risk_progress.unique_id',
    type_name       varchar(128)                       null comment '冗余的风险类型名称，用于加速查询',
    session_id      varchar(255)                       not null,
    snapshot_period varchar(32)                        not null,
    calc_phase      varchar(16)                        not null,
    opportunity_id  varchar(255)                       not null,
    owner_id        varchar(255)                       null,
    department_id   varchar(255)                       null,
    relation_reason text                               null,
    relation_rank   int                                null,
    relation_weight decimal(8, 4)                      null,
    metadata        json                               null,
    created_at      datetime default CURRENT_TIMESTAMP not null,
    updated_at      datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP,
    constraint uk_risk_opp_relation
        unique (risk_unique_id, opportunity_id)
)
    comment '风险与商机关联关系表';

create index idx_opportunity_id
    on `autoflow-demo`.crm_review_risk_opportunity_relation (opportunity_id);

create index idx_risk_unique_id
    on `autoflow-demo`.crm_review_risk_opportunity_relation (risk_unique_id);

create index idx_session_period_phase
    on `autoflow-demo`.crm_review_risk_opportunity_relation (session_id, snapshot_period, calc_phase);

create table `autoflow-demo`.crm_review_session
(
    id                             int auto_increment
        primary key,
    unique_id                      varchar(255)                       not null comment 'Unique session identifier (UUID)',
    session_name                   varchar(255)                       null comment 'Display name',
    department_id                  varchar(255)                       not null comment 'FK → crm_department.unique_id',
    department_name                varchar(255)                       null comment 'Department name',
    review_type                    varchar(64)                        not null comment 'Review type',
    period_type                    varchar(32)                        not null comment 'weekly/monthly/quarterly',
    period varchar (32) not null comment 'Period identifier (e.g., 2026-W10)',
    fiscal_year                    varchar(16)                        null comment 'Fiscal year',
    stage                          varchar(32)                        not null comment 'initial_edit/first_calculating/first_calc_ready/lead_review/second_calculating/completed. Note: FCST eval starts async at T1 during initial_edit (background optimization)',
    review_phase                   varchar(32)                        null comment 'not_started/edit/closed - controls if attendees can edit',
    t1_time                        datetime                           not null comment 'T1: Session launch',
    t2_time                        datetime                           not null comment 'T2: First calc',
    t3_time                        datetime                           not null comment 'T3: Open to lead',
    t4_time                        datetime                           not null comment 'T4: Second calc',
    initial_window_open_time       datetime                           null comment 'When initial edit window opened',
    initial_window_close_time      datetime                           null comment 'When initial edit window closed',
    first_calc_start_time          datetime                           null,
    first_calc_end_time            datetime                           null,
    first_calc_execution_id        varchar(255)                       null,
    meeting_opened_by              varchar(255)                       null,
    meeting_opened_by_id           varchar(255)                       null,
    meeting_opened_at              datetime                           null,
    meeting_closed_at              datetime                           null,
    meeting_open_count             int                                null,
    meeting_total_duration_minutes int                                null,
    second_calc_start_time         datetime                           null,
    second_calc_end_time           datetime                           null,
    second_calc_execution_id       varchar(255)                       null,
    launched_by                    varchar(255)                       null,
    launched_by_id                 varchar(255)                       null,
    plan_id                        varchar(255)                       null,
    report_date                    date                               not null,
    report_week_of_year            int                                null,
    report_month_of_year           int                                null,
    report_quarter_of_year         int                                null,
    report_year                    int                                not null,
    period_start                   date                               not null comment 'Start date of the review period',
    period_end                     date                               not null comment 'End date of the review period',
    report_fy_quarter              varchar(10)                        null comment 'Report fiscal year quarter for performance queries',
    create_time                    datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time                    datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at                     datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                     datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '复盘会话表';

create index idx_department_id
    on `autoflow-demo`.crm_review_session (department_id);

create index idx_report_fy_quarter
    on `autoflow-demo`.crm_review_session (report_fy_quarter);

create index idx_report_year_week
    on `autoflow-demo`.crm_review_session (report_year, report_week_of_year);

create index idx_review_phase
    on `autoflow-demo`.crm_review_session (review_phase);

create index idx_stage
    on `autoflow-demo`.crm_review_session (stage);

create index idx_t1_time
    on `autoflow-demo`.crm_review_session (t1_time);

create index idx_t2_time
    on `autoflow-demo`.crm_review_session (t2_time);

create index idx_t3_time
    on `autoflow-demo`.crm_review_session (t3_time);

create index idx_t4_time
    on `autoflow-demo`.crm_review_session (t4_time);

create index idx_unique_id
    on `autoflow-demo`.crm_review_session (unique_id);

create table `autoflow-demo`.crm_sales_activities
(
    id                      int auto_increment
        primary key,
    unique_id               varchar(255)                       not null comment '唯一性ID（必填）',
    category                varchar(50)                        null comment '活动类别（如update/callhigh/其他）',
    data_source             varchar(100)                       null comment '数据来源（URL/飞书/CRM/Chatbot/等）',
    record_date             date                               not null comment '记录日期（YYYY-MM-DD）',
    location                varchar(255)                       null comment '活动地点',
    communication_medium    varchar(255)                       null comment '活动形式及沟通方式（如：线上会议/线下会议/电话/邮件/拜访/演示/提案等）',
    internal_participants   text                               null comment '内部参与者（JSON格式）',
    external_participants   text                               null comment '外部参与者即客户（JSON格式）',
    key_stakeholders        text                               null comment '关键干系人',
    account_id              varchar(255)                       null comment '关联的客户ID',
    account_name            varchar(255)                       null comment '关联的客户名称',
    opportunity_id          varchar(255)                       null comment '关联的商机ID',
    opportunity_name        varchar(255)                       null comment '关联的商机名称',
    linked_account_ids      text                               null comment 'Mandatory: 关联的客户ID列表（JSON格式）',
    linked_opportunity_ids  text                               null comment 'Mandatory: 关联的商机ID列表（JSON格式）',
    owner_id                varchar(255)                       null comment '负责人ID',
    owner_name              varchar(255)                       null comment '负责人姓名',
    summary                 varchar(500)                       not null comment '活动摘要',
    detailed_notes          text                               null comment '详细记录',
    next_steps              text                               null comment '下一步行动计划',
    blockers                text                               null comment '当前障碍或挑战,即要解决的问题',
    core_biz_info           text                               null comment '核心业务信息',
    deal_probability_change varchar(50)                        null comment '成单概率变化（上升/下降/不变）',
    customer_sentiment      varchar(50)                        null comment '客户态度（积极/中性/消极）',
    correlation_id          varchar(255)                       null comment '关联ID',
    creator                 varchar(255)                       null comment '创建人',
    creator_id              varchar(255)                       null comment '创建人唯一性ID',
    create_time             datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    last_modifier           varchar(255)                       null comment '最后修改人',
    last_modified_time      datetime default CURRENT_TIMESTAMP not null comment '最后修改时间',
    created_at              datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at              datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '销售活动记录表';

create index idx_account_id
    on `autoflow-demo`.crm_sales_activities (account_id);

create index idx_activity_type
    on `autoflow-demo`.crm_sales_activities (communication_medium);

create index idx_correlation_id
    on `autoflow-demo`.crm_sales_activities (correlation_id);

create index idx_opportunity_id
    on `autoflow-demo`.crm_sales_activities (opportunity_id);

create index idx_record_date
    on `autoflow-demo`.crm_sales_activities (record_date);

create table `autoflow-demo`.crm_sales_records
(
    id                         bigint auto_increment comment '主键ID（自增序列）'
        primary key,
    unique_id                  varchar(255)   null comment '唯一性ID（必填）',
    related_api_names          varchar(1024)  null comment '关联业务对象',
    lock_rule                  varchar(1024)  null comment '锁定规则',
    active_record_type         varchar(255)   null comment '跟进类型',
    active_record_content      text           null comment '记录内容',
    origin_source              varchar(255)   null comment '数据来源',
    lock_user                  varchar(1024)  null comment '加锁人',
    extend_obj_data_id         varchar(255)   null comment '扩展字段在mt_data中的记录ID',
    is_deleted                 tinyint(1)     null comment 'is_deleted',
    life_status_before_invalid varchar(255)   null comment '作废前生命状态',
    owner_department           varchar(255)   null comment '负责人主属部门',
    out_owner                  varchar(1024)  null comment '外部负责人',
    owner                      varchar(1024)  null comment '负责人',
    lock_status                varchar(255)   null comment '锁定状态',
    last_modified_time         datetime       null comment '最后修改时间',
    create_time                datetime       null comment '创建时间',
    life_status                varchar(255)   null comment '生命状态',
    related_object_data        varchar(1024)  null comment '关联业务数据',
    last_modified_by           varchar(1024)  null comment '最后修改人',
    out_tenant_id              varchar(255)   null comment '外部企业',
    version                    decimal(18, 2) null comment 'version',
    created_by                 varchar(1024)  null comment '创建人',
    relevant_team              varchar(1024)  null comment '相关团队',
    record_type                varchar(255)   null comment '业务类型',
    related_object             varchar(1024)  null comment '关联业务模块',
    field_zzD04__c             text           null comment '跟进记录内容',
    data_own_department        varchar(1024)  null comment '归属部门',
    name                       varchar(255)   null comment '记录ID',
    order_by                   decimal(18, 2) null comment 'order_by',
    opportunity_id             varchar(255)   null comment '商机ID',
    next_action_plan           text           null comment '下一步行动计划',
    visiting_personnel         varchar(255)   null comment '拜访人员',
    delete_flag                tinyint(1)     null comment '删除标识（0-正常，1-已删除）',
    extra                      json           null comment '扩展内容'
)
    comment '销售记录表';

create table `autoflow-demo`.crm_sentinel_events
(
    id           int auto_increment
        primary key,
    event_id     varchar(255)                          not null comment 'Public event ID',
    check_name   varchar(100)                          not null comment 'Check name e.g. stale_task',
    severity     varchar(20)                           not null comment 'INFO/WARNING/CRITICAL',
    status       varchar(20) default 'OPEN'            not null comment 'OPEN/RESOLVED/SUPPRESSED',
    subject_type varchar(100)                          not null comment 'task_execution/work_item/celery_queue/db_session',
    subject_id   varchar(255)                          not null comment 'Subject identifier',
    message      text                                  not null comment 'Human-readable description',
    detail       json                                  null comment 'Structured payload',
    resolved_at  datetime                              null comment 'When finding was resolved',
    created_at   datetime    default CURRENT_TIMESTAMP not null comment 'Create time',
    updated_at   datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment 'Update time',
    constraint idx_sentinel_event_id
        unique (event_id)
)
    comment 'Sentinel health monitor events';

create index idx_sentinel_check_status
    on `autoflow-demo`.crm_sentinel_events (check_name, status);

create index idx_sentinel_open_lookup
    on `autoflow-demo`.crm_sentinel_events (check_name, subject_id, status);

create index idx_sentinel_severity_status_created
    on `autoflow-demo`.crm_sentinel_events (severity, status, created_at);

create index idx_sentinel_subject
    on `autoflow-demo`.crm_sentinel_events (subject_type, subject_id);

create table `autoflow-demo`.crm_sentinel_schedule_log
(
    id             int auto_increment
        primary key,
    log_id         varchar(255)                          not null comment 'Public log ID',
    plan_id        varchar(255)                          not null comment 'Workflow plan ID',
    execution_id   varchar(255)                          not null comment 'Expected task execution ID',
    triggered_at   datetime                              not null comment 'When trigger succeeded',
    trigger_source varchar(50) default 'manual'          not null comment 'cronicle/manual',
    verified_at    datetime                              null comment 'When submission check completed',
    status         varchar(20) default 'PENDING'         not null comment 'PENDING/VERIFIED/MISSING',
    created_at     datetime    default CURRENT_TIMESTAMP not null comment 'Create time',
    updated_at     datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment 'Update time',
    constraint idx_sentinel_schedule_log_id
        unique (log_id)
)
    comment 'Sentinel scheduled trigger audit log';

create index idx_sentinel_schedule_execution
    on `autoflow-demo`.crm_sentinel_schedule_log (execution_id);

create index idx_sentinel_schedule_plan_status
    on `autoflow-demo`.crm_sentinel_schedule_log (plan_id, status);

create table `autoflow-demo`.crm_stage
(
    id                         bigint auto_increment comment '主键ID（自增序列）'
        primary key,
    workflow_id                varchar(255)   null comment '阶段推进器版本号',
    workflow_name              varchar(255)   null comment '流程名称',
    accumulate_time            decimal(18, 2) null comment '任务历史停留时长',
    life_status_before_invalid varchar(255)   null comment '作废前生命状态',
    activity_id                varchar(255)   null comment '节点定义id',
    state                      varchar(255)   null comment '任务状态',
    candidate_ids              text           null comment '待处理人',
    total_spent_time           varchar(512)   null comment '任务停留总时长',
    timeout_time               varchar(512)   null comment '超时时长',
    create_time                timestamp      null comment '创建时间',
    stage_id                   varchar(255)   null comment '所属阶段',
    link_app_type              decimal(18, 2) null comment '外部业务类型',
    link_app_id                varchar(255)   null comment '外部所属业务',
    version                    decimal(18, 2) null comment 'version',
    created_by                 json           null comment '创建人',
    relevant_team              json           null comment '相关团队',
    start_time                 timestamp      null comment '任务开始时间',
    is_time_out                tinyint(1)     null comment '是否超时',
    data_own_department        json           null comment '归属部门',
    object_api_name            varchar(255)   null comment '关联对象',
    object_describe_id         varchar(255)   null comment 'object_describe_id',
    name                       varchar(255)   null comment '名称',
    _id                        varchar(255)   null comment '_id',
    remind_latency             decimal(18, 2) null comment '允许停留时长',
    object_record_type         varchar(255)   null comment '对象业务类型',
    object_data_id             varchar(255)   null comment '关联数据',
    origin_source              varchar(255)   null comment '数据来源',
    is_deleted                 tinyint(1)     null comment 'is_deleted',
    recent_enter_time          timestamp      null comment '最近进入任务时间',
    out_owner                  json           null comment '外部负责人',
    owner                      json           null comment '负责人',
    actual_duration            decimal(18, 2) null comment '耗时(仅工作时间)',
    last_modified_time         timestamp      null comment '最后修改时间',
    processor_ids              json           null comment '已执行人',
    life_status                varchar(255)   null comment '生命状态',
    end_time                   timestamp      null comment '任务结束时间',
    last_modified_by           json           null comment '最后修改人',
    out_tenant_id              varchar(255)   null comment '外部企业',
    record_type                varchar(255)   null comment '业务类型',
    related_object             json           null comment '所属对象',
    workflow_instance_id       varchar(255)   null comment '所属阶段实例',
    current_candidate_ids      text           null comment '当前待处理人',
    read_employee              json           null comment '已读人员',
    order_by                   decimal(18, 2) null comment 'order_by',
    source_workflow_id         varchar(255)   null comment '流程的apiName',
    stage_field_api_name       varchar(255)   null comment '对象字段',
    delete_flag                tinyint(1)     null comment '删除标识（0-正常，1-已删除）',
    extra                      json           null comment '扩展内容'
)
    comment '阶段表';

create table `autoflow-demo`.crm_sync_status
(
    table_name     varchar(100)                          not null comment '表名'
        primary key,
    last_sync_time datetime                              null comment '最后同步时间',
    sync_type      enum ('full', 'incremental')          null comment '同步类型',
    total_records  int                                   null comment '总记录数',
    sync_status    enum ('success', 'failed', 'running') null comment '同步状态',
    error_message  text                                  null comment '错误信息',
    created_at     datetime default CURRENT_TIMESTAMP    null comment '创建时间',
    updated_at     datetime default CURRENT_TIMESTAMP    null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment 'CRM同步状态表';

create table `autoflow-demo`.crm_system_configurations
(
    id           int auto_increment
        primary key,
    config_type  varchar(255)                       not null comment '配置类型（如CommunicationCategory/VisitStatus/UserRoles等）',
    config_key   varchar(255)                       not null comment '配置键',
    config_value varchar(255)                       not null comment '配置值',
    is_active    tinyint(1)                         not null comment '是否启用',
    description  text                               null comment '配置描述',
    create_time  datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time  datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at   datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at   datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '系统配置表';

create index idx_config_key
    on `autoflow-demo`.crm_system_configurations (config_key);

create index idx_config_type
    on `autoflow-demo`.crm_system_configurations (config_type);

create index idx_config_type_key
    on `autoflow-demo`.crm_system_configurations (config_type, config_key);

create table `autoflow-demo`.crm_todo_merge_events
(
    id                      int auto_increment
        primary key,
    unique_id               varchar(255)                       not null comment '唯一性ID',
    job_id                  varchar(255)                       null comment '合并任务ID',
    survivor_todo_id        varchar(255)                       not null comment '保留的待办唯一ID',
    merged_todo_id          varchar(255)                       null comment '被合并并软删除的待办唯一ID',
    incoming_source         varchar(50)                        null comment '新待办来源',
    survivor_source         varchar(50)                        null comment '保留待办来源',
    decision                varchar(100)                       not null comment '合并决策',
    merge_action            varchar(100)                       null comment 'LLM合并动作',
    duplicate_reason        text                               null comment '重复判断原因',
    llm_decision_json       json                               null comment 'LLM原始决策',
    validated_decision_json json                               null comment '校验后的决策',
    raw_candidate_json      json                               null comment '新待办候选内容',
    created_at              datetime default CURRENT_TIMESTAMP not null comment '创建时间'
)
    comment '待办合并审计表';

create index idx_todo_merge_events_decision
    on `autoflow-demo`.crm_todo_merge_events (decision);

create index idx_todo_merge_events_job
    on `autoflow-demo`.crm_todo_merge_events (job_id);

create index idx_todo_merge_events_merged
    on `autoflow-demo`.crm_todo_merge_events (merged_todo_id);

create index idx_todo_merge_events_survivor
    on `autoflow-demo`.crm_todo_merge_events (survivor_todo_id);

create table `autoflow-demo`.crm_todo_merge_jobs
(
    id                      int auto_increment
        primary key,
    job_id                  varchar(255)                          not null comment '合并任务ID',
    status                  varchar(50) default 'PENDING'         not null comment '任务状态',
    trigger_source          varchar(100)                          null comment '触发来源',
    scope_key               varchar(512)                          null comment '合并范围键',
    new_todo_ids_json       json                                  not null comment '新建待办ID列表',
    candidate_todo_ids_json json                                  null comment '候选待办ID列表',
    attempt_count           int         default 0                 not null comment '尝试次数',
    last_error              text                                  null comment '最近错误',
    created_at              datetime    default CURRENT_TIMESTAMP not null comment '创建时间',
    started_at              datetime                              null comment '开始时间',
    completed_at            datetime                              null comment '完成时间',
    updated_at              datetime    default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint job_id
        unique (job_id)
)
    comment '待办语义合并任务表';

create index idx_todo_merge_jobs_scope
    on `autoflow-demo`.crm_todo_merge_jobs (scope_key);

create index idx_todo_merge_jobs_status
    on `autoflow-demo`.crm_todo_merge_jobs (status);

create table `autoflow-demo`.crm_todo_metrics_facts
(
    id           char(32)                               not null
        primary key,
    anchor       varchar(20)                            not null,
    grain        varchar(10)                            not null,
    period_start date                                   not null,
    period_end   date                                   not null,
    hour_of_day  int          default 0                 not null,
    subject_type varchar(20)                            not null,
    subject_id   varchar(100)                           not null,
    data_source  varchar(100) default ''                not null,
    metric       varchar(50)                            not null,
    value_int    int          default 0                 not null,
    created_at   datetime     default CURRENT_TIMESTAMP null,
    updated_at   datetime     default CURRENT_TIMESTAMP null,
    constraint ux_crm_todo_metrics_facts
        unique (anchor, grain, period_start, period_end, hour_of_day, subject_type, subject_id, data_source, metric)
);

create index idx_todo_company_week_anchor_metric_ds
    on `autoflow-demo`.crm_todo_metrics_facts (anchor, grain, subject_type, subject_id, metric, data_source,
                                               period_start);

create index ix_crm_todo_metrics_facts_anchor_grain_period_metric_ds
    on `autoflow-demo`.crm_todo_metrics_facts (anchor, grain, period_start, period_end, metric, data_source);

create index ix_crm_todo_metrics_facts_subject_period_metric
    on `autoflow-demo`.crm_todo_metrics_facts (subject_type, subject_id, period_start, metric);

create table `autoflow-demo`.crm_todos
(
    id                     int auto_increment
        primary key,
    unique_id              varchar(255)                         not null comment '唯一性ID（必填）',
    title                  varchar(255)                         not null comment '待办事项标题',
    description            text                                 null comment '详细描述',
    status                 varchar(50)                          null comment '状态（待处理/进行中/已完成/已取消）系统状态',
    priority               varchar(50)                          null comment '优先级（高/中/低）',
    start_date             date                                 null comment '开始日期',
    due_date               date                                 null comment '截止日期',
    reminder_date          date                                 null comment '提醒日期',
    owner_status           varchar(50)                          null comment '负责人状态（待处理/进行中/已完成/已取消）',
    ai_status              varchar(50)                          null comment 'AI建议状态（待处理/进行中/已完成/已取消）',
    ai_note                text                                 null comment 'AI建议备注',
    eval_time              datetime                             null comment '评估时间',
    owner_id               varchar(255)                         null comment '负责人唯一性ID',
    owner_name             varchar(255)                         null comment '负责人姓名',
    opportunity_id         varchar(255)                         null comment '关联的商机唯一ID',
    opportunity_name       varchar(255)                         null comment '关联的商机名称',
    opportunity_stage      varchar(255)                         null comment '关联的商机阶段',
    account_id             varchar(255)                         null comment '关联的客户唯一ID',
    account_name           varchar(255)                         null comment '关联的客户名称',
    department             varchar(255)                         null comment '部门',
    department_id          varchar(255)                         null comment '部门唯一性ID',
    internal_participants  text                                 null comment '内部参与者（JSON格式）',
    external_participants  text                                 null comment '外部参与者即客户（JSON格式）',
    linked_account_ids     text                                 null comment 'Mandatory: 关联的客户ID列表（JSON格式）',
    linked_opportunity_ids text                                 null comment 'Mandatory: 关联的商机ID列表（JSON格式）',
    todo_type              varchar(50)                          null comment '待办类型（跟进/会议/电话/邮件/其他）',
    category               varchar(50)                          null comment '分类（销售/客户服务/内部协调等）',
    tags                   varchar(255)                         null comment '标签（逗号分隔）',
    todo_suggestion        text                                 null comment '待办建议',
    suggested_material     text                                 null comment '建议材料',
    playbook_item_ref      varchar(255)                         null comment '销售手册项目引用，格式：playbook_{stage}_{idx}，如playbook_Qualification_0，多个引用用逗号分隔',
    completion_date        datetime                             null comment '完成日期',
    completion_note        text                                 null comment '完成说明',
    user_update_time       datetime                             null comment '用户更新时间（用户更新状态、完成说明或截止日期时的时间戳）',
    data_source            varchar(50)                          null comment '数据来源（Review/Playbook/Meeting/Chatbot/CRM/等）',
    creator                varchar(255)                         null comment '创建人',
    creator_id             varchar(255)                         null comment '创建人唯一性ID',
    create_time            datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    last_modifier          varchar(255)                         null comment '最后修改人',
    update_time            datetime   default CURRENT_TIMESTAMP not null comment '最后修改时间',
    is_deleted             tinyint(1) default 0                 null comment '是否删除',
    delete_time            datetime                             null comment '删除时间',
    correlation_id         varchar(255)                         null comment '关联ID',
    created_at             datetime   default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at             datetime   default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '待办事项表';

create index idx_crm_todos_account_id
    on `autoflow-demo`.crm_todos (account_id, is_deleted);

create index idx_crm_todos_opportunity_id
    on `autoflow-demo`.crm_todos (opportunity_id, is_deleted);

create index idx_crm_todos_overdue
    on `autoflow-demo`.crm_todos (ai_status, due_date, is_deleted);

create index idx_crm_todos_owner_id
    on `autoflow-demo`.crm_todos (owner_id, is_deleted);

create table `autoflow-demo`.crm_todos_weekly_metrics
(
    id            char(32)                               not null
        primary key,
    week_start    date                                   not null,
    week_end      date                                   not null,
    assignee_id   varchar(100)                           not null,
    department_id varchar(100)                           not null,
    metric        varchar(50)                            not null,
    data_source   varchar(100) default ''                not null,
    value         int          default 0                 not null,
    created_at    datetime     default CURRENT_TIMESTAMP null,
    updated_at    datetime     default CURRENT_TIMESTAMP null,
    constraint ux_crm_todos_weekly_metrics
        unique (week_start, week_end, assignee_id, department_id, metric, data_source)
);

create index ix_week_start_week_end_dept_id_metric_data_source
    on `autoflow-demo`.crm_todos_weekly_metrics (week_start, week_end, department_id, metric, data_source);

create index ix_week_start_week_end_metric_data_source
    on `autoflow-demo`.crm_todos_weekly_metrics (week_start, week_end, metric, data_source);

create table `autoflow-demo`.crm_tracked_field_snapshots
(
    id                     int auto_increment
        primary key,
    unique_id              varchar(255)                       not null comment '唯一性ID（必填）',
    source_table           varchar(255)                       null comment '源数据表名',
    source_id              int                                null comment '源数据记录ID',
    source_unique_id       varchar(255)                       null comment '源数据记录唯一性ID',
    source_field_name      varchar(255)                       null comment '源数据字段名称',
    last_processed_content text                               null comment '最后处理内容',
    last_processed_hash    varchar(255)                       null comment '最后处理哈希值',
    last_processed_time    datetime                           null comment '最后处理时间',
    delta_content          text                               null comment '增量内容',
    flag                   varchar(255)                       null comment '标志位,标记该数据被处理的任务',
    create_time            datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    update_time            datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    created_at             datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at             datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
    comment '跟踪字段快照表';

create index idx_unique_id
    on `autoflow-demo`.crm_tracked_field_snapshots (unique_id);

create table `autoflow-demo`.crm_user
(
    unique_id     varchar(64)  null,
    user_name     varchar(255) null,
    department    varchar(255) null,
    role          varchar(255) null,
    created_time  datetime     null,
    updated_time  datetime     null,
    sf_raw        json         null,
    extra         json         null,
    manager_id    varchar(255) null comment '上级管理者ID',
    region_name   varchar(255) null comment '所属区域名称',
    role_type     varchar(50)  null comment '角色类型(管理/成员)',
    id            int auto_increment comment '主键ID'
        primary key,
    department_id varchar(255) null comment '部门ID（关联 crm_department.unique_id）',
    delete_flag   tinyint(1)   null comment '删除标识（0-正常，1-已删除）',
    client_id     varchar(64)  null comment '客户/租户ID',
    email         varchar(255) null comment '邮箱',
    phone         varchar(50)  null comment '电话号码',
    constraint uq_crm_user_unique_id
        unique (unique_id)
)
    comment 'CRM 用户表';

create table `autoflow-demo`.crm_visit_metrics_facts
(
    id              char(32)                               not null
        primary key,
    anchor          varchar(20)                            not null,
    grain           varchar(10)                            not null,
    period_start    date                                   not null,
    period_end      date                                   not null,
    subject_type    varchar(20)                            not null,
    subject_id      varchar(100)                           not null,
    department_id   varchar(100) default ''                not null,
    department_name varchar(255) default ''                not null,
    metric          varchar(50)                            not null,
    weekday_iso     int          default 0                 not null,
    value_int       int          default 0                 not null,
    created_at      datetime     default CURRENT_TIMESTAMP null,
    updated_at      datetime     default CURRENT_TIMESTAMP null,
    constraint ux_crm_visit_metrics_facts
        unique (anchor, grain, period_start, period_end, subject_type, subject_id, department_id, metric, weekday_iso)
);

create index idx_visit_company_week_anchor_metric
    on `autoflow-demo`.crm_visit_metrics_facts (anchor, grain, subject_type, subject_id, metric, weekday_iso,
                                                period_start);

create index ix_crm_visit_metrics_facts_anchor_grain_period_metric
    on `autoflow-demo`.crm_visit_metrics_facts (anchor, grain, period_start, period_end, metric);

create index ix_crm_visit_metrics_facts_dept_period_metric
    on `autoflow-demo`.crm_visit_metrics_facts (department_id, period_start, period_end, metric);

create index ix_crm_visit_metrics_facts_subject_period
    on `autoflow-demo`.crm_visit_metrics_facts (subject_type, subject_id, period_start, period_end);

create table `autoflow-demo`.crm_weekly_followup_entity_summary
(
    id                  char(32)                           not null
        primary key,
    week_start          date                               not null,
    week_end            date                               not null,
    department_id       varchar(100)                       null,
    department_name     varchar(255)                       not null,
    entity_type         varchar(50)                        not null,
    entity_id           varchar(255)                       not null,
    account_id          varchar(255)                       null,
    account_name        varchar(255)                       null,
    opportunity_id      varchar(255)                       null,
    opportunity_name    varchar(255)                       null,
    partner_id          varchar(255)                       null,
    partner_name        varchar(255)                       null,
    owner_user_id       varchar(64)                        null,
    owner_name          varchar(255)                       null,
    progress            text                               null,
    risks               text                               null,
    evidence_record_ids text                               null,
    comments            json                               null,
    created_at          datetime default CURRENT_TIMESTAMP not null,
    updated_at          datetime default CURRENT_TIMESTAMP not null,
    constraint ux_crm_weekly_followup_entity
        unique (week_start, week_end, department_name, entity_type, entity_id)
);

create index idx_weekly_followup_entity_dept
    on `autoflow-demo`.crm_weekly_followup_entity_summary (department_name);

create index idx_weekly_followup_entity_dept_id
    on `autoflow-demo`.crm_weekly_followup_entity_summary (department_id);

create index idx_weekly_followup_entity_entity
    on `autoflow-demo`.crm_weekly_followup_entity_summary (entity_type, entity_id);

create index idx_weekly_followup_entity_owner
    on `autoflow-demo`.crm_weekly_followup_entity_summary (owner_user_id);

create index idx_weekly_followup_entity_week
    on `autoflow-demo`.crm_weekly_followup_entity_summary (week_start, week_end);

create table `autoflow-demo`.crm_weekly_followup_leader_engagement
(
    id              char(32)                               not null
        primary key,
    summary_id      char(32)                               not null,
    week_start      date                                   not null,
    week_end        date                                   not null,
    department_id   varchar(100) default ''                not null,
    department_name varchar(255) default ''                not null,
    leader_user_id  varchar(64)                            not null,
    reviewed_at     datetime                               null,
    commented_at    datetime                               null,
    created_at      datetime     default CURRENT_TIMESTAMP null,
    updated_at      datetime     default CURRENT_TIMESTAMP null,
    constraint ux_weekly_followup_leader_engagement
        unique (summary_id, leader_user_id)
);

create index idx_weekly_followup_leader_engagement_leader_reviewed
    on `autoflow-demo`.crm_weekly_followup_leader_engagement (leader_user_id, reviewed_at);

create index idx_weekly_followup_leader_engagement_summary
    on `autoflow-demo`.crm_weekly_followup_leader_engagement (summary_id);

create index idx_weekly_followup_leader_engagement_week_dept
    on `autoflow-demo`.crm_weekly_followup_leader_engagement (week_start, week_end, department_name);

create index idx_weekly_followup_leader_engagement_week_dept_id
    on `autoflow-demo`.crm_weekly_followup_leader_engagement (week_start, week_end, department_id);

create table `autoflow-demo`.crm_weekly_followup_summary
(
    id              char(32)                               not null
        primary key,
    week_start      date                                   not null,
    week_end        date                                   not null,
    summary_type    varchar(50)                            not null,
    department_id   varchar(100) default ''                not null,
    department_name varchar(255) default ''                not null,
    title           varchar(255) default ''                not null,
    summary_content text                                   null,
    created_at      datetime     default CURRENT_TIMESTAMP not null,
    updated_at      datetime     default CURRENT_TIMESTAMP not null,
    constraint ux_crm_weekly_followup_summary
        unique (week_start, week_end, summary_type, department_name)
);

create index idx_weekly_followup_summary_dept_id
    on `autoflow-demo`.crm_weekly_followup_summary (department_id);

create index idx_weekly_followup_summary_type_dept
    on `autoflow-demo`.crm_weekly_followup_summary (summary_type, department_name);

create index idx_weekly_followup_summary_week
    on `autoflow-demo`.crm_weekly_followup_summary (week_start, week_end);

create table `autoflow-demo`.crm_writeback_logs
(
    id             bigint auto_increment comment '主键ID'
        primary key,
    writeback_type varchar(50)                        not null comment '回写类型：VISIT_RECORD',
    unique_id      varchar(100)                       not null comment '来源拜访记录ID（原始数据表的主键）',
    external_id    varchar(100)                       null comment 'CRM对象记录ID（回写成功后获得）',
    status         varchar(20)                        not null comment '状态：SUCCESS, FAILED',
    request_data   text                               null comment '请求数据JSON',
    response_data  text                               null comment '响应数据JSON',
    error_message  text                               null comment '错误信息',
    execution_time int                                null comment '执行时间（毫秒）',
    create_time    datetime default CURRENT_TIMESTAMP not null comment '创建时间'
)
    comment 'CRM数据回写日志表';

create index idx_create_time
    on `autoflow-demo`.crm_writeback_logs (create_time);

create index idx_external_id
    on `autoflow-demo`.crm_writeback_logs (external_id);

create index idx_status
    on `autoflow-demo`.crm_writeback_logs (status);

create index idx_type_status_time
    on `autoflow-demo`.crm_writeback_logs (writeback_type, status, create_time);

create index idx_unique_status
    on `autoflow-demo`.crm_writeback_logs (unique_id, status);

create table `autoflow-demo`.department_mirror
(
    id              int auto_increment
        primary key,
    create_time     datetime   default CURRENT_TIMESTAMP null,
    update_time     datetime   default CURRENT_TIMESTAMP null,
    unique_id       varchar(100)                         not null,
    department_name varchar(255)                         not null,
    parent_id       varchar(100)                         null,
    path            varchar(500)                         null,
    is_active       tinyint(1) default 1                 not null,
    description     varchar(500)                         null,
    constraint ix_department_mirror_unique_id
        unique (unique_id),
    constraint unique_id
        unique (unique_id)
);

create index ix_department_mirror_parent_id
    on `autoflow-demo`.department_mirror (parent_id);

create index ix_department_mirror_path
    on `autoflow-demo`.department_mirror (path);

create table `autoflow-demo`.diagnostic_playbook
(
    id                           int auto_increment
        primary key,
    plan_id                      varchar(64)                        not null comment '执行计划ID',
    report_id                    varchar(64)                        null comment '报告ID',
    execution_id                 varchar(255)                       not null comment '执行ID, naming convention: plan_<plan_id>_<version>',
    handbook_id                  varchar(64)                        not null comment '手册ID',
    name                         varchar(255)                       not null comment '手册名称',
    version                      varchar(255)                       not null comment '手册版本',
    status                       varchar(255)                       not null comment '手册状态: active(生效中), draft(草稿), archived(已归档), deprecated(已废弃)',
    type                         varchar(255)                       not null comment '手册类型',
    sequence                     int                                not null comment '销售阶段顺序，用于确定阶段的先后顺序，从1开始',
    sales_stage                  varchar(255)                       null comment '销售阶段',
    sales_key_activities         text                               null comment '销售关键动作',
    sales_deliverables           text                               null comment '交付成果',
    sales_exit_criteria          text                               null comment '阶段转化标准',
    sales_key_info               text                               null comment '关键获取信息(CRM必填项)',
    sales_outcomes               text                               null comment '销售阶段任务',
    customer_behavior_purchase   text                               null comment '客户采购行为',
    customer_behavior_supporting text                               null comment '客户支持行为',
    sales_alerts                 text                               null comment '预警',
    fcst_eval_checklist          text                               null comment 'FCST评估清单',
    fcst_eval_guidance           text                               null comment 'FCST评估指引',
    created_at                   datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at                   datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
    stage_category               varchar(64)                        null comment '阶段语义分类: open/closed_won/closed_lost/cancelled',
    stage_attributes             json                               null comment '阶段行为属性覆盖(JSON)'
)
    comment '诊断Playbook表';

create index idx_diagnostic_playbook_stage_category
    on `autoflow-demo`.diagnostic_playbook (handbook_id, stage_category);

create index idx_diagnostic_playbook_stage_lookup
    on `autoflow-demo`.diagnostic_playbook (handbook_id, status, sales_stage);

create table `autoflow-demo`.embedding_models
(
    created_at       datetime default CURRENT_TIMESTAMP null,
    updated_at       datetime default CURRENT_TIMESTAMP null,
    id               int auto_increment
        primary key,
    name             varchar(64)                        not null,
    provider         varchar(32)                        not null,
    model            varchar(256)                       not null,
    config           json                               null,
    credentials      blob                               null,
    is_default       tinyint(1)                         not null,
    vector_dimension int                                not null
);

create table `autoflow-demo`.entities
(
    name          varchar(512)                                          not null,
    description   text                                                  null,
    meta          json                                                  null,
    entity_type   enum ('original', 'synopsis')                         not null,
    synopsis_info json                                                  null,
    id            int auto_increment
        primary key,
    description_vec vector(1536) null comment 'hnsw(distance=cosine)',
    meta_vec vector(1536) null comment 'hnsw(distance=cosine)',
    graph_type    enum ('general', 'playbook', 'crm') default 'general' not null
);

create index idx_entity_graph_type
    on `autoflow-demo`.entities (graph_type);

create index idx_entity_type
    on `autoflow-demo`.entities (entity_type);

create table `autoflow-demo`.entities_1
(
    id            int auto_increment
        primary key,
    name          varchar(512)                                          not null,
    description   text                                                  null,
    meta          json                                                  null,
    entity_type   enum ('original', 'synopsis')                         not null,
    synopsis_info json                                                  null,
    description_vec vector(1024) not null,
    meta_vec vector(1024) not null,
    graph_type    enum ('general', 'playbook', 'crm') default 'general' not null
);

create index idx_entity_name
    on `autoflow-demo`.entities_1 (name);

create index idx_entity_type
    on `autoflow-demo`.entities_1 (entity_type);

create index vec_idx_description_vec
    on `autoflow-demo`.entities_1 (description_vec);

create index vec_idx_meta_vec
    on `autoflow-demo`.entities_1 (meta_vec);

create table `autoflow-demo`.entities_2
(
    id            int auto_increment
        primary key,
    name          varchar(512)                                          not null,
    description   text                                                  null,
    meta          json                                                  null,
    entity_type   enum ('original', 'synopsis')                         not null,
    synopsis_info json                                                  null,
    description_vec vector(1024) not null,
    meta_vec vector(1024) not null,
    graph_type    enum ('general', 'playbook', 'crm') default 'general' not null
);

create index idx_entity_name
    on `autoflow-demo`.entities_2 (name);

create index idx_entity_type
    on `autoflow-demo`.entities_2 (entity_type);

create index vec_idx_description_vec
    on `autoflow-demo`.entities_2 (description_vec);

create index vec_idx_meta_vec
    on `autoflow-demo`.entities_2 (meta_vec);

create table `autoflow-demo`.feishu_billing_usage_report
(
    id                  char(32)                           not null
        primary key,
    trace_id            varchar(220)                       not null,
    ai_module_key       varchar(128)                       not null,
    operator            varchar(128)                       not null,
    review_detail       text                               null,
    status              varchar(20)                        not null,
    last_api_code       int                                null,
    last_message        text                               null,
    attempts            int                                not null,
    last_exception_type varchar(200)                       null,
    created_at          datetime default CURRENT_TIMESTAMP null,
    updated_at          datetime default CURRENT_TIMESTAMP null,
    constraint ux_feishu_billing_usage_report_trace
        unique (trace_id)
);

create index idx_feishu_billing_usage_module_created
    on `autoflow-demo`.feishu_billing_usage_report (ai_module_key, created_at);

create index idx_feishu_billing_usage_status_created
    on `autoflow-demo`.feishu_billing_usage_report (status, created_at);

create table `autoflow-demo`.llms
(
    created_at  datetime default CURRENT_TIMESTAMP null,
    updated_at  datetime default CURRENT_TIMESTAMP null,
    id          int auto_increment
        primary key,
    name        varchar(64)                        not null,
    provider    varchar(32)                        not null,
    model       varchar(256)                       not null,
    config      json                               null,
    credentials blob                               null,
    is_default  tinyint(1)                         not null
);

create table `autoflow-demo`.local_contacts
(
    id                    int auto_increment comment '主键ID（自增）'
        primary key,
    unique_id             varchar(255)                       not null comment '唯一性ID（必填）',
    name                  varchar(255)                       not null comment '联系人姓名（必填）',
    customer_id           varchar(255)                       not null comment '客户ID（关联crm_accounts.unique_id，必填）',
    customer_name         varchar(255)                       not null comment '客户名称（必填）',
    position              varchar(255)                       not null comment '联系人职位（必填）',
    gender                varchar(10)                        null comment '性别',
    mobile                varchar(255)                       null comment '手机',
    phone                 varchar(255)                       null comment '电话',
    email                 varchar(255)                       null comment '邮件',
    wechat                varchar(255)                       null comment '微信',
    address               varchar(512)                       null comment '联系地址',
    key_decision_maker    tinyint(1)                         null comment '是否为关键决策人',
    source                varchar(255)                       null comment '来源',
    remarks               text                               null comment '备注',
    delete_flag           tinyint(1)                         null comment '删除标识',
    created_at            datetime default CURRENT_TIMESTAMP null comment '创建时间',
    updated_at            datetime default CURRENT_TIMESTAMP null comment '更新时间',
    created_by            char(32)                           null comment '创建人ID',
    updated_by            char(32)                           null comment '最后修改人ID',
    crm_unique_id         varchar(255)                       null comment 'CRM系统唯一ID（回写后填充）',
    synced_to_crm         tinyint(1)                         null comment '是否已同步到CRM',
    synced_at             datetime                           null comment '同步到CRM的时间',
    department            varchar(255)                       null comment '部门',
    direct_superior       varchar(255)                       null comment '直属上级',
    status                varchar(255)                       null comment '状态',
    business_relationship varchar(255)                       null comment '商务关系',
    constraint idx_local_contacts_unique_id
        unique (unique_id)
);

create index idx_local_contacts_customer_id
    on `autoflow-demo`.local_contacts (customer_id);

create index idx_local_contacts_customer_name
    on `autoflow-demo`.local_contacts (customer_name);

create index idx_local_contacts_delete_flag
    on `autoflow-demo`.local_contacts (delete_flag);

create index idx_local_contacts_name
    on `autoflow-demo`.local_contacts (name);

create table `autoflow-demo`.oauth_alembic_version
(
    version_num varchar(32) not null
        primary key
);

create table `autoflow-demo`.relationships
(
    description      text                                                  null,
    meta             json                                                  null,
    weight           int                                                   not null,
    source_entity_id int                                                   not null,
    target_entity_id int                                                   not null,
    last_modified_at datetime                                              null,
    id               int auto_increment
        primary key,
    description_vec vector(1536) null comment 'hnsw(distance=cosine)',
    chunk_id         char(32)                                              null,
    document_id      int                                                   null,
    graph_type       enum ('general', 'playbook', 'crm') default 'general' not null,
    constraint fk_1
        foreign key (source_entity_id) references `autoflow-demo`.entities (id),
    constraint fk_2
        foreign key (target_entity_id) references `autoflow-demo`.entities (id)
);

create index idx_relationship_graph_type
    on `autoflow-demo`.relationships (graph_type);

create table `autoflow-demo`.relationships_1
(
    id               int auto_increment
        primary key,
    description      text                                                  null,
    meta             json                                                  null,
    weight           int                                                   not null,
    source_entity_id int                                                   not null,
    target_entity_id int                                                   not null,
    last_modified_at datetime                                              null,
    document_id      int                                                   null,
    chunk_id         char(32)                                              null,
    description_vec vector(1024) not null,
    graph_type       enum ('general', 'playbook', 'crm') default 'general' not null,
    constraint fk_1
        foreign key (source_entity_id) references `autoflow-demo`.entities_1 (id),
    constraint fk_2
        foreign key (target_entity_id) references `autoflow-demo`.entities_1 (id)
);

create index idx_relationship_chunk_id
    on `autoflow-demo`.relationships_1 (chunk_id);

create index idx_relationship_document_id
    on `autoflow-demo`.relationships_1 (document_id);

create index idx_relationship_graph_chunk
    on `autoflow-demo`.relationships_1 (graph_type, chunk_id);

create index idx_relationship_graph_doc
    on `autoflow-demo`.relationships_1 (graph_type, document_id);

create index idx_relationship_graph_type
    on `autoflow-demo`.relationships_1 (graph_type);

create index vec_idx_description_vec
    on `autoflow-demo`.relationships_1 (description_vec);

create table `autoflow-demo`.relationships_2
(
    id               int auto_increment
        primary key,
    description      text                                                  null,
    meta             json                                                  null,
    weight           int                                                   not null,
    source_entity_id int                                                   not null,
    target_entity_id int                                                   not null,
    last_modified_at datetime                                              null,
    document_id      int                                                   null,
    chunk_id         char(32)                                              null,
    description_vec vector(1024) not null,
    graph_type       enum ('general', 'playbook', 'crm') default 'general' not null,
    constraint fk_1
        foreign key (source_entity_id) references `autoflow-demo`.entities_2 (id),
    constraint fk_2
        foreign key (target_entity_id) references `autoflow-demo`.entities_2 (id)
);

create index idx_relationship_chunk_id
    on `autoflow-demo`.relationships_2 (chunk_id);

create index idx_relationship_document_id
    on `autoflow-demo`.relationships_2 (document_id);

create index idx_relationship_graph_chunk
    on `autoflow-demo`.relationships_2 (graph_type, chunk_id);

create index idx_relationship_graph_doc
    on `autoflow-demo`.relationships_2 (graph_type, document_id);

create index idx_relationship_graph_type
    on `autoflow-demo`.relationships_2 (graph_type);

create index vec_idx_description_vec
    on `autoflow-demo`.relationships_2 (description_vec);

create table `autoflow-demo`.reranker_models
(
    created_at  datetime default CURRENT_TIMESTAMP null,
    updated_at  datetime default CURRENT_TIMESTAMP null,
    name        varchar(64)                        not null,
    provider    varchar(32)                        not null,
    model       varchar(256)                       not null,
    top_n       int                                not null,
    config      json                               null,
    is_default  tinyint(1)                         not null,
    id          int auto_increment
        primary key,
    credentials blob                               null
);

create table `autoflow-demo`.chat_engines
(
    created_at     datetime default CURRENT_TIMESTAMP null,
    updated_at     datetime default CURRENT_TIMESTAMP null,
    id             int auto_increment
        primary key,
    name           varchar(256)                       not null,
    engine_options json                               null,
    is_default     tinyint(1)                         not null,
    deleted_at     datetime                           null,
    llm_id         int                                null,
    fast_llm_id    int                                null,
    reranker_id    int                                null,
    is_public      tinyint(1)                         not null,
    constraint fk_1
        foreign key (fast_llm_id) references `autoflow-demo`.llms (id),
    constraint fk_2
        foreign key (llm_id) references `autoflow-demo`.llms (id),
    constraint fk_3
        foreign key (reranker_id) references `autoflow-demo`.reranker_models (id)
);

create table `autoflow-demo`.semantic_cache
(
    id         int auto_increment
        primary key,
    query      text                               null,
    query_vec vector(1536) null comment 'hnsw(distance=cosine)',
    value      text                               null,
    value_vec vector(1536) null comment 'hnsw(distance=cosine)',
    meta       json                               null,
    created_at datetime default CURRENT_TIMESTAMP null,
    updated_at datetime default CURRENT_TIMESTAMP null
);

create table `autoflow-demo`.site_settings
(
    created_at datetime(6) default CURRENT_TIMESTAMP(6) null,
    updated_at datetime(6) default CURRENT_TIMESTAMP(6) null on update CURRENT_TIMESTAMP(6),
    id         int auto_increment
        primary key,
    name       varchar(256)                             not null,
    data_type  varchar(256)                             not null,
    value      json                                     null,
    constraint name
        unique (name)
);

create table `autoflow-demo`.staff_action_logs
(
    id          int auto_increment
        primary key,
    action      varchar(255)                       not null,
    action_time datetime default CURRENT_TIMESTAMP null,
    target_type varchar(255)                       not null,
    target_id   int                                not null,
    `before`    json                               null,
    after       json                               null
);

create table `autoflow-demo`.user
(
    id               bigint auto_increment comment 'db主键id'
        primary key,
    uid              varchar(255)                         null comment '为用户生成的uid',
    user_id          varchar(255)                         null comment '用户自定义/企业飞书内id',
    role             varchar(255)                         null comment '用户角色',
    name             varchar(255)                         null comment '用户姓名',
    en_name          varchar(255)                         null comment '用户英文名',
    avatar_url       varchar(255)                         null comment '用户头像URL',
    email            varchar(255)                         null comment '用户邮箱',
    mobile           varchar(20)                          null comment '用户手机号',
    password         varchar(255)                         null comment '用户密码',
    email_verified   datetime                             null comment '邮箱验证时间',
    corporation_id   varchar(255)                         null comment '企业ID',
    open_id          varchar(255)                         null comment '开放ID',
    union_id         varchar(255)                         null comment '统一ID',
    enterprise_email varchar(255)                         null comment '企业邮箱',
    tenant_key       varchar(255)                         null comment '租户密钥',
    employee_no      varchar(255)                         null comment '员工编号',
    creator          varchar(255)                         null comment '创建者',
    create_time      datetime   default CURRENT_TIMESTAMP null comment '创建时间',
    updater          varchar(255)                         null comment '更新者',
    update_time      datetime   default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP comment '最后更新时间',
    version          int        default 1                 null comment '数据版本',
    delete_flag      tinyint(1) default 0                 null comment '删除标识, 1已删除',
    channel          varchar(255)                         null comment '登录渠道',
    ask_user_id      varchar(255)                         null comment 'ask服务的email',
    ask_id           varchar(255)                         null comment 'ask服务的id',
    fxiaoke_id       varchar(255)                         null comment 'fxiaoke用户id',
    extra_info       json                                 null comment '扩展信息'
);

create index idx_delete_flag
    on `autoflow-demo`.user (delete_flag);

create table `autoflow-demo`.user_department_relation
(
    id            int auto_increment
        primary key,
    create_time   datetime   default CURRENT_TIMESTAMP null,
    update_time   datetime   default CURRENT_TIMESTAMP null,
    user_id       char(36)                             null,
    crm_user_id   varchar(100)                         not null,
    department_id varchar(100)                         not null,
    is_primary    tinyint(1) default 0                 not null,
    is_leader     tinyint(1) default 0                 not null,
    title         varchar(100)                         null,
    user_name     varchar(100)                         null,
    is_active     tinyint(1) default 1                 not null
);

create index ix_user_department_relation_crm_user_id
    on `autoflow-demo`.user_department_relation (crm_user_id);

create index ix_user_department_relation_department_id
    on `autoflow-demo`.user_department_relation (department_id);

create index ix_user_department_relation_is_active
    on `autoflow-demo`.user_department_relation (is_active);

create index ix_user_department_relation_is_leader
    on `autoflow-demo`.user_department_relation (is_leader);

create index ix_user_department_relation_is_primary
    on `autoflow-demo`.user_department_relation (is_primary);

create index ix_user_department_relation_user_id
    on `autoflow-demo`.user_department_relation (user_id);

create table `autoflow-demo`.user_reporting_relation
(
    id           int auto_increment
        primary key,
    from_user_id varchar(100)                         not null comment '上级用户ID（CRM用户ID），表示 from_user_id 是 to_user_id 的上级',
    to_user_id   varchar(100)                         not null comment '下级用户ID（CRM用户ID），表示 to_user_id 是 from_user_id 的下级',
    level        int        default 1                 not null comment '层级（1=直接上级/下级，2=间接上级/下级，以此类推）',
    is_active    tinyint(1) default 1                 not null comment '关系是否有效',
    create_time  datetime   default CURRENT_TIMESTAMP null,
    update_time  datetime   default CURRENT_TIMESTAMP null,
    constraint uq_user_reporting_relation
        unique (from_user_id, to_user_id, level)
);

create index ix_user_reporting_relation_from_user_active
    on `autoflow-demo`.user_reporting_relation (from_user_id, is_active);

create index ix_user_reporting_relation_from_user_id
    on `autoflow-demo`.user_reporting_relation (from_user_id);

create index ix_user_reporting_relation_from_user_level
    on `autoflow-demo`.user_reporting_relation (from_user_id, level, is_active);

create index ix_user_reporting_relation_is_active
    on `autoflow-demo`.user_reporting_relation (is_active);

create index ix_user_reporting_relation_level
    on `autoflow-demo`.user_reporting_relation (level);

create index ix_user_reporting_relation_to_user_active
    on `autoflow-demo`.user_reporting_relation (to_user_id, is_active);

create index ix_user_reporting_relation_to_user_id
    on `autoflow-demo`.user_reporting_relation (to_user_id);

create index ix_user_reporting_relation_to_user_level
    on `autoflow-demo`.user_reporting_relation (to_user_id, level, is_active);

create table `autoflow-demo`.users
(
    id              char(32)                           not null
        primary key,
    email           varchar(255)                       not null,
    hashed_password varchar(255)                       not null,
    is_active       tinyint(1)                         not null,
    is_superuser    tinyint(1)                         not null,
    is_verified     tinyint(1)                         not null,
    created_at      datetime default CURRENT_TIMESTAMP null,
    updated_at      datetime default CURRENT_TIMESTAMP null,
    constraint ix_users_email
        unique (email)
);

create table `autoflow-demo`.api_keys
(
    created_at      datetime default CURRENT_TIMESTAMP null,
    updated_at      datetime default CURRENT_TIMESTAMP null,
    id              int auto_increment
        primary key,
    description     varchar(100)                       not null,
    hashed_secret   varchar(255)                       not null,
    api_key_display varchar(100)                       not null,
    is_active       tinyint(1)                         not null,
    user_id         char(32)                           not null,
    constraint hashed_secret
        unique (hashed_secret),
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.chats
(
    created_at     datetime                                                 default CURRENT_TIMESTAMP null,
    updated_at     datetime                                                 default CURRENT_TIMESTAMP null,
    id             char(32)                                                                           not null
        primary key,
    title          varchar(256)                                                                       not null,
    engine_id      int                                                                                null,
    engine_options json                                                                               null,
    deleted_at     datetime                                                                           null,
    user_id        char(32)                                                                           null,
    browser_id     varchar(50)                                                                        null,
    origin         varchar(256)                                                                       null,
    visibility     int                                                                                not null,
    chat_type      enum ('default', 'client_visit_guide', 'review_session') default 'default'         not null,
    constraint fk_1
        foreign key (engine_id) references `autoflow-demo`.chat_engines (id),
    constraint fk_2
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.chat_messages
(
    created_at                   datetime   default CURRENT_TIMESTAMP null,
    updated_at                   datetime   default CURRENT_TIMESTAMP null,
    id                           int auto_increment
        primary key,
    ordinal                      int                                  not null,
    role                         varchar(64)                          not null,
    content                      text                                 null,
    error                        text                                 null,
    sources                      json                                 null,
    trace_url                    varchar(512)                         null,
    finished_at                  datetime                             null,
    chat_id                      char(32)                             not null,
    user_id                      char(32)                             null,
    graph_data                   json                                 null,
    post_verification_result_url varchar(512)                         null,
    meta                         json                                 null,
    is_best_answer               tinyint(1) default 0                 not null,
    constraint fk_1
        foreign key (chat_id) references `autoflow-demo`.chats (id),
    constraint fk_2
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create index ix_chat_message_is_best_answer
    on `autoflow-demo`.chat_messages (is_best_answer);

create index ix_chats_id
    on `autoflow-demo`.chats (id);

create table `autoflow-demo`.crm_sales_visit_records
(
    id                                  int auto_increment
        primary key,
    account_name                        varchar(255)   null,
    account_id                          varchar(255)   null,
    opportunity_name                    varchar(255)   null,
    opportunity_id                      varchar(255)   null,
    partner_name                        varchar(255)   null,
    customer_lead_source                varchar(255)   null,
    visit_object_category               varchar(255)   null,
    contact_position                    varchar(255)   null,
    contact_name                        varchar(255)   null,
    contact_id                          varchar(255)   null comment '联系人ID（关联local_contacts或crm_contacts的unique_id）',
    recorder                            varchar(255)   null,
    collaborative_participants          text           null,
    visit_communication_date            date           null,
    counterpart_location                varchar(255)   null,
    visit_communication_method          varchar(255)   null,
    communication_duration              varchar(255)   null,
    expectation_achieved                varchar(255)   null,
    followup_record                     text           null,
    followup_quality_level_zh           varchar(100)   null,
    followup_quality_reason_zh          text           null,
    next_steps                          text           null,
    next_steps_quality_level_zh         varchar(100)   null,
    next_steps_quality_reason_zh        text           null,
    attachment                          longtext       null,
    parent_record                       varchar(255)   null,
    remarks                             text           null,
    last_modified_time                  datetime       null,
    record_id                           varchar(100)   null,
    is_first_visit                      tinyint(1)     null,
    recorder_id                         char(32)       null,
    visit_type                          varchar(20)    null,
    visit_url                           text           null,
    is_call_high                        tinyint(1)     null,
    subject                             varchar(50)    null,
    followup_content                    text           null,
    followup_record_zh                  text           null,
    next_steps_zh                       text           null,
    followup_record_en                  text           null,
    followup_quality_level_en           varchar(100)   null,
    followup_quality_reason_en          text           null,
    next_steps_en                       text           null,
    next_steps_quality_level_en         varchar(100)   null,
    next_steps_quality_reason_en        text           null,
    partner_id                          varchar(255)   null,
    visit_start_time                    varchar(19)    null,
    visit_end_time                      varchar(19)    null,
    record_type                         varchar(50)    null,
    visit_purpose                       varchar(255)   null,
    latitude                            decimal(10, 7) null comment '纬度，范围 -90 到 90',
    longitude                           decimal(11, 7) null comment '经度，范围 -180 到 180',
    comments                            json           null comment '评论列表（人工可编辑，JSON数组）',
    contacts                            json           null comment '联系人列表（支持多个联系人，JSON数组）',
    recorder_department_id              varchar(100)   null comment '记录人部门ID（快照）',
    recorder_department_name            varchar(255)   null comment '记录人部门名称（快照）',
    assessment_flag                     varchar(10)    null,
    assessment_description              text           null,
    card_push_status                    varchar(32)    null,
    external_collaboration_partner_name varchar(255)   null,
    external_collaboration_partner_id   varchar(255)   null,
    constraint fk_recorder_id
        foreign key (recorder_id) references `autoflow-demo`.users (id)
);

create index idx_account_name
    on `autoflow-demo`.crm_sales_visit_records (account_name);

create index idx_card_push_status
    on `autoflow-demo`.crm_sales_visit_records (card_push_status);

create index idx_contact_id
    on `autoflow-demo`.crm_sales_visit_records (contact_id);

create index idx_is_first_visit
    on `autoflow-demo`.crm_sales_visit_records (is_first_visit);

create index idx_recorder
    on `autoflow-demo`.crm_sales_visit_records (recorder);

create index idx_subject
    on `autoflow-demo`.crm_sales_visit_records (subject);

create index idx_visit_date
    on `autoflow-demo`.crm_sales_visit_records (visit_communication_date);

create index idx_visit_record_account_id
    on `autoflow-demo`.crm_sales_visit_records (account_id);

create index idx_visit_record_last_modified_time
    on `autoflow-demo`.crm_sales_visit_records (last_modified_time);

create index idx_visit_record_partner_name
    on `autoflow-demo`.crm_sales_visit_records (partner_name);

create index idx_visit_record_recorder_date
    on `autoflow-demo`.crm_sales_visit_records (recorder_id, visit_communication_date);

create index idx_visit_record_recorder_department_id
    on `autoflow-demo`.crm_sales_visit_records (recorder_department_id);

create index idx_visit_record_recorder_id
    on `autoflow-demo`.crm_sales_visit_records (recorder_id);

create index idx_visit_type
    on `autoflow-demo`.crm_sales_visit_records (visit_type);

create table `autoflow-demo`.data_sources
(
    created_at       datetime default CURRENT_TIMESTAMP null,
    updated_at       datetime default CURRENT_TIMESTAMP null,
    id               int auto_increment
        primary key,
    name             varchar(256)                       not null,
    description      varchar(512)                       not null,
    data_source_type varchar(256)                       not null,
    config           json                               null,
    build_kg_index   tinyint(1)                         not null,
    user_id          char(32)                           null,
    llm_id           int                                null,
    deleted_at       datetime                           null,
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id),
    constraint fk_2
        foreign key (llm_id) references `autoflow-demo`.llms (id)
);

create table `autoflow-demo`.document_contents
(
    id                  int auto_increment comment '自增主键ID'
        primary key,
    user_id             char(32)                           not null comment '用户ID',
    visit_record_id     varchar(128)                       null comment '关联的拜访记录ID',
    document_type       varchar(50)                        not null comment '文档类型: feishu_doc, feishu_minute, file',
    source_url          text                               not null comment '原文档URL',
    raw_content         mediumtext                         not null comment '原始文档内容',
    title               varchar(500)                       null comment '文档标题',
    file_size           int                                null comment '文件大小(字节)',
    created_at          datetime default CURRENT_TIMESTAMP not null comment '创建时间',
    updated_at          datetime default CURRENT_TIMESTAMP not null comment '更新时间',
    meeting_summary     mediumtext                         null,
    summary_status      varchar(20)                        null,
    qa_pairs            json                               null comment '从文档内容中抽取的问答对列表',
    qa_extract_status   varchar(20)                        null comment '问答对抽取状态: success, failed',
    risk_info           mediumtext                         null comment '从文档内容中提取的风险信息',
    risk_extract_status varchar(20)                        null comment '风险信息提取状态: success, failed',
    constraint fk_document_contents_user_id
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.customer_documents
(
    id                  int auto_increment comment '自增主键ID'
        primary key,
    file_category       varchar(255) not null comment '文件类别，如ABP、CallHigh等',
    account_name        varchar(255) not null comment '客户名称',
    account_id          varchar(255) not null comment '客户ID',
    document_url        text         not null comment '文档链接',
    document_type       varchar(255) null comment '文档类型',
    document_title      varchar(500) null comment '文档标题',
    uploader_id         char(32)     not null comment '上传者ID',
    uploader_name       varchar(255) not null comment '上传者姓名',
    created_at          datetime     not null comment '创建时间',
    updated_at          datetime     not null comment '更新时间',
    document_content_id int          null comment '关联的文档内容ID',
    constraint fk_customer_documents_document_content_id
        foreign key (document_content_id) references `autoflow-demo`.document_contents (id),
    constraint fk_2
        foreign key (document_content_id) references `autoflow-demo`.document_contents (id),
    constraint fk_customer_documents_uploader_id
        foreign key (uploader_id) references `autoflow-demo`.users (id),
    constraint fk_1
        foreign key (uploader_id) references `autoflow-demo`.users (id)
);

create index idx_created_at
    on `autoflow-demo`.document_contents (created_at);

create index idx_document_type
    on `autoflow-demo`.document_contents (document_type);

create index idx_qa_extract_status
    on `autoflow-demo`.document_contents (qa_extract_status);

create index idx_risk_extract_status
    on `autoflow-demo`.document_contents (risk_extract_status);

create index idx_summary_status
    on `autoflow-demo`.document_contents (summary_status);

create index idx_user_id
    on `autoflow-demo`.document_contents (user_id);

create index idx_user_type
    on `autoflow-demo`.document_contents (user_id, document_type);

create index idx_visit_record_id
    on `autoflow-demo`.document_contents (visit_record_id);

create table `autoflow-demo`.evaluation_datasets
(
    created_at datetime default CURRENT_TIMESTAMP null,
    updated_at datetime default CURRENT_TIMESTAMP null,
    id         int auto_increment
        primary key,
    name       varchar(255)                       not null,
    user_id    char(32)                           null,
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.evaluation_dataset_items
(
    created_at            datetime default CURRENT_TIMESTAMP null,
    updated_at            datetime default CURRENT_TIMESTAMP null,
    id                    int auto_increment
        primary key,
    query                 text                               null,
    reference             text                               null,
    retrieved_contexts    json                               null,
    extra                 json                               null,
    evaluation_dataset_id int                                null,
    constraint fk_1
        foreign key (evaluation_dataset_id) references `autoflow-demo`.evaluation_datasets (id)
);

create table `autoflow-demo`.evaluation_tasks
(
    created_at datetime default CURRENT_TIMESTAMP null,
    updated_at datetime default CURRENT_TIMESTAMP null,
    id         int auto_increment
        primary key,
    name       varchar(255)                       not null,
    user_id    char(32)                           null,
    dataset_id int                                null,
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.evaluation_task_items
(
    created_at          datetime default CURRENT_TIMESTAMP null,
    updated_at          datetime default CURRENT_TIMESTAMP null,
    id                  int auto_increment
        primary key,
    chat_engine         varchar(255)                       not null,
    status              varchar(32)                        not null,
    query               text                               null,
    reference           text                               null,
    response            text                               null,
    retrieved_contexts  json                               null,
    extra               json                               null,
    error_msg           text                               null,
    factual_correctness float                              null,
    semantic_similarity float                              null,
    evaluation_task_id  int                                null,
    constraint fk_1
        foreign key (evaluation_task_id) references `autoflow-demo`.evaluation_tasks (id)
);

create table `autoflow-demo`.feedbacks
(
    created_at      datetime default CURRENT_TIMESTAMP null,
    updated_at      datetime default CURRENT_TIMESTAMP null,
    feedback_type   enum ('LIKE', 'DISLIKE')           not null,
    comment         varchar(500)                       not null,
    id              int auto_increment
        primary key,
    chat_id         char(32)                           not null,
    chat_message_id int                                not null,
    user_id         char(32)                           null,
    origin          varchar(256)                       null,
    constraint fk_1
        foreign key (chat_id) references `autoflow-demo`.chats (id),
    constraint fk_2
        foreign key (chat_message_id) references `autoflow-demo`.chat_messages (id),
    constraint fk_3
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.knowledge_bases
(
    id                 int auto_increment
        primary key,
    name               varchar(255)                       not null,
    description        mediumtext                         null,
    index_methods      json                               null,
    llm_id             int                                null,
    embedding_model_id int                                null,
    documents_total    int                                not null,
    data_sources_total int                                not null,
    created_by         char(32)                           null,
    created_at         datetime default CURRENT_TIMESTAMP null,
    updated_by         char(32)                           null,
    updated_at         datetime default CURRENT_TIMESTAMP null,
    deleted_by         char(32)                           null,
    deleted_at         datetime                           null,
    chunking_config    json                               null,
    constraint fk_1
        foreign key (created_by) references `autoflow-demo`.users (id),
    constraint fk_2
        foreign key (deleted_by) references `autoflow-demo`.users (id),
    constraint fk_3
        foreign key (embedding_model_id) references `autoflow-demo`.embedding_models (id),
    constraint fk_4
        foreign key (llm_id) references `autoflow-demo`.llms (id),
    constraint fk_5
        foreign key (updated_by) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.knowledge_base_datasources
(
    knowledge_base_id int not null,
    data_source_id    int not null,
    primary key (knowledge_base_id, data_source_id),
    constraint fk_1
        foreign key (data_source_id) references `autoflow-demo`.data_sources (id),
    constraint fk_2
        foreign key (knowledge_base_id) references `autoflow-demo`.knowledge_bases (id)
);

create table `autoflow-demo`.oauth_accounts
(
    uid                 char(36)                           not null comment '主键ID'
        primary key,
    user_id             char(32)                           not null comment '用户ID，外键关联users.id',
    provider            varchar(50)                        not null comment 'OAuth提供商：feishu, dingtalk, wecom, github, google等',
    open_id             varchar(255)                       null comment '开放ID',
    union_id            varchar(255)                       null comment '统一ID',
    user_id_in_platform varchar(255)                       null comment '钉钉/飞书内部用户ID',
    password            varchar(100)                       null comment '用户密码，适用于系统内账号密码注册',
    tenant_key          varchar(255)                       null comment '租户密钥',
    corporation_id      bigint                             null comment '企业ID',
    create_time         datetime default CURRENT_TIMESTAMP null comment '创建时间',
    update_time         datetime default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP comment '更新时间',
    constraint uq_oauth_user
        unique (user_id, provider, open_id, user_id_in_platform),
    constraint fk_oauth_user_id
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create index idx_oauth_open_id
    on `autoflow-demo`.oauth_accounts (open_id);

create index idx_oauth_provider
    on `autoflow-demo`.oauth_accounts (provider);

create index idx_oauth_union_id
    on `autoflow-demo`.oauth_accounts (union_id);

create index idx_oauth_user_provider
    on `autoflow-demo`.oauth_accounts (user_id, provider);

create index ix_oauth_user_id_in_platform
    on `autoflow-demo`.oauth_accounts (user_id_in_platform);

create table `autoflow-demo`.recommend_questions
(
    created_at      datetime default CURRENT_TIMESTAMP null,
    updated_at      datetime default CURRENT_TIMESTAMP null,
    id              int auto_increment
        primary key,
    questions       json                               null,
    chat_message_id int                                not null,
    constraint fk_1
        foreign key (chat_message_id) references `autoflow-demo`.chat_messages (id)
);

create index ix_recommend_questions_chat_message_id
    on `autoflow-demo`.recommend_questions (chat_message_id);

create table `autoflow-demo`.uploads
(
    created_at datetime default CURRENT_TIMESTAMP null,
    updated_at datetime default CURRENT_TIMESTAMP null,
    id         int auto_increment
        primary key,
    name       varchar(255)                       not null,
    size       int                                not null,
    path       varchar(255)                       not null,
    mime_type  varchar(128)                       not null,
    user_id    char(32)                           null,
    meta       json                               null,
    category   varchar(100) as (null),
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.documents
(
    created_at        datetime default CURRENT_TIMESTAMP                                null,
    updated_at        datetime default CURRENT_TIMESTAMP                                null,
    id                int auto_increment
        primary key,
    hash              varchar(32)                                                       not null,
    name              varchar(256)                                                      not null,
    content           mediumtext                                                        null,
    mime_type         varchar(128)                                                      not null,
    source_uri        varchar(512)                                                      not null,
    meta              json                                                              null,
    last_modified_at  datetime                                                          null,
    index_status      enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    index_result      text                                                              null,
    data_source_id    int                                                               null,
    knowledge_base_id int                                                               null,
    file_id           int                                                               null,
    constraint fk_d_on_data_source_id
        foreign key (data_source_id) references `autoflow-demo`.data_sources (id),
    constraint fk_d_on_knowledge_base_id
        foreign key (knowledge_base_id) references `autoflow-demo`.knowledge_bases (id),
    constraint fk_documents_on_file_id
        foreign key (file_id) references `autoflow-demo`.uploads (id)
);

create table `autoflow-demo`.chunks
(
    created_at            datetime default CURRENT_TIMESTAMP                                null,
    updated_at            datetime default CURRENT_TIMESTAMP                                null,
    id                    char(32)                                                          not null
        primary key,
    hash                  varchar(64)                                                       not null,
    text                  text                                                              null,
    meta                  json                                                              null,
    embedding vector(1536) null comment 'hnsw(distance=cosine)',
    document_id           int                                                               null,
    relations             json                                                              null,
    source_uri            varchar(512)                                                      null,
    index_status          enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    index_result          text                                                              null,
    playbook_index_status enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    playbook_index_result text                                                              null,
    crm_index_status      enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    crm_index_result      text                                                              null,
    constraint fk_1
        foreign key (document_id) references `autoflow-demo`.documents (id)
);

create index ix_chunks_id
    on `autoflow-demo`.chunks (id);

create table `autoflow-demo`.chunks_1
(
    created_at            datetime default CURRENT_TIMESTAMP                                null,
    updated_at            datetime default CURRENT_TIMESTAMP                                null,
    id                    char(32)                                                          not null
        primary key,
    hash                  varchar(64)                                                       not null,
    text                  text                                                              null,
    meta                  json                                                              null,
    embedding vector(1024) not null,
    document_id           int                                                               null,
    relations             json                                                              null,
    source_uri            varchar(512)                                                      null,
    index_status          enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    index_result          text                                                              null,
    playbook_index_status enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    playbook_index_result text                                                              null,
    crm_index_status      enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    crm_index_result      text                                                              null,
    constraint fk_1
        foreign key (document_id) references `autoflow-demo`.documents (id)
);

create index ix_chunks_1_id
    on `autoflow-demo`.chunks_1 (id);

create index vec_idx_embedding
    on `autoflow-demo`.chunks_1 (embedding);

create table `autoflow-demo`.chunks_2
(
    created_at            datetime default CURRENT_TIMESTAMP                                null,
    updated_at            datetime default CURRENT_TIMESTAMP                                null,
    id                    char(32)                                                          not null
        primary key,
    hash                  varchar(64)                                                       not null,
    text                  text                                                              null,
    meta                  json                                                              null,
    embedding vector(1024) not null,
    document_id           int                                                               null,
    relations             json                                                              null,
    source_uri            varchar(512)                                                      null,
    index_status          enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    index_result          text                                                              null,
    playbook_index_status enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    playbook_index_result text                                                              null,
    crm_index_status      enum ('NOT_STARTED', 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED') not null,
    crm_index_result      text                                                              null,
    constraint fk_1
        foreign key (document_id) references `autoflow-demo`.documents (id)
);

create index ix_chunks_2_id
    on `autoflow-demo`.chunks_2 (id);

create index vec_idx_embedding
    on `autoflow-demo`.chunks_2 (embedding);

create index ix_documents_file_id
    on `autoflow-demo`.documents (file_id);

create table `autoflow-demo`.file_permissions
(
    id              int auto_increment
        primary key,
    file_id         int                                              not null,
    user_id         char(32)                                         null,
    permission_type enum ('read', 'owner') default 'read'            not null,
    granted_by      char(32)                                         not null,
    granted_at      datetime               default CURRENT_TIMESTAMP not null,
    expires_at      datetime                                         null,
    constraint fk_1
        foreign key (file_id) references `autoflow-demo`.uploads (id),
    constraint fk_2
        foreign key (granted_by) references `autoflow-demo`.users (id),
    constraint fk_3
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create index ix_file_permissions_file_id
    on `autoflow-demo`.file_permissions (file_id);

create index ix_file_permissions_file_id_user_id
    on `autoflow-demo`.file_permissions (file_id, user_id);

create index ix_file_permissions_user_id
    on `autoflow-demo`.file_permissions (user_id);

create index ix_uploads_category
    on `autoflow-demo`.uploads (category);

create table `autoflow-demo`.user_profiles
(
    id                  int auto_increment
        primary key,
    user_id             char(32)      null,
    oauth_user_id       char(36)      null,
    feishu_open_id      varchar(255)  null,
    name                varchar(255)  null,
    department          varchar(255)  null,
    position            varchar(255)  null,
    direct_manager_id   char(36)      null,
    direct_manager_name varchar(255)  null,
    is_active           tinyint(1)    not null,
    create_time         datetime      null,
    update_time         datetime      null,
    platform            varchar(50)   null,
    open_id             varchar(255)  null,
    notification_tags   varchar(1000) null,
    role                varchar(100)  null,
    en_name             varchar(100)  null,
    avatar_url          text          null,
    email               varchar(255)  null,
    phone               varchar(50)   null,
    crm_user_id         varchar(100)  null,
    extra               json          null,
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create index idx_user_profiles_department_is_active
    on `autoflow-demo`.user_profiles (department, is_active);

create index idx_user_profiles_direct_manager_id_is_active
    on `autoflow-demo`.user_profiles (direct_manager_id, is_active);

create index ix_user_profiles_oauth_user_id
    on `autoflow-demo`.user_profiles (oauth_user_id);

create index ix_user_profiles_open_id
    on `autoflow-demo`.user_profiles (open_id);

create index ix_user_profiles_platform
    on `autoflow-demo`.user_profiles (platform);

create index ix_user_profiles_user_id
    on `autoflow-demo`.user_profiles (user_id);

create table `autoflow-demo`.user_sessions
(
    token      varchar(43)                        not null
        primary key,
    created_at datetime default CURRENT_TIMESTAMP null,
    user_id    char(32)                           not null,
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create table `autoflow-demo`.user_sessions_archive_20260522
(
    token      varchar(43)                        not null
        primary key,
    created_at datetime default CURRENT_TIMESTAMP null,
    user_id    char(32)                           not null,
    constraint fk_1
        foreign key (user_id) references `autoflow-demo`.users (id)
);

create index ix_users_id
    on `autoflow-demo`.users (id);

