From c23c123fb88fc680573e870d8e7335ce32277c6b Mon Sep 17 00:00:00 2001 From: spudding <1115683088@qq.com> Date: Sat, 19 Sep 2026 12:11:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E5=A3=B3=E5=AD=90?= =?UTF-8?q?=E5=86=85=E7=BD=AE=E5=AE=9A=E6=97=B6=E4=BB=BB=E5=8A=A1=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=EF=BC=8C=E6=94=AF=E6=8C=81=E9=85=8D=E7=BD=AE=E5=A4=87?= =?UTF-8?q?=E4=BB=BD=E4=B8=8E=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 本次提交新增完整的定时任务系统: 1. 后端支持cron表达式调度插件执行,与手动运行共用执行链路 2. 前端新增定时任务管理页面,支持增删改查与启停操作 3. 实现配置自动备份到中心机,启动时自动从云端恢复任务 4. 配套新增数据库表与控制面API接口 5. 同时优化了考勤异常检查的规则细节 --- _tmp_verify_match.py | 25 - aa.json | 657 ++++++++++++++++++ desktop/controlplane/apis/schedules.py | 78 +++ desktop/controlplane/app.py | 2 + desktop/controlplane/core/db.py | 12 +- desktop/controlplane/tools/schema_mysql.sql | 10 + desktop/webhost/backend/apis/runs.py | 59 +- desktop/webhost/backend/apis/schedules.py | 105 +++ desktop/webhost/backend/core/runner.py | 56 ++ desktop/webhost/backend/core/tasks.py | 417 +++++++++++ desktop/webhost/backend/main.py | 5 + desktop/webhost/frontend/src/App.vue | 27 +- desktop/webhost/frontend/src/api.js | 29 + .../frontend/src/components/SchedulePage.vue | 361 ++++++++++ .../XQ0010 EHR系统月考勤异常处理/需求文档.md | 8 +- .../attendance_abnormal_monthly.py | 94 ++- 16 files changed, 1816 insertions(+), 129 deletions(-) delete mode 100644 _tmp_verify_match.py create mode 100644 desktop/controlplane/apis/schedules.py create mode 100644 desktop/webhost/backend/apis/schedules.py create mode 100644 desktop/webhost/backend/core/tasks.py create mode 100644 desktop/webhost/frontend/src/components/SchedulePage.vue diff --git a/_tmp_verify_match.py b/_tmp_verify_match.py deleted file mode 100644 index 40a232a..0000000 --- a/_tmp_verify_match.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -"""临时验证脚本:用实际 Excel 数据验证新 _match_rule 筛选(用后即删)""" -import sys -sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0015 参保成功及异常告知书制作与下发") -import py_compile -py_compile.compile(r"d:\work\code\37duAutomation\workflows\XQ0015 参保成功及异常告知书制作与下发\notice_mail_merge.py", doraise=True) -print("SYNTAX OK") - -import notice_mail_merge as nm - -excel = r"D:\资料\人资\告知书制作与下发\2026年9月社保变更及增减名单及人数统计.xlsx" -records = nm._read_insurance_records(excel) -print("参保名单记录数:", len(records)) -if records: - keys = [k for k in records[0].keys()] - print("首条字段数:", len(keys), "含参保告知:", "参保告知" in keys, "含费用:", "费用" in keys) - -for rn, rule in nm.TEMPLATES.items(): - if rn == "社保转移": - continue - matched = [r for r in records if nm._match_rule(r, rule["status"], rule["type"])] - print(f"[{rn}] status={rule['status']} type={rule['type']} -> 命中 {len(matched)} 人") - for r in matched[:10]: - print(" ", r.get("姓名"), "| 参保类型:", r.get("参保类型"), "| 办理状态:", r.get("办理状态"), - "| 参保告知:", repr(r.get("参保告知")), "| 费用:", r.get("费用"), "| 人员类型:", r.get("人员类型"), "| 二级部门:", r.get("二级部门")) diff --git a/aa.json b/aa.json index e69de29..2618657 100644 --- a/aa.json +++ b/aa.json @@ -0,0 +1,657 @@ +{ + "attributeMap" : null, + "count" : 4, + "datas" : [ { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "18", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "小时特假", + "time_unit" : "小时", + "start_time" : "2026-08-29 21:00:00", + "end_time" : "2026-08-29 23:00:00", + "leave_num" : "2", + "leave_reason" : "身体不适", + "status" : "002", + "leave_hours" : "2.00", + "leave_days" : "", + "businessKey" : "bpmac0815d04a6049de9c955cbfa0727dfb", + "process_id" : "39c7ec81-194b-4d62-882f-45ea0540b12d", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpmac0815d04a6049de9c955cbfa0727dfb", + "operat_time" : "2026-09-02 10:03:38", + "apply_time" : "2026-09-01 16:07:12", + "leave_hours_ori" : "2", + "leave_days_ori" : "0", + "begin_date" : "2026-08-29", + "begin_other_name" : "", + "end_date" : null, + "end_other_name" : "", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-29 ", + "end_date_other_name" : null, + "operat_user_id" : "178b0efa-8a65-11f1-a7d9-000c296f9469", + "operat_user_name" : "人资专用号", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + }, { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "24", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "年度福利假", + "time_unit" : "天", + "start_time" : "2026-08-30 18:03:00", + "end_time" : "2026-08-30 23:00:00", + "leave_num" : "0.5", + "leave_reason" : "年假", + "status" : "002", + "leave_hours" : "", + "leave_days" : "0.50", + "businessKey" : "bpmc374402650fb47e28c8c73b0c0dfaa39", + "process_id" : "a10c41a1-371b-4e26-bcb7-e3d186ecf564", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpmc374402650fb47e28c8c73b0c0dfaa39", + "operat_time" : "2026-09-02 08:59:57", + "apply_time" : "2026-09-01 16:08:11", + "leave_hours_ori" : "0", + "leave_days_ori" : "0.5", + "begin_date" : "2026-08-30", + "begin_other_name" : "2", + "end_date" : "2026-08-30", + "end_other_name" : "2", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-30 下半段", + "end_date_other_name" : "2026-08-30 下半段", + "operat_user_id" : "4d6e363b-65fb-11f0-a0a5-000c296f9469", + "operat_user_name" : "胡青青", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + }, { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "18", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "小时特假", + "time_unit" : "小时", + "start_time" : "2026-08-17 21:00:00", + "end_time" : "2026-08-17 23:00:00", + "leave_num" : "2", + "leave_reason" : "身体不适", + "status" : "002", + "leave_hours" : "2.00", + "leave_days" : "", + "businessKey" : "bpmd46808c352f14a17b959f5fa653f5884", + "process_id" : "2f7c5437-13bb-4e3f-990b-b5abb52313bf", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpmd46808c352f14a17b959f5fa653f5884", + "operat_time" : "2026-08-22 10:38:19", + "apply_time" : "2026-08-21 15:32:25", + "leave_hours_ori" : "2", + "leave_days_ori" : "0", + "begin_date" : "2026-08-17", + "begin_other_name" : "", + "end_date" : null, + "end_other_name" : "", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-17 ", + "end_date_other_name" : null, + "operat_user_id" : "178b0efa-8a65-11f1-a7d9-000c296f9469", + "operat_user_name" : "人资专用号", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + }, { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "18", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "小时特假", + "time_unit" : "小时", + "start_time" : "2026-08-10 21:00:00", + "end_time" : "2026-08-10 23:00:00", + "leave_num" : "2", + "leave_reason" : "身体不适", + "status" : "002", + "leave_hours" : "2.00", + "leave_days" : "", + "businessKey" : "bpm174fe7ae7491482082559e19ab69d6d3", + "process_id" : "2ec8df22-575a-4e2f-8a94-79770591b0b1", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpm174fe7ae7491482082559e19ab69d6d3", + "operat_time" : "2026-08-11 21:31:21", + "apply_time" : "2026-08-11 20:21:13", + "leave_hours_ori" : "2", + "leave_days_ori" : "0", + "begin_date" : "2026-08-10", + "begin_other_name" : "", + "end_date" : null, + "end_other_name" : "", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-10 ", + "end_date_other_name" : null, + "operat_user_id" : "ab8caf79-31dd-45bf-bf32-b4aa56edbd31", + "operat_user_name" : "潘贰", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + } ], + "pageSize" : 15, + "start" : 0, + "pageNo" : 1, + "pageCount" : 1, + "allDatas" : { + "#result-set-1" : [ { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "18", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "小时特假", + "time_unit" : "小时", + "start_time" : "2026-08-29 21:00:00", + "end_time" : "2026-08-29 23:00:00", + "leave_num" : "2", + "leave_reason" : "身体不适", + "status" : "002", + "leave_hours" : "2.00", + "leave_days" : "", + "businessKey" : "bpmac0815d04a6049de9c955cbfa0727dfb", + "process_id" : "39c7ec81-194b-4d62-882f-45ea0540b12d", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpmac0815d04a6049de9c955cbfa0727dfb", + "operat_time" : "2026-09-02 10:03:38", + "apply_time" : "2026-09-01 16:07:12", + "leave_hours_ori" : "2", + "leave_days_ori" : "0", + "begin_date" : "2026-08-29", + "begin_other_name" : "", + "end_date" : null, + "end_other_name" : "", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-29 ", + "end_date_other_name" : null, + "operat_user_id" : "178b0efa-8a65-11f1-a7d9-000c296f9469", + "operat_user_name" : "人资专用号", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + }, { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "24", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "年度福利假", + "time_unit" : "天", + "start_time" : "2026-08-30 18:03:00", + "end_time" : "2026-08-30 23:00:00", + "leave_num" : "0.5", + "leave_reason" : "年假", + "status" : "002", + "leave_hours" : "", + "leave_days" : "0.50", + "businessKey" : "bpmc374402650fb47e28c8c73b0c0dfaa39", + "process_id" : "a10c41a1-371b-4e26-bcb7-e3d186ecf564", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpmc374402650fb47e28c8c73b0c0dfaa39", + "operat_time" : "2026-09-02 08:59:57", + "apply_time" : "2026-09-01 16:08:11", + "leave_hours_ori" : "0", + "leave_days_ori" : "0.5", + "begin_date" : "2026-08-30", + "begin_other_name" : "2", + "end_date" : "2026-08-30", + "end_other_name" : "2", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-30 下半段", + "end_date_other_name" : "2026-08-30 下半段", + "operat_user_id" : "4d6e363b-65fb-11f0-a0a5-000c296f9469", + "operat_user_name" : "胡青青", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + }, { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "18", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "小时特假", + "time_unit" : "小时", + "start_time" : "2026-08-17 21:00:00", + "end_time" : "2026-08-17 23:00:00", + "leave_num" : "2", + "leave_reason" : "身体不适", + "status" : "002", + "leave_hours" : "2.00", + "leave_days" : "", + "businessKey" : "bpmd46808c352f14a17b959f5fa653f5884", + "process_id" : "2f7c5437-13bb-4e3f-990b-b5abb52313bf", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpmd46808c352f14a17b959f5fa653f5884", + "operat_time" : "2026-08-22 10:38:19", + "apply_time" : "2026-08-21 15:32:25", + "leave_hours_ori" : "2", + "leave_days_ori" : "0", + "begin_date" : "2026-08-17", + "begin_other_name" : "", + "end_date" : null, + "end_other_name" : "", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-17 ", + "end_date_other_name" : null, + "operat_user_id" : "178b0efa-8a65-11f1-a7d9-000c296f9469", + "operat_user_name" : "人资专用号", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + }, { + "ORG_FULL_PATH" : "集团-金色印象事业部-第一大区-金色印象重庆第二经营中心-第一片区-观音桥步行街行政会馆", + "person_status" : "1", + "IDCARD" : "511303198708052459", + "base_code" : "37013784", + "POST_NO" : "390", + "BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469", + "BELONG_UNIT_ORG_NAME" : "金色印象事业部", + "POST_ALIAS" : "店长", + "POST_ORG_NAME" : "店长", + "staff_id" : "47259659bc954ae28b88374e9105ac07", + "staff_name" : "李春", + "DEPT_STRU_ID" : "4d73b945-d76b-11ed-b449-000c296f9469", + "DEPT_ORG_NAME" : "观音桥步行街行政会馆", + "POST_ALIAS_NAME" : "店长", + "leave_type" : "18", + "DEPT_ORG_ONE" : "第一大区", + "DEPT_ORG_TWO" : "金色印象重庆第二经营中心", + "DEPT_ORG_THREE" : "第一片区", + "DEPT_ORG_FOUR" : "观音桥步行街行政会馆", + "DEPT_ORG_FIVE" : null, + "dept_one" : null, + "dept_two" : null, + "vacation_type_name" : "小时特假", + "time_unit" : "小时", + "start_time" : "2026-08-10 21:00:00", + "end_time" : "2026-08-10 23:00:00", + "leave_num" : "2", + "leave_reason" : "身体不适", + "status" : "002", + "leave_hours" : "2.00", + "leave_days" : "", + "businessKey" : "bpm174fe7ae7491482082559e19ab69d6d3", + "process_id" : "2ec8df22-575a-4e2f-8a94-79770591b0b1", + "form_id" : "399b1612-d410-4a59-86cb-b5260b933232", + "source" : "1", + "leave_id" : "bpm174fe7ae7491482082559e19ab69d6d3", + "operat_time" : "2026-08-11 21:31:21", + "apply_time" : "2026-08-11 20:21:13", + "leave_hours_ori" : "2", + "leave_days_ori" : "0", + "begin_date" : "2026-08-10", + "begin_other_name" : "", + "end_date" : null, + "end_other_name" : "", + "if_other_name_open" : "1", + "begin_date_other_name" : "2026-08-10 ", + "end_date_other_name" : null, + "operat_user_id" : "ab8caf79-31dd-45bf-bf32-b4aa56edbd31", + "operat_user_name" : "潘贰", + "processing_reason" : null, + "remark" : null, + "kqext_create_user_id" : null, + "kqext_create_time" : null, + "kqext_operator_id" : null, + "kqext_operate_time" : null, + "hrext_hsb_ext_speciality" : "", + "hrext_ext_technician_code" : "", + "hrext_ext_cal_person2" : "", + "hrext_ext_call_phone2" : "", + "hrext_ext_star_level" : "六星", + "hrext_ext_rehiring_reason_type" : "", + "hrext_ext_staff_type" : "门店中层管理", + "hrext_ext_insurance_type" : "社会保险", + "hrext_ext_recruit_way" : "其它", + "hrext_ext_call_relationship2" : "", + "hrext_ext_is_CRBT_open" : "否", + "hrext_ext_dept_principal" : "", + "hrext_ext_yb_pay_year" : "2023", + "hrext_ext_Have_worked" : "是", + "hrext_ext_family_join" : "否", + "hrext_ext_criminal_record" : "否", + "hrext_ext_infectious_disease" : "否", + "hrext_ext_References" : "", + "hrext_ext_References_phone" : "", + "hrext_ext_References_outside" : "", + "hrext_ext_outside_References_phone" : "", + "hrext_ext_is_dormitory" : "否", + "hrext_ext_process_approval_status" : "", + "hrext_ext_trans_type" : "其他" + } ] + }, + "url" : null, + "state" : "1", + "meg" : "", + "des" : "", + "viewMapper" : null +} \ No newline at end of file diff --git a/desktop/controlplane/apis/schedules.py b/desktop/controlplane/apis/schedules.py new file mode 100644 index 0000000..459c776 --- /dev/null +++ b/desktop/controlplane/apis/schedules.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +"""壳子定时任务配置备份(服务端侧):执行机变更后全量推送,仅存数据防丢失。 + +- 中心机只做「备份/恢复」存储(schedule_backups 表,按账号一行),不做管理界面; +- 身份来源(对齐 webhost cpapi._cp_headers):登录云令牌 Bearer → 签名票据 → + X-API-Token + X-Admin-User 兜底(_resolve_login),与配置时登录账号一致; +- 推送/拉取同一账号自己的备份(身份即账号,不校验 is_admin,普通员工自助备份)。 +""" +from __future__ import annotations + +import json + +from fastapi import APIRouter, Header, HTTPException +from pydantic import BaseModel + +from controlplane.core.auth import _cloud_account, _resolve_login +from controlplane.core.db import _db, _now + +router = APIRouter() + + +class _BackupIn(BaseModel): + data: dict = {} + + +def _identity(authorization: str = "", x_admin_token: str = "", + x_api_token: str = "", x_admin_user: str = "") -> str: + """解析请求身份;无效则抛 401。""" + account = _cloud_account(authorization) + if not account: + try: + account = _resolve_login(x_admin_token, x_api_token, x_admin_user) + except Exception: + account = "" + if not account: + raise HTTPException(401, "登录态无效或已过期,请重新登录") + return account + + +@router.post("/api/schedules/backup") +def sched_backup_save(b: _BackupIn, + authorization: str = Header(default="", alias="Authorization"), + x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token"), + x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict: + """覆盖保存某账号的定时任务全量配置(执行机变更后异步推送)。""" + account = _identity(authorization, x_admin_token, x_api_token, x_admin_user) + payload = b.data if isinstance(b.data, dict) else {} + if not isinstance(payload.get("schedules"), list): + raise HTTPException(400, "data.schedules 必须为数组") + with _db() as conn: + conn.execute( + "INSERT INTO schedule_backups(account, data, updated_at) VALUES (%s, %s, %s) " + "ON DUPLICATE KEY UPDATE data = VALUES(data), updated_at = VALUES(updated_at)", + (account, json.dumps(payload, ensure_ascii=False), _now())) + conn.commit() + return {"ok": True, "account": account} + + +@router.get("/api/schedules/backup") +def sched_backup_load(authorization: str = Header(default="", alias="Authorization"), + x_admin_token: str = Header(default="", alias="X-Admin-Token"), + x_api_token: str = Header(default="", alias="X-API-Token"), + x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict: + """读取某账号备份的定时任务全量配置(执行机启动时合并恢复缺失任务)。""" + account = _identity(authorization, x_admin_token, x_api_token, x_admin_user) + with _db() as conn: + row = conn.execute( + "SELECT data FROM schedule_backups WHERE account = %s", (account,)).fetchone() + if not row: + return {"data": {"schedules": []}} + try: + data = json.loads(row["data"]) + except (TypeError, ValueError): + data = {} + if not isinstance(data, dict) or not isinstance(data.get("schedules"), list): + return {"data": {"schedules": []}} + return {"data": data} diff --git a/desktop/controlplane/app.py b/desktop/controlplane/app.py index a1a8378..a58f690 100644 --- a/desktop/controlplane/app.py +++ b/desktop/controlplane/app.py @@ -34,6 +34,7 @@ from controlplane.apis import dingtalk as api_dingtalk from controlplane.apis import file_sources as api_file_sources from controlplane.apis import meta as api_meta from controlplane.apis import plugins as api_plugins +from controlplane.apis import schedules as api_schedules @asynccontextmanager @@ -52,6 +53,7 @@ app.include_router(api_plugins.router) app.include_router(api_auth.router) app.include_router(api_config_push.router) app.include_router(api_file_sources.router) +app.include_router(api_schedules.router) app.include_router(api_dingtalk.router) app.include_router(api_admin.router) diff --git a/desktop/controlplane/core/db.py b/desktop/controlplane/core/db.py index eeaca44..6d9333a 100644 --- a/desktop/controlplane/core/db.py +++ b/desktop/controlplane/core/db.py @@ -19,9 +19,9 @@ from controlplane.core import config from controlplane.core.crypto import _hash_password # 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑 -_SCHEMA_VERSION = "20260917_001" +_SCHEMA_VERSION = "20260919_001" -# 全量 DDL(13 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致) +# 全量 DDL(14 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致) _DDL_TABLES = ( """ CREATE TABLE IF NOT EXISTS schema_migrations ( @@ -226,6 +226,14 @@ _DDL_TABLES = ( KEY idx_created (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)' """, + """ + CREATE TABLE IF NOT EXISTS schedule_backups ( + account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)', + data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (account) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)' + """, ) diff --git a/desktop/controlplane/tools/schema_mysql.sql b/desktop/controlplane/tools/schema_mysql.sql index 4635f9e..9236513 100644 --- a/desktop/controlplane/tools/schema_mysql.sql +++ b/desktop/controlplane/tools/schema_mysql.sql @@ -241,3 +241,13 @@ CREATE TABLE IF NOT EXISTS download_tickets ( PRIMARY KEY (nonce), KEY idx_created (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)'; + +-- ------------------------------------------------------------ +-- 壳子定时任务配置备份:执行机变更后全量推送,仅存数据防丢失(不做管理界面) +-- ------------------------------------------------------------ +CREATE TABLE IF NOT EXISTS schedule_backups ( + account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)', + data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (account) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)'; diff --git a/desktop/webhost/backend/apis/runs.py b/desktop/webhost/backend/apis/runs.py index e51e356..eada5a9 100644 --- a/desktop/webhost/backend/apis/runs.py +++ b/desktop/webhost/backend/apis/runs.py @@ -1,19 +1,18 @@ # -*- coding: utf-8 -*- -"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。""" +"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。 + +手动启动入口复用 runner.submit_run(与定时任务共用同一执行链路); +本文件只承担:登录门槛 + 插件查找 + 授权校验(403 前置门禁)。 +""" from __future__ import annotations import logging -import threading -import time -import uuid -from datetime import datetime from fastapi import APIRouter, HTTPException, Request, WebSocket from webhost.backend import licensing -from webhost.backend import scheduler as _scheduler from webhost.backend import state as _st -from webhost.backend.core.runner import RunReq, _run_target, terminate_run +from webhost.backend.core.runner import RunReq, submit_run, terminate_run from webhost.backend.core.hub import HUB from webhost.backend.plugins import PLUGINS from webhost.backend.core.session import _require_login, _sess_account @@ -36,51 +35,7 @@ def start_run(req: RunReq, request: Request) -> dict: if deny: _LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny) raise HTTPException(403, deny) - run_id = uuid.uuid4().hex - with _st.RUN_LOCK: - if len(_st.RUNS) >= _st.MAX_RUNS: - _st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录 - _st.RUNS[run_id] = {"status": "running", "account": account, - "version": getattr(plugin, "version", "0"), - "started": time.time(), - "result": None, "error": None} - HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id, - "at": datetime.now().strftime("%H:%M:%S")}) - licensing.report(account=account, device_id="", plugin_id=plugin.id, - version=getattr(plugin, "version", "0"), status="start") - - def _queued(): - # 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢 - gate = _st._ns_gate(plugin.platform) - if gate.locked(): - HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id, - "level": "INFO", - "msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"}) - with gate: - # 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前 - if _scheduler._is_busy(): - HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id, - "level": "INFO", - "msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"}) - - # start_fn 无参调用(scheduler 约定):run_id 由外层闭包捕获; - # 之前签名带 _run_id 形参会因 TypeError 启动失败且被静默吞掉,运行记录永久卡 running - def _start(): - threading.Thread(target=_run_target, - args=(plugin, req.fields, run_id), - daemon=True, name=f"exec-{plugin.id}").start() - return run_id - r = _scheduler.request_start(account, plugin.id, - getattr(plugin, "version", "0"), _start) - if not r.get("ok"): - # 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待 - _st._set_run(run_id, status="error", result=None, - error=r.get("error") or "启动失败") - HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, - "error": r.get("error") or "启动失败"}) - - threading.Thread(target=_queued, daemon=True, - name=f"run-{plugin.id}").start() + run_id = submit_run(account, plugin, req.fields or {}) return {"run_id": run_id} diff --git a/desktop/webhost/backend/apis/schedules.py b/desktop/webhost/backend/apis/schedules.py new file mode 100644 index 0000000..5c29565 --- /dev/null +++ b/desktop/webhost/backend/apis/schedules.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +"""webhost 宿主「定时任务」路由:增删改查 + 启停;变更后自动备份到中心机(防丢失)。 + +- 任务归属创建者账号(配置时登录账号),仅创建者可修改/删除/启停。 +- cron 为 5 段标准表达式(分 时 日 月 周),由 core.tasks 解析与触发。 +""" +from __future__ import annotations + +import logging + +from fastapi import APIRouter, HTTPException, Request +from pydantic import BaseModel + +from webhost.backend.core import tasks as _tasks +from webhost.backend.core.session import _require_login +from webhost.backend.plugins import PLUGINS + +_LOGGER = logging.getLogger(__name__) + +router = APIRouter() + + +class _SchedIn(BaseModel): + name: str = "" + plugin_id: str = "" + fields: dict = {} + cron: str = "" + enabled: bool = True + + +class _ToggleIn(BaseModel): + enabled: bool + + +def _find_owned(sid: str, account: str) -> dict: + """按 id 取任务并校验归属;不存在/非本人抛 HTTP 异常。""" + s = _tasks.get_schedule(sid) + if s is None: + raise HTTPException(404, "任务不存在") + if s.get("account") != account: + raise HTTPException(403, "仅创建者可管理该任务") + return s + + +@router.get("/api/schedules") +def sched_list(request: Request) -> dict: + account = _require_login(request) + return {"schedules": _tasks.list_schedules(account)} + + +@router.post("/api/schedules", status_code=201) +def sched_create(b: _SchedIn, request: Request) -> dict: + account = _require_login(request) + if not b.plugin_id: + raise HTTPException(400, "请选择插件") + try: + PLUGINS.find(b.plugin_id) + except KeyError: + raise HTTPException(404, "插件不存在") + try: + rec = _tasks.create_schedule(account, b.model_dump()) + except ValueError as e: + raise HTTPException(400, f"cron 表达式无效:{e}") + _tasks.push_backup_async(request, account) + return rec + + +@router.put("/api/schedules/{sid}") +def sched_update(sid: str, b: _SchedIn, request: Request) -> dict: + account = _require_login(request) + _find_owned(sid, account) + if b.plugin_id: + try: + PLUGINS.find(b.plugin_id) + except KeyError: + raise HTTPException(404, "插件不存在") + try: + rec = _tasks.update_schedule(sid, b.model_dump(exclude_unset=True)) + except ValueError as e: + raise HTTPException(400, f"cron 表达式无效:{e}") + if rec is None: + raise HTTPException(404, "任务不存在") + _tasks.push_backup_async(request, account) + return rec + + +@router.delete("/api/schedules/{sid}") +def sched_delete(sid: str, request: Request) -> dict: + account = _require_login(request) + _find_owned(sid, account) + if not _tasks.delete_schedule(sid): + raise HTTPException(404, "任务不存在") + _tasks.push_backup_async(request, account) + return {"ok": True} + + +@router.post("/api/schedules/{sid}/toggle") +def sched_toggle(sid: str, b: _ToggleIn, request: Request) -> dict: + account = _require_login(request) + _find_owned(sid, account) + rec = _tasks.toggle_schedule(sid, b.enabled) + if rec is None: + raise HTTPException(404, "任务不存在") + _tasks.push_backup_async(request, account) + return rec diff --git a/desktop/webhost/backend/core/runner.py b/desktop/webhost/backend/core/runner.py index 08aee96..095ac27 100644 --- a/desktop/webhost/backend/core/runner.py +++ b/desktop/webhost/backend/core/runner.py @@ -13,6 +13,7 @@ import subprocess import sys import threading import time +import uuid from datetime import datetime from pathlib import Path @@ -32,6 +33,61 @@ class RunReq(BaseModel): fields: dict = {} +def submit_run(account: str, plugin, fields: dict) -> str: + """启动一次插件运行(手动 POST /api/runs 与定时任务共用入口)。 + + - 登记运行记录 + 广播 run_start + 上报 start; + - 后台线程执行:命名空间并发闸(同平台串行)→ 设备级单活(排队等待当前插件结束) + → 拉起执行子进程;启动失败回滚单活槽位并广播 run_done(error)。 + 返回 run_id。 + """ + run_id = uuid.uuid4().hex + with _st.RUN_LOCK: + if len(_st.RUNS) >= _st.MAX_RUNS: + _st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录 + _st.RUNS[run_id] = {"status": "running", "account": account, + "version": getattr(plugin, "version", "0"), + "started": time.time(), + "result": None, "error": None} + HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id, + "at": datetime.now().strftime("%H:%M:%S")}) + licensing.report(account=account, device_id="", plugin_id=plugin.id, + version=getattr(plugin, "version", "0"), status="start") + + def _queued(): + # 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢 + gate = _st._ns_gate(plugin.platform) + if gate.locked(): + HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id, + "level": "INFO", + "msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"}) + with gate: + # 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前 + if _scheduler._is_busy(): + HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id, + "level": "INFO", + "msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"}) + + def _start(): + threading.Thread(target=_run_target, + args=(plugin, fields, run_id), + daemon=True, name=f"exec-{plugin.id}").start() + return run_id + + r = _scheduler.request_start(account, plugin.id, + getattr(plugin, "version", "0"), _start) + if not r.get("ok"): + # 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待 + _st._set_run(run_id, status="error", result=None, + error=r.get("error") or "启动失败") + HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, + "error": r.get("error") or "启动失败"}) + + threading.Thread(target=_queued, daemon=True, + name=f"run-{plugin.id}").start() + return run_id + + # ==================== 手动强制停止 ==================== # run_id → 执行中 Job 句柄(供 POST /api/runs/{id}/stop 整树强杀,含浏览器孙进程) _ACTIVE: dict = {} diff --git a/desktop/webhost/backend/core/tasks.py b/desktop/webhost/backend/core/tasks.py new file mode 100644 index 0000000..e0d9634 --- /dev/null +++ b/desktop/webhost/backend/core/tasks.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +"""webhost 宿主定时任务(壳子内置定时):按 cron 触发插件运行。 + +- 配置真源:%LOCALAPPDATA%\\37duAutomation\\schedules.json(按账号隔离,任务归属创建者账号)。 +- 触发链路与手动 POST /api/runs 完全一致(runner.submit_run): + 命名空间并发闸 + 设备级单活排队 + 授权/下架/禁用/强制更新校验(licensing.run_check_allowed)。 +- 变更即备份:增删改/启停后把该账号全量配置推送到中心机(/api/schedules/backup); + 本地缺失时启动按账号从服务端合并恢复(见 restore_from_cloud),配置不丢失。 +- 后台线程每 30s 检查一次,到点触发;last_run_at 记忆上次触发时刻, + 壳子重启后错过的触发点会立即补跑(last_run_at 之前的值保留,不重复触发同一时刻)。 +""" +from __future__ import annotations + +import json +import logging +import os +import threading +import time +from datetime import datetime, timedelta +from pathlib import Path + +_LOGGER = logging.getLogger(__name__) + +_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") + or Path.home(), "37duAutomation") +_SCHED_FILE = _APP_DATA / "schedules.json" + +_TICK_SECS = 30 # 后台检查周期(秒) +_STARTED = False + +_LOCK = threading.RLock() +# 内存中的任务列表(dict 列表),持久化到 _SCHED_FILE +_SCHEDULES: list = [] + + +# ==================== 标准 5 段 cron 解析 ==================== +# 字段顺序:分 时 日 月 周(minute hour day-of-month month day-of-week) +def _parse_field(spec: str, lo: int, hi: int) -> set: + """解析单个 cron 字段为命中集合;支持 * ? */n a-b a-b/n 与逗号列表。非法抛 ValueError。""" + if spec in ("*", "?"): + return set(range(lo, hi + 1)) + out: set = set() + for part in str(spec).split(","): + part = part.strip() + if not part: + continue + step = 1 + if "/" in part: + part, _, step_s = part.partition("/") + try: + step = int(step_s) + except ValueError: + raise ValueError(f"无效步长:{step_s}") + if step < 1: + raise ValueError(f"无效步长:{step_s}") + if part in ("*", "?"): + rng = (lo, hi) + elif "-" in part: + a, _, b = part.partition("-") + rng = (int(a), int(b)) + else: + v = int(part) + rng = (v, v) + a, b = rng + if not (lo <= a <= hi and lo <= b <= hi) or a > b: + raise ValueError(f"字段越界:{part}") + out.update(range(a, b + 1, step)) + if not out: + raise ValueError("空字段") + return out + + +def parse_cron(expr: str) -> dict: + """解析 5 段 cron 表达式;非法抛 ValueError。返回 {minute,hour,dom,month,dow} 集合。""" + parts = str(expr or "").strip().split() + if len(parts) != 5: + raise ValueError("cron 需为 5 段:分 时 日 月 周") + minute = _parse_field(parts[0], 0, 59) + hour = _parse_field(parts[1], 0, 23) + dom = _parse_field(parts[2], 1, 31) + month = _parse_field(parts[3], 1, 12) + dow = _parse_field(parts[4], 0, 7) + has7 = 7 in dow # 标准 cron 中 0 与 7 均表示周日 + dow.discard(7) + if has7: + dow.add(0) + return {"minute": minute, "hour": hour, "dom": dom, "month": month, "dow": dow} + + +def _cron_dow(dt: datetime) -> int: + """cron 周日编号:0=周日,1=周一 … 6=周六。""" + return (dt.weekday() + 1) % 7 + + +def next_match(cron: dict, after: datetime) -> datetime | None: + """返回严格晚于 after 的最近一个匹配时刻;一年内无匹配返回 None(如 2 月 30 日)。""" + minute, hour, dom, month, dow = (cron["minute"], cron["hour"], cron["dom"], + cron["month"], cron["dow"]) + dom_any = dom == set(range(1, 32)) + dow_any = dow == set(range(0, 7)) + t = after.replace(second=0, microsecond=0) + timedelta(minutes=1) + for _ in range(10000): + if t.month not in month: + y, m = (t.year + 1, 1) if t.month == 12 else (t.year, t.month + 1) + t = datetime(y, m, 1) + continue + # 标准语义:dom 与 dow 均有限制时,命中其一即可;仅一方限制则只按该方 + if not dom_any and not dow_any: + day_ok = (t.day in dom) or (_cron_dow(t) in dow) + elif not dow_any: + day_ok = _cron_dow(t) in dow + elif not dom_any: + day_ok = t.day in dom + else: + day_ok = True + if not day_ok: + t = (t + timedelta(days=1)).replace(hour=0, minute=0) + continue + if t.hour not in hour: + t = (t + timedelta(hours=1)).replace(minute=0) + continue + if t.minute not in minute: + t += timedelta(minutes=1) + continue + return t + return None + + +# ==================== 本地存储与 CRUD ==================== +def _load() -> None: + global _SCHEDULES + with _LOCK: + if _SCHED_FILE.is_file(): + try: + data = json.loads(_SCHED_FILE.read_text(encoding="utf-8")) + _SCHEDULES = [s for s in (data or {}).get("schedules", []) + if isinstance(s, dict)] + except (OSError, ValueError): + _LOGGER.warning("定时任务配置损坏,已忽略:%s", _SCHED_FILE) + _SCHEDULES = [] + else: + _SCHEDULES = [] + + +def _persist() -> None: + with _LOCK: + _SCHED_FILE.parent.mkdir(parents=True, exist_ok=True) + _SCHED_FILE.write_text( + json.dumps({"schedules": _SCHEDULES}, ensure_ascii=False, indent=2), + encoding="utf-8") + + +def _now() -> str: + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + +def _new_id() -> str: + return f"{int(time.time() * 1000):x}{os.urandom(4).hex()}" + + +def get_schedule(sid: str) -> dict | None: + """按 id 取原始记录(调用方须持锁前读取,路由层只读不持有引用长期使用)。""" + with _LOCK: + for s in _SCHEDULES: + if s.get("id") == sid: + return dict(s) + return None + + +def list_schedules(account: str) -> list: + with _LOCK: + return [_public(s) for s in _SCHEDULES if s.get("account") == account] + + +def create_schedule(account: str, payload: dict) -> dict: + """新增定时任务(cron 非法抛 ValueError)。""" + cron = (payload.get("cron") or "").strip() + parse_cron(cron) + rec = { + "id": _new_id(), + "name": (payload.get("name") or "").strip() or "定时任务", + "account": account, + "plugin_id": payload.get("plugin_id", ""), + "fields": payload.get("fields") or {}, + "cron": cron, + "enabled": bool(payload.get("enabled", True)), + "last_run_at": "", + "created_at": _now(), + "updated_at": _now(), + } + with _LOCK: + _SCHEDULES.append(rec) + _persist() + return dict(rec) + + +def update_schedule(sid: str, payload: dict) -> dict | None: + """更新任务(仅覆盖 payload 中出现的字段;cron 非法抛 ValueError)。""" + if payload.get("cron"): + parse_cron(payload["cron"]) + with _LOCK: + for s in _SCHEDULES: + if s.get("id") != sid: + continue + if "name" in payload: + s["name"] = (payload["name"] or "").strip() or "定时任务" + if "plugin_id" in payload: + s["plugin_id"] = payload["plugin_id"] + if "fields" in payload: + s["fields"] = payload["fields"] or {} + if payload.get("cron"): + s["cron"] = payload["cron"].strip() + if "enabled" in payload: + s["enabled"] = bool(payload["enabled"]) + s["updated_at"] = _now() + _persist() + return dict(s) + return None + + +def delete_schedule(sid: str) -> bool: + with _LOCK: + for i, s in enumerate(_SCHEDULES): + if s.get("id") == sid: + _SCHEDULES.pop(i) + _persist() + return True + return False + + +def toggle_schedule(sid: str, enabled: bool) -> dict | None: + with _LOCK: + for s in _SCHEDULES: + if s.get("id") == sid: + s["enabled"] = bool(enabled) + s["updated_at"] = _now() + _persist() + return dict(s) + return None + + +def next_run_at(s: dict) -> datetime | None: + """该任务最近一次触发后的下一次触发时刻(未跑过则取首次未来触发)。""" + try: + cron = parse_cron(s.get("cron", "")) + except ValueError: + return None + try: + last = datetime.fromisoformat(s.get("last_run_at")) if s.get("last_run_at") else None + except (TypeError, ValueError): + last = None + return next_match(cron, last if last else datetime.now()) + + +def _public(s: dict) -> dict: + out = dict(s) + out["enabled"] = bool(out.get("enabled")) + out["last_run_at"] = out.get("last_run_at") or "" + nxt = next_run_at(s) + out["next_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") if nxt else "" + return out + + +def _export(account: str) -> list: + with _LOCK: + return [dict(s) for s in _SCHEDULES if s.get("account") == account] + + +# ==================== 后台触发 ==================== +def start() -> None: + """启动后台定时检查线程(幂等)。""" + global _STARTED + with _LOCK: + if _STARTED: + return + _STARTED = True + threading.Thread(target=_loop, daemon=True, name="sched-tick").start() + _LOGGER.info("定时任务后台检查已启动(每 %ds 一次)", _TICK_SECS) + + +def _loop() -> None: + while True: + try: + _tick() + except Exception as _exc: # noqa: BLE001 单轮异常不影响后续检查 + _LOGGER.warning("定时任务检查异常:%s", _exc) + time.sleep(_TICK_SECS) + + +def _tick() -> None: + now = datetime.now() + due = [] + with _LOCK: + for s in _SCHEDULES: + if not s.get("enabled"): + continue + try: + cron = parse_cron(s.get("cron", "")) + except ValueError: + continue + try: + last = (datetime.fromisoformat(s.get("last_run_at")) + if s.get("last_run_at") else None) + except (TypeError, ValueError): + last = None + nxt = next_match(cron, last if last else now) + if nxt and nxt <= now: + due.append((s, nxt)) + fired = False + for s, nxt in due: + if _fire(s): + with _LOCK: + s["last_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") + fired = True + if fired: + _persist() + + +def _fire(s: dict) -> bool: + """触发一次定时任务:授权校验通过后走 submit_run 启动;返回是否已启动。""" + from webhost.backend.plugins import PLUGINS + from webhost.backend.core import licensing + from webhost.backend.core.runner import submit_run + + try: + plugin = PLUGINS.find(s.get("plugin_id", "")) + except KeyError: + _LOGGER.warning("定时任务「%s」的插件 %s 不存在,跳过触发", + s.get("name"), s.get("plugin_id")) + return False + account = s.get("account", "") + deny = licensing.run_check_allowed(plugin.id, account, licensing.is_online()) + if deny: + _LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s", + s.get("name"), account, deny) + return False + try: + submit_run(account, plugin, s.get("fields") or {}) + except Exception as _exc: # noqa: BLE001 + _LOGGER.error("定时任务「%s」启动失败:%s", s.get("name"), _exc) + return False + _LOGGER.info("定时任务触发:「%s」(插件 %s,账号 %s)", + s.get("name"), plugin.id, account) + return True + + +# ==================== 中心机备份(防丢失) ==================== +def push_backup_async(request, account: str) -> None: + """变更后把该账号全量配置异步备份到中心机;失败静默(不阻断用户操作)。""" + from webhost.backend import config + if not config.CONTROLPLANE_URL: + return + + def _run(): + try: + from webhost.backend.core.cpapi import _cp_headers, _cp_call + headers = {**_cp_headers(request), "Content-Type": "application/json"} + _cp_call("POST", "/api/schedules/backup", + headers=headers, + json={"data": {"schedules": _export(account)}}) + except Exception as _exc: # noqa: BLE001 + _LOGGER.warning("定时任务备份失败(账号 %s):%s", account, _exc) + + threading.Thread(target=_run, daemon=True, name="sched-backup").start() + + +def restore_from_cloud() -> None: + """启动时按当前活跃账号从中心机合并恢复缺失的任务(本地已有 id 不覆盖)。 + + 仅作「防丢失」兜底:本地配置为真源,服务端备份只在本地缺失对应任务时补充。 + """ + from webhost.backend import config + if not config.CONTROLPLANE_URL: + return + from webhost.backend.core.session import _sess_active_account, _ACCT_CLOUD_TOKEN + account = _sess_active_account() + if not account: + return + headers = {"X-Admin-User": account} + if config.CONTROLPLANE_TOKEN: + headers["X-API-Token"] = config.CONTROLPLANE_TOKEN + cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account) + if cloud_tok: + headers["Authorization"] = f"Bearer {cloud_tok}" + import requests + try: + r = requests.get(f"{config.CONTROLPLANE_URL}/api/schedules/backup", + headers=headers, timeout=5) + r.raise_for_status() + remote = (r.json().get("data") or {}).get("schedules") or [] + except Exception as _exc: # noqa: BLE001 恢复失败不影响启动 + _LOGGER.warning("定时任务云端恢复失败(跳过):%s", _exc) + return + added = 0 + with _LOCK: + local_ids = {s.get("id") for s in _SCHEDULES} + for s in remote: + if (not isinstance(s, dict) or s.get("id") in local_ids + or s.get("account") != account): + continue + try: + parse_cron(s.get("cron", "")) + except ValueError: + continue + _SCHEDULES.append(s) + added += 1 + if added: + _persist() + if added: + _LOGGER.info("定时任务云端恢复 %d 条(账号 %s)", added, account) + + +def init() -> None: + """启动初始化:加载本地配置 + 启动后台检查线程 + 云端补恢复。""" + _load() + start() + restore_from_cloud() diff --git a/desktop/webhost/backend/main.py b/desktop/webhost/backend/main.py index c7a4199..9e1d54e 100644 --- a/desktop/webhost/backend/main.py +++ b/desktop/webhost/backend/main.py @@ -33,6 +33,7 @@ from webhost.backend.apis import dingtalk as api_dingtalk from webhost.backend.apis import meta as api_meta from webhost.backend.apis import plugin_ui as api_plugin_ui from webhost.backend.apis import runs as api_runs +from webhost.backend.apis import schedules as api_schedules _LOGGER = logging.getLogger(__name__) @@ -92,6 +93,9 @@ async def lifespan(app: FastAPI): from webhost.backend.core import shell_updater as _shell_updater _shell_updater.start_check() _shell_updater.start_periodic_check() + # 壳子内置定时任务:加载本地配置 + 启动后台触发线程 + 从中心机合并恢复(防丢失) + from webhost.backend.core import tasks as _boot_tasks + _boot_tasks.init() yield except BaseException: # lifespan 失败会被 uvicorn 吞成 SystemExit(3);frozen 下 stderr 已重定向 devnull, @@ -115,6 +119,7 @@ app.include_router(api_admin.router) app.include_router(api_dingtalk.router) app.include_router(api_meta.router) app.include_router(api_runs.router) +app.include_router(api_schedules.router) app.include_router(api_plugin_ui.router) diff --git a/desktop/webhost/frontend/src/App.vue b/desktop/webhost/frontend/src/App.vue index c7d7726..f26fa5f 100644 --- a/desktop/webhost/frontend/src/App.vue +++ b/desktop/webhost/frontend/src/App.vue @@ -137,6 +137,12 @@