Compare commits

...

40 Commits

Author SHA1 Message Date
超级管理员 4c055d6469 20240203 2 years ago
超级管理员 7a501005a7 修改判断方式 2 years ago
超级管理员 67bb9dbf4d 修改工作流 2 years ago
超级管理员 6fe4de1e44 修改数据 2 years ago
超级管理员 4f73a36a6b 自定义表单 2 years ago
超级管理员 1771ecce38 编辑新内容 3 years ago
超级管理员 61e4846d0e 修改数据穿透 3 years ago
超级管理员 4fc0ff2f77 更新通知模板 3 years ago
超级管理员 47ff2ac85a 权限认证通讯 3 years ago
超级管理员 10c8da5460 方案BUG修复完成 3 years ago
超级管理员 777ca3235e 部门方案修改完成 3 years ago
超级管理员 7603842783 定量考核流程完成,进行企业微信相关通讯 3 years ago
超级管理员 1a8e799e97 定量考核流程完成 3 years ago
超级管理员 ae60bbf89e 定性考核步进器完成 3 years ago
超级管理员 898b1edbb3 定性审批流步进器完成 3 years ago
超级管理员 095bf14e02 审批流同意与驳回 3 years ago
超级管理员 93f60c41a0 工作流图形转化步进节点完成 3 years ago
超级管理员 cc449056a2 手机端首页接口 3 years ago
超级管理员 cac80aaa44 修改审批记录 3 years ago
超级管理员 db20594d50 岗位指标与部门指标页面更新优化完毕 3 years ago
超级管理员 22c7def3ea 添加岗位指标细则完成 3 years ago
超级管理员 6f04cb161d 2023.02.02 3 years ago
超级管理员 86fff911be 修改岗位提交 3 years ago
超级管理员 cb721eccaa 修改部门考核方案添加 3 years ago
超级管理员 c93c60ca31 修改系统授权 3 years ago
超级管理员 29fb45807f 修改授权认证 3 years ago
超级管理员 fcbcf745a6 修改权限验证模块 3 years ago
超级管理员 35d2b86c2f 实验物料读数据 3 years ago
超级管理员 00b863558f 系统角色增删改查 3 years ago
超级管理员 b1b9d35cd9 手机端V1.0开发完成 3 years ago
超级管理员 87951fd2c9 修改审批状态 3 years ago
超级管理员 2e53eb87dc 修改登录返回参数 3 years ago
超级管理员 df48214c27 工位工作流完成 3 years ago
超级管理员 d219e98376 企业微信回调处理 3 years ago
超级管理员 0b4c9cf121 企业微信回调 3 years ago
超级管理员 c55a55baa8 修改配置读取文件 3 years ago
超级管理员 31e7c5ac56 修改目标设定 3 years ago
超级管理员 2eb177ad1a 权限区域划分 3 years ago
超级管理员 cf704d73b0 考核目标设置 3 years ago
超级管理员 0cf839bd0c 授权菜单获取 3 years ago
  1. 16
      DevLog.md
  2. 230
      README.md
  3. 224
      api/base/loginVerify/login.go
  4. 26
      api/base/loginVerify/type.go
  5. 41
      api/base/loginVerify/verifyCode.go
  6. 670
      api/base/loginVerify/work_js_sdk.go
  7. 142
      api/empower/authorize/empower.go
  8. 25
      api/empower/authorize/type.go
  9. 241
      api/shiyan/maptostruct/cang_chu.go
  10. 587
      api/shiyan/maptostruct/department.go
  11. 317
      api/shiyan/maptostruct/maptostr.go
  12. 433
      api/shiyan/maptostruct/sendwechat.go
  13. 57
      api/shiyan/maptostruct/type.go
  14. 1103
      api/version1/departmentseting/departmentpc/departtarget.go
  15. 634
      api/version1/departmentseting/departmentpc/detailscont.go
  16. 670
      api/version1/departmentseting/departmentpc/ding_xing.go
  17. 897
      api/version1/departmentseting/departmentpc/dingliang.go
  18. 1613
      api/version1/departmentseting/departmentpc/programme.go
  19. 784
      api/version1/departmentseting/departmentpc/qualitativekpi.go
  20. 142
      api/version1/departmentseting/departmentpc/rulesmatrix.go
  21. 502
      api/version1/departmentseting/departmentpc/type.go
  22. 1792
      api/version1/departmentseting/departmentweb/department.go
  23. 243
      api/version1/departmentseting/departmentweb/type.go
  24. 147
      api/version1/departmentseting/departmentweb/web.go
  25. 12
      api/version1/empower/system_license.go
  26. 8
      api/version1/entry.go
  27. 291
      api/version1/flowchart/entry.go
  28. 429
      api/version1/flowchart/flow.go
  29. 965
      api/version1/flowchart/myworkflow.go
  30. 258
      api/version1/flowchart/sendmsg.go
  31. 16
      api/version1/jurisdiction/jurisdictionpc/appsystem.go
  32. 102
      api/version1/jurisdiction/jurisdictionpc/people.go
  33. 233
      api/version1/jurisdiction/jurisdictionpc/postpower.go
  34. 874
      api/version1/jurisdiction/jurisdictionpc/power.go
  35. 665
      api/version1/jurisdiction/jurisdictionpc/systemrole.go
  36. 193
      api/version1/jurisdiction/jurisdictionpc/type.go
  37. 17
      api/version1/newsclass/type.go
  38. 1516
      api/version1/postseting/postpc/details.go
  39. 229
      api/version1/postseting/postpc/scheme.go
  40. 1247
      api/version1/postseting/postpc/serpostconfig.go
  41. 586
      api/version1/postseting/postpc/targetpost.go
  42. 155
      api/version1/postseting/postpc/teshutype.go
  43. 856
      api/version1/postseting/postpc/teshuxuqiu.go
  44. 273
      api/version1/postseting/postpc/type.go
  45. 749
      api/version1/postseting/postweb/appflowlog.go
  46. 30
      api/version1/postseting/postweb/flowmap.go
  47. 259
      api/version1/postseting/postweb/postration.go
  48. 1461
      api/version1/postseting/postweb/posttarget.go
  49. 172
      api/version1/postseting/postweb/type.go
  50. 564
      api/version1/statistics/newpc.go
  51. 231
      api/version1/statistics/orgMonths.go
  52. 140
      api/version1/statistics/orgstatistics.go
  53. 1594
      api/version1/statistics/pc.go
  54. 151
      api/version1/statistics/pcplant.go
  55. 283
      api/version1/statistics/type.go
  56. 29
      api/version1/systemapproval/entry.go
  57. 1022
      api/version1/systemapproval/post_nature.go
  58. 705
      api/workflow/currency_recipe/general_method.go
  59. 558
      api/workflow/currency_recipe/structural_analysis.go
  60. 247
      api/workflow/currency_recipe/type.go
  61. 11
      api/workflow/entry.go
  62. 150
      api/workflow/workflowengine/class.go
  63. 21
      api/workflow/workflowengine/entry.go
  64. 120
      api/workflow/workflowengine/es.go
  65. 297
      api/workflow/workflowengine/flowhandle.go
  66. 66
      api/workflow/workflowengine/shiyan.go
  67. 179
      api/workflow/workflowengine/type.go
  68. 544
      api/workflow/workflowengine/workflow.go
  69. 207
      api/workflow/workflowengine/workflowapi.go
  70. 190
      api/workwechat/entry.go
  71. 253
      api/workwechat/entrypublic.go
  72. 279
      api/workwechat/message.go
  73. 36
      apirouter/apishiyan/maptostruct.go
  74. 9
      apirouter/empower/apirouter.go
  75. 31
      apirouter/entry.go
  76. 20
      apirouter/v1/approvalsystem/approval_route.go
  77. 4
      apirouter/v1/approvalsystem/type.go
  78. 46
      apirouter/v1/departmentseting/pc.go
  79. 14
      apirouter/v1/departmentseting/web.go
  80. 18
      apirouter/v1/newsclassrouter/apirouter.go
  81. 4
      apirouter/v1/newsclassrouter/type.go
  82. 54
      apirouter/v1/postseting/pc.go
  83. 25
      apirouter/v1/postseting/web.go
  84. 44
      apirouter/v1/statisticsrouter/pc.go
  85. 14
      apirouter/v1/statisticsrouter/type.go
  86. 33
      apirouter/v1/systempower/pc.go
  87. 23
      apirouter/verifyLogin/route.go
  88. 5
      apirouter/wechaturl/entry.go
  89. 20
      apirouter/wechaturl/wechatrouter.go
  90. 12
      apirouter/workflowchart/entry.go
  91. 24
      apirouter/workflowchart/flowes.go
  92. 14
      apirouter/workflowrouter/entry.go
  93. 38
      apirouter/workflowrouter/flowrouter.go
  94. 17
      config/configApp/server.go
  95. 10
      config/configDatabase/database.go
  96. 47
      config/configDatabase/database.yaml
  97. 1
      go.mod
  98. 2
      go.sum
  99. 13
      identification/interceptor/identity.go
  100. 8
      identification/interceptor/type.go

16
DevLog.md

@ -37,3 +37,19 @@
### 2022/8/23
//文本信息发送
{
"code": 0,
"msg": "成功",
"data": {
"errcode": 0,
"errmsg": "ok",
"invaliduser": "",
"invalidparty": "",
"invalidtag": "",
"unlicenseduser": "",
"msgid": "mrVtVXE39it1tWVvd57npMpx5AjKZ1VvM-pj7nMCULC0FrlcENid7lRqMZbLvltWcOzLOrKSbGUqV0ngefx2xQ",
"response_code": ""
}
}

230
README.md

@ -1,6 +1,5 @@
# KPI综合管理系统
```Project
|—— api
└── version1
@ -21,31 +20,32 @@
|—— overall
|—— middleware
```
## Hr 文件结构说明
| 文件夹 | 说明 | 描述|
|--------- |------ |-----|
| `api` | api相关业务 | api业务实现 |
| `--version1` | 业务版本文件夹 | 版本界定 |
| `--empower` |OAuth 2.0 授权 |授权Token|
| `apirouter` | 路由器 | 业务路由设定 |
| `initialization` | 初始化相关业务 | 系统初始化方面的实现 |
| `--database` | 数据库业务 | 数据库业务初始化实现 |
| `--nosql` | nosql数据库业务 | nosql业务初始化实现(例:Redis) |
| `--app` | app数据库业务 | app业务初始化实现 |
| `--route` | 路由初始化 | 路由初始化 |
| `identification` | 授权验证器 | 授权验证器 |
| `config` | 系统配置相关业务 | 系统系统配置方面的实现 |
| `--configDatabase` | 数据库业务 | 数据库业务系统配置实现 |
| `--configNosql` | nosql数据库业务 | nosql业务系统配置实现(例:Redis) |
| `--configAapp` | app系统业务 | app业务系统配置实现 |
| `--configJson` | app JSON业务 | app业务系统配置实现 |
| `models` | 数据模型 | 数据库方面的配置 |
| `overall` | 全局对象 | 全局对象|
| `middleware` | 中间件 | 中间件 |
## Hr 文件结构说明
| 文件夹 | 说明 | 描述 |
| -------------------- | ---------------- | ---------------------------------- |
| `api` | api相关业务 | api业务实现 |
| `--version1` | 业务版本文件夹 | 版本界定 |
| `--empower` | OAuth 2.0 授权 | 授权Token |
| `apirouter` | 路由器 | 业务路由设定 |
| `initialization` | 初始化相关业务 | 系统初始化方面的实现 |
| `--database` | 数据库业务 | 数据库业务初始化实现 |
| `--nosql` | nosql数据库业务 | nosql业务初始化实现(例:Redis) |
| `--app` | app数据库业务 | app业务初始化实现 |
| `--route` | 路由初始化 | 路由初始化 |
| `identification` | 授权验证器 | 授权验证器 |
| `config` | 系统配置相关业务 | 系统系统配置方面的实现 |
| `--configDatabase` | 数据库业务 | 数据库业务系统配置实现 |
| `--configNosql` | nosql数据库业务 | nosql业务系统配置实现(例:Redis) |
| `--configAapp` | app系统业务 | app业务系统配置实现 |
| `--configJson` | app JSON业务 | app业务系统配置实现 |
| `models` | 数据模型 | 数据库方面的配置 |
| `overall` | 全局对象 | 全局对象 |
| `middleware` | 中间件 | 中间件 |
## 加密规则
```
1、分解步骤
one = md5(CodeString)+md5(AppKey)
@ -55,7 +55,14 @@
md5(md5(md5(CodeString)+md5(AppKey))+AppKey)
```
## 企业微信按钮key定义
KPI_post_OrderId_1_1 或 KPI_post_OrderId_2_1
| 系统 | 类别 | 审批流ID | 操作 | 步进器 |
| ---- | ---------- | -------- | --------------- | ---------- |
| KPI | post | OrderId | 1:批准;2:驳回 | 当前步进位 |
| KPI | department | OrderId | 1:批准;2:驳回 | 当前步进位 |
## 开发日志
@ -125,23 +132,24 @@ CREATE TABLE `target_report` (
```
```
Time:2022-08-16
创建子栏目关联指标视图 son_target_father
select `qt`.`q_id` AS `q_id`,`qt`.`q_title` AS `q_title`,`qt`.`q_parent_id` AS `q_parent_id`,`qt`.`q_state` AS `q_state`,`qt`.`q_time` AS `q_time`,`qt`.`q_depart` AS `q_depart`,`et`.`et_title` AS `et_title`,`et`.`et_type` AS `et_type`,`et`.`et_dimension` AS `et_dimension`,`et`.`et_key` AS `et_key`,`et`.`et_unit` AS `et_unit`,`et`.`et_cycle` AS `et_cycle`,`et`.`et_cycleattr` AS `et_cycleattr`,`et`.`et_scoring_method` AS `et_scoring_method` from (`qualitative_target` `qt` left join `evaluationtarget` `et` on((`qt`.`q_parent_id` = `et`.`et_id`)))
```
创建用户与职务、岗位关联视图 user_post_duties (HR数据库)
```
select `pc`.`mobilephone` AS `mobilephone`,`pc`.`gender` AS `gender`,`ps`.`name` AS `postname`,`ps`.`person_in_charge` AS `leading_cadre`,`ps`.`superior` AS `post_superior`,`ps`.`menu_permit` AS `menu_permit`,`ps`.`button_permit` AS `button_permit`,`pd`.`name` AS `duties_name`,`pa`.`id` AS `id`,`pa`.`number` AS `number`,`pa`.`name` AS `name`,`pa`.`icon` AS `icon`,`pa`.`company` AS `company`,`pa`.`maindeparment` AS `maindeparment`,`pa`.`admin_org` AS `admin_org`,`pa`.`position` AS `position`,`pa`.`job_id` AS `job_id`,`pa`.`job_leve` AS `job_leve`,`pa`.`wechat` AS `wechat`,`pa`.`work_wechat` AS `work_wechat`,`pa`.`is_admin` AS `is_admin`,`pa`.`key` AS `key`,`pa`.`role` AS `role`,`pa`.`password` AS `password`,`pa`.`sun_main_deparment` AS `sun_main_deparment`,`pa`.`teamid` AS `teamid` from (((`person_archives` `pa` join `personnel_content` `pc` on((`pa`.`key` = `pc`.`key`))) join `position` `ps` on((`pa`.`position` = `ps`.`id`))) join `duties` `pd` on((`pa`.`job_id` = `pd`.`id`)))
```
<span style="color:#FF0000; font-size:20px;">
Time:2022-08-16 <br>
`<span style="color:#FF0000; font-size:20px;">`
Time:2022-08-16
埋坑(1) 待以后编写相应模块 PS:该问题解决后删除此记录
</span>
`</span>`
```
@ -155,54 +163,53 @@ F:\goobject\src\key_performance_indicators\api\version1\departmentseting\departm
```
<span style="color:#D98719; font-size:20px;">
Time:2022-08-24 <br>
`<span style="color:#D98719; font-size:20px;">`
Time:2022-08-24 `<br>`
数据库增加考核项目与提报人关联视图
</span>
`</span>`
```
select `qes`.`id` AS `id`,`qes`.`version_number` AS `version_number`,`qes`.`company_id` AS `company_id`,`qes`.`department_id` AS `department_id`,`qes`.`org_id` AS `org_id`,`qes`.`post_id` AS `post_id`,`qes`.`title` AS `title`,`qes`.`dimension_id` AS `dimension_id`,`qes`.`target_id` AS `target_id`,`qes`.`son_target_id` AS `son_target_id`,`qes`.`details_id` AS `details_id`,`qes`.`attribute` AS `attribute`,`qes`.`min_score` AS `min_score`,`qes`.`max_score` AS `max_score`,`qes`.`scoring_method` AS `scoring_method`,`qes`.`state` AS `state`,`qes`.`addtime` AS `addtime`,`qes`.`eitetime` AS `eitetime`,`qes`.`censor_type` AS `censor_type`,`qes`.`source` AS `source`,`qes`.`run_state` AS `run_state`,`tr`.`type` AS `tr_type`,`tr`.`man_key` AS `man_key`,`tr`.`man_department` AS `man_department`,`tr`.`class` AS `tr_class`,`tr`.`type_level` AS `tr_level` from (`qualitative_evaluation_scheme` `qes` join `target_report` `tr` on(((`qes`.`dimension_id` = `tr`.`dimension_id`) and (`qes`.`target_id` = `tr`.`target_id`) and (`qes`.`son_target_id` = `tr`.`target_sun_id`) and (`qes`.`details_id` = `tr`.`target_bylaws`) and (`qes`.`post_id` = `tr`.`post_id`) and (`qes`.`org_id` = `tr`.`department_id`))))
```
<span style="color:#D98719; font-size:20px;">
Time:2022-08-29 <br>
`<span style="color:#D98719; font-size:20px;">`
Time:2022-08-29 `<br>`
数据库增加 岗位审批工作流 数据表
</span>
`</span>`
```
CREATE TABLE `post_workflow_orders` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`order_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '审批单ID',
`step` int(5) unsigned NOT NULL DEFAULT '0' COMMENT '当前执行到第几步',
`next_step` int(5) unsigned NOT NULL DEFAULT '0' COMMENT '下一步执行哪个步骤',
`step` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '当前执行到第几步',
`next_step` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '下一步执行哪个步骤',
`count_step` int(5) unsigned NOT NULL DEFAULT '1' COMMENT '总共几步',
`work_flow` longtext COMMENT '工作流(审批json字符串)',
`company_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '公司',
`department_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '部门',
`org_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '行政组织',
`post_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '岗位',
`class` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '属性1、定性;2、定量',
`class` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '属性1、定性;2、定量',
`dimension` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '维度',
`target` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '指标',
`son_target` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '指标子栏目',
`detailed` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '指标细则',
`executor` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '执行人',
`executor_department` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '执行人部门',
`state` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '流程状态 1:草稿;2:驳回;3:审批中;4:归档;5:废弃;6:删除',
`state` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '流程状态 1:草稿;2:驳回;3:审批中;4:归档;5:废弃;6:删除',
`start_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '流程开始时间',
`time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '时间',
`enclosure_format` longtext COMMENT '附件',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='岗位审批工作流';
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='岗位审批工作流';
```
<span style="color:#D98719; font-size:20px;">
Time:2022-08-29 <br>
`<span style="color:#D98719; font-size:20px;">`
Time:2022-08-29 `<br>`
数据库增加 定性考核流水 数据表
</span>
`</span>`
```
CREATE TABLE `post_nature_flow` (
@ -239,11 +246,10 @@ CREATE TABLE `post_nature_flow` (
```
<span style="color:#D98719; font-size:20px;">
Time:2022-08-29 <br>
`<span style="color:#D98719; font-size:20px;">`
Time:2022-08-29 `<br>`
数据库增加 岗位定量考核流水 数据表
</span>
`</span>`
```
CREATE TABLE `post_metering_flow` (
@ -274,14 +280,14 @@ CREATE TABLE `post_metering_flow` (
```
<span style="color:#D98719; font-size:20px;">
Time:2022-09-04 <br>
`<span style="color:#D98719; font-size:20px;">`
Time:2022-09-04 `<br>`
增加权限配置管理相关模块
</span>
## database.yaml添加权限数据库配置
`</span>`
```
1、文件地址:config\configDatabase\database.yaml
2、系统权限配置数据库
@ -322,8 +328,6 @@ systemPermission:
}
```
## 增加仓储系统参数
1、config\configDatabase\database.go
@ -345,11 +349,10 @@ systemPermission:
}
```
<span style="color:#D98719; font-size:20px;">
Time:2022-09-07 <br>
`<span style="color:#D98719; font-size:20px;">`
Time:2022-09-07 `<br>`
数据库增加 应用系统 数据表
</span>
`</span>`
```
CREATE TABLE `appsystem` (
@ -362,4 +365,117 @@ CREATE TABLE `appsystem` (
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='应用系统';
```
`<span style="color:#D98719; font-size:20px;">`
Time:2022-10-05 `<br>`
数据库增加 审批记录 数据表
`</span>`
```
CREATE TABLE `open_approval_change_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`type` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '类型(1:部门;2:岗位)',
`title` varchar(255) DEFAULT '' COMMENT '节点名称',
`operator` varchar(255) NOT NULL DEFAULT '' COMMENT '操作人',
`orderid` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '订单ID',
`operatortime` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '操作时间',
`step` int(5) unsigned NOT NULL DEFAULT '1' COMMENT '操作第几步',
`operatortype` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '操作状态',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='审批记录';
```
`<span style="color:#D98719; font-size:20px;">`
Time:2022-10-05 `<br>`
数据库增加 当前节点是否可操作 数据表
`</span>`
```
CREATE TABLE `operator_is_true` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`orderid` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '订单ID',
`step` int(5) unsigned NOT NULL DEFAULT '1' COMMENT '审批到第几步',
`state` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态:1:可操作;2:不可操作',
`time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '时间',
`msgid` varchar(255) DEFAULT '' COMMENT '消息id,用于撤回应用消息',
`response_code` varchar(255) DEFAULT '' COMMENT '仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,24小时内有效,且只能使用一次',
`stepper` int(5) unsigned NOT NULL DEFAULT '1' COMMENT '步进器',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='当前节点是否可操作';
```
`<span style="color:#D98719; font-size:20px;">`
Time:2022-10-24 `<br>`
数据库增加 定性考核与流程关联视图 nature_flow_order
`</span>`
```
select `pf`.`id` AS `id`,`pf`.`order_id` AS `order_id`,`pf`.`add_or_decrease` AS `add_or_decrease`,`pf`.`score` AS `score`,`pf`.`money` AS `money`,`pf`.`reason` AS `reason`,`pf`.`sheme_id` AS `sheme_id`,`pf`.`sheme_version` AS `sheme_version`,`pf`.`dimension` AS `dimension`,`pf`.`target` AS `target`,`pf`.`son_target` AS `son_target`,`pf`.`detailed` AS `detailed`,`pf`.`year` AS `year`,`pf`.`quarter` AS `quarter`,`pf`.`month` AS `month`,`pf`.`week` AS `week`,`pf`.`person_liable` AS `person_liable`,`pf`.`company_id` AS `company_id`,`pf`.`department_id` AS `department_id`,`pf`.`org_id` AS `org_id`,`pf`.`post_id` AS `post_id`,`pf`.`executor` AS `executor`,`pf`.`executor_department` AS `executor_department`,`pf`.`rectification` AS `rectification`,`pf`.`correction_time` AS `correction_time`,`pf`.`happen_time` AS `happen_time`,`pf`.`happen_count` AS `happen_count`,`pf`.`time` AS `time`,`po`.`class` AS `class`,`po`.`state` AS `state`,`po`.`participants` AS `participants` from (`post_nature_flow` `pf` left join `post_workflow_orders` `po` on((`pf`.`order_id` = `po`.`order_id`)))
```
`<span style="color:#D98719; font-size:20px;">`
Time:2022-11-08 `<br>`
数据库增加 角色权限分配 role_empower
`</span>`
```
CREATE TABLE `role_empower` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`role_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '角色',
`system` varchar(255) NOT NULL DEFAULT '' COMMENT '系统',
`point_id` longtext NOT NULL COMMENT '权限点位',
`operation` longtext COMMENT '操作点位',
`state` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '状态(1:启用;2:禁用;3:删除)',
`level` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '授权范围等级(1:本岗位;2:本部门;3:本分部;4:指定行政组织;5:所有)',
`time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='角色权限分配';
```
`<span style="color:#D98719; font-size:20px;">`
Time:2022-11-08 `<br>`
数据库增加 系统角色表 system_role
`</span>`
```
CREATE TABLE `system_role` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '' COMMENT '角色名称',
`state` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '1:启用;2:禁用;3:删除',
`time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '写入时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='系统角色表';
```
`<span style="color:#D98719; font-size:20px;">`
Time:2023-03-24
数据库增加 工作流主体 work_flow 、工作流版本 work_flow_version
增加数据视图 work_flow_cont
`</span>`
```
CREATE TABLE `work_flow` (
`id` bigint(20) unsigned NOT NULL,
`name` varchar(255) DEFAULT '',
`time` bigint(20) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`) USING HASH COMMENT '主键'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工作流主体';
CREATE TABLE `work_flow_version` (
`id` bigint(20) unsigned NOT NULL,
`content` longtext COMMENT '流程主体',
`version` varchar(255) DEFAULT '' COMMENT '版本号',
`time` bigint(20) unsigned NOT NULL DEFAULT '0',
`state` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态(1:启用;2:禁用;3:删除)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工作流版本';
select `wf`.`id` AS `id`,`wf`.`name` AS `name`,`wf`.`time` AS `time`,`wfv`.`content` AS `content`,`wfv`.`version` AS `version`,`wfv`.`state` AS `state` from (`work_flow` `wf` join `work_flow_version` `wfv` on((`wf`.`id` = `wfv`.`id`)))
```

224
api/base/loginVerify/login.go

@ -1,12 +1,14 @@
package loginVerify
import (
"encoding/json"
"fmt"
"key_performance_indicators/middleware/grocerystore"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelsschool"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"github.com/gin-gonic/gin"
)
@ -28,13 +30,14 @@ func (a *ApiMethod) ScanCodeLogin(c *gin.Context) {
return
}
// if store.Verify(requestData.CaptchaId, requestData.Captcha, true) != true {
// publicmethod.Result(1, requestData, c, "验证码不正确!")
// return
// }
if !store.Verify(requestData.CaptchaId, requestData.Captcha, true) {
publicmethod.Result(1, requestData, c, "验证码不正确!")
return
}
userAgent := c.Request.Header.Get("User-Agent") // 获取用户代理
// userAgent := c.Request.Header.Get("User-Agent") // 获取用户代理
// userAgent = "250"
userAgent := overall.CONSTANT_CONFIG.Appsetup.AppKey
var md5JiaMiPwd publicmethod.Md5Encryption
md5JiaMiPwd.Md5EncryptionInit(requestData.Password)
@ -65,16 +68,22 @@ func (a *ApiMethod) ScanCodeLogin(c *gin.Context) {
return
}
uuIdVal := publicmethod.GetUUid(3)
uuIdValStr := strconv.FormatInt(uuIdVal, 10)
fmt.Printf("%v\n", uuIdValStr)
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(userAgent)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
var md5JiaMiNumber publicmethod.Md5Encryption
// md5JiaMiNumber.Md5EncryptionInit(userCont.Number + uuIdValStr)
md5JiaMiNumber.Md5EncryptionInit(userCont.Number)
userKeyCode := md5JiaMiNumber.Md5EncryptionAlgorithm()
// sha1Str := userKeyCode + userCont.Number + userCont.Password + md5Token + uuIdValStr
sha1Str := userKeyCode + userCont.Number + userCont.Password + md5Token
sha1Token := publicmethod.Sha1Encryption(sha1Str)
fmt.Printf("token=========>\n%v\n---->%v\n---->%v\n---->%v\n---->%v\n---->%v\n", userKeyCode, userCont.Number, userCont.Password, md5Token, sha1Token, userAgent)
//返回值
saveData := publicmethod.MapOut[string]()
@ -97,18 +106,32 @@ func (a *ApiMethod) ScanCodeLogin(c *gin.Context) {
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
redisClient.SetRedisTime(10800)
redisClient.HashMsetAdd(redisFileKey, writeRedisData)
groupId, companyId, departmentId, sunDepartId, workShopId := publicmethod.GetOrgStructurees(userCont.AdminOrg)
fmt.Printf("groupId----->%v\ncompanyId----->%v\ndepartmentId----->%v\nsunDepartId----->%v\nworkShopId----->%v\n", groupId, companyId, departmentId, sunDepartId, workShopId)
var sunmaindeparment int64
if companyId != sunDepartId {
sunmaindeparment = sunDepartId
}
//缓存写入个人信息
redisMyContKey := fmt.Sprintf("ScanCode:Authentication:UserCont_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userCont.Number)
myCont := publicmethod.MapOut[string]()
myCont["id"] = userCont.Id
myCont["number"] = userCont.Number //员工工号
myCont["name"] = userCont.Name //姓名
myCont["icon"] = userCont.Icon //头像
myCont["hireclass"] = userCont.HireClass //雇佣类型(1:雇佣入职;2:再入职;)
myCont["emptype"] = userCont.EmpType //用工关系(1:临时工 , 2:编外人员 ;3:实习&实习生;4:试用员工;5:待分配;6:待岗;7:临时调入;8:正式员工;9:长期病假;10:停薪留职;11:退休;12:辞职;13:辞退;14:离职)
myCont["company"] = userCont.Company //入职公司
myCont["maindeparment"] = userCont.MainDeparment //主部门
myCont["sunmaindeparment"] = userCont.SunMainDeparment //二级主部门
myCont["number"] = userCont.Number //员工工号
myCont["name"] = userCont.Name //姓名
myCont["icon"] = userCont.Icon //头像
myCont["hireclass"] = userCont.HireClass //雇佣类型(1:雇佣入职;2:再入职;)
myCont["emptype"] = userCont.EmpType //用工关系(1:临时工 , 2:编外人员 ;3:实习&实习生;4:试用员工;5:待分配;6:待岗;7:临时调入;8:正式员工;9:长期病假;10:停薪留职;11:退休;12:辞职;13:辞退;14:离职)
myCont["company"] = userCont.Company //入职公司
// myCont["maindeparment"] = userCont.MainDeparment //主部门
// myCont["sunmaindeparment"] = userCont.SunMainDeparment //二级主部门
myCont["maindeparment"] = companyId //主部门
myCont["sunmaindeparment"] = sunmaindeparment //二级主部门
myCont["deparment"] = userCont.Deparment //部门
myCont["adminorg"] = userCont.AdminOrg //所属行政组织
myCont["teamid"] = userCont.TeamId //班组
@ -149,9 +172,31 @@ func (a *ApiMethod) ScanCodeLogin(c *gin.Context) {
myCont["probationperiod"] = userCont.Probationperiod //试用期
myCont["planformaldate"] = userCont.Planformaldate //预计转正日期
myCont["political_outlook"] = userCont.PoliticalOutlook //政治面貌(1:群众;2:无党派;3:台盟会员;4:九三社员;5:致公党员;6:农工党员;7:民进会员;8:民建会员;9:民盟盟员;10:民革会员,11:共青团员;12:预备党员;13:中共党员)
var companyCont modelshr.AdministrativeOrganization
companyCont.GetCont(map[string]interface{}{"`id`": userCont.Company}, "`name`")
myCont["companyname"] = companyCont.Name
var departmentCont modelshr.AdministrativeOrganization
departmentCont.GetCont(map[string]interface{}{"`id`": userCont.MainDeparment}, "`name`")
myCont["maindeparmentname"] = departmentCont.Name
var postInfo modelshr.Position
postInfo.GetCont(map[string]interface{}{"`id`": userCont.Position}, "`name`")
myCont["positionname"] = postInfo.Name
redisClient.HashMsetAdd(redisMyContKey, myCont)
// fmt.Printf("redisMyContKey------Login----->%v\n", redisMyContKey)
saveData["usercont"] = myCont
var sendKpiCont WriteIderCont
sendKpiCont.Openid = requestData.OpenId
sendKpiCont.Key = userKeyCode
sendKpiCont.Token = sha1Token
sendKpiCont.UserInfo.Key = strconv.FormatInt(userCont.Key, 10)
sendKpiCont.UserInfo.Number = userCont.Number
sendKpiCont.UserInfo.Password = userCont.Password
sendDate, _ := json.Marshal(sendKpiCont)
publicmethod.CurlPostJosn("http://120.224.6.6:39168/shiyan/write_token", sendDate)
// fmt.Printf("redisMyContKey------Login----->%v\n", sdff)
publicmethod.Result(0, saveData, c)
}
@ -164,6 +209,8 @@ func getRoleSeat(roleId string) (menuStr, buttonStr string) {
}
menuStr = roleInfo.MenuOper
buttonStr = roleInfo.Jurisdiction
// jsonStr, _ := json.Marshal(roleInfo)
// fmt.Printf("roleInfo-->%v-menuStr->%v\n-buttonStr->%v----jsonStr--->%v\n", roleId, menuStr, buttonStr, string(jsonStr))
return
}
@ -189,3 +236,152 @@ func (a *ApiMethod) SignOut(c *gin.Context) {
redisClient.DelKey(redisMyContKey)
publicmethod.Result(0, isTrue, c, "退出成功!")
}
// 无验证码登录
func (a *ApiMethod) ScanCodeLoginNotVerify(c *gin.Context) {
var requestData Login
c.ShouldBindJSON(&requestData)
if requestData.Username == "" {
publicmethod.Result(1, requestData, c, "请输入用户名!")
return
}
if requestData.Password == "" {
publicmethod.Result(1, requestData, c, "请输入密码!")
return
}
// if requestData.Captcha == "" {
// publicmethod.Result(1, requestData, c, "请输入验证码!")
// return
// }
// if store.Verify(requestData.CaptchaId, requestData.Captcha, true) != true {
// publicmethod.Result(1, requestData, c, "验证码不正确!")
// return
// }
// userAgent := c.Request.Header.Get("User-Agent") // 获取用户代理
// userAgent = "250"
userAgent := overall.CONSTANT_CONFIG.Appsetup.AppKey
var md5JiaMiPwd publicmethod.Md5Encryption
md5JiaMiPwd.Md5EncryptionInit(requestData.Password)
md5TokenPwd := md5JiaMiPwd.Md5EncryptionAlgorithm()
// var oldAdmin OldSchollAdmin
// oldErr := overall.CONSTANT_DB_Master.Model(&models.SystemUser{}).Select("system_user.*,system_user_attribute.*").Joins("left join system_user_attribute on system_user.u_key = system_user_attribute.ua_id").Where("`u_name` = ? AND `u_password` = ?", requestData.Username, md5TokenPwd).First(&oldAdmin).Error
// if oldErr == nil {
// //原知行学院管理员账号登录
// }
//新的登录认证方式
var userCont modelshr.ManCont
userErr := userCont.GetCont(map[string]interface{}{"number": requestData.Username, "password": md5TokenPwd})
if userErr != nil {
publicmethod.Result(2000, userErr, c)
return
}
if requestData.OpenId != "" {
var userInfo modelshr.PersonArchives
userInfo.EiteCont(map[string]interface{}{"id": userCont.Id}, map[string]interface{}{"work_wechat": requestData.OpenId})
}
if userCont.State == 2 {
publicmethod.Result(1, userErr, c, "登陆失败! 该账号已经被禁用!")
return
}
if userCont.State == 3 {
publicmethod.Result(1, userErr, c, "登陆失败! 该账号不存在!")
return
}
uuIdVal := publicmethod.GetUUid(3)
uuIdValStr := strconv.FormatInt(uuIdVal, 10)
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(userAgent)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
var md5JiaMiNumber publicmethod.Md5Encryption
md5JiaMiNumber.Md5EncryptionInit(userCont.Number + uuIdValStr)
userKeyCode := md5JiaMiNumber.Md5EncryptionAlgorithm()
sha1Str := userKeyCode + userCont.Number + userCont.Password + md5Token + uuIdValStr
sha1Token := publicmethod.Sha1Encryption(sha1Str)
//返回值
saveData := publicmethod.MapOut[string]()
saveData["key"] = userKeyCode
saveData["token"] = sha1Token
saveData["userinfo"] = userCont
menuoper, jurisdiction := getRoleSeat(userCont.Role)
writeRedisData := map[string]interface{}{
"userkey": userKeyCode,
"key": userCont.Key,
"usernumber": userCont.Number,
"userpwd": userCont.Password,
"usertoken": sha1Token,
"jurisdiction": jurisdiction,
"menuOper": menuoper,
"wand": 118,
}
//API Token数据
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userKeyCode)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
redisClient.SetRedisTime(10800)
redisClient.HashMsetAdd(redisFileKey, writeRedisData)
//缓存写入个人信息
redisMyContKey := fmt.Sprintf("ScanCode:Authentication:UserCont_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userCont.Number)
myCont := publicmethod.MapOut[string]()
myCont["id"] = userCont.Id
myCont["number"] = userCont.Number //员工工号
myCont["name"] = userCont.Name //姓名
myCont["icon"] = userCont.Icon //头像
myCont["hireclass"] = userCont.HireClass //雇佣类型(1:雇佣入职;2:再入职;)
myCont["emptype"] = userCont.EmpType //用工关系(1:临时工 , 2:编外人员 ;3:实习&实习生;4:试用员工;5:待分配;6:待岗;7:临时调入;8:正式员工;9:长期病假;10:停薪留职;11:退休;12:辞职;13:辞退;14:离职)
myCont["company"] = userCont.Company //入职公司
myCont["maindeparment"] = userCont.MainDeparment //主部门
myCont["sunmaindeparment"] = userCont.SunMainDeparment //二级主部门
myCont["deparment"] = userCont.Deparment //部门
myCont["adminorg"] = userCont.AdminOrg //所属行政组织
myCont["teamid"] = userCont.TeamId //班组
myCont["position"] = userCont.Position //职位
myCont["jobclass"] = userCont.JobClass //职务分类
myCont["jobid"] = userCont.JobId //职务
myCont["jobleve"] = userCont.JobLeve //职务等级
myCont["wechat"] = userCont.Wechat //微信UserId
myCont["workwechat"] = userCont.WorkWechat //企业微信UserId
myCont["state"] = userCont.State //状态(1:启用;2:禁用;3:删除)
myCont["key"] = userCont.Key //key
myCont["isadmin"] = userCont.IsAdmin //是否为管理员(1:不是;2:分公司;3:集团管理员;4:超级管
myCont["password"] = userCont.Password //密码
myCont["role"] = userCont.Role //角色
myCont["idcardno"] = userCont.Idcardno //身份证号
myCont["passportno"] = userCont.Passportno //护照号码
myCont["globalroaming"] = userCont.Globalroaming //国际区号
myCont["mobilephone"] = userCont.Mobilephone //手机号码
myCont["email"] = userCont.Email //电子邮件
myCont["gender"] = userCont.Gender //性别(1:男性;2:女性;3:中性)
myCont["birthday"] = userCont.Birthday //birthday
myCont["myfolk"] = userCont.Myfolk //民族
myCont["nativeplace"] = userCont.Nativeplace //籍贯
myCont["idcardstartdate"] = userCont.Idcardstartdate //身份证有效期开始
myCont["idcardenddate"] = userCont.Idcardenddate //身份证有效期结束
myCont["idcardaddress"] = userCont.Idcardaddress //身份证地址
myCont["idcardIssued"] = userCont.IdcardIssued //身份证签发机关
myCont["health"] = userCont.Health //健康状况(1:良好;2:一般;3:较弱,4:有生理缺陷;5:残废)
myCont["maritalstatus"] = userCont.Maritalstatus //婚姻状况(1:未婚;2:已婚;3:丧偶;4:离异)
myCont["internaltelephone"] = userCont.Internaltelephone //内线电话
myCont["currentresidence"] = userCont.Currentresidence //现居住地址
myCont["constellationing"] = userCont.Constellation //星座(1:白羊座;2:金牛座;3:双子座;4:巨蟹座;5:狮子座;6:处女座;7:天枰座;8:天蝎座;9:射手座;10:摩羯座;11:水瓶座;12:双鱼座)
myCont["isdoubleworker"] = userCont.Isdoubleworker //是否双职工(1:是;2:否)
myCont["isveterans"] = userCont.Isveterans //是否为退役军人(1:是;2:否)
myCont["veteransnumber"] = userCont.Veteransnumber //退役证编号
myCont["jobstartdate"] = userCont.Jobstartdate //参加工作日期
myCont["entrydate"] = userCont.Entrydate //入职日期
myCont["probationperiod"] = userCont.Probationperiod //试用期
myCont["planformaldate"] = userCont.Planformaldate //预计转正日期
myCont["political_outlook"] = userCont.PoliticalOutlook //政治面貌(1:群众;2:无党派;3:台盟会员;4:九三社员;5:致公党员;6:农工党员;7:民进会员;8:民建会员;9:民盟盟员;10:民革会员,11:共青团员;12:预备党员;13:中共党员)
redisClient.HashMsetAdd(redisMyContKey, myCont)
publicmethod.Result(0, saveData, c)
}

26
api/base/loginVerify/type.go

@ -36,3 +36,29 @@ type OldSchollAdmin struct {
modelsschool.SystemUser
modelsschool.SystemUserAttribute
}
// 验证授权
type VerifyEmpowerKey struct {
UserKey string `json:"userKey"`
}
// 配置参数
type ExamConfig struct {
Url string `json:"url"`
State int `json:"state"`
}
// 写入身份认证
type WriteIderCont struct {
Openid string `json:"openid"`
Key string `json:"key"`
Token string `json:"token"`
UserInfo UserInfoCont `json:"userinfo"`
}
// 人员信息
type UserInfoCont struct {
Number string `json:"number"`
Password string `json:"password"`
Key string `json:"key"`
}

41
api/base/loginVerify/verifyCode.go

@ -1,6 +1,8 @@
package loginVerify
import (
"fmt"
"key_performance_indicators/middleware/grocerystore"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
@ -25,3 +27,42 @@ func (a *ApiMethod) Captcha(c *gin.Context) {
}, c)
}
}
// 验证授权是否还有效
func (a *ApiMethod) VerifyEmpower(c *gin.Context) {
userKey := c.Request.Header.Get("user-key")
if userKey == "" {
publicmethod.Result(9001, userKey, c, "未获得授权信息!")
return
}
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userKey)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
userRedisToken, isTrue := redisClient.HashGetAll(redisFileKey)
if isTrue == false {
publicmethod.Result(9002, userKey, c, "授权超时!")
return
}
publicmethod.Result(0, userRedisToken, c)
}
// 验证授权是否过期
func (a *ApiMethod) VerifyEmpowerIsTrue(c *gin.Context) {
var requestData VerifyEmpowerKey
err := c.ShouldBindJSON(&requestData)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if requestData.UserKey == "" {
publicmethod.Result(9001, requestData, c, "未获得授权信息!")
return
}
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, requestData.UserKey)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
userRedisToken, isTrue := redisClient.HashGetAll(redisFileKey)
if isTrue == false {
publicmethod.Result(9002, requestData, c, "授权超时!")
return
}
publicmethod.Result(0, userRedisToken, c)
}

670
api/base/loginVerify/work_js_sdk.go

@ -0,0 +1,670 @@
package loginVerify
import (
"encoding/json"
"fmt"
"key_performance_indicators/middleware/grocerystore"
"key_performance_indicators/middleware/wechatapp/wechatstatice"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelssystempermission"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2022-10-31 13:31:05
@ 功能: 获取企业微信基础配置
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) GetWorkWechatJsApiConfig(c *gin.Context) {
host := c.Request.Header.Get("Host")
userAgent := c.Request.Header.Get("User-Agent")
wechatTokenStr := fmt.Sprintf("%v_%v", host, userAgent)
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(wechatTokenStr)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
var receivedValue ExamConfig
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.Url == "" {
publicmethod.Result(1, receivedValue, c, "参数错误!请重新提交!")
return
}
if receivedValue.State == 0 {
receivedValue.State = 1
}
//获取JsApi_ticket
_, jsapiTicker, err := GetJsapiTicket("kpi", md5Token, receivedValue.State)
if err != nil {
publicmethod.Result(1, err, c, "获取jsapi_ticket数据失败!")
return
}
noncestr := publicmethod.GetUUid(3)
timestamp := time.Now().Unix()
url := receivedValue.Url
jiamistr := fmt.Sprintf("jsapi_ticket=%v&noncestr=%v&timestamp=%v&url=%v", jsapiTicker, noncestr, timestamp, url)
jiamistrHa1 := publicmethod.Sha1Encryption(jiamistr)
outData := publicmethod.MapOut[string]()
outData["corpid"] = overall.CONSTANT_CONFIG.WechatCompany.CompanyId
outData["agentid"] = overall.CONSTANT_CONFIG.WechatKpi.Agentid
outData["timestamp"] = strconv.FormatInt(timestamp, 10)
outData["nonceStr"] = strconv.FormatInt(noncestr, 10)
outData["signature"] = jiamistrHa1
outData["orderid"] = strconv.FormatInt(publicmethod.GetUUid(2), 10)
outData["jsapi_ticket"] = jsapiTicker
outData["state"] = receivedValue.State
response.Result(0, outData, "查询成功", c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-31 13:07:35
@ 功能: 获取企业的jsapi_ticket 获取应用的jsapi_ticket
@ 参数
#systemApp 系统
#key 身份识别
#calss 1应用2企业
@ 返回值
#sendUrlstr jsapiTicket访问URL
*/
func GetJsapiTicket(systemApp, key string, class int) (sendUrlstr, jsApiTickerStr string, err error) {
//获取token
tokenStr, err := wechatstatice.GetWechatTokenEs(systemApp, key, 1)
if class != 1 {
sendUrlstr = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + tokenStr //获取企业级
} else {
sendUrlstr = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" + tokenStr + "&type=agent_config" //获取应用级
}
jsApiTicketRedis := fmt.Sprintf("WorkWechat:JsapiTicket:%v_%v_%v", systemApp, overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, class)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS3)
isTrue, jsApiTickerStr := redisClient.Get(jsApiTicketRedis) //读取redis数据
if isTrue != true {
//获取企业微信jsapi_ticket
jsapiTickerMsg := publicmethod.CurlGet(sendUrlstr)
var callBackCont wechatstatice.WeChatCallBack
err = json.Unmarshal(jsapiTickerMsg, &callBackCont)
if err != nil {
return
}
if callBackCont.Errcode != 0 {
return
}
jsApiTickerStr = callBackCont.Ticket
redisClient.SetRedisTime(7200)
redisClient.Set(jsApiTicketRedis, jsApiTickerStr)
} else {
return
}
return
}
// 获取身份认证
func (a *ApiMethod) AuthenticationUser(c *gin.Context) {
host := c.Request.Header.Get("Host")
userAgent := c.Request.Header.Get("User-Agent")
wechatTokenStr := fmt.Sprintf("%v_%v", host, userAgent)
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(wechatTokenStr)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
//获取token
tokenStr, err := wechatstatice.GetWechatTokenEs("kpi", md5Token, 1)
if err != nil {
publicmethod.Result(100, err, c, "身份认证失败!----------------->")
// user_code_url := fmt.Sprintf("%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl)
// c.Redirect(http.StatusMovedPermanently, user_code_url)
return
}
//重定向身份认证
callBackUrl := url.QueryEscape(fmt.Sprintf("%v/kpiapi/base/callbackauthuser", overall.CONSTANT_CONFIG.Appsetup.WebUrl))
redirectUrl := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%v&redirect_uri=%v&response_type=code&scope=snsapi_base&state=%v#wechat_redirect", overall.CONSTANT_CONFIG.WechatCompany.CompanyId, callBackUrl, tokenStr)
c.Redirect(http.StatusMovedPermanently, redirectUrl)
// publicmethod.Result(1, tokenStr, c, "身份认证失败!!")
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-01 10:02:09
@ 功能: 企业微信身份回调认证
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) CallBackAuthUser(c *gin.Context) {
code := c.Query("code")
state := c.Query("state")
if code == "" || state == "" {
publicmethod.Result(1, code, c, "未能查询到您的信息!企业微信授权失败!1")
return
}
sendUser := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=%v&code=%v", state, code)
tokenByte := publicmethod.CurlGet(sendUser)
var callBackData wechatstatice.WorkWechatUserAuter
err := json.Unmarshal(tokenByte, &callBackData)
if err != nil {
publicmethod.Result(1, err, c, "未能查询到您的信息!企业微信授权失败!2")
return
}
if callBackData.Errcode != 0 {
if callBackData.Errcode == 42001 {
AgainEmpower(c)
return
}
publicmethod.Result(1, callBackData, c, "未能查询到您的信息!企业微信授权失败!3")
return
}
var userWechatId string
if callBackData.OpenId != "" {
userWechatId = callBackData.OpenId
}
if callBackData.Userid != "" {
userWechatId = callBackData.Userid
}
if userWechatId == "" {
publicmethod.Result(1, err, c, "未能查询到您的信息!企业微信授权失败!4")
return
}
_, sendMap, msg, isTrue := SetUpUserLogin(userWechatId)
callBackLoginUrl := fmt.Sprintf("%v/#/pages/login/login", overall.CONSTANT_CONFIG.Appsetup.WebUrl)
switch isTrue {
case 2:
publicmethod.Result(1, err, c, msg)
return
case 3:
publicmethod.Result(1, err, c, msg)
return
case 4:
callBackLoginUrl = fmt.Sprintf("%v?exitstr=0&openid=%v&userkey=%v&token=%v", callBackLoginUrl, userWechatId, sendMap["key"], sendMap["token"])
default:
callBackLoginUrl = fmt.Sprintf("%v?exitstr=1&openid=%v", callBackLoginUrl, userWechatId)
}
c.Redirect(http.StatusMovedPermanently, callBackLoginUrl)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-02 13:22:08
@ 功能: 重新等下授权
@ 参数
#
@ 返回值
#
*/
func AgainEmpower(c *gin.Context) {
host := c.Request.Header.Get("Host")
userAgent := c.Request.Header.Get("User-Agent")
wechatTokenStr := fmt.Sprintf("%v_%v", host, userAgent)
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(wechatTokenStr)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
//获取token
tokenStr, err := wechatstatice.GetWechatTokenEs("kpi", md5Token, 2)
if err != nil {
// publicmethod.Result(1, err, c, "身份认证失败!")
user_code_url := fmt.Sprintf("%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl)
c.Redirect(http.StatusMovedPermanently, user_code_url)
return
}
//重定向身份认证
callBackUrl := url.QueryEscape(fmt.Sprintf("%v/kpiapi/base/callbackauthuser", overall.CONSTANT_CONFIG.Appsetup.WebUrl))
redirectUrl := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%v&redirect_uri=%v&response_type=code&scope=snsapi_base&state=%v#wechat_redirect", overall.CONSTANT_CONFIG.WechatCompany.CompanyId, callBackUrl, tokenStr)
c.Redirect(http.StatusMovedPermanently, redirectUrl)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-01 11:24:40
@ 功能: 设定登录信息
@ 参数
#
@ 返回值
#
*/
func SetUpUserLogin(openId string) (userCont modelshr.ManCont, sendMap map[string]interface{}, msg string, isTrue int) {
isTrue = 1
// var userCont modelshr.ManCont
err := overall.CONSTANT_DB_HR.Where("`wechat` = ? OR `work_wechat` = ?", openId, openId).First(&userCont).Error //获取人员信息
if err != nil {
return
}
if userCont.State == 2 {
msg = "登陆失败! 该账号已经被禁用!"
isTrue = 2
return
}
if userCont.State == 3 {
msg = "登陆失败! 该账号不存在!"
isTrue = 3
return
}
uuIdVal := publicmethod.GetUUid(3) //获取随机数
uuIdValStr := strconv.FormatInt(uuIdVal, 10)
fmt.Printf("%v\n", uuIdValStr)
//Token定参
userAgent := overall.CONSTANT_CONFIG.Appsetup.AppKey
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(userAgent)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
//工号MD5加密
var md5JiaMiNumber publicmethod.Md5Encryption
// md5JiaMiNumber.Md5EncryptionInit(userCont.Number + uuIdValStr)
md5JiaMiNumber.Md5EncryptionInit(userCont.Number)
userKeyCode := md5JiaMiNumber.Md5EncryptionAlgorithm()
//组成Token字符串进行
// sha1Str := userKeyCode + userCont.Number + userCont.Password + md5Token + uuIdValStr
sha1Str := userKeyCode + userCont.Number + userCont.Password + md5Token
sha1Token := publicmethod.Sha1Encryption(sha1Str)
//身份识别数据
// menuoper, jurisdiction := getRoleSeat(userCont.Role)
//获取身份权限
menuoper, jurisdiction := GetRoleAndPostPower("kpi", userCont.Role, userCont.AdminOrg, userCont.Position)
writeRedisData := map[string]interface{}{
"userkey": userKeyCode,
"key": userCont.Key,
"usernumber": userCont.Number,
"userpwd": userCont.Password,
"usertoken": sha1Token,
"jurisdiction": jurisdiction,
"menuOper": menuoper,
"wand": 118,
}
// fmt.Printf("writeRedisData--------->%v\n", writeRedisData)
//API Token数据
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userKeyCode)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
redisClient.SetRedisTime(10800)
redisClient.HashMsetAdd(redisFileKey, writeRedisData)
//缓存写入个人信息
redisMyContKey := fmt.Sprintf("ScanCode:Authentication:UserCont_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userCont.Number)
myCont := publicmethod.MapOut[string]()
myCont["id"] = userCont.Id
myCont["number"] = userCont.Number //员工工号
myCont["name"] = userCont.Name //姓名
myCont["icon"] = userCont.Icon //头像
myCont["hireclass"] = userCont.HireClass //雇佣类型(1:雇佣入职;2:再入职;)
myCont["emptype"] = userCont.EmpType //用工关系(1:临时工 , 2:编外人员 ;3:实习&实习生;4:试用员工;5:待分配;6:待岗;7:临时调入;8:正式员工;9:长期病假;10:停薪留职;11:退休;12:辞职;13:辞退;14:离职)
myCont["company"] = userCont.Company //入职公司
myCont["maindeparment"] = userCont.MainDeparment //主部门
myCont["sunmaindeparment"] = userCont.SunMainDeparment //二级主部门
myCont["deparment"] = userCont.Deparment //部门
myCont["adminorg"] = userCont.AdminOrg //所属行政组织
myCont["teamid"] = userCont.TeamId //班组
myCont["position"] = userCont.Position //职位
myCont["jobclass"] = userCont.JobClass //职务分类
myCont["jobid"] = userCont.JobId //职务
myCont["jobleve"] = userCont.JobLeve //职务等级
myCont["wechat"] = userCont.Wechat //微信UserId
myCont["workwechat"] = userCont.WorkWechat //企业微信UserId
myCont["state"] = userCont.State //状态(1:启用;2:禁用;3:删除)
myCont["key"] = userCont.Key //key
myCont["isadmin"] = userCont.IsAdmin //是否为管理员(1:不是;2:分公司;3:集团管理员;4:超级管
myCont["password"] = userCont.Password //密码
myCont["role"] = userCont.Role //角色
myCont["idcardno"] = userCont.Idcardno //身份证号
myCont["passportno"] = userCont.Passportno //护照号码
myCont["globalroaming"] = userCont.Globalroaming //国际区号
myCont["mobilephone"] = userCont.Mobilephone //手机号码
myCont["email"] = userCont.Email //电子邮件
myCont["gender"] = userCont.Gender //性别(1:男性;2:女性;3:中性)
myCont["birthday"] = userCont.Birthday //birthday
myCont["myfolk"] = userCont.Myfolk //民族
myCont["nativeplace"] = userCont.Nativeplace //籍贯
myCont["idcardstartdate"] = userCont.Idcardstartdate //身份证有效期开始
myCont["idcardenddate"] = userCont.Idcardenddate //身份证有效期结束
myCont["idcardaddress"] = userCont.Idcardaddress //身份证地址
myCont["idcardIssued"] = userCont.IdcardIssued //身份证签发机关
myCont["health"] = userCont.Health //健康状况(1:良好;2:一般;3:较弱,4:有生理缺陷;5:残废)
myCont["maritalstatus"] = userCont.Maritalstatus //婚姻状况(1:未婚;2:已婚;3:丧偶;4:离异)
myCont["internaltelephone"] = userCont.Internaltelephone //内线电话
myCont["currentresidence"] = userCont.Currentresidence //现居住地址
myCont["constellationing"] = userCont.Constellation //星座(1:白羊座;2:金牛座;3:双子座;4:巨蟹座;5:狮子座;6:处女座;7:天枰座;8:天蝎座;9:射手座;10:摩羯座;11:水瓶座;12:双鱼座)
myCont["isdoubleworker"] = userCont.Isdoubleworker //是否双职工(1:是;2:否)
myCont["isveterans"] = userCont.Isveterans //是否为退役军人(1:是;2:否)
myCont["veteransnumber"] = userCont.Veteransnumber //退役证编号
myCont["jobstartdate"] = userCont.Jobstartdate //参加工作日期
myCont["entrydate"] = userCont.Entrydate //入职日期
myCont["probationperiod"] = userCont.Probationperiod //试用期
myCont["planformaldate"] = userCont.Planformaldate //预计转正日期
myCont["political_outlook"] = userCont.PoliticalOutlook //政治面貌(1:群众;2:无党派;3:台盟会员;4:九三社员;5:致公党员;6:农工党员;7:民进会员;8:民建会员;9:民盟盟员;10:民革会员,11:共青团员;12:预备党员;13:中共党员)
var companyCont modelshr.AdministrativeOrganization
companyCont.GetCont(map[string]interface{}{"`id`": userCont.Company}, "`name`")
myCont["companyname"] = companyCont.Name
var departmentCont modelshr.AdministrativeOrganization
departmentCont.GetCont(map[string]interface{}{"`id`": userCont.MainDeparment}, "`name`")
myCont["maindeparmentname"] = departmentCont.Name
var postInfo modelshr.Position
postInfo.GetCont(map[string]interface{}{"`id`": userCont.Position}, "`name`")
myCont["positionname"] = postInfo.Name
redisClient.HashMsetAdd(redisMyContKey, myCont)
//返回值
saveData := publicmethod.MapOut[string]()
saveData["key"] = userKeyCode
saveData["token"] = sha1Token
saveData["userinfo"] = userCont
saveData["usercont"] = myCont
sendMap = saveData
isTrue = 4
return
}
// 手机端免登录验证
func (a *ApiMethod) LaissezPasser(c *gin.Context) {
userKey := c.Request.Header.Get("user-key")
userToken := c.Request.Header.Get("user-token")
//API Token数据
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userKey)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
userRedisToken, isTrue := redisClient.HashGetAll(redisFileKey)
if !isTrue {
publicmethod.Result(1, isTrue, c, "未登录或非法访问!")
return
}
if userToken != userRedisToken["usertoken"] {
publicmethod.Result(1, isTrue, c, "令牌不正确!非法访问!")
return
}
userCont, myErr := publicmethod.GetUserRedisCont(userRedisToken["usernumber"])
if myErr != nil {
publicmethod.Result(1, isTrue, c, "登录超时!请重新登录!")
return
}
myCont := publicmethod.MapOut[string]()
myCont["id"] = userCont.Id
myCont["number"] = userCont.Number //员工工号
myCont["name"] = userCont.Name //姓名
myCont["icon"] = userCont.Icon //头像
myCont["hireclass"] = userCont.HireClass //雇佣类型(1:雇佣入职;2:再入职;)
myCont["emptype"] = userCont.EmpType //用工关系(1:临时工 , 2:编外人员 ;3:实习&实习生;4:试用员工;5:待分配;6:待岗;7:临时调入;8:正式员工;9:长期病假;10:停薪留职;11:退休;12:辞职;13:辞退;14:离职)
myCont["company"] = userCont.Company //入职公司
myCont["maindeparment"] = userCont.MainDeparment //主部门
myCont["sunmaindeparment"] = userCont.SunMainDeparment //二级主部门
myCont["deparment"] = userCont.Deparment //部门
myCont["adminorg"] = userCont.AdminOrg //所属行政组织
myCont["teamid"] = userCont.TeamId //班组
myCont["position"] = userCont.Position //职位
myCont["jobclass"] = userCont.JobClass //职务分类
myCont["jobid"] = userCont.JobId //职务
myCont["jobleve"] = userCont.JobLeve //职务等级
myCont["wechat"] = userCont.Wechat //微信UserId
myCont["workwechat"] = userCont.WorkWechat //企业微信UserId
myCont["state"] = userCont.State //状态(1:启用;2:禁用;3:删除)
myCont["key"] = userCont.Key //key
myCont["isadmin"] = userCont.IsAdmin //是否为管理员(1:不是;2:分公司;3:集团管理员;4:超级管
myCont["password"] = userCont.Password //密码
myCont["role"] = userCont.Role //角色
myCont["idcardno"] = userCont.Idcardno //身份证号
myCont["passportno"] = userCont.Passportno //护照号码
myCont["globalroaming"] = userCont.Globalroaming //国际区号
myCont["mobilephone"] = userCont.Mobilephone //手机号码
myCont["email"] = userCont.Email //电子邮件
myCont["gender"] = userCont.Gender //性别(1:男性;2:女性;3:中性)
myCont["birthday"] = userCont.Birthday //birthday
myCont["myfolk"] = userCont.Myfolk //民族
myCont["nativeplace"] = userCont.Nativeplace //籍贯
myCont["idcardstartdate"] = userCont.Idcardstartdate //身份证有效期开始
myCont["idcardenddate"] = userCont.Idcardenddate //身份证有效期结束
myCont["idcardaddress"] = userCont.Idcardaddress //身份证地址
myCont["idcardIssued"] = userCont.IdcardIssued //身份证签发机关
myCont["health"] = userCont.Health //健康状况(1:良好;2:一般;3:较弱,4:有生理缺陷;5:残废)
myCont["maritalstatus"] = userCont.Maritalstatus //婚姻状况(1:未婚;2:已婚;3:丧偶;4:离异)
myCont["internaltelephone"] = userCont.Internaltelephone //内线电话
myCont["currentresidence"] = userCont.Currentresidence //现居住地址
myCont["constellationing"] = userCont.Constellation //星座(1:白羊座;2:金牛座;3:双子座;4:巨蟹座;5:狮子座;6:处女座;7:天枰座;8:天蝎座;9:射手座;10:摩羯座;11:水瓶座;12:双鱼座)
myCont["isdoubleworker"] = userCont.Isdoubleworker //是否双职工(1:是;2:否)
myCont["isveterans"] = userCont.Isveterans //是否为退役军人(1:是;2:否)
myCont["veteransnumber"] = userCont.Veteransnumber //退役证编号
myCont["jobstartdate"] = userCont.Jobstartdate //参加工作日期
myCont["entrydate"] = userCont.Entrydate //入职日期
myCont["probationperiod"] = userCont.Probationperiod //试用期
myCont["planformaldate"] = userCont.Planformaldate //预计转正日期
myCont["political_outlook"] = userCont.PoliticalOutlook //政治面貌(1:群众;2:无党派;3:台盟会员;4:九三社员;5:致公党员;6:农工党员;7:民进会员;8:民建会员;9:民盟盟员;10:民革会员,11:共青团员;12:预备党员;13:中共党员)
var companyCont modelshr.AdministrativeOrganization
companyCont.GetCont(map[string]interface{}{"`id`": userCont.Company}, "`name`")
myCont["companyname"] = companyCont.Name
var departmentCont modelshr.AdministrativeOrganization
departmentCont.GetCont(map[string]interface{}{"`id`": userCont.MainDeparment}, "`name`")
myCont["maindeparmentname"] = departmentCont.Name
var postInfo modelshr.Position
postInfo.GetCont(map[string]interface{}{"`id`": userCont.Position}, "`name`")
myCont["positionname"] = postInfo.Name
//返回值
saveData := publicmethod.MapOut[string]()
saveData["key"] = userKey
saveData["token"] = userToken
saveData["userinfo"] = userCont
saveData["usercont"] = myCont
publicmethod.Result(0, saveData, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-08 13:10:54
@ 功能: 扫码登录
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) ScanQrCodeCallBackAuthUser(c *gin.Context) {
code := c.Query("code")
state := c.Query("state")
if code == "" || state == "" {
publicmethod.Result(1, code, c, "未能查询到您的信息!企业微信授权失败!1")
return
}
host := c.Request.Header.Get("Host")
userAgent := c.Request.Header.Get("User-Agent")
wechatTokenStr := fmt.Sprintf("%v_%v", host, userAgent)
var md5JiaMi publicmethod.Md5Encryption
md5JiaMi.Md5EncryptionInit(wechatTokenStr)
md5Token := md5JiaMi.Md5EncryptionAlgorithm()
//获取token
tokenStr, err := wechatstatice.GetWechatTokenEs("kpi", md5Token, 1)
if err != nil {
publicmethod.Result(1, err, c, "未能查询到您的信息!企业微信授权失败!4")
return
}
sendUser := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=%v&code=%v", tokenStr, code)
tokenByte := publicmethod.CurlGet(sendUser)
var callBackData wechatstatice.WorkWechatUserAuter
err = json.Unmarshal(tokenByte, &callBackData)
if err != nil {
publicmethod.Result(1, err, c, "未能查询到您的信息!企业微信授权失败!2")
return
}
if callBackData.Errcode != 0 {
if callBackData.Errcode == 42001 {
AgainEmpower(c)
return
}
publicmethod.Result(1, callBackData, c, "未能查询到您的信息!企业微信授权失败!3")
return
}
var userWechatId string
if callBackData.OpenId != "" {
userWechatId = callBackData.OpenId
}
if callBackData.Userid != "" {
userWechatId = callBackData.Userid
}
if userWechatId == "" {
publicmethod.Result(1, err, c, "未能查询到您的信息!企业微信授权失败!4")
return
}
// userWechatId := "KaiXinGuo"
_, sendMap, msg, isTrue := SetUpUserLogin(userWechatId)
callBackLoginUrl := fmt.Sprintf("%v/#/ceshi", overall.CONSTANT_CONFIG.Appsetup.PcbUrl)
switch isTrue {
case 2:
publicmethod.Result(1, err, c, msg)
return
case 3:
publicmethod.Result(1, err, c, msg)
return
case 4:
callBackLoginUrl = fmt.Sprintf("%v?token=%v&key=%v", callBackLoginUrl, sendMap["token"], sendMap["key"])
default:
callBackLoginUrl = fmt.Sprintf("%v?token=%v&key=%v", callBackLoginUrl, sendMap["token"], sendMap["key"])
}
// publicmethod.Result(1, callBackLoginUrl, c, "未能查询到您的信息!企业微信授权失败!5")
c.Redirect(http.StatusMovedPermanently, callBackLoginUrl)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-23 15:02:11
@ 功能: 获取新权限
@ 参数
#systemName 系统
#roleId 角色Id
#orgId 行政组织ID
#postId 岗位ID
@ 返回值
#menuPower 菜单权限
#operationPower 操作权限
@ 方法原型
#GetRoleAndPostPower(systemName , roleId string, orgId, postId int64) (menuPower, operationPower string)
*/
func GetRoleAndPostPower(systemName, roleId string, orgId, postId int64) (menuPower, operationPower string) {
var menuAry []string
var operationAry []string
if roleId != "" {
roleIdAry := strings.Split(roleId, ",")
if len(roleIdAry) > 0 {
var roleContList []modelssystempermission.RoleEmpower
// err := roleCont.GetCont(map[string]interface{}{"`system`": systemName, "`role_id`": roleId}, "`point_id`", "`operation`")
err := overall.CONSTANT_DB_System_Permission.Model(&modelssystempermission.RoleEmpower{}).Select("`point_id`,`operation`,`level`").Where("`system` = ? AND `role_id` IN ?", systemName, roleIdAry).Find(&roleContList).Error
if err == nil && len(roleContList) > 0 {
for _, rev := range roleContList {
menuList := strings.Split(rev.PointId, ",")
for _, mv := range menuList { //菜单权限
if publicmethod.IsInTrue[string](mv, menuAry) == false {
menuAry = append(menuAry, mv)
}
}
operList := strings.Split(rev.Operation, ",")
for _, ov := range operList { //操作权限
if publicmethod.IsInTrue[string](ov, operationAry) == false {
operationAry = append(operationAry, ov)
}
}
}
}
}
}
if orgId != 0 && postId != 0 {
var postCont modelssystempermission.Empower
err := postCont.GetCont(map[string]interface{}{"`system`": systemName, "`organization`": orgId, "`post_id`": postId}, "`point_id`", "`operation`")
if err == nil {
if postCont.PointId != "" {
if len(menuAry) < 1 {
menuAry = strings.Split(postCont.PointId, ",")
} else {
guoduPostAry := strings.Split(postCont.PointId, ",")
for _, v := range guoduPostAry {
if publicmethod.IsInTrue[string](v, menuAry) == false {
menuAry = append(menuAry, v)
}
}
}
}
if postCont.Operation != "" {
if len(operationAry) < 1 {
operationAry = strings.Split(postCont.Operation, ",")
} else {
guoduPostAryOp := strings.Split(postCont.Operation, ",")
for _, v := range guoduPostAryOp {
if publicmethod.IsInTrue[string](v, operationAry) == false {
operationAry = append(operationAry, v)
}
}
}
}
}
}
if len(menuAry) > 1 {
menuPower = strings.Join(menuAry, ",")
}
if len(operationAry) > 1 {
operationPower = strings.Join(operationAry, ",")
}
return
}

142
api/empower/authorize/empower.go

@ -1,10 +1,12 @@
package authorize
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall"
"strconv"
"strings"
"github.com/gin-gonic/gin"
@ -145,3 +147,143 @@ func (e *EmpowerApi) Encryption(c *gin.Context) {
outputCont["step"] = dfg
publicmethod.Result(0, outputCont, c)
}
// 写入令牌
func (a *EmpowerApi) WriteToken(c *gin.Context) {
var requestData WriteIderCont
err := c.ShouldBindJSON(&requestData)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if requestData.Openid == "" || requestData.Key == "" || requestData.Token == "" {
publicmethod.Result(101, err, c)
return
}
if requestData.UserInfo.Number == "" || requestData.UserInfo.Password == "" || requestData.UserInfo.Key == "" {
publicmethod.Result(101, err, c)
return
}
var userCont modelshr.ManCont
err = userCont.GetCont(map[string]interface{}{"`number`": requestData.UserInfo.Number, "`key`": requestData.UserInfo.Key, "`password`": requestData.UserInfo.Password})
if err != nil {
publicmethod.Result(105, err, c)
return
}
if requestData.Openid != userCont.Wechat && requestData.Openid != userCont.WorkWechat {
publicmethod.Result(105, err, c)
return
}
_, pointId, operation, _ := publicmethod.GetNewAccredit("cangchu", userCont.Role, userCont.Key, userCont.AdminOrg, userCont.Position)
saveData := publicmethod.MapOut[string]()
saveData["key"] = requestData.Key
saveData["token"] = requestData.Token
saveData["userinfo"] = userCont
writeRedisData := map[string]interface{}{
"userkey": requestData.Key,
"key": userCont.Key,
"usernumber": userCont.Number,
"userpwd": userCont.Password,
"usertoken": requestData.Token,
"jurisdiction": operation,
"menuOper": pointId,
"wand": 118,
}
var surisdictionStr []string
var surisdictionInt []int64
jsonErr := json.Unmarshal([]byte(operation), &surisdictionStr)
if jsonErr == nil {
for _, jurVal := range surisdictionStr {
jurValInt, jurValErr := strconv.ParseInt(jurVal, 10, 64)
if jurValErr == nil {
surisdictionInt = append(surisdictionInt, jurValInt)
}
}
}
var menuOperStr []string
var menuOperInts []int64
menuOperStr = strings.Split(pointId, ",")
for _, menuOperVal := range menuOperStr {
menuOperInt, menuOperErr := strconv.ParseInt(menuOperVal, 10, 64)
if menuOperErr == nil {
menuOperInts = append(menuOperInts, menuOperInt)
}
}
// redisFileKey := "ScanCode:Authentication:LoginApi_" + global.GVA_CONFIG.RedisPrefix.Alias + "_" + userKeyCode
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, requestData.Key)
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
redisClient.SetRedisTime(10800)
redisClient.HashMsetAdd(redisFileKey, writeRedisData)
//缓存写入个人信息
redisMyContKey := fmt.Sprintf("ScanCode:Authentication:UserCont_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, userCont.Number)
myCont := publicmethod.MapOut[string]()
myCont["id"] = userCont.Id
myCont["number"] = userCont.Number //员工工号
myCont["name"] = userCont.Name //姓名
myCont["icon"] = userCont.Icon //头像
myCont["hireclass"] = userCont.HireClass //雇佣类型(1:雇佣入职;2:再入职;)
myCont["emptype"] = userCont.EmpType //用工关系(1:临时工 , 2:编外人员 ;3:实习&实习生;4:试用员工;5:待分配;6:待岗;7:临时调入;8:正式员工;9:长期病假;10:停薪留职;11:退休;12:辞职;13:辞退;14:离职)
myCont["company"] = userCont.Company //入职公司
myCont["maindeparment"] = userCont.MainDeparment //主部门
myCont["sunmaindeparment"] = userCont.SunMainDeparment //二级主部门
myCont["deparment"] = userCont.Deparment //部门
myCont["adminorg"] = userCont.AdminOrg //所属行政组织
myCont["teamid"] = userCont.TeamId //班组
myCont["position"] = userCont.Position //职位
myCont["jobclass"] = userCont.JobClass //职务分类
myCont["jobid"] = userCont.JobId //职务
myCont["jobleve"] = userCont.JobLeve //职务等级
myCont["wechat"] = userCont.Wechat //微信UserId
myCont["workwechat"] = userCont.WorkWechat //企业微信UserId
myCont["state"] = userCont.State //状态(1:启用;2:禁用;3:删除)
myCont["key"] = userCont.Key //key
myCont["isadmin"] = userCont.IsAdmin //是否为管理员(1:不是;2:分公司;3:集团管理员;4:超级管
myCont["password"] = userCont.Password //密码
myCont["role"] = userCont.Role //角色
myCont["idcardno"] = userCont.Idcardno //身份证号
myCont["passportno"] = userCont.Passportno //护照号码
myCont["globalroaming"] = userCont.Globalroaming //国际区号
myCont["mobilephone"] = userCont.Mobilephone //手机号码
myCont["email"] = userCont.Email //电子邮件
myCont["gender"] = userCont.Gender //性别(1:男性;2:女性;3:中性)
myCont["birthday"] = userCont.Birthday //birthday
myCont["myfolk"] = userCont.Myfolk //民族
myCont["nativeplace"] = userCont.Nativeplace //籍贯
myCont["idcardstartdate"] = userCont.Idcardstartdate //身份证有效期开始
myCont["idcardenddate"] = userCont.Idcardenddate //身份证有效期结束
myCont["idcardaddress"] = userCont.Idcardaddress //身份证地址
myCont["idcardIssued"] = userCont.IdcardIssued //身份证签发机关
myCont["health"] = userCont.Health //健康状况(1:良好;2:一般;3:较弱,4:有生理缺陷;5:残废)
myCont["maritalstatus"] = userCont.Maritalstatus //婚姻状况(1:未婚;2:已婚;3:丧偶;4:离异)
myCont["internaltelephone"] = userCont.Internaltelephone //内线电话
myCont["currentresidence"] = userCont.Currentresidence //现居住地址
myCont["constellationing"] = userCont.Constellation //星座(1:白羊座;2:金牛座;3:双子座;4:巨蟹座;5:狮子座;6:处女座;7:天枰座;8:天蝎座;9:射手座;10:摩羯座;11:水瓶座;12:双鱼座)
myCont["isdoubleworker"] = userCont.Isdoubleworker //是否双职工(1:是;2:否)
myCont["isveterans"] = userCont.Isveterans //是否为退役军人(1:是;2:否)
myCont["veteransnumber"] = userCont.Veteransnumber //退役证编号
myCont["jobstartdate"] = userCont.Jobstartdate //参加工作日期
myCont["entrydate"] = userCont.Entrydate //入职日期
myCont["probationperiod"] = userCont.Probationperiod //试用期
myCont["planformaldate"] = userCont.Planformaldate //预计转正日期
myCont["political_outlook"] = userCont.PoliticalOutlook //政治面貌(1:群众;2:无党派;3:台盟会员;4:九三社员;5:致公党员;6:农工党员;7:民进会员;8:民建会员;9:民盟盟员;10:民革会员,11:共青团员;12:预备党员;13:中共党员)
var companyCont modelshr.AdministrativeOrganization
companyCont.GetCont(map[string]interface{}{"`id`": userCont.Company}, "`name`")
myCont["companyname"] = companyCont.Name
var departmentCont modelshr.AdministrativeOrganization
departmentCont.GetCont(map[string]interface{}{"`id`": userCont.MainDeparment}, "`name`")
myCont["maindeparmentname"] = departmentCont.Name
var postInfo modelshr.Position
postInfo.GetCont(map[string]interface{}{"`id`": userCont.Position}, "`name`")
myCont["positionname"] = postInfo.Name
redisClient.HashMsetAdd(redisMyContKey, myCont)
saveData["usercont"] = myCont
// fmt.Printf("redisMyContKey------Login----->%v\n", redisMyContKey)
publicmethod.Result(0, saveData, c)
}

25
api/empower/authorize/type.go

@ -8,34 +8,49 @@ import (
type EmpowerApi struct{}
//入口
// 入口
func (e *EmpowerApi) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["entry"] = "授权入口"
publicmethod.Result(0, outputCont, c)
}
//授权
// 授权
type gainAuthorize struct {
UserNumber string `json:"username"`
Password string `json:"password"`
}
//输出Token
// 输出Token
type SendToken struct {
Token string `json:"token"`
Number string `json:"number"`
}
//保存Redis Token
// 保存Redis Token
type SaveToken struct {
Number string `json:"number"` //随机数
UserKey string `json:"userkey"` //用户名
PassWord string `json:"password"` //密码
}
//加密参数
// 加密参数
type EncryptionData struct {
Number string `json:"number"`
AppKey string `json:"appkey"`
}
// 写入身份认证
type WriteIderCont struct {
Openid string `json:"openid"`
Key string `json:"key"`
Token string `json:"token"`
UserInfo UserInfoCont `json:"userinfo"`
}
// 人员信息
type UserInfoCont struct {
Number string `json:"number"`
Password string `json:"password"`
Key string `json:"key"`
}

241
api/shiyan/maptostruct/cang_chu.go

@ -0,0 +1,241 @@
package maptostruct
import (
"fmt"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/models/modelsstorage"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2022-11-14 16:43:22
@ 功能: 实验仓储类型树
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) CangChuThree(c *gin.Context) {
var mType []modelsstorage.MaterialType
overall.CONSTANT_DB_Storage.Where("`state` = 1").Find(&mType)
var toalVal int64
// overall.CONSTANT_DB_Storage.Model(&modelsstorage.Material{}).Where("`state` = 1").Count(&toalVal)
// var materList []modelsstorage.Material
// err = overall.CONSTANT_DB_Storage.Find(&materList).Error
// var jibuq []int
// toalVal := 0
var mTypeGroup []modelsstorage.MaterialType
var mttt readDataLock
for i, v := range mType {
if (i+1)%100 == 0 {
syncSeting.Add(1)
mTypeGroup = append(mTypeGroup, v)
go mttt.chuLiType(mTypeGroup, toalVal)
mTypeGroup = []modelsstorage.MaterialType{}
} else {
mTypeGroup = append(mTypeGroup, v)
}
// if i == 0 {
// // syncSeting.Add(1)
// mTypeGroup = append(mTypeGroup, v)
// // go mttt.chuLiType(mTypeGroup, toalVal)
// }
}
if len(mTypeGroup) > 0 {
syncSeting.Add(1)
go mttt.chuLiType(mTypeGroup, toalVal)
}
syncSeting.Wait()
// fmt.Printf("%v", mttt)
var chanzongshu int
chanzongshu = 0
for _, vvv := range mttt.MaterialAry {
chanzongshu = chanzongshu + len(vvv.MaterialList)
fmt.Printf("%v------>%v------>%v\n", vvv.Id, vvv.Name, len(vvv.MaterialList))
}
threeList := GetMenuThreePeiQuan(0, mttt.MaterialAry)
outData := publicmethod.MapOut[string]()
outData["mttt_count"] = len(mttt.MaterialAry)
outData["chanzongshu"] = chanzongshu
// outData["mtttList"] = mttt.MaterialAry
outData["threeList"] = threeList
fmt.Printf("%v------>%v------>%v------>%v\n", len(mType), toalVal, toalVal/1000, toalVal%1000)
publicmethod.Result(0, outData, c)
}
// 多类别数据处理
func (m *readDataLock) chuLiType(mType []modelsstorage.MaterialType, toalVal int64) {
defer syncSeting.Done()
var idList []int64
for _, v := range mType {
idList = append(idList, v.OrderId)
}
pageSum := toalVal / 1000
if toalVal%1000 > 0 {
pageSum = pageSum + 1
}
var i int64
for i = 1; i <= pageSum; i++ {
// pageSize := publicmethod.LimitPage64(i, 1000)
// fmt.Printf("第%v页,结束点%v\n", i, pageSize)
// syncSetings.Add(1)
// go m.Xiecheng(idList, pageSize, mType)
}
pageSize := publicmethod.LimitPage64(i, 1000)
syncSetings.Add(1)
go m.Xiecheng(idList, pageSize, mType)
syncSetings.Wait()
// fmt.Println("--------------------------------")
}
func (m *readDataLock) Xiecheng(id []int64, pageSize int64, mType []modelsstorage.MaterialType) {
defer syncSetings.Done()
// pageSizeStr := strconv.FormatInt(pageSize, 10)
// pageSizeInt, _ := strconv.Atoi(pageSizeStr)
var materList []modelsstorage.Material
// overall.CONSTANT_DB_Storage.Where("`type_id` IN ? AND `state` = 1", id).Limit(1000).Offset(pageSizeInt).Find(&materList)
overall.CONSTANT_DB_Storage.Where("`type_id` IN ? AND `state` = 1", id).Find(&materList)
for _, v := range mType {
var materialCont MaterialCont
materialCont.Id = v.Id //
materialCont.Name = v.Name // 类型名称"`
materialCont.Introduce = v.Introduce // 类型介绍"`
materialCont.State = v.State //状态(启用2禁用3删除4不对其做任何操作)"`
materialCont.ParentId = v.ParentId //父级"`
materialCont.OrderId = v.OrderId //导入时id"`
for _, mv := range materList {
if v.OrderId == mv.TypeId {
var materialcont modelsstorage.Material
materialcont.Id = mv.Id // `json:"id" gorm:"primaryKey;column:id;type:bigint(20) unsigned;not null;index"`
materialcont.DepositoryId = mv.DepositoryId // `json:"depositoryid" gorm:"column:depository_id;type:bigint(20) unsigned;default:0;not null;comment:仓库编号"`
materialcont.Name = mv.Name // `json:"name" gorm:"column:mname;type:varchar(100);comment:材料名称"`
materialcont.Quantity = mv.Quantity // `json:"quantity" gorm:"column:type;quantity:int(11) unsigned;default:1;not null;comment:数量"`
materialcont.Amounts = mv.Amounts // `json:"amounts" gorm:"column:amounts;type:int(11) unsigned;default:1;not null;comment:总金额"`
materialcont.TypeId = mv.TypeId // `json:"typeid" gorm:"column:type_id;type:bigint(20) unsigned;default:0;not null;comment:材料种类id"`
materialcont.State = mv.State // `json:"state" gorm:"column:state;type:int(1) unsigned;default:1;not null;comment:状态(1:启用;2:禁用;3:删除)"`
materialcont.Code = mv.Code // `json:"code" gorm:"column:code;type:varchar(255);comment:存货编码"`
materialcont.Version = mv.Version // `json:"version" gorm:"column:version;type:varchar(255);comment:规格型号"`
materialcont.Price = mv.Price // `json:"price" gorm:"column:price;type:int(11) unsigned;default:1;not null;comment:单价"`
materialcont.Unit = mv.Unit // `json:"unit" gorm:"column:unit;type:varchar(255);comment:计量单位"`
materialcont.Texture = mv.Texture // `json:"texture" gorm:"column:texture;type:varchar(255);comment:材质"`
materialcont.DepositoryCode = mv.DepositoryCode // `json:"depositoryCode" gorm:"column:depositoryCode;type:varchar(255);comment:货位码(存放位置)"`
materialcont.Kingdeecode = mv.Kingdeecode // `json:"kingdeecode" gorm:"column:kingdeecode;type:varchar(255);comment:计量单位"`
materialcont.NumberOfTemporary = mv.NumberOfTemporary // `json:"numberoftemporary" gorm:"column:number_of_temporary;type:int(11) unsigned;default:1;not null;comment:临时数目(临时出库数目)"`
materialCont.MaterialList = append(materialCont.MaterialList, materialcont)
}
}
m.MaterialAry = append(m.MaterialAry, materialCont)
}
}
// 递归无限极菜单树
/*
@parentId 上级ID
@threeData 结果值
*/
func GetMenuThreePeiQuan(parentId int64, threeData []MaterialCont) []CaiDanShu {
treeList := []CaiDanShu{}
for _, v := range threeData {
if v.ParentId == parentId {
child := GetMenuThreePeiQuan(v.OrderId, threeData)
var node CaiDanShu
node.Id = v.Id //
node.Name = v.Name // 类型名称"`
node.Introduce = v.Introduce // 类型介绍"`
node.State = v.State //状态(启用2禁用3删除4不对其做任何操作)"`
node.ParentId = v.ParentId //父级"`
node.OrderId = v.OrderId //导入时id"`
node.MaterialList = v.MaterialList
node.Child = child
treeList = append(treeList, node)
}
}
return treeList
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-08 15:25:49
@ 功能: 校正原审批流信息
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) CheckOldWorkflow(c *gin.Context) {
var oldFlowList []modelskpi.EvaluationProcess
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.EvaluationProcess{}).Where("ep_old = 1").Find(&oldFlowList).Error
if err == nil {
for _, v := range oldFlowList {
if v.TypeClass == 1 {
//定性
var scoreFlowCont modelskpi.ScoreFlow
errSore := scoreFlowCont.GetCont(map[string]interface{}{"`sf_key`": v.OrderKey})
if errSore == nil {
scoreEdit := publicmethod.MapOut[string]()
scoreEdit["ep_setup_department"] = scoreFlowCont.EvaluationDepartment
scoreEdit["ep_target"] = scoreFlowCont.TargetId
scoreEdit["ep_detailedtarget"] = scoreFlowCont.DetailedId
scoreEdit["ep_creater"] = scoreFlowCont.EvaluationUser
scoreEdit["ep_state"] = 4
scoreEdit["ep_next_step"] = 0
scoreEdit["ep_next_executor"] = ""
var editDingXingEvalPros modelskpi.EvaluationProcess
editDingXingEvalPros.EiteCont(map[string]interface{}{"`ep_id`": v.Id}, scoreEdit)
}
} else {
//定量
var dingLiangCont modelskpi.FlowLog
errSore := dingLiangCont.GetCont(map[string]interface{}{"`fl_key`": v.OrderKey})
if errSore == nil {
scoreEditLiang := publicmethod.MapOut[string]()
scoreEditLiang["ep_setup_department"] = dingLiangCont.EvaluationDepartment
var fldId []int64
overall.CONSTANT_DB_KPI.Model(&modelskpi.FlowLogData{}).Select("fld_target_id").Where("fld_flow_log = ?", v.OrderKey).Find(&fldId)
var idStr []string
for _, v := range fldId {
vInt := strconv.FormatInt(v, 10)
idStr = append(idStr, vInt)
}
scoreEditLiang["ep_target"] = strings.Join(idStr, ",")
scoreEditLiang["ep_creater"] = dingLiangCont.EvaluationUser
scoreEditLiang["ep_state"] = 4
scoreEditLiang["ep_next_step"] = 0
scoreEditLiang["ep_next_executor"] = ""
var editDingLiangEvalPros modelskpi.EvaluationProcess
editDingLiangEvalPros.EiteCont(map[string]interface{}{"`ep_id`": v.Id}, scoreEditLiang)
}
}
}
}
publicmethod.Result(0, err, c)
}

587
api/shiyan/maptostruct/department.go

@ -0,0 +1,587 @@
package maptostruct
import (
"fmt"
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// 验证指标关联部门与指标关联提报人数据
func (a *ApiMethod) CorrectingDepartAndMan(c *gin.Context) {
var targetList []modelskpi.EvaluationTarget
err := overall.CONSTANT_DB_KPI.Find(&targetList).Error
if err != nil {
publicmethod.Result(1, err, c, "没有数据")
return
}
for _, v := range targetList {
handDepartment(v)
}
}
// 处理部门指标,提报人关联关系
func handDepartment(targetCont modelskpi.EvaluationTarget) {
//提报部门关联关系
if targetCont.RelevantDepartments != "" {
orgIdStr := strings.Split(targetCont.RelevantDepartments, ",")
if len(orgIdStr) > 0 {
for _, ov := range orgIdStr {
handDepartmentTarget(targetCont.Dimension, targetCont.Id, 0, 0, 0, 1, 1, targetCont.Type, ov)
}
}
}
//提报人与指标关联关系
if targetCont.Report != "" {
reportKey := strings.Split(targetCont.Report, ",")
if len(reportKey) > 0 {
for _, rv := range reportKey {
handPeopleTarget(targetCont, rv)
}
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-07 11:05:21
@ 功能: 编辑部门字表关联关系
@ 参数
#dimensionId 纬度
#targetId 指标
#targetSunId 栏目
#targetBylaws 指标细则
#typeInt 类型1指标2子目标3细则
#orgId 行政组织
#postId 岗位
#class 1定性考核2定量考核
#level 级别1部门级2岗位级
@ 返回值
#err
@ 方法原型
#handDepartmentTarget(dimensionId, targetId, targetSunId, targetBylaws, postId int64, typeInt, level, class int, orgId string) (err error)
*/
func handDepartmentTarget(dimensionId, targetId, targetSunId, targetBylaws, postId int64, typeInt, level, class int, orgId string) (err error) {
var tarDepartCont modelskpi.TargetDepartment
err = tarDepartCont.GetCont(map[string]interface{}{"`target_id`": targetId, "`department_id`": orgId, "`target_sun_id`": targetSunId, "`target_bylaws`": targetBylaws, "`type`": typeInt, "`post_id`": postId, "`level`": level})
if err != nil {
var addCont modelskpi.TargetDepartment
addCont.Dimension = dimensionId //维度"`
addCont.TargetId = targetId //指标ID"`
addCont.TargetSunId = targetSunId //子目标"`
addCont.TargetBylaws = targetBylaws //指标细则"`
addCont.Type = typeInt //类型(1:指标;2:子目标;3:细则)"`
orgIdInt, _ := strconv.ParseInt(orgId, 10, 64)
addCont.DepartmentId = orgIdInt //部门ID"`
addCont.PostId = postId //岗位ID"`
addCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
addCont.Time = time.Now().Unix() //写入时间"`
addCont.Class = class //1:定性考核;2:定量考核"`
addCont.Level = 1 //:级别(1:部门级;2:岗位级)"`
err = overall.CONSTANT_DB_KPI.Create(&addCont).Error
} else {
editCont := publicmethod.MapOut[string]()
if tarDepartCont.State != 1 {
editCont["`state`"] = 1
}
if tarDepartCont.Class != class {
editCont["`class`"] = class
}
if tarDepartCont.Dimension != dimensionId {
editCont["`dimension_id`"] = dimensionId
}
// fmt.Printf("遍布------------------->%v----------->%v\n", tarDepartCont.Dimension, dimensionId)
if len(editCont) > 0 {
editCont["`time`"] = time.Now().Unix()
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Where("`id` = ?", tarDepartCont.Id).Updates(&editCont).Error
}
}
return
}
// 编辑部门指标提报人逻辑关系
func handPeopleTarget(targetCont modelskpi.EvaluationTarget, manKey string) (err error) {
orgIdStr := strings.Split(targetCont.RelevantDepartments, ",")
if len(orgIdStr) > 0 {
for _, ov := range orgIdStr {
err = handTarReport(targetCont.Dimension, targetCont.Id, 0, 0, 0, 1, targetCont.Type, 1, ov, manKey)
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-07 11:29:53
@ 功能: 处理指标提交人
@ 参数
#dimensionId 纬度
#targetId 指标
#targetSunId 栏目
#targetBylaws 指标细则
#orgId 行政组织ID
#postId 岗位
#typeInt 类型1公司级2部门级
#manKey 提报人Key
#class 1定性考核2定量考核
#level 1指标2子目标3细则
@ 返回值
#err
@ 方法原型
#handTarReport(dimensionId, targetId, targetSunId, targetBylaws, postId int64, typeInt, class, level int, orgId, manKey string) (err error)
*/
func handTarReport(dimensionId, targetId, targetSunId, targetBylaws, postId int64, typeInt, class, level int, orgId, manKey string) (err error) {
var tarReportCont modelskpi.TargetReport
err = tarReportCont.GetCont(map[string]interface{}{"`target_id`": targetId, "`target_sun_id`": targetSunId, "`target_bylaws`": targetBylaws, "`department_id`": orgId, "`post_id`": postId, "`type`": typeInt, "`man_key`": manKey, "`type_level`": level})
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": manKey}, "`maindeparment`")
if err != nil {
var addCont modelskpi.TargetReport
addCont.Dimension = dimensionId //维度"`
addCont.TargetId = targetId //指标ID"`
addCont.TargetSunId = targetSunId //子目标"`
addCont.TargetBylaws = targetBylaws //指标细则"`
orgIdInt, _ := strconv.ParseInt(orgId, 10, 64)
addCont.DepartmentId = orgIdInt //部门ID"`
addCont.PostId = postId //岗位ID"`
addCont.Type = typeInt //类型(1:公司级;2:部门级)"`
addCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
manKeyInt, _ := strconv.ParseInt(manKey, 10, 64)
addCont.ReportPerson = manKeyInt //上报人"`
addCont.ManDepartment = userCont.MainDeparment //提报人所在部门"`
addCont.Time = time.Now().Unix() //写入时间"`
addCont.Class = class //定性考核;2:定量考核"`
addCont.Level = level //类型(1:指标;2:子目标;3:细则)"`
err = overall.CONSTANT_DB_KPI.Create(&addCont).Error
} else {
editCont := publicmethod.MapOut[string]()
if tarReportCont.State != 1 {
editCont["`state`"] = 1
}
if tarReportCont.Class != class {
editCont["`class`"] = class
}
if tarReportCont.ManDepartment != userCont.MainDeparment {
editCont["`man_department`"] = userCont.MainDeparment
}
if tarReportCont.Dimension != dimensionId {
editCont["`dimension_id`"] = dimensionId
}
if len(editCont) > 0 {
editCont["`time`"] = time.Now().Unix()
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Where("`id` = ?", tarReportCont.Id).Updates(&editCont).Error
}
}
return
}
// 验证部门子栏目关联对照
func (a *ApiMethod) VerifDepartSonTarget(c *gin.Context) {
var qualTargetContList []modelskpi.QualitativeTarget
err := overall.CONSTANT_DB_KPI.Find(&qualTargetContList).Error
if err != nil || len(qualTargetContList) < 1 {
publicmethod.Result(1, err, c, "没有数据")
return
}
for _, v := range qualTargetContList {
if v.Depart != "" { //判断是否有关联部门
orgIdStr := strings.Split(v.Depart, ",") //转换程切片
if len(orgIdStr) > 0 {
var tarCont modelskpi.EvaluationTarget
tarCont.GetCont(map[string]interface{}{"`et_id`": v.ParentId}, "`et_dimension`", "`et_type`")
for _, ov := range orgIdStr { //循环处理栏目对照关系
handDepartmentTarget(tarCont.Dimension, v.ParentId, v.Id, 0, 0, 2, 1, tarCont.Type, ov)
}
}
}
}
publicmethod.Result(0, err, c)
}
// 验证部门指标细则关系对照
func (a *ApiMethod) VerifDepartDetasil(c *gin.Context) {
var detasilCont []modelskpi.DetailedTarget
err := overall.CONSTANT_DB_KPI.Find(&detasilCont).Error
if err != nil || len(detasilCont) < 1 {
publicmethod.Result(1, err, c, "没有数据")
return
}
for _, v := range detasilCont {
if v.Paretment != "" { //判断是否有关联部门
orgIdStr := strings.Split(v.Paretment, ",") //转换程切片部门
reportList := strings.Split(v.Reportary, ",") //转换程切片人
if len(orgIdStr) > 0 {
var tarCont modelskpi.EvaluationTarget
tarCont.GetCont(map[string]interface{}{"`et_id`": v.ParentId}, "`et_dimension`", "`et_type`")
for _, ov := range orgIdStr { //循环处理栏目对照关系
handDepartmentTarget(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 3, 1, tarCont.Type, ov)
if len(reportList) > 0 {
syncSeting.Add(1)
go ChuLiTiBaoRenGuoDu(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 1, tarCont.Type, 3, ov, reportList)
}
}
}
}
}
syncSeting.Wait()
publicmethod.Result(0, err, c)
}
// 处理提报人过度
/*
#dimensionId 纬度
#targetId 指标
#targetSunId 栏目
#targetBylaws 指标细则
#orgId 行政组织ID
#postId 岗位
#typeInt 类型1公司级2部门级
#manKey 提报人Key
#class 1定性考核2定量考核
#level 1指标2子目标3细则
*/
func ChuLiTiBaoRenGuoDu(dimensionId, targetId, targetSunId, targetBylaws, postId int64, typeInt, class, level int, orgId string, manKey []string) {
defer syncSeting.Done()
if len(manKey) > 0 {
for _, v := range manKey {
handTarReport(dimensionId, targetId, targetSunId, targetBylaws, postId, typeInt, class, level, orgId, v)
}
}
}
func ChuLiTiBaoRenGuoDuss(dimensionId, targetId, targetSunId, targetBylaws, postId int64, typeInt, class, level int, orgId string, manKey []string) {
if len(manKey) > 0 {
for _, v := range manKey {
handTarReport(dimensionId, targetId, targetSunId, targetBylaws, postId, typeInt, class, level, orgId, v)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-17 14:00:49
@ 功能: 校正被考核部门
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) XiangzhengBeikaoBumen(c *gin.Context) {
var receivedValue XiaoZengTime
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.DateTime == "" {
publicmethod.Result(100, err, c)
return
}
tayTime := time.Now().Unix()
currentYears := publicmethod.UnixTimeToDay(tayTime, 16)
currentMonths := publicmethod.UnixTimeToDay(tayTime, 17)
if receivedValue.DateTime != "" {
var dayTime publicmethod.DateTimeTotimes
dayTime.BaisStrToTime(receivedValue.DateTime)
if dayTime.Years != "" {
currentYears = dayTime.Years
}
if dayTime.Months != "" {
currentMonths = dayTime.Months
}
}
riQiStr := fmt.Sprintf("%v-%v", currentYears, currentMonths)
startTime, endTime := publicmethod.GetAppointMonthStarAndEndTime(riQiStr)
var evalProcess []modelskpi.EvaluationProcess
err = overall.CONSTANT_DB_KPI.Where("`ep_happen_time` BETWEEN ? AND ?", startTime, endTime).Find(&evalProcess).Error
if err != nil || len(evalProcess) < 1 {
publicmethod.Result(107, err, c)
return
}
for _, v := range evalProcess {
if v.TypeClass == 1 {
//定性
HuiGaiDingXing(v.OrderKey)
} else {
//定量
HuiGaiDingLiang(v.OrderKey)
}
}
publicmethod.Result(0, err, c)
}
// 回改定量考核部门
func HuiGaiDingLiang(key int64) {
var scoreFlowCont modelskpi.FlowLog
err := scoreFlowCont.GetCont(map[string]interface{}{"`fl_key`": key}, "`fl_duty_department`")
if err == nil {
if scoreFlowCont.DutyDepartment != 0 {
var evalProCont modelskpi.EvaluationProcess
evalProCont.EiteCont(map[string]interface{}{"`ep_order_key`": key}, map[string]interface{}{"`ep_accept_department`": scoreFlowCont.DutyDepartment})
}
}
}
// 回改定性考核部门
func HuiGaiDingXing(key int64) {
var scoreFlowCont modelskpi.ScoreFlow
err := scoreFlowCont.GetCont(map[string]interface{}{"`sf_key`": key}, "`sf_duty_department`")
if err == nil {
if scoreFlowCont.DutyDepartment != 0 {
var evalProCont modelskpi.EvaluationProcess
evalProCont.EiteCont(map[string]interface{}{"`ep_order_key`": key}, map[string]interface{}{"`ep_accept_department`": scoreFlowCont.DutyDepartment})
}
}
}
// 验证工作流
func (a *ApiMethod) TestAndVerifyWorkflow(c *gin.Context) {
var receivedValue publicmethod.PublicId
c.ShouldBindJSON(&receivedValue)
//自定义判断
var zdyPd []currency_recipe.CustomFields
var zdyPdOne currency_recipe.CustomFields
zdyPdOne.WordField = "attribute"
zdyPdOne.LeftVal = "1"
zdyPd = append(zdyPd, zdyPdOne)
var zdyPdTwo currency_recipe.CustomFields
zdyPdTwo.WordField = "correct"
zdyPdTwo.LeftVal = "1"
zdyPd = append(zdyPd, zdyPdTwo)
//条件设定
var tijiao1 currency_recipe.JudgingCondition
tijiao1.Class = 1
tijiao1.MyCustom = zdyPd
var workflowInfo currency_recipe.WorkflowEngine
workflowInfo.JudCond = append(workflowInfo.JudCond, tijiao1)
// workflowInfo.VersionId = "1"
jieguo := workflowInfo.InitWorkflow(receivedValue.Id, "", "16047344045376832", "103").SendData()
if jieguo.IsTrue != true {
publicmethod.Result(1000, jieguo, c)
} else {
publicmethod.Result(0, jieguo, c)
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-10 15:09:21
@ 功能: 校正指标细则关联关系
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) XiaoZhengBumenBylaws(c *gin.Context) {
var detasilCont []modelskpi.DetailedTarget
// err := overall.CONSTANT_DB_KPI.Where("`dt_id` = 806").Find(&detasilCont).Error
err := overall.CONSTANT_DB_KPI.Find(&detasilCont).Error
if err != nil || len(detasilCont) < 1 {
publicmethod.Result(1, err, c, "没有数据")
return
}
var fenZhu []modelskpi.DetailedTarget
jbq := 0
for i, v := range detasilCont {
if (i+1)%300 == 0 {
jbq++
fenZhu = append(fenZhu, v)
fmt.Printf("满100分组---->%v---->%v---->%v---->%v\n", i, jbq, len(fenZhu), (i+1)%100)
syncSetings.Add(1)
go XiaoZhengCont(fenZhu)
var newFenzu []modelskpi.DetailedTarget
fenZhu = newFenzu
} else {
fenZhu = append(fenZhu, v)
}
}
if len(fenZhu) > 0 {
syncSetings.Add(1)
go XiaoZhengCont(fenZhu)
jbq++
fmt.Printf("还有剩余得---->%v---->%v\n", jbq, len(fenZhu))
}
syncSetings.Wait()
publicmethod.Result(0, jbq, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-10 15:15:38
@ 功能: 部门细则校正操作
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func XiaoZhengCont(bylawsList []modelskpi.DetailedTarget) {
defer syncSetings.Done()
if len(bylawsList) > 0 {
for _, v := range bylawsList {
//获取指标内容
var tarCont modelskpi.EvaluationTarget
tarCont.GetCont(map[string]interface{}{"`et_id`": v.ParentId}, "`et_dimension`", "`et_type`", "`et_relevant_departments`", "`et_report`")
orgIdStr := strings.Split(v.Paretment, ",") //关联部门
reportList := strings.Split(v.Reportary, ",") //关联提报人
if v.Paretment != "" && v.Reportary != "" {
fmt.Printf("人员信息----1----》%v----》%v----》%v\n", reportList, v.Reportary, len(reportList))
for _, ov := range orgIdStr { //循环处理栏目对照关系
handDepartmentTarget(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 3, 1, tarCont.Type, ov)
if len(reportList) > 0 {
syncSeting.Add(1)
go ChuLiTiBaoRenGuoDu(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 1, tarCont.Type, 3, ov, reportList)
}
}
}
if v.Paretment != "" && v.Reportary == "" && tarCont.Report != "" {
reportDepartList := strings.Split(tarCont.Report, ",") //关联提报人
fmt.Printf("人员信息----2----》%v\n", reportDepartList)
for _, ov := range orgIdStr { //循环处理栏目对照关系
handDepartmentTarget(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 3, 1, tarCont.Type, ov)
syncSeting.Add(1)
go ChuLiTiBaoRenGuoDu(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 1, tarCont.Type, 3, ov, reportDepartList)
}
}
if v.Paretment == "" && v.Reportary != "" && tarCont.RelevantDepartments != "" {
orgDepartIdStr := strings.Split(tarCont.RelevantDepartments, ",") //关联部门
fmt.Printf("人员信息----3----》%v\n", reportList)
for _, ov := range orgDepartIdStr { //循环处理栏目对照关系
handDepartmentTarget(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 3, 1, tarCont.Type, ov)
if len(reportList) > 0 {
syncSeting.Add(1)
go ChuLiTiBaoRenGuoDu(tarCont.Dimension, v.ParentId, v.ParentIdSun, v.Id, 0, 1, tarCont.Type, 3, ov, reportList)
}
}
}
}
syncSeting.Wait()
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-15 08:19:52
@ 功能: 校正方案提报人
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) XiaoZhengFangAn(c *gin.Context) {
var shemeList []modelskpi.QualitativeEvaluation
err := overall.CONSTANT_DB_KPI.Where("qe_state = 1").Find(&shemeList).Error
if err != nil || len(shemeList) <= 0 {
publicmethod.Result(1, err, c, "没有数据")
return
}
var fenZhu []modelskpi.QualitativeEvaluation
jbq := 0
for i, v := range shemeList {
if (i+1)%1000 == 0 {
jbq++
fenZhu = append(fenZhu, v)
fmt.Printf("满1000分组---->%v---->%v---->%v---->%v\n", i, jbq, len(fenZhu), (i+1)%100)
syncSetings.Add(1)
go XiaoZhengSchemeData(fenZhu)
var newFenzu []modelskpi.QualitativeEvaluation
fenZhu = newFenzu
} else {
fenZhu = append(fenZhu, v)
}
}
if len(fenZhu) > 0 {
syncSetings.Add(1)
go XiaoZhengSchemeData(fenZhu)
jbq++
fmt.Printf("还有剩余得---->%v---->%v\n", jbq, len(fenZhu))
}
syncSetings.Wait()
publicmethod.Result(0, fenZhu, c)
}
// 校正方案数据
func XiaoZhengSchemeData(shemeList []modelskpi.QualitativeEvaluation) {
defer syncSetings.Done()
if len(shemeList) > 0 {
for _, v := range shemeList {
//获取指标内容
var tarCont modelskpi.EvaluationTarget
tarCont.GetCont(map[string]interface{}{"`et_id`": v.Target}, "`et_dimension`", "`et_type`", "`et_relevant_departments`", "`et_report`")
accDepart := strconv.FormatInt(v.AcceptEvaluation, 10)
handDepartmentTarget(tarCont.Dimension, v.Target, v.TargetSun, v.DetailedTarget, 0, 3, 1, v.Type, accDepart)
if v.Operator != "" {
reportList := strings.Split(v.Operator, ",") //关联提报人
// ChuLiTiBaoRenGuoDuss(tarCont.Dimension, v.Target, v.TargetSun, v.DetailedTarget, 0, 1, v.Type, 3, accDepart, reportList)
syncSeting.Add(1)
go ChuLiTiBaoRenGuoDu(tarCont.Dimension, v.Target, v.TargetSun, v.DetailedTarget, 0, 1, v.Type, 3, accDepart, reportList)
}
}
}
syncSeting.Wait()
}

317
api/shiyan/maptostruct/maptostr.go

@ -1,13 +1,19 @@
package maptostruct
import (
"encoding/xml"
"fmt"
"key_performance_indicators/middleware/wechatapp/wechatcallback"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"time"
"github.com/gin-gonic/gin"
)
//map 装 struct 实验
// map 装 struct 实验
func (a *ApiMethod) MapToStructShiyan(c *gin.Context) {
mapShiyan := map[string]string{
"name": "秦东",
@ -26,3 +32,312 @@ func (a *ApiMethod) MapToStructShiyan(c *gin.Context) {
fmt.Printf("shiyanType---->%v\n", shiyanVal)
publicmethod.Result(0, shiyanVal, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-06 11:08:11
@ 功能: 模拟回调
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) SimulationCallBack(c *gin.Context) {
var receivedValue callBackCont
c.ShouldBindJSON(&receivedValue)
var jieMiCont wechatcallback.DecryptMsgCont
jieMiCont.MsgSignature = receivedValue.MsgSignature
jieMiCont.Timestamp = receivedValue.Timestamp
jieMiCont.Nonce = receivedValue.Nonce
jieMiCont.ToUsername = receivedValue.ToUsername
jieMiCont.Agentid = receivedValue.Agentid
jieMiCont.Encrypt = receivedValue.Encrypt
decryptMsgCont, jsonErr := jieMiCont.DecryptMsgInfo()
fmt.Printf("Xml----->%v----->%v\n\n", string(decryptMsgCont), jsonErr)
var msgCont wechatcallback.MsgContentXml
errXml := xml.Unmarshal(decryptMsgCont, &msgCont)
if errXml != nil {
fmt.Printf("回调事件失败!%v\n", errXml)
return
}
fmt.Printf("XmlCont----->%v\n\nwxcptJson----->%v\n\n", string(decryptMsgCont), msgCont)
switch msgCont.MsgType {
/*消息格式类型
*/
case "text": //文本
case "image": //图片
case "voice": //语音
case "video": //视频
case "location": //位置
wechatcallback.GeographicalPosition(decryptMsgCont)
case "link": //链接
/*事件格式类型*/
case "event":
/*
事件附属格式
*/
wechatcallback.EventProcessing(decryptMsgCont, jieMiCont, c)
// return
default:
}
// outData := publicmethod.MapOut[string]()
// outData["Xml"] = string(decryptMsgCont)
// outData["jieMiCont"] = jieMiCont
// outData["jsonErr"] = jsonErr
// outData["msgCont"] = msgCont
// publicmethod.Result(0, outData, c)
}
// 设置HR系统对接账号和密码
func (a *ApiMethod) SetUpHrSystem(c *gin.Context) {
var receivedValue hrUsernameAndPassword
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
var hrCont modelshr.EmpowerUser
err = hrCont.GetCont(map[string]interface{}{"`userkey`": receivedValue.Username}, "`id`")
if err == nil {
publicmethod.Result(1, err, c, "该授权已经存在!请不要重复!")
return
}
//密码加密
var passWordMd5 publicmethod.Md5Encryption
passWordMd5.Md5EncryptionInit(receivedValue.Password)
passWordMd5Str := passWordMd5.Md5EncryptionAlgorithm()
hrCont.UserKey = receivedValue.Username
hrCont.Password = passWordMd5Str
hrCont.Name = receivedValue.Name
hrCont.State = 1
hrCont.Time = time.Now().Unix()
hrCont.EiteTime = time.Now().Unix()
hrCont.VerificationCode = receivedValue.VerificationCode
err = overall.CONSTANT_DB_HR.Create(&hrCont).Error
if err != nil {
publicmethod.Result(104, err, c)
return
}
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-05 13:25:07
@ 功能: 审批流规制发生时间
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EvalProcTime(c *gin.Context) {
var listCont []modelskpi.EvaluationProcess
err := overall.CONSTANT_DB_KPI.Find(&listCont).Error
var dingXingOrd []int64
var dingLiangOrd []int64
if err == nil {
for _, v := range listCont {
if v.TypeClass == 1 {
if publicmethod.IsInTrue[int64](v.OrderKey, dingXingOrd) == false {
dingXingOrd = append(dingXingOrd, v.OrderKey)
}
} else {
if publicmethod.IsInTrue[int64](v.OrderKey, dingLiangOrd) == false {
dingLiangOrd = append(dingLiangOrd, v.OrderKey)
}
}
}
}
syncSeting.Add(1)
go DingXingJiaoDui(dingXingOrd)
syncSeting.Add(1)
go DingLiangJiaoDui(dingLiangOrd)
syncSeting.Wait()
outData := publicmethod.MapOut[string]()
outData["err"] = err
outData["dingXingOrd"] = dingXingOrd
outData["dingXingOrdCount"] = len(dingXingOrd)
outData["dingLiangOrd"] = dingLiangOrd
outData["dingLiangOrdCount"] = len(dingLiangOrd)
publicmethod.Result(0, outData, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-05 13:40:35
@ 功能: 定性审批流校对
@ 参数
#ordId 审批单ID
@ 返回值
#
@ 方法原型
#
*/
func DingXingJiaoDui(ordId []int64) {
defer syncSeting.Done()
if len(ordId) > 100 {
var fenPi []int64
for i, v := range ordId {
if publicmethod.IsInTrue[int64](v, fenPi) == false {
fenPi = append(fenPi, v)
}
if (i+1)%100 == 0 {
syncSetings.Add(1)
go EditEvalProcDingXing(fenPi)
// fmt.Printf("%v--------->%v--------->%v\n", i, len(fenPi), fenPi)
fenPi = []int64{}
}
}
if len(fenPi) > 0 {
syncSetings.Add(1)
go EditEvalProcDingXing(fenPi)
}
syncSetings.Wait()
// fmt.Printf("结束--------->%v--------->%v\n", len(fenPi), fenPi)
} else {
if len(ordId) > 0 {
for _, v := range ordId {
var scoreFlowCont modelskpi.ScoreFlow
err := scoreFlowCont.GetCont(map[string]interface{}{"`sf_key`": v}, "`sf_happen_time`", "`sf_duty_department`")
if err == nil {
saveData := publicmethod.MapOut[string]()
saveData["ep_happen_time"] = scoreFlowCont.HappenTime
saveData["ep_accept_department"] = scoreFlowCont.DutyDepartment
saveData["ep_time"] = time.Now().Unix()
var editEvalProce modelskpi.EvaluationProcess
editEvalProce.EiteCont(map[string]interface{}{"`ep_order_key`": v}, saveData)
}
}
}
}
}
func EditEvalProcDingXing(ordId []int64) {
defer syncSetings.Done()
if len(ordId) > 0 {
for _, v := range ordId {
var scoreFlowCont modelskpi.ScoreFlow
err := scoreFlowCont.GetCont(map[string]interface{}{"`sf_key`": v}, "`sf_happen_time`", "`sf_duty_department`")
if err == nil {
saveData := publicmethod.MapOut[string]()
saveData["ep_happen_time"] = scoreFlowCont.HappenTime
saveData["ep_accept_department"] = scoreFlowCont.DutyDepartment
saveData["ep_time"] = time.Now().Unix()
var editEvalProce modelskpi.EvaluationProcess
editEvalProce.EiteCont(map[string]interface{}{"`ep_order_key`": v}, saveData)
}
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-05 13:40:35
@ 功能: 定量审批流校对
@ 参数
#ordId 审批单ID
@ 返回值
#
@ 方法原型
#
*/
func DingLiangJiaoDui(ordId []int64) {
defer syncSeting.Done()
if len(ordId) > 100 {
var fenPi []int64
for i, v := range ordId {
if publicmethod.IsInTrue[int64](v, fenPi) == false {
fenPi = append(fenPi, v)
}
if (i+1)%100 == 0 {
syncSetings.Add(1)
go EditEvalProcDingLiang(fenPi)
// fmt.Printf("定量----》%v--------->%v--------->%v\n", i, len(fenPi), fenPi)
fenPi = []int64{}
}
}
if len(fenPi) > 0 {
syncSetings.Add(1)
go EditEvalProcDingLiang(fenPi)
}
syncSetings.Wait()
// fmt.Printf("定量----》结束--------->%v--------->%v\n", len(fenPi), fenPi)
} else {
if len(ordId) > 0 {
for _, v := range ordId {
var flowLogCont modelskpi.FlowLog
err := flowLogCont.GetCont(map[string]interface{}{"`fl_key`": v}, "`fl_year`", "`fl_month`", "`fl_day`", "`fl_duty_department`")
if err == nil {
monthStr := fmt.Sprintf("%v", flowLogCont.Month)
if flowLogCont.Month <= 9 {
monthStr = fmt.Sprintf("0%v", flowLogCont.Month)
}
dayStr := fmt.Sprintf("%v", flowLogCont.ToDay)
if flowLogCont.ToDay <= 9 {
dayStr = fmt.Sprintf("0%v", flowLogCont.ToDay)
}
saveData := publicmethod.MapOut[string]()
saveData["ep_happen_time"] = publicmethod.DateToTimeStampOld(fmt.Sprintf("%v-%v-%v 12:00:00", flowLogCont.Year, monthStr, dayStr))
saveData["ep_accept_department"] = flowLogCont.DutyDepartment
saveData["ep_time"] = time.Now().Unix()
var editEvalProce modelskpi.EvaluationProcess
editEvalProce.EiteCont(map[string]interface{}{"`ep_order_key`": v}, saveData)
}
}
}
}
}
func EditEvalProcDingLiang(ordId []int64) {
defer syncSetings.Done()
if len(ordId) > 0 {
for _, v := range ordId {
var flowLogCont modelskpi.FlowLog
err := flowLogCont.GetCont(map[string]interface{}{"`fl_key`": v}, "`fl_year`", "`fl_month`", "`fl_day`", "`fl_duty_department`")
if err == nil {
monthStr := fmt.Sprintf("%v", flowLogCont.Month)
if flowLogCont.Month <= 9 {
monthStr = fmt.Sprintf("0%v", flowLogCont.Month)
}
dayStr := fmt.Sprintf("%v", flowLogCont.ToDay)
if flowLogCont.ToDay <= 9 {
dayStr = fmt.Sprintf("0%v", flowLogCont.ToDay)
}
timeString := fmt.Sprintf("%v-%v-%v 12:00:00", flowLogCont.Year, monthStr, dayStr)
fmt.Printf("定量---->%v---------->%v\n", v, timeString)
saveData := publicmethod.MapOut[string]()
saveData["ep_happen_time"] = publicmethod.DateToTimeStampOld(timeString)
saveData["ep_accept_department"] = flowLogCont.DutyDepartment
saveData["ep_time"] = time.Now().Unix()
var editEvalProce modelskpi.EvaluationProcess
editEvalProce.EiteCont(map[string]interface{}{"`ep_order_key`": v}, saveData)
}
}
}
}

433
api/shiyan/maptostruct/sendwechat.go

@ -0,0 +1,433 @@
package maptostruct
import (
"encoding/json"
"fmt"
"key_performance_indicators/api/workwechat"
"key_performance_indicators/middleware/grocerystore"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-04-14 08:29:21
@ 功能: 发送文本信息
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SendMessage(c *gin.Context) {
var receivedValue publicmethod.PublicName
c.ShouldBindJSON(&receivedValue)
if receivedValue.Name == "" {
receivedValue.Name = "KaiXinGuo"
}
var sendMsg workwechat.SentMessage
sendMsg.ToUser = receivedValue.Name
sendMsg.MsgType = "template_card"
sendMsg.AgentId = 1000036
sendMsg.EnableIdTrans = 0
sendMsg.EnableDuplicateCheck = 0
sendMsg.DuplicateCheckInterval = 1800
var templateCard workwechat.TemplateCardMsgCont
templateCard.CardType = "text_notice"
//头部左标题部分
templateCard.Source.IconUrl = "https://docu.hxgk.group/images/2022_01/3f7a1120a559e9bee3991b85eb34d103.png"
templateCard.Source.Desc = "恒信高科头部信息"
templateCard.Source.DescColor = 1
//头部下拉菜单部分
templateCard.ActionMenu.Desc = "头部下拉"
var actionContOne workwechat.ActionListCont
actionContOne.Text = "头部下拉选项一"
actionContOne.Key = "head_click_1"
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, actionContOne)
var actionContTwo workwechat.ActionListCont
actionContTwo.Text = "头部下拉选项二"
actionContTwo.Key = "head_click_2"
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, actionContTwo)
//任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成
templateCard.TaskId = fmt.Sprintf("task_%v", publicmethod.GetUUid(5))
//主内容框
templateCard.MainTitle.Title = "主内容标题"
templateCard.MainTitle.Desc = "主内容"
//引用文献样式
templateCard.QuoteArea.Type = 1
templateCard.QuoteArea.Url = "https://work.weixin.qq.com"
templateCard.QuoteArea.Title = "企业微信的引用样式标题"
templateCard.QuoteArea.QuoteText = "企业微信的引用样式内容"
//关键数据样式
templateCard.EmphasisContent.Title = "100"
templateCard.EmphasisContent.Desc = "核心数据"
//二级普通文本,建议不超过160个字
templateCard.SubTitleText = "二级普通文本,建议不超过160个字"
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
var hcListCont1 workwechat.HorizontalContentListCont
hcListCont1.Type = 0
hcListCont1.Keyname = "姓名:"
hcListCont1.Value = "秦东"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont1)
var hcListCont2 workwechat.HorizontalContentListCont
hcListCont2.Type = 1
hcListCont2.Keyname = "企业微信官网"
hcListCont2.Value = "点击访问"
hcListCont2.Url = "https://work.weixin.qq.com"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont2)
var hcListCont3 workwechat.HorizontalContentListCont
hcListCont3.Type = 3
hcListCont3.Keyname = "姓名"
hcListCont3.Value = "开心果"
hcListCont3.UserId = "KaiXinGuo"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont3)
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
var jmpCont1 workwechat.JumpListCont
jmpCont1.Type = 1
jmpCont1.Title = "跳转1"
jmpCont1.Url = "https://work.weixin.qq.com"
templateCard.JumpList = append(templateCard.JumpList, jmpCont1)
var jmpCont2 workwechat.JumpListCont
jmpCont2.Type = 0
jmpCont2.Title = "不跳转2"
templateCard.JumpList = append(templateCard.JumpList, jmpCont2)
//整体卡片的点击跳转事件,text_notice必填本字段
templateCard.CardAction.Type = 1
templateCard.CardAction.Url = "https://www.baidu.com"
sendMsg.TemplateCard = templateCard
callbackID, err := sendMsg.SendMessage()
outPut := make(map[string]interface{})
outPut["callbackID"] = string(callbackID)
outPut["err"] = err
outPut["sendMsg"] = sendMsg
publicmethod.Result(0, outPut, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-14 11:27:42
@ 功能: 更新文本消息
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) UpdateTextMsg(c *gin.Context) {
var receivedValue publicmethod.PublicName
err := c.ShouldBindJSON(&receivedValue)
if receivedValue.Name == "" {
publicmethod.Result(1, err, c, "未知参数")
return
}
var sendMsg workwechat.UpdateMessage
sendMsg.UserIds = append(sendMsg.UserIds, "KaiXinGuo")
sendMsg.AgentId = 1000036
sendMsg.ResponseCode = receivedValue.Name
sendMsg.EnableIdTrans = 0
var templateCard workwechat.UpdateTemplateCardMsgCont
templateCard.CardType = "text_notice"
//头部左标题部分
templateCard.Source.IconUrl = "https://docu.hxgk.group/images/2022_01/3f7a1120a559e9bee3991b85eb34d103.png"
templateCard.Source.Desc = "恒信高科头部信息-->1"
templateCard.Source.DescColor = 1
//头部下拉菜单部分
templateCard.ActionMenu.Desc = "头部下拉-->1"
var actionContOne workwechat.ActionListCont
actionContOne.Text = "头部下拉选项一-->1"
actionContOne.Key = "head_click_1"
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, actionContOne)
var actionContTwo workwechat.ActionListCont
actionContTwo.Text = "头部下拉选项二-->1"
actionContTwo.Key = "head_click_2"
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, actionContTwo)
//主内容框
templateCard.MainTitle.Title = "主内容标题-->1"
templateCard.MainTitle.Desc = "主内容-->1"
//引用文献样式
templateCard.QuoteArea.Type = 1
templateCard.QuoteArea.Url = "https://work.weixin.qq.com"
templateCard.QuoteArea.Title = "企业微信的引用样式标题-->1"
templateCard.QuoteArea.QuoteText = "企业微信的引用样式内容-->1"
//关键数据样式
templateCard.EmphasisContent.Title = "100-->1"
templateCard.EmphasisContent.Desc = "核心数据-->1"
//二级普通文本,建议不超过160个字
templateCard.SubTitleText = "二级普通文本,建议不超过160个字-->1"
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
var hcListCont1 workwechat.HorizontalContentListCont
hcListCont1.Type = 0
hcListCont1.Keyname = "姓名:"
hcListCont1.Value = "秦东-->1"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont1)
var hcListCont2 workwechat.HorizontalContentListCont
hcListCont2.Type = 1
hcListCont2.Keyname = "企业微信官网-->1"
hcListCont2.Value = "点击访问-->1"
hcListCont2.Url = "https://work.weixin.qq.com"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont2)
var hcListCont3 workwechat.HorizontalContentListCont
hcListCont3.Type = 3
hcListCont3.Keyname = "姓名-->1"
hcListCont3.Value = "开心果-->1"
hcListCont3.UserId = "KaiXinGuo"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont3)
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
var jmpCont1 workwechat.JumpListCont
jmpCont1.Type = 1
jmpCont1.Title = "跳转1-->1"
jmpCont1.Url = "https://work.weixin.qq.com"
templateCard.JumpList = append(templateCard.JumpList, jmpCont1)
var jmpCont2 workwechat.JumpListCont
jmpCont2.Type = 0
jmpCont2.Title = "不跳转2-->1"
templateCard.JumpList = append(templateCard.JumpList, jmpCont2)
//整体卡片的点击跳转事件,text_notice必填本字段
templateCard.CardAction.Type = 1
templateCard.CardAction.Url = "https://www.baidu.com"
sendMsg.TemplateCard = templateCard
callbackID, err := sendMsg.UpdateMessage()
outPut := make(map[string]interface{})
outPut["callbackID"] = string(callbackID)
outPut["err"] = err
publicmethod.Result(0, outPut, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-23 10:22:02
@ 功能: 发送迷你文本消息
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SendMessageMini(c *gin.Context) {
var receivedValue publicmethod.PublicName
c.ShouldBindJSON(&receivedValue)
if receivedValue.Name == "" {
receivedValue.Name = "KaiXinGuo"
}
var sendMsg workwechat.SentMiniMessage
//主题信息
sendMsg.ToUser = receivedValue.Name
var templateCard workwechat.TemplateCardMsgContMini
uuid := publicmethod.GetUUid(5)
//头部左标题部分
templateCard.Source.Desc = "恒信高科头部信息"
//任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成
templateCard.TaskId = fmt.Sprintf("kpi_ratify_%v", uuid)
templateCard.ActionMenu.Desc = "恒信高科"
var rightHand workwechat.ActionListCont
rightHand.Text = "恒信高科"
rightHand.Key = fmt.Sprintf("kpi_head_%v", publicmethod.GetUUid(7))
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, rightHand)
//主内容框
templateCard.MainTitle.Title = "维度"
// templateCard.MainTitle.Desc = "指标"
//引用文献样式
// templateCard.QuoteArea.Title = "提报时间:2023-04-23 10:29"
setMsg := fmt.Sprintf("%v\n%v\n%v", "扣除5分", "原因:员工违规操作", "提报时间:2023-04-23 10:29")
templateCard.QuoteArea.QuoteText = setMsg
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
var hcListCont1 workwechat.HorizontalContentListCont
hcListCont1.Type = 0
hcListCont1.Keyname = "提报部门:"
hcListCont1.Value = "企管部"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont1)
var hcListCont3 workwechat.HorizontalContentListCont
hcListCont3.Type = 3
hcListCont3.Keyname = "提报人:"
hcListCont3.Value = "秦东(300450)"
hcListCont3.UserId = "KaiXinGuo"
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont3)
//审批详情也米娜
jumpUrl := fmt.Sprintf("%v/#/pages/approval/departworkflowcont?id=%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl, 2190)
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
var jmpCont1 workwechat.JumpListCont
jmpCont1.Type = 1
jmpCont1.Title = "前往处理"
jmpCont1.Url = jumpUrl
templateCard.JumpList = append(templateCard.JumpList, jmpCont1)
//整体卡片的点击跳转事件,text_notice必填本字段
templateCard.CardAction.Url = jumpUrl
sendMsg.TemplateCard = templateCard
callbackID, err := sendMsg.InitMes().SendMessage()
var enforcer []string
enforcer = append(enforcer, receivedValue.Name)
workwechatErr := workwechat.WriteUpdateWechatTempmsg(callbackID, sendMsg, 1, uuid, enforcer)
var callbackCont publicmethod.WechatCallBack
json.Unmarshal(callbackID, &callbackCont)
outPut := make(map[string]interface{})
outPut["callbackID"] = string(callbackID)
outPut["err"] = err
outPut["sendMsg"] = sendMsg
outPut["callbackCont"] = callbackCont
outPut["workwechatErr"] = workwechatErr
publicmethod.Result(0, outPut, c)
}
// 更新卡片mini
func (a *ApiMethod) UpdateMiniCard(c *gin.Context) {
var receivedValue UpdateMiniTemp
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Type == 0 {
receivedValue.Type = 1
}
if receivedValue.Orderkey == "" {
publicmethod.Result(1, err, c, "未知参数")
return
}
if receivedValue.Enforcer == "" {
publicmethod.Result(1, err, c, "未知参数")
return
}
var updateWechatCont modelskpi.UpdateWechatTempmsg
err = overall.CONSTANT_DB_KPI.Where("`type` = ? AND `orderkey` = ? AND FIND_IN_SET(?,`enforcer`)", receivedValue.Type, receivedValue.Orderkey, receivedValue.Enforcer).Find(&updateWechatCont).Error
if err != nil || updateWechatCont.Sendmsgcont == "" || updateWechatCont.ResponseCode == "" || updateWechatCont.State == 1 {
publicmethod.Result(105, err, c)
return
}
sendUpdateMsg := publicmethod.MapOut[string]()
var weChatMsgCont workwechat.SentMiniMessage
json.Unmarshal([]byte(updateWechatCont.Sendmsgcont), &weChatMsgCont)
templateCardCont := publicmethod.MapOut[string]()
templateCardCont["card_type"] = weChatMsgCont.TemplateCard.CardType
templateCardCont["source"] = weChatMsgCont.TemplateCard.Source
templateCardCont["main_title"] = weChatMsgCont.TemplateCard.MainTitle
templateCardCont["task_id"] = weChatMsgCont.TemplateCard.TaskId
templateCardCont["action_menu"] = weChatMsgCont.TemplateCard.ActionMenu
templateCardCont["quote_area"] = weChatMsgCont.TemplateCard.QuoteArea
templateCardCont["horizontal_content_list"] = weChatMsgCont.TemplateCard.HorizontalContentList
templateCardCont["card_action"] = weChatMsgCont.TemplateCard.CardAction
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": receivedValue.Enforcer}, "`name`")
titleStr := fmt.Sprintf("%v已处理,查看详情", userCont.Name)
for i, v := range weChatMsgCont.TemplateCard.JumpList {
if v.Type == 1 {
weChatMsgCont.TemplateCard.JumpList[i].Title = titleStr
}
}
templateCardCont["jump_list"] = weChatMsgCont.TemplateCard.JumpList
receiveMsgMan := strings.Split(updateWechatCont.Enforcer, ",")
if len(receiveMsgMan) < 1 {
publicmethod.Result(105, err, c)
return
}
var weCahtOpenId []string
for _, v := range receiveMsgMan {
var userContWechat modelshr.PersonArchives
userContWechat.GetCont(map[string]interface{}{"`key`": v}, "`wechat`", "`work_wechat`")
if userContWechat.Wechat != "" {
if !publicmethod.IsInTrue[string](userContWechat.Wechat, weCahtOpenId) {
weCahtOpenId = append(weCahtOpenId, userContWechat.Wechat)
}
}
if userContWechat.WorkWechat != "" {
if !publicmethod.IsInTrue[string](userContWechat.WorkWechat, weCahtOpenId) {
weCahtOpenId = append(weCahtOpenId, userContWechat.WorkWechat)
}
}
}
if len(weCahtOpenId) < 1 {
publicmethod.Result(105, err, c)
return
}
sendUpdateMsg["userids"] = weCahtOpenId
sendUpdateMsg["agentid"] = weChatMsgCont.AgentId
sendUpdateMsg["response_code"] = updateWechatCont.ResponseCode
sendUpdateMsg["enable_id_trans"] = 1
sendUpdateMsg["template_card"] = templateCardCont
UpDateCont, err := workwechat.UpdateMessageMap(sendUpdateMsg)
var editUpdateWechatCont modelskpi.UpdateWechatTempmsg
editCont := publicmethod.MapOut[string]()
editCont["`sate`"] = 1
editCont["`time`"] = time.Now().Unix()
editErr := editUpdateWechatCont.EiteCont(map[string]interface{}{"`id`": updateWechatCont.Id}, editCont)
outPut := publicmethod.MapOut[string]()
outPut["UpDateCont"] = UpDateCont
outPut["err"] = err
outPut["editErr"] = editErr
outPut["sendUpdateMsg"] = sendUpdateMsg
publicmethod.Result(0, outPut, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-09 08:44:15
@ 功能: 实验读取哈希
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetHashGet(c *gin.Context) {
redisFileKey := fmt.Sprintf("ScanCode:Authentication:LoginApi_%v_%v", overall.CONSTANT_CONFIG.RedisPrefixStr.Alias, "e3bfa398fe9d0e1ab78a00ff59eff788")
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
userRedisToken, _ := redisClient.HashGetAll(redisFileKey)
_, userRedisTokens := redisClient.HashGet(redisFileKey, "usertoken")
outPut := publicmethod.MapOut[string]()
outPut["userRedisToken"] = userRedisToken
outPut["userRedisTokens"] = userRedisTokens
publicmethod.Result(0, outPut, c)
}

57
api/shiyan/maptostruct/type.go

@ -1,21 +1,42 @@
package maptostruct
import (
"key_performance_indicators/models/modelsstorage"
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
type ApiMethod struct{}
//实验入口
// 协程设置
var syncSeting = sync.WaitGroup{}
var syncSetings = sync.WaitGroup{}
type readDataLock struct {
MaterialAry []MaterialCont `json:"materialary"`
}
type MaterialCont struct {
modelsstorage.MaterialType
MaterialList []modelsstorage.Material `json:"materiallist"`
}
// 菜单树
type CaiDanShu struct {
MaterialCont
Child []CaiDanShu `json:"child"`
}
// 实验入口
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "实验入口"
publicmethod.Result(0, outputCont, c)
}
//实验数据
// 实验数据
type shiyanType struct {
Name string `json:"name"`
Age int `json:"age"`
@ -24,3 +45,35 @@ type shiyanType struct {
Time2 float32 `json:"time2"`
Time3 float64 `json:"time3"`
}
// 模拟回调
type callBackCont struct {
MsgSignature string `json:"msg_signature"`
Timestamp string `json:"timestamp"`
Nonce string `json:"nonce"`
Echostr string `json:"echostr"`
DataType string `json:"datatype"`
SystemApp string `json:"systemapp"`
ToUsername string `json:"ToUserName"`
Agentid uint32 `json:"AgentID"`
Encrypt string `json:"encrypt"`
}
// Hr username AND password
type hrUsernameAndPassword struct {
Username string `json:"username"`
Password string `json:"password"`
VerificationCode string `json:"verification_code"`
publicmethod.PublicName
}
type XiaoZengTime struct {
DateTime string `json"datetime"`
}
// 更新mini文本模板
type UpdateMiniTemp struct {
Type int `json:"type"` //'类型(1:文本通知型;2:图文展示型;3:按钮交互型;4:投票选择型;5:多项选择型)'
Orderkey string `json:"orderkey"` //流程识别符
Enforcer string `json:"enforcer"` //执行人
}

1103
api/version1/departmentseting/departmentpc/departtarget.go

File diff suppressed because it is too large

634
api/version1/departmentseting/departmentpc/detailscont.go

@ -0,0 +1,634 @@
package departmentpc
import (
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-02-16 08:52:27
@ 功能: 新版添加部门指标细则
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) NewAddDepartDetails(c *gin.Context) {
var receivedValue NewDetailsCont
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.TargetId == "" {
publicmethod.Result(1, receivedValue, c, "未知指标!请指定该细则归属指标")
return
}
if receivedValue.TableName == "" {
publicmethod.Result(1, receivedValue, c, "未知栏目名称!请选择已有栏目或新输入一个栏目名称!")
return
}
if len(receivedValue.DetailsList) < 1 {
publicmethod.Result(1, receivedValue, c, "没有细则内容提交!请输入至少一条细则内容!")
return
}
writeIsTrue := false
//验证细则内容
for _, v := range receivedValue.DetailsList {
if v.Title == "" {
writeIsTrue = true
}
if v.Standard == "" {
writeIsTrue = true
} else {
scoreAry := strings.Split(v.Standard, "-")
if len(scoreAry) < 1 {
writeIsTrue = true
}
}
if v.Unit == "" {
writeIsTrue = true
}
if v.Types == 0 {
writeIsTrue = true
}
if len(v.InspeMethod) < 1 {
writeIsTrue = true
}
if len(v.Department) < 1 {
writeIsTrue = true
}
if len(v.Executor) < 1 {
writeIsTrue = true
}
}
if writeIsTrue {
publicmethod.Result(1, receivedValue, c, "至少一条考核细则内容填写不符合规范!请检查并补充完成后,重新提交!")
return
}
// tragetId, _ := strconv.ParseInt(receivedValue.TargetId, 10, 64)
//获取指标内容
var targetCont modelskpi.EvaluationTarget
err = targetCont.GetCont(map[string]interface{}{"`et_id`": receivedValue.TargetId})
if err != nil {
publicmethod.Result(1, err, c, "没有此指标!")
return
}
if len(receivedValue.TargetOrgList) < 1 {
receivedValue.TargetOrgList = GetTargetAboutDepart(targetCont)
}
var targetOrgIdList []string
for _, tov := range receivedValue.TargetOrgList {
if publicmethod.IsInTrue[string](tov.Key, targetOrgIdList) == false {
targetOrgIdList = append(targetOrgIdList, tov.Key)
}
}
//处理栏目数据
tableId, err := HandleTableCont(targetCont.Dimension, targetCont.Id, targetCont.Type, receivedValue.TableName, targetOrgIdList)
if err != nil {
publicmethod.Result(104, receivedValue, c)
return
}
// var insetContList []modelskpi.DetailedTarget
for _, v := range receivedValue.DetailsList {
var insetDeatilsCont modelskpi.DetailedTarget
insetDeatilsCont.Title = v.Title //指标细则"`
insetDeatilsCont.Content = v.Remarks //指标说明"`
insetDeatilsCont.ParentId = targetCont.Id //归属指标栏目"`
insetDeatilsCont.ParentIdSun = tableId //归属指标子栏目"`
insetDeatilsCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
insetDeatilsCont.AddTime = time.Now().Unix() //制定时间"`
insetDeatilsCont.MinScore, insetDeatilsCont.MaxScore = SplitCriteria(v.Standard) //最小分*100保存"`,最大分*100保存"`
insetDeatilsCont.Company = v.Unit //单位"`
insetDeatilsCont.AddReduce = v.Types //1:减少;2:增加;3:无属性,现场确认加或减"`
insetDeatilsCont.CensorType = strings.Join(v.InspeMethod, ",") //检查方式"`
insetDeatilsCont.CensorCont = v.Evidence //检查依据"`
insetDeatilsCont.CensorRate = v.Frequency //检查频次"`
insetDeatilsCont.Cycles = v.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
insetDeatilsCont.CycleAttres = 1 //辅助计数"`
insetDeatilsCont.Paretment = strings.Join(v.Department, ",") //接受考核的部门"`
insetDeatilsCont.Reportary = strings.Join(v.Executor, ",") //提报人"`
// insetContList = append(insetContList, insetDeatilsCont)
addErr := overall.CONSTANT_DB_KPI.Create(&insetDeatilsCont).Error
if addErr == nil {
SyncSeting.Add(1)
go DepartAboutTarget(targetCont.Dimension, targetCont.Id, tableId, insetDeatilsCont.Id, v.Department, 3, targetCont.Type, 1)
SyncSeting.Add(1)
go DepartAndReportAboutTarget(targetCont.Dimension, targetCont.Id, tableId, insetDeatilsCont.Id, v.Department, v.Executor, 1, targetCont.Type, 3)
}
}
SyncSeting.Wait()
publicmethod.Result(0, err, c)
}
// 拆分指标细则考核标准
func SplitCriteria(detailsCriteria string) (minScore, maxScore int64) {
scoreAry := strings.Split(detailsCriteria, "-")
scoreLen := len(scoreAry)
if scoreLen > 0 {
if scoreLen == 1 {
maxScoreFloat, _ := strconv.ParseFloat(scoreAry[0], 64)
maxScore, _ = strconv.ParseInt(strconv.FormatFloat(maxScoreFloat*100, 'f', -1, 64), 10, 64)
minScore = 0
} else {
minScoreFloat, _ := strconv.ParseFloat(scoreAry[0], 64)
maxScoreFloat, _ := strconv.ParseFloat(scoreAry[scoreLen-1], 64)
minScore, _ = strconv.ParseInt(strconv.FormatFloat(minScoreFloat*100, 'f', -1, 64), 10, 64)
maxScore, _ = strconv.ParseInt(strconv.FormatFloat(maxScoreFloat*100, 'f', -1, 64), 10, 64)
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-16 10:06:59
@ 功能: 处理栏目数据
@ 参数
#dimensionId 维度
#tragetId 指标Id
#title 栏目名称
#targetOrgIdList 关联岗位
#class 属性1定性考核2定量考核
@ 返回值
#tableId 栏目ID
#err 状态数据
@ 方法原型
#HandleTableCont(dimensionId, tragetId int64, class int, title string, targetOrgIdList []string) (tableId int64, err error)
*/
func HandleTableCont(dimensionId, tragetId int64, class int, title string, targetOrgIdList []string) (tableId int64, err error) {
var tableCont modelskpi.QualitativeTarget
err = tableCont.GetCont(map[string]interface{}{"`q_title`": title, "`q_parent_id`": tragetId})
if err != nil {
//不存在就新增
var insetTableCont modelskpi.QualitativeTarget
insetTableCont.Title = title // 指标子栏目名称
insetTableCont.ParentId = tragetId //归属指标
insetTableCont.State = 1 //状态(1:启用;2:禁用;3:删除)
insetTableCont.AddTime = time.Now().Unix() //制定时间"`
insetTableCont.Depart = strings.Join(targetOrgIdList, ",") //关联部门"`
err = overall.CONSTANT_DB_KPI.Create(&insetTableCont).Error
tableId = insetTableCont.Id
SyncSeting.Add(1)
go DepartAboutTarget(dimensionId, tragetId, insetTableCont.Id, 0, targetOrgIdList, 2, class, 1)
} else {
tableId = tableCont.Id
//存在就修改
editCont := publicmethod.MapOut[string]()
if tableCont.State != 1 {
editCont["q_state"] = 1
}
orgListStr := strings.Join(targetOrgIdList, ",")
if tableCont.Depart != orgListStr {
editCont["q_depart"] = orgListStr
SyncSeting.Add(1)
go DepartAboutTarget(dimensionId, tragetId, tableCont.Id, 0, targetOrgIdList, 2, class, 1)
}
if len(editCont) > 0 {
editCont["q_time"] = time.Now().Unix()
var editTableCont modelskpi.QualitativeTarget
err = editTableCont.EiteCont(map[string]interface{}{"q_id": tableCont.Id}, editCont)
}
}
SyncSeting.Wait()
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-16 14:01:48
@ 功能: 编辑指标细则状态
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EditDetailsState(c *gin.Context) {
var receivedValue publicmethod.PublicState
c.ShouldBindJSON(&receivedValue)
// err := c.ShouldBindJSON(&receivedValue)
// if err != nil {
// publicmethod.Result(100, err, c)
// return
// }
if receivedValue.Id == "" {
publicmethod.Result(1, receivedValue, c, "未知指标细则!请确认后再提交处理!")
return
}
if receivedValue.State == 0 {
receivedValue.State = 1
}
if receivedValue.IsTrue == 0 {
receivedValue.IsTrue = 2
}
where := publicmethod.MapOut[string]()
where["dt_id"] = receivedValue.Id
var detailsCont modelskpi.DetailedTarget
err := detailsCont.GetCont(where, "dt_id", "dt_parentid", "dt_parentid_sun")
if err != nil {
publicmethod.Result(107, err, c)
return
}
softDel := 1
if receivedValue.State == 3 && receivedValue.IsTrue == 1 {
//强制删除
//判断该指标细则是否在使用中,使用中的只能软删除
var epIdList []int64
overall.CONSTANT_DB_KPI.Model(&modelskpi.EvaluationProcess{}).Select("`ep_id`").Where("FIND_IN_SET(?,`ep_detailedtarget`)", receivedValue.Id).Find(&epIdList)
if len(epIdList) > 0 {
softDel = 1
} else {
softDel = 2
}
}
delTime := time.Now().Unix()
var editDetailsInfo modelskpi.DetailedTarget
if softDel == 1 {
//软删除
editDetailsInfo.EiteCont(where, map[string]interface{}{"`dt_state`": receivedValue.State, "`dt_time`": delTime})
} else {
//硬删除
editDetailsInfo.DelCont(where)
}
SyncSeting.Add(1)
go TarDepartState(detailsCont.ParentId, detailsCont.ParentIdSun, detailsCont.Id, receivedValue.State, softDel, 1, 3) // 处理关联部门
SyncSeting.Add(1)
go TarAboutReport(detailsCont.ParentId, detailsCont.ParentIdSun, detailsCont.Id, receivedValue.State, softDel, 1, 3) // 处理相关提报人
SyncSeting.Wait()
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-18 08:33:09
@ 功能: 编辑单一指标细则内容新版
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EditDetailsCont(c *gin.Context) {
var receivedValue EditOneDetailsCont
c.ShouldBindJSON(&receivedValue)
if receivedValue.Id == "" {
publicmethod.Result(1, receivedValue, c, "未知指标细则!请确认后再提交处理!")
return
}
var minVal int64
var maxVal int64
if receivedValue.Standard == "" {
publicmethod.Result(1, receivedValue, c, "请输入考核标准!")
return
} else {
scoreAry := strings.Split(receivedValue.Standard, "-")
if len(scoreAry) < 1 {
publicmethod.Result(1, receivedValue, c, "您输入的考核标准不符合规范!(例:1或0.1或0.1-0.5等类型)")
return
} else {
scoreLen := len(scoreAry)
if scoreLen == 1 {
maxScoreFloat, _ := strconv.ParseFloat(scoreAry[0], 64)
maxVal, _ = strconv.ParseInt(strconv.FormatFloat(maxScoreFloat*100, 'f', -1, 64), 10, 64)
minVal = 0
} else {
minScoreFloat, _ := strconv.ParseFloat(scoreAry[0], 64)
maxScoreFloat, _ := strconv.ParseFloat(scoreAry[scoreLen-1], 64)
minVal, _ = strconv.ParseInt(strconv.FormatFloat(minScoreFloat*100, 'f', -1, 64), 10, 64)
maxVal, _ = strconv.ParseInt(strconv.FormatFloat(maxScoreFloat*100, 'f', -1, 64), 10, 64)
}
}
}
if receivedValue.Unit == "" {
publicmethod.Result(1, receivedValue, c, "请输入计量单位!")
return
}
if receivedValue.Types == 0 {
publicmethod.Result(1, receivedValue, c, "请选择操作类型!")
return
}
if len(receivedValue.InspeMethod) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择检查方式!")
return
}
if len(receivedValue.Department) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择接受考核部门!")
return
}
if len(receivedValue.Executor) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择执行人")
return
}
where := publicmethod.MapOut[string]()
where["dt_id"] = receivedValue.Id
var detailsCont modelskpi.DetailedTarget
err := detailsCont.GetCont(where)
if err != nil {
publicmethod.Result(107, err, c)
return
}
var targetCont modelskpi.EvaluationTarget
err = targetCont.GetCont(map[string]interface{}{"`et_id`": detailsCont.ParentId}, "et_dimension", "et_type")
if err != nil {
publicmethod.Result(1, err, c, "没有此指标!")
return
}
editDateCont := publicmethod.MapOut[string]()
if receivedValue.Title != detailsCont.Title {
editDateCont["dt_title"] = receivedValue.Title
}
if minVal != detailsCont.MinScore {
editDateCont["dt_min_score"] = minVal
}
if maxVal != detailsCont.MaxScore {
editDateCont["dt_max_score"] = maxVal
}
if receivedValue.Unit != detailsCont.Company {
editDateCont["dt_company"] = receivedValue.Unit
}
if receivedValue.Types != detailsCont.AddReduce {
editDateCont["dt_add_reduce"] = receivedValue.Types
}
censorType := strings.Join(receivedValue.InspeMethod, ",")
if censorType != detailsCont.CensorType {
editDateCont["dt_censor_type"] = censorType
}
if receivedValue.Cycle != detailsCont.Cycles {
editDateCont["dt_cycle"] = receivedValue.Cycle
}
if receivedValue.Frequency != detailsCont.CensorRate {
editDateCont["dt_censor_rate"] = receivedValue.Frequency
}
if receivedValue.Evidence != detailsCont.CensorCont {
editDateCont["dt_censor_cont"] = receivedValue.Evidence
}
if receivedValue.Remarks != detailsCont.Content {
editDateCont["dt_content"] = receivedValue.Remarks
}
orgStr := strings.Join(receivedValue.Department, ",")
if orgStr != detailsCont.Paretment {
editDateCont["dt_paretment"] = orgStr
}
reportStr := strings.Join(receivedValue.Executor, ",")
if reportStr != detailsCont.Reportary {
editDateCont["reportary"] = reportStr
}
if len(editDateCont) > 0 {
editDateCont["dt_time"] = time.Now().Unix()
editDateCont["dt_state"] = 1
var editDetaCont modelskpi.DetailedTarget
errEdit := editDetaCont.EiteCont(where, editDateCont)
if errEdit != nil {
publicmethod.Result(107, err, c)
return
}
}
SyncSeting.Add(1)
go DepartAboutTarget(targetCont.Dimension, detailsCont.ParentId, detailsCont.ParentIdSun, detailsCont.Id, receivedValue.Department, 3, targetCont.Type, 1)
SyncSeting.Add(1)
go DepartAndReportAboutTarget(targetCont.Dimension, detailsCont.ParentId, detailsCont.ParentIdSun, detailsCont.Id, receivedValue.Department, receivedValue.Executor, 1, targetCont.Type, 3)
SyncSeting.Wait()
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-18 13:00:31
@ 功能: 根据栏目添加细则
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) TableAddDetailses(c *gin.Context) {
var receivedValue TableAddDetaCont
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.TargetId == "" {
publicmethod.Result(1, receivedValue, c, "未知指标!请指定该细则归属指标")
return
}
if receivedValue.TableiId == "" {
publicmethod.Result(1, receivedValue, c, "未知栏目!请指定栏目!")
return
}
if len(receivedValue.DetailsList) < 1 {
publicmethod.Result(1, receivedValue, c, "没有细则内容提交!请输入至少一条细则内容!")
return
}
writeIsTrue := false
//验证细则内容
for _, v := range receivedValue.DetailsList {
if v.Title == "" {
writeIsTrue = true
}
if v.Standard == "" {
writeIsTrue = true
} else {
scoreAry := strings.Split(v.Standard, "-")
if len(scoreAry) < 1 {
writeIsTrue = true
}
}
if v.Unit == "" {
writeIsTrue = true
}
if v.Types == 0 {
writeIsTrue = true
}
if len(v.InspeMethod) < 1 {
writeIsTrue = true
}
if len(v.Department) < 1 {
writeIsTrue = true
}
if len(v.Executor) < 1 {
writeIsTrue = true
}
}
if writeIsTrue {
publicmethod.Result(1, receivedValue, c, "至少一条考核细则内容填写不符合规范!请检查并补充完成后,重新提交!")
return
}
// tragetId, _ := strconv.ParseInt(receivedValue.TargetId, 10, 64)
//获取指标内容
var targetCont modelskpi.EvaluationTarget
err = targetCont.GetCont(map[string]interface{}{"`et_id`": receivedValue.TargetId}, "`et_id`", "`et_type`", "`et_dimension`")
if err != nil {
publicmethod.Result(1, err, c, "没有此指标!")
return
}
//
var tableInfo modelskpi.QualitativeTarget
err = tableInfo.GetCont(map[string]interface{}{"`q_id`": receivedValue.TableiId}, "`q_id`", "`q_state`")
if err != nil {
publicmethod.Result(1, err, c, "没有此指标!")
return
}
if tableInfo.State != 1 {
var editTableInfo modelskpi.QualitativeTarget
editTableInfo.EiteCont(map[string]interface{}{"`q_id`": receivedValue.TableiId}, map[string]interface{}{"`q_state`": 1, "`q_time`": time.Now().Unix()})
}
for _, v := range receivedValue.DetailsList {
var insetDeatilsCont modelskpi.DetailedTarget
insetDeatilsCont.Title = v.Title //指标细则"`
insetDeatilsCont.Content = v.Remarks //指标说明"`
insetDeatilsCont.ParentId = targetCont.Id //归属指标栏目"`
insetDeatilsCont.ParentIdSun = tableInfo.Id //归属指标子栏目"`
insetDeatilsCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
insetDeatilsCont.AddTime = time.Now().Unix() //制定时间"`
insetDeatilsCont.MinScore, insetDeatilsCont.MaxScore = SplitCriteria(v.Standard) //最小分*100保存"`,最大分*100保存"`
insetDeatilsCont.Company = v.Unit //单位"`
insetDeatilsCont.AddReduce = v.Types //1:减少;2:增加;3:无属性,现场确认加或减"`
insetDeatilsCont.CensorType = strings.Join(v.InspeMethod, ",") //检查方式"`
insetDeatilsCont.CensorCont = v.Evidence //检查依据"`
insetDeatilsCont.CensorRate = v.Frequency //检查频次"`
insetDeatilsCont.Cycles = v.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
insetDeatilsCont.CycleAttres = 1 //辅助计数"`
insetDeatilsCont.Paretment = strings.Join(v.Department, ",") //接受考核的部门"`
insetDeatilsCont.Reportary = strings.Join(v.Executor, ",") //提报人"`
// insetContList = append(insetContList, insetDeatilsCont)
addErr := overall.CONSTANT_DB_KPI.Create(&insetDeatilsCont).Error
if addErr == nil {
SyncSeting.Add(1)
go DepartAboutTarget(targetCont.Dimension, targetCont.Id, tableInfo.Id, insetDeatilsCont.Id, v.Department, 3, targetCont.Type, 1)
SyncSeting.Add(1)
go DepartAndReportAboutTarget(targetCont.Dimension, targetCont.Id, tableInfo.Id, insetDeatilsCont.Id, v.Department, v.Executor, 1, targetCont.Type, 3)
}
}
SyncSeting.Wait()
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-18 13:53:23
@ 功能: 修改栏目名称及关联岗位和提报人
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EditTableContAndDepartOfMan(c *gin.Context) {
var receivedValue EditTableInfo
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(1, receivedValue, c, "未知指标!请指定该细则归属指标")
return
}
//获取栏目内容
var targetTableCont modelskpi.QualitativeTarget
err = targetTableCont.GetCont(map[string]interface{}{"`q_id`": receivedValue.Id})
if err != nil {
publicmethod.Result(1, err, c, "没有此栏目!")
return
}
//获取指标内容
var targetCont modelskpi.EvaluationTarget
err = targetCont.GetCont(map[string]interface{}{"`et_id`": targetTableCont.ParentId})
if err != nil {
publicmethod.Result(1, err, c, "没有此指标!")
return
}
editSaveData := publicmethod.MapOut[string]()
if receivedValue.Title != "" && receivedValue.Title != targetTableCont.Title {
editSaveData["q_title"] = receivedValue.Title
}
if len(receivedValue.Departmentint) > 0 {
departStr := strings.Join(receivedValue.Departmentint, ",")
if departStr != targetTableCont.Depart {
editSaveData["q_depart"] = departStr
}
SyncSeting.Add(1)
go DepartAboutTarget(targetCont.Dimension, targetTableCont.ParentId, targetTableCont.Id, 0, receivedValue.Departmentint, 2, targetCont.Type, 1)
}
if len(receivedValue.UserList) > 0 {
SyncSeting.Add(1)
go DepartAndReportAboutTarget(targetCont.Dimension, targetTableCont.ParentId, targetTableCont.Id, 0, receivedValue.Departmentint, receivedValue.UserList, 1, targetCont.Type, 2)
}
if len(editSaveData) > 0 {
editSaveData["q_time"] = time.Now().Unix()
var editTargetCont modelskpi.QualitativeTarget
editTargetCont.EiteCont(map[string]interface{}{"`q_id`": receivedValue.Id}, editSaveData)
}
//该栏目的所有细则
var bylawsId []int64
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.DetailedTarget{}).Select("dt_id").Where("`dt_parentid` = ? AND `dt_parentid_sun` = ?", targetTableCont.ParentId, targetTableCont.Id).Find(&bylawsId).Error
if err == nil && len(bylawsId) > 0 {
for _, v := range bylawsId {
SyncSeting.Add(1)
go DepartAboutTarget(targetCont.Dimension, targetTableCont.ParentId, targetTableCont.Id, v, receivedValue.Departmentint, 3, targetCont.Type, 1)
SyncSeting.Add(1)
go DepartAndReportAboutTarget(targetCont.Dimension, targetTableCont.ParentId, targetTableCont.Id, v, receivedValue.Departmentint, receivedValue.UserList, 1, targetCont.Type, 3)
}
}
SyncSeting.Wait()
publicmethod.Result(0, err, c)
}

670
api/version1/departmentseting/departmentpc/ding_xing.go

@ -0,0 +1,670 @@
package departmentpc
import (
"encoding/json"
"fmt"
"key_performance_indicators/api/workflow/workflowengine"
"key_performance_indicators/api/workwechat"
"key_performance_indicators/models/modelshonory"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-04-01 08:16:22
@ 功能: 获取定性考核任务列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetQualityTasks(c *gin.Context) {
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
var receivedValue GetQuanTasks
c.ShouldBindJSON(&receivedValue)
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 15
}
var qualEvaCont modelskpi.QualitativeEvaluationView
gormDb := overall.CONSTANT_DB_KPI.Table(fmt.Sprintf("%s qe", qualEvaCont.TableName())).Distinct("qe.`qe_accept_evaluation`,qe.`qe_target`,qe.`et_title`").Where("qe.`qe_type` = 1 AND qe.`qe_state` = 1 ")
gormDb = gormDb.Joins("JOIN target_report td ON qe.qe_target = td.target_id AND qe.qe_accept_evaluation = td.`department_id` AND td.target_bylaws = qe.`qe_detailed_target` AND td.`type` = 1 AND td.`post_id` = 0 AND td.state = 1 AND td.type_level = 3 AND td.`man_key` = ?", myLoginCont.Key)
if receivedValue.OrgId != "" {
gormDb = gormDb.Where("`qe_accept_evaluation` = ?", receivedValue.OrgId)
}
if receivedValue.Title != "" {
gormDb = gormDb.Where("et_title LIKE ?", "%"+receivedValue.Title+"%")
}
var total int
var qualEvaListCount []modelskpi.QualitativeEvaluationView
totalErr := gormDb.Find(&qualEvaListCount).Error
if totalErr != nil {
total = 0
} else {
total = len(qualEvaListCount)
}
var qualEvaList []modelskpi.QualitativeEvaluationView
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("qe_accept_evaluation ASC,qe_target ASC").Find(&qualEvaList).Error
if err != nil {
publicmethod.Result(105, err, c)
return
}
todayVal := time.Now().Unix()
yearVal := publicmethod.UnixTimeToDay(todayVal, 16)
monthVal := publicmethod.UnixTimeToDay(todayVal, 17)
if receivedValue.Time != "" {
var dayTime publicmethod.DateTimeTotimes
dayTime.BaisStrToTime(receivedValue.Time)
yearVal = dayTime.Years
monthVal = dayTime.Months
}
var sendContList []OutPutDingXingCont
for _, v := range qualEvaList {
var sendCont OutPutDingXingCont
sendCont.OrgId = strconv.FormatInt(v.AcceptEvaluation, 10) //行政组织Id
var orgCont modelshr.AdministrativeOrganization
orgCont.GetCont(map[string]interface{}{"`id`": v.AcceptEvaluation}, "`name`")
sendCont.OrgName = orgCont.Name
sendCont.TargetId = strconv.FormatInt(v.Target, 10) //指标ID
sendCont.Title = v.EtTitle //指标名称
sendCont.MinusScore, sendCont.BonusPoints = CalculatePlusOrMinusPoints(v.AcceptEvaluation, v.Target, yearVal, monthVal) //总减分,总加分
sendContList = append(sendContList, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, int64(total), int64(len(sendContList)), sendContList, c)
}
/**
@ 作者: 秦东
@ 时间: 2023-04-01 10:06:37
@ 功能: 计算加减分
@ 参数
#orgId 行政组织
#targetId 指标
#years
#months
@ 返回值
#minusScore 减去的分数
#bonusPoints 加上的分数
@ 方法原型
#func CalculatePlusOrMinusPoints(orgId, targetId int64, years, months string) (minusScore, bonusPoints float64)
*/
func CalculatePlusOrMinusPoints(orgId, targetId int64, years, months string) (minusScore, bonusPoints float64) {
var examineListCont []modelskpi.ScoreFlow
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.ScoreFlow{}).Select("sf_score,sf_plus_reduce_score,sf_count").Where("sf_reply IN ? AND sf_duty_department = ? AND sf_year = ? AND sf_month = ? AND sf_target_id = ?", []int{2, 3}, orgId, years, months, targetId).Find(&examineListCont).Error
if err == nil && len(examineListCont) > 0 {
for _, v := range examineListCont {
if v.PlusReduceScore == 1 {
//加分操作
bonusPoints = bonusPoints + (float64(v.Score) * float64(v.Count)) //分值=原分值+(评分乘以发生次数)
} else {
//减分操作
minusScore = minusScore + (float64(v.Score) * float64(v.Count)) //分值=原分值+(评分乘以发生次数)
}
}
}
bonusPoints = publicmethod.DecimalEs(bonusPoints/100, 2)
minusScore = publicmethod.DecimalEs(minusScore/100, 2)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-01 14:09:42
@ 功能: 相关提报人定性考核细则列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetQualityBylawsTasks(c *gin.Context) {
var receivedValue BylawsAboutPeople
c.ShouldBindJSON(&receivedValue)
if receivedValue.OrgId == "" || receivedValue.TargetId == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 15
}
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
var qualEvaCont modelskpi.QualitativeEvaluationView
gormDb := overall.CONSTANT_DB_KPI.Table(fmt.Sprintf("%s qe", qualEvaCont.TableName())).Select("qe.qe_id,qe.qe_target_sun,qe.qe_detailed_target,qe.qe_content,qe.qe_censor_cont,qe.qe_min_score,qe.qe_max_score,qe.qe_unit").Where("qe.`qe_type` = 1 AND qe.`qe_state` = 1 AND qe.`qe_accept_evaluation` = ? AND qe.`qe_target` = ?", receivedValue.OrgId, receivedValue.TargetId)
gormDb = gormDb.Joins("JOIN target_report td ON qe.qe_target = td.target_id AND qe.qe_accept_evaluation = td.`department_id` AND td.target_bylaws = qe.`qe_detailed_target` AND td.`type` = 1 AND td.`post_id` = 0 AND td.state = 1 AND td.`man_key` = ?", myLoginCont.Key)
if receivedValue.OrgId != "" {
gormDb = gormDb.Where("`qe_accept_evaluation` = ?", receivedValue.OrgId)
}
if receivedValue.Title != "" {
gormDb = gormDb.Where("et_title LIKE ?", "%"+receivedValue.Title+"%")
}
var total int
var qualEvaListCount []modelskpi.QualitativeEvaluationView
totalErr := gormDb.Find(&qualEvaListCount).Error
if totalErr != nil {
total = 0
} else {
total = len(qualEvaListCount)
}
var qualEvaList []modelskpi.QualitativeEvaluationView
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("qe_accept_evaluation ASC,qe_target ASC").Find(&qualEvaList).Error
if err != nil {
publicmethod.Result(105, err, c)
return
}
var sendContList []OutPutBylawsCont
for _, v := range qualEvaList {
var sendCont OutPutBylawsCont
sendCont.Id = strconv.FormatInt(v.Id, 10)
var bylawsCont modelskpi.DetailedTarget
bylawsCont.GetCont(map[string]interface{}{"`dt_id`": v.DetailedTarget}, "`dt_title`", "`dt_content`", `dt_add_reduce`)
var columnCont modelskpi.QualitativeTarget
columnCont.GetCont(map[string]interface{}{"`q_id`": v.TargetSun}, "`q_title`")
sendCont.ColumnTitle = columnCont.Title
sendCont.Title = bylawsCont.Title //考核项目
sendCont.Content = bylawsCont.Content //考核内容
if v.Content != "" {
sendCont.Content = v.Content
}
if v.CensorCont != "" {
sendCont.Content = v.CensorCont
}
sendCont.MaxScore = publicmethod.DecimalEs(float64(v.MaxScore)/100, 2)
sendCont.MinScore = publicmethod.DecimalEs(float64(v.MinScore)/100, 2)
if sendCont.MinScore > 0 && sendCont.MaxScore > 0 {
sendCont.Standard = fmt.Sprintf("%v-%v", sendCont.MinScore, sendCont.MaxScore) //标准
sendCont.ScoreType = 2
} else if sendCont.MinScore > 0 && sendCont.MaxScore <= 0 {
sendCont.Standard = fmt.Sprintf("%v", sendCont.MinScore)
sendCont.ScoreType = 1
} else if sendCont.MinScore <= 0 && sendCont.MaxScore > 0 {
sendCont.Standard = fmt.Sprintf("%v", sendCont.MaxScore)
sendCont.ScoreType = 1
} else {
sendCont.Standard = "0"
sendCont.ScoreType = 3
}
sendCont.Unit = v.Unit //单位
sendCont.PlusMinusScore = bylawsCont.AddReduce //加减分
sendContList = append(sendContList, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, int64(total), int64(len(sendContList)), sendContList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-06 16:16:42
@ 功能: 提交定性考核
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SubmitQualityAssess(c *gin.Context) {
var receivedValue HaveQualityAssessData
c.ShouldBindJSON(&receivedValue)
if receivedValue.ScoreFlowCont.ItemId == "" {
publicmethod.Result(1, receivedValue, c, "未知考核项目!不可进行提交")
return
}
if len(receivedValue.WorkFlowView) < 1 {
publicmethod.Result(1, receivedValue, c, "未知工作流!不可进行提交")
return
} else {
if !workflowengine.JudgeWorkflowIsTrue(receivedValue.WorkFlowView) {
publicmethod.Result(1, receivedValue, c, "未知工作流!不可进行提交")
return
}
}
if receivedValue.Orgid == "" {
publicmethod.Result(1, receivedValue, c, "未知接受考核部门!不可进行提交")
return
}
var qualEvalCont modelskpi.QualitativeEvaluation
err := qualEvalCont.GetCont(map[string]interface{}{"`qe_id`": receivedValue.ScoreFlowCont.ItemId})
if err != nil {
publicmethod.Result(1, receivedValue, c, "未知考核项目!不可进行提交")
return
}
if receivedValue.ScoreFlowCont.Type == 0 {
receivedValue.ScoreFlowCont.Type = 2
}
scoreType := 1
var dingFen float64
if qualEvalCont.MinScore > 0 && qualEvalCont.MaxScore > 0 {
dingFen = receivedValue.ScoreFlowCont.Score * 100
scoreType = 2
} else if qualEvalCont.MinScore > 0 && qualEvalCont.MaxScore <= 0 {
dingFen = float64(qualEvalCont.MinScore)
scoreType = 1
} else if qualEvalCont.MinScore <= 0 && qualEvalCont.MaxScore > 0 {
dingFen = float64(qualEvalCont.MaxScore)
scoreType = 1
} else {
dingFen = 0
scoreType = 3
}
if scoreType == 2 {
if receivedValue.ScoreFlowCont.Score == 0 {
publicmethod.Result(1, receivedValue, c, "请输入分值!")
return
}
judgeScore := receivedValue.ScoreFlowCont.Score * 100
if judgeScore > float64(qualEvalCont.MaxScore) {
publicmethod.Result(1, receivedValue, c, fmt.Sprintf("您提交的分数超过允许提交的最大值(最大值:%v)!", float64(qualEvalCont.MaxScore)/100))
return
}
if judgeScore < float64(qualEvalCont.MinScore) {
publicmethod.Result(1, receivedValue, c, fmt.Sprintf("您提交的分数超过允许提交的最小值(最小值:%v)!", float64(qualEvalCont.MinScore)/100))
return
}
} else {
if receivedValue.ScoreFlowCont.Frequency == 0 {
receivedValue.ScoreFlowCont.Frequency = 1
}
}
if receivedValue.ScoreFlowCont.Reason == "" {
publicmethod.Result(1, receivedValue, c, "请输入这样操作得原因!")
return
}
operationTime := time.Now().Unix() //统一操作时间
occurrenceTime := operationTime
//计算发生时间
currentYears := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 1), 10)
currentQuarter := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 2), 10)
currentMonths := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 3), 10)
currentWeek := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 4), 10)
if receivedValue.ScoreFlowCont.Time == "" {
publicmethod.Result(1, receivedValue, c, "请确认发生时间!")
return
} else {
var dayTime publicmethod.DateTimeTotimes
dayTime.BaisStrToTime(receivedValue.ScoreFlowCont.Time)
if dayTime.Years != "" {
currentYears = dayTime.Years
}
if dayTime.Quarter != "" {
currentQuarter = dayTime.Quarter
}
if dayTime.Months != "" {
currentMonths = dayTime.Months
}
if dayTime.Week != "" {
currentWeek = dayTime.Week
}
occurrenceTime = dayTime.AllTime
}
currentYearsInt, _ := strconv.ParseInt(currentYears, 10, 64) //年
currentQuarterInt, _ := strconv.ParseInt(currentQuarter, 10, 64) //季度
currentMonthsInt, _ := strconv.ParseInt(currentMonths, 10, 64) //月
currentWeekInt, _ := strconv.ParseInt(currentWeek, 10, 64) //周
var correctionTime int64
if receivedValue.ScoreFlowCont.Correct == 0 || receivedValue.ScoreFlowCont.Correct == 1 {
receivedValue.ScoreFlowCont.Correct = 1
if receivedValue.ScoreFlowCont.DueTime == "" {
publicmethod.Result(1, receivedValue, c, "请指定整改最晚完成期限!")
return
} else {
var dayCorreTime publicmethod.DateTimeTotimes
dayCorreTime.BaisStrToTime(receivedValue.ScoreFlowCont.DueTime)
correctionTime = dayCorreTime.AllTime
}
}
uuid := publicmethod.GetUUid(7) //上报数据唯一识别码
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
var addScoreFlow modelskpi.ScoreFlow
addScoreFlow.EvaluationPlan = qualEvalCont.Id //考核方案项目ID"`
addScoreFlow.PlusReduceScore = receivedValue.ScoreFlowCont.Type //1:加分;2:减分"`
dingFenStr := strconv.FormatFloat(dingFen, 'f', -1, 64)
dingFenInt, _ := strconv.ParseInt(dingFenStr, 10, 64)
addScoreFlow.Score = dingFenInt //分值(乘100录入)"`
addScoreFlow.Key = uuid //识别标志"`
addScoreFlow.Reason = receivedValue.ScoreFlowCont.Reason //操作原因"`
addScoreFlow.Time = operationTime //创建时间"`
addScoreFlow.EiteTime = operationTime //修改时间"`
addScoreFlow.EvaluationDepartment = myLoginCont.MainDeparment //测评部门"`
addScoreFlow.EvaluationUser = myLoginCont.Key //测评人"`
addScoreFlow.EvaluationGroup = myLoginCont.Company //测评集团"`
addScoreFlow.Year = currentYearsInt //年分"`
addScoreFlow.Quarter = currentQuarterInt //季度"`
addScoreFlow.Month = currentMonthsInt //月"`
addScoreFlow.Week = currentWeekInt //周"`
if len(receivedValue.UploadFiles) > 0 {
fileJson, jsonErr := json.Marshal(receivedValue.UploadFiles)
if jsonErr == nil {
addScoreFlow.Enclosure = string(fileJson) //附件"`
}
}
addScoreFlow.DutyGroup = qualEvalCont.Group //职责集团"`
addScoreFlow.DutyDepartment = qualEvalCont.AcceptEvaluation //职责部门"`
addScoreFlow.Reply = 2 //状态(0:删除;1:起草;2:审批;3:通过)"`
addScoreFlow.Rectification = receivedValue.ScoreFlowCont.Correct //1、需要整改;2:无需整改"`
addScoreFlow.HappenTime = occurrenceTime //发生时间"`
addScoreFlow.Count = receivedValue.ScoreFlowCont.Frequency //发生次数"`
addScoreFlow.CorrectionTime = correctionTime //整改期限"`
addScoreFlow.PlanVersion = qualEvalCont.QualEvalId //版本号"`
addScoreFlow.TargetId = qualEvalCont.Target //指标ID"`
addScoreFlow.DetailedId = qualEvalCont.DetailedTarget //指标细则"`
//获取工作流
var haveWorkflow workflowengine.OperateWorkflow
haveWorkflow.Step = 1 //操作哪一步
// haveWorkflow.OrderId = uuid //发起表单ID
// haveWorkflow.Attribute = qualEvalCont.Type //属性 1、定性;2、定量
haveWorkflow.OperationStatus = 2 //操作状态
var caoZuoRen workflowengine.ManipulatePeopleInfo
caoZuoRen.Key = strconv.FormatInt(myLoginCont.Key, 10) //操作人
caoZuoRen.OrgId = strconv.FormatInt(myLoginCont.AdminOrg, 10) //操作人行政组织
haveWorkflow.ManipulatePeople = caoZuoRen //操作人相关
haveWorkflow.WorkFlowList = receivedValue.WorkFlowView //流程步进图
flowView := haveWorkflow.ManipulateWorkflow()
//审批主体信息
var evalProFlowView modelskpi.EvaluationProcess
evalProFlowView.OrderKey = uuid //发起表单key"`
evalProFlowView.Step = haveWorkflow.Step //当前执行到第几部"`
flowAllJson, _ := json.Marshal(flowView)
evalProFlowView.Content = string(flowAllJson) //流程步进值"`
nextNodeJson, _ := json.Marshal(haveWorkflow.NextNodeCont)
evalProFlowView.NextContent = string(nextNodeJson) //下一步内容"`
evalProFlowView.Time = operationTime //创建时间"`
evalProFlowView.State = 2 //1:起草,2:审批中;3:通过;4:驳回"`
evalProFlowView.RoleGroup = 0 //角色组"`
evalProFlowView.TypeClass = qualEvalCont.Type //1、定性;2、定量"`
evalProFlowView.Participants = strings.Join(haveWorkflow.Participant, ",") //参与人"`
evalProFlowView.StartTime = operationTime //流程开始时间"`
evalProFlowView.NextStep = haveWorkflow.NextStep //下一步"`
evalProFlowView.NextExecutor = strings.Join(haveWorkflow.NextNodeContExecutor, ",") //下一步执行人"`
evalProFlowView.SetupDepartment = myLoginCont.MainDeparment //发起部门"`
evalProFlowView.Dimension = strconv.FormatInt(qualEvalCont.Dimension, 10) //维度"`
evalProFlowView.Target = strconv.FormatInt(qualEvalCont.Target, 10) //指标"`
evalProFlowView.DetailedTarget = strconv.FormatInt(qualEvalCont.DetailedTarget, 10) //指标细则"`
evalProFlowView.AcceptDepartment = qualEvalCont.AcceptEvaluation //接受考核部门"`
evalProFlowView.HappenTime = occurrenceTime
flowKyeInt, _ := strconv.ParseInt(receivedValue.FlowKey, 10, 64)
evalProFlowView.FlowKey = flowKyeInt //流程图唯一识别符
flowVersionInt, _ := strconv.ParseInt(receivedValue.FlowVersion, 10, 64)
evalProFlowView.FlowVid = flowVersionInt //流程版本"`
evalProFlowView.EpOld = 2
evalProFlowView.Creater = myLoginCont.Key //发起人
evalProFlowView.Clique = myLoginCont.Company //流程归属公司
//审批记录
var stepsTotal int64
overall.CONSTANT_DB_KPI.Model(&modelskpi.OpenApprovalChangeLog{}).Where("`orderid` = ?", uuid).Count(&stepsTotal)
var flowLogCont modelskpi.OpenApprovalChangeLog
flowLogCont.Type = 1 //类型(1:部门;2:岗位)"`
flowLogCont.Title = haveWorkflow.CurrentNode.NodeName //节点名称"`
flowLogCont.Operator = myLoginCont.Key //操作人"`
flowLogCont.OrderId = uuid //订单ID"`
flowLogCont.OperatorTime = operationTime //操作时间"`
flowLogCont.Step = stepsTotal + 1 //操作第几步"`
flowLogCont.OperatorType = haveWorkflow.CurrentNode.State //操作状态(1:位操作;2:已操作)"`
flowLogCont.Msgid = "" //消息id,用于撤回应用消息"`
flowLogCont.ResponseCode = "" //仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,24小时内有效,且只能使用一次"`
flowLogCont.Stepper = haveWorkflow.CurrentNode.Step //步进器"`
flowLogCont.ChangeIsTrue = 1 //是否可变更(1:可变更;2:不可变更)"`
flowLogCont.Eiteyime = operationTime //变动时间"`
flowLogCont.YesOrNo = haveWorkflow.CurrentNode.State //未操作;1:同意;2:驳回;3:撤回"`
gormDb := overall.CONSTANT_DB_KPI.Begin()
scoreFlowErr := gormDb.Create(&addScoreFlow).Error
evalProFlowErr := gormDb.Create(&evalProFlowView).Error
flowLogContErr := gormDb.Create(&flowLogCont).Error
var callbackMsg []byte //
var workwechatErr error
if scoreFlowErr == nil && evalProFlowErr == nil && flowLogContErr == nil {
addErr := gormDb.Commit().Error
fmt.Printf("addErr--->%v\n", addErr)
if addErr == nil {
if len(receivedValue.UploadFiles) > 0 {
SyncSetFiles.Add(1)
EditFileHandel(uuid, "score_flow", receivedValue.UploadFiles)
SyncSetFiles.Wait()
}
//下一个节点内容
nextNodeStr := string(nextNodeJson)
if nextNodeStr != "" { //判断下个节点是否为空
fmt.Printf("nextNodeStr--->%v\n", nextNodeStr)
if len(haveWorkflow.NextNodeCont.UserList) > 0 { //判断下个节点是够有审批人
var recipient []string
var sendWechatUserKey []string
for _, v := range haveWorkflow.NextNodeCont.UserList { //获取接收人得微信或企业微信Openid用作发送消息的唯一识别码
if !publicmethod.IsInTrue[string](v.Id, sendWechatUserKey) {
sendWechatUserKey = append(sendWechatUserKey, v.Id)
}
if v.Wechat != "" {
if !publicmethod.IsInTrue[string](v.Wechat, recipient) {
recipient = append(recipient, v.Wechat)
}
} else {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.Id}, "`wechat`", "`work_wechat`")
if userCont.Wechat != "" {
if !publicmethod.IsInTrue[string](userCont.Wechat, recipient) {
recipient = append(recipient, userCont.Wechat)
}
}
if userCont.WorkWechat != "" {
if !publicmethod.IsInTrue[string](userCont.WorkWechat, recipient) {
recipient = append(recipient, userCont.WorkWechat)
}
}
}
}
if len(recipient) > 0 { //判断是否有接收人
//开始组装消息内容
var sendMsg workwechat.SentMiniMessage
sendMsg.ToUser = strings.Join(recipient, "|") //收件人配置
var templateCard workwechat.TemplateCardMsgContMini //模版卡片主体
//头部左标题部分
nodeType := publicmethod.GetSetpNodeName(haveWorkflow.NextNodeCont.Type)
templateCard.Source.Desc = fmt.Sprintf("%v-%v", haveWorkflow.NextNodeCont.NodeName, nodeType)
//任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成
templateCard.TaskId = fmt.Sprintf("kpi_ratify_%v", uuid)
templateCard.ActionMenu.Desc = "恒信高科"
var rightHand workwechat.ActionListCont
rightHand.Text = "恒信高科"
rightHand.Key = fmt.Sprintf("kpi_head_%v", publicmethod.GetUUid(7))
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, rightHand)
//主内容框
var dimeCont modelskpi.DutyClass
dimeCont.GetCont(map[string]interface{}{"`id`": qualEvalCont.Dimension}, "`title`")
templateCard.MainTitle.Title = dimeCont.Title
var targetCont modelskpi.EvaluationTarget
targetCont.GetCont(map[string]interface{}{"`et_id`": qualEvalCont.Target}, "`et_title`")
templateCard.MainTitle.Desc = targetCont.Title
//引用文献样式
var bylawsCont modelskpi.DetailedTarget
bylawsCont.GetCont(map[string]interface{}{"`dt_id`": qualEvalCont.DetailedTarget}, "`dt_title`")
templateCard.QuoteArea.Title = bylawsCont.Title
//1:加分;2:减分"`
var quoteText string
if receivedValue.ScoreFlowCont.Type == 1 {
if receivedValue.ScoreFlowCont.Reason != "" {
quoteText = fmt.Sprintf("奖励: %v 分\n原因:%v\n发生时间:%v", publicmethod.DecimalEs(dingFen/100, 2), receivedValue.ScoreFlowCont.Reason, publicmethod.UnixTimeToDay(occurrenceTime, 12))
} else {
quoteText = fmt.Sprintf("奖励: %v 分\n发生时间:%v", publicmethod.DecimalEs(dingFen/100, 2), publicmethod.UnixTimeToDay(occurrenceTime, 12))
}
} else {
if receivedValue.ScoreFlowCont.Reason != "" {
quoteText = fmt.Sprintf("扣除: %v 分\n原因:%v\n发生时间:%v", publicmethod.DecimalEs(dingFen/100, 2), receivedValue.ScoreFlowCont.Reason, publicmethod.UnixTimeToDay(occurrenceTime, 12))
} else {
quoteText = fmt.Sprintf("扣除: %v 分\n发生时间:%v", publicmethod.DecimalEs(dingFen/100, 2), publicmethod.UnixTimeToDay(occurrenceTime, 12))
}
}
templateCard.QuoteArea.QuoteText = quoteText
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
var userRecarCont modelshr.PersonArchives
userRecarCont.GetCont(map[string]interface{}{"`key`": myLoginCont.Key}, "`wechat`", "`work_wechat`", "`maindeparment`")
recipientWechat := userRecarCont.Wechat
if userRecarCont.WorkWechat != "" {
recipientWechat = userRecarCont.WorkWechat
}
var orgContInfo modelshr.AdministrativeOrganization
orgContInfo.GetCont(map[string]interface{}{"`id`": userRecarCont.MainDeparment}, "name")
var hcListCont1 workwechat.HorizontalContentListCont
hcListCont1.Type = 0
hcListCont1.Keyname = "提报部门:"
hcListCont1.Value = orgContInfo.Name
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont1)
var hcListCont3 workwechat.HorizontalContentListCont
hcListCont3.Keyname = "提报人:"
hcListCont3.Value = fmt.Sprintf("%v(%v)", myLoginCont.Name, myLoginCont.Number)
if recipientWechat != "" {
hcListCont3.Type = 3
hcListCont3.UserId = recipientWechat
} else {
hcListCont3.Type = 0
}
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont3)
//审批详情访问地址
jumpUrl := fmt.Sprintf("%v/#/pages/approval/departworkflowcont?id=%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl, evalProFlowView.Id)
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
var jmpCont1 workwechat.JumpListCont
jmpCont1.Type = 1
jmpCont1.Title = "前往处理"
jmpCont1.Url = jumpUrl
templateCard.JumpList = append(templateCard.JumpList, jmpCont1)
//整体卡片的点击跳转事件,text_notice必填本字段
templateCard.CardAction.Url = jumpUrl
sendMsg.TemplateCard = templateCard
callbackMsg, err = sendMsg.InitMes().SendMessage()
fmt.Printf("callbackMsg--->%v\n", string(callbackMsg))
workwechatErr = workwechat.WriteUpdateWechatTempmsg(callbackMsg, sendMsg, 1, uuid, sendWechatUserKey)
}
}
}
outErr := publicmethod.MapOut[string]()
outErr["addErr"] = addErr
outErr["err"] = err
outErr["workwechatErr"] = workwechatErr
outErr["callbackMsg"] = string(callbackMsg)
publicmethod.Result(0, addErr, c)
} else {
addErr := gormDb.Rollback().Error
publicmethod.Result(104, addErr, c)
}
} else {
outErr := publicmethod.MapOut[string]()
addErr := gormDb.Rollback().Error
outErr["scoreFlowErr"] = scoreFlowErr
outErr["evalProFlowErr"] = evalProFlowErr
outErr["flowLogContErr"] = flowLogContErr
outErr["addErr"] = addErr
outErr["callbackMsg"] = string(callbackMsg)
publicmethod.Result(1014, outErr, c)
}
// outPut := publicmethod.MapOut[string]()
// outPut["evalProFlowView"] = evalProFlowView
// outPut["flowkk"] = flowView
// outPut["addScoreFlow"] = addScoreFlow
// outPut["flowLogCont"] = flowLogCont
// publicmethod.Result(0, outPut, c, "限!")
}
/**
@ 作者: 秦东
@ 时间: 2023-04-07 10:07:07
@ 功能: 写入附件
@ 参数
#ascriptionId 识别码
#ascriptionDataSheet 归属表单
#fileList 文件列表
@ 返回值
#
@ 方法原型
#
*/
func EditFileHandel(ascriptionId int64, ascriptionDataSheet string, fileList []UploadFilesCont) {
defer SyncSetFiles.Done()
if len(fileList) > 0 {
operationTime := time.Now().Unix() //统一操作时间
for _, v := range fileList {
var phpGalCont modelshonory.PhotosGallery
err := phpGalCont.GetCont(map[string]interface{}{"`ascription_data_sheet`": ascriptionDataSheet, "`ascription_id`": ascriptionId, "`img_path`": v.PhysicsPath})
if err != nil {
var addCont modelshonory.PhotosGallery
addCont.Url = v.FileUrl //图片地址"`
addCont.ImgPath = v.PhysicsPath //物理地址"`
addCont.Name = v.Name //文档名称"`
addCont.FileSize = v.Size //文档大小"`
addCont.Time = operationTime //创建时间"`
addCont.AscriptionId = ascriptionId //归属"`
addCont.AscriptionDataSheet = ascriptionDataSheet //归属拿个数据表"`
addCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
overall.CONSTANT_DB_MANAGE_ARCHIVES.Create(&addCont)
} else {
editCont := publicmethod.MapOut[string]()
if v.FileUrl != phpGalCont.Url {
editCont["`url`"] = v.FileUrl
}
if v.PhysicsPath != phpGalCont.ImgPath {
editCont["`img_path`"] = v.PhysicsPath
}
if v.Name != phpGalCont.Name {
editCont["`name`"] = v.Name
}
if v.Size != phpGalCont.FileSize {
editCont["`file_size`"] = v.Size
}
if len(editCont) > 0 {
editCont["`state`"] = 1
editCont["`file_size`"] = operationTime
}
var editContInfo modelshonory.PhotosGallery
editContInfo.EiteCont(map[string]interface{}{"`id`": phpGalCont.Id}, editCont)
}
}
}
}

897
api/version1/departmentseting/departmentpc/dingliang.go

@ -0,0 +1,897 @@
package departmentpc
import (
"encoding/json"
"fmt"
"key_performance_indicators/api/version1/postseting/postweb"
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/api/workflow/workflowengine"
"key_performance_indicators/api/workwechat"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-01-15 09:42:53
@ 功能: 获取定量考核任务列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetQuantitativeTasks(c *gin.Context) {
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
//获取参数
var receivedValue GetQuanTasks
c.ShouldBindJSON(&receivedValue)
// var listCont []modelskpi.QualitativeEvaluation
// gormDb := overall.CONSTANT_DB_KPI.Where("`qe_type` = 2 AND `qe_state` = 1 AND FIND_IN_SET(?,`qe_operator`)", myLoginCont.Key)
// if receivedValue.OrgId != "" {
// gormDb = gormDb.Where("qe_accept_evaluation = ?", receivedValue.OrgId)
// }
// if receivedValue.Title != "" {
// gormDb = gormDb.Joins("LEFT JOIN evaluationtarget ON et_id = qe_target").Where("et_title LIKE ?", "%"+receivedValue.Title+"%")
// }
// gormDb := overall.CONSTANT_DB_KPI.Where("`qe_type` = 2 AND `qe_state` = 1 ")
// if receivedValue.OrgId != "" {
// gormDb = gormDb.Where("qe_accept_evaluation = ?", receivedValue.OrgId)
// }
// if receivedValue.Title != "" {
// gormDb = gormDb.Joins("LEFT JOIN evaluationtarget ON et_id = qe_target").Where("et_title LIKE ?", "%"+receivedValue.Title+"%")
// }
var qualEvaCont modelskpi.QualitativeEvaluationView
gormDb := overall.CONSTANT_DB_KPI.Table(fmt.Sprintf("%s qe", qualEvaCont.TableName())).Select("qe.`qe_accept_evaluation`,qe.`qe_target`,qe.`et_title`").Where("qe.`qe_type` = 2 AND qe.`qe_state` = 1 ")
gormDb = gormDb.Joins("JOIN target_report td ON qe.qe_target = td.target_id AND qe.qe_accept_evaluation = td.`department_id` AND td.target_bylaws = qe.`qe_detailed_target` AND td.`type` = 1 AND td.`post_id` = 0 AND td.state = 1 AND td.type_level = 1 AND td.`man_key` = ?", myLoginCont.Key)
if receivedValue.OrgId != "" {
gormDb = gormDb.Where("`qe_accept_evaluation` = ?", receivedValue.OrgId)
}
if receivedValue.Title != "" {
gormDb = gormDb.Where("et_title LIKE ?", "%"+receivedValue.Title+"%")
}
var qualEvaList []modelskpi.QualitativeEvaluationView
err := gormDb.Order("qe_accept_evaluation ASC,qe_target ASC").Find(&qualEvaList).Error
// publicmethod.Result(1, qualEvaList, c, "您没有要参加的考核项目!")
// return
// err := gormDb.Order("qe_type ASC,qe_group ASC,qe_accept_evaluation ASC,qe_dimension ASC,qe_target ASC,qe_target_sun ASC,qe_detailed_target ASC").Find(&listCont).Error
if err != nil || len(qualEvaList) < 1 {
publicmethod.Result(1, qualEvaList, c, "您没有要参加的考核项目!")
return
}
var idInAry []int64
var sendListCont []TargetContOutCont
for _, vsss := range qualEvaList {
var v modelskpi.QualitativeEvaluation
v.GetCont(map[string]interface{}{"`qe_accept_evaluation`": vsss.AcceptEvaluation, "`qe_target`": vsss.Target, "`qe_state`": 1})
if !publicmethod.IsInTrue[int64](v.Id, idInAry) {
idInAry = append(idInAry, v.Id)
var sendCont TargetContOutCont
sendCont.Id = strconv.FormatInt(v.Id, 10)
sendCont.Type = v.Type
sendCont.Group = strconv.FormatInt(v.Group, 10)
//公司
var groupCont modelshr.AdministrativeOrganization
groupCont.GetCont(map[string]interface{}{"`id`": v.Group}, "`name`")
sendCont.GroupNAme = groupCont.Name
//部门
var departCont modelshr.AdministrativeOrganization
departCont.GetCont(map[string]interface{}{"`id`": v.AcceptEvaluation}, "`name`")
sendCont.DepartmentName = departCont.Name
sendCont.DepartmentId = strconv.FormatInt(v.AcceptEvaluation, 10)
sendCont.PlanVersionNumber = v.QualEvalId //执行方案版本号
//维度相关信息
sendCont.Dimension = strconv.FormatInt(v.Dimension, 10)
var dimeCont modelskpi.DutyClass
dimeCont.GetCont(map[string]interface{}{"`id`": v.Dimension}, "`title`")
sendCont.DimensionName = dimeCont.Title
//指标信息
sendCont.Target = strconv.FormatInt(v.Target, 10)
var targetCont modelskpi.EvaluationTarget
targetCont.GetCont(map[string]interface{}{"`et_id`": v.Target}, "`et_title`", "`et_scoring_method`")
sendCont.TargetName = targetCont.Title
//子栏目
sendCont.ScoringMethod = int64(targetCont.ScoringMethod)
if v.TargetSun != 0 {
sendCont.TargetSun = strconv.FormatInt(v.TargetSun, 10)
var sunTargetCont modelskpi.QualitativeTarget
sunTargetCont.GetCont(map[string]interface{}{"`q_id`": v.Target}, "`q_title`")
sendCont.TargetSunName = sunTargetCont.Title
}
//指标细则
if v.DetailedTarget != 0 {
sendCont.DetailedTarget = strconv.FormatInt(v.DetailedTarget, 10)
var detailedTargetCont modelskpi.DetailedTarget
detailedTargetCont.GetCont(map[string]interface{}{"`dt_id`": v.Target}, "`dt_title`", "`dt_content`")
sendCont.DetailedTargetName = detailedTargetCont.Title
sendCont.Content = detailedTargetCont.Content
}
sendCont.Unit = v.Unit
sendCont.ReferenceScore = v.ReferenceScore
sendCont.Cycles = v.Cycles
sendCont.CycleAttres = v.CycleAttres
sendCont.State = v.State
userAry := strings.Split(v.Operator, ",")
sendCont.UserList = userAry
for _, u_v := range userAry {
var repoCont modelshr.PersonArchives
repoErr := repoCont.GetCont(map[string]interface{}{"`key`": u_v}, "`number`", "`name`")
if repoErr == nil {
var userCont QualEvalArrt
userCont.Id = u_v
userCont.Name = repoCont.Name
sendCont.UserListAry = append(sendCont.UserListAry, userCont)
}
}
fmt.Printf("版本号吗!--->%v\n", v.QualEvalId)
sendCont.DimensionWeight, sendCont.TargetWeight = getPlanVersionWeghit(v.QualEvalId, strconv.FormatInt(v.Dimension, 10), strconv.FormatInt(v.Target, 10))
//获取目标设定
quanTitWhere := publicmethod.MapOut[string]()
// quanTitWhere["company_id"] = v.Group
quanTitWhere["departmentid"] = v.AcceptEvaluation
// quanTitWhere["dimension"] = v.Dimension
quanTitWhere["target"] = v.Target
if v.DetailedTarget != 0 {
quanTitWhere["targetconfig"] = v.DetailedTarget
}
quanTitWhere["year"] = publicmethod.UnixTimeToDay(time.Now().Unix(), 16)
quanTitWhere["timecopy"] = AllZreoConfig(v.Cycles)
//目标值设定
var quanTitCont modelskpi.QuantitativeConfig
quanTitCont.GetCont(quanTitWhere)
//全奖值、零奖值、封顶值
sendCont.ZeroPrize = strconv.FormatFloat(float64(quanTitCont.Zeroprize)/100, 'f', -1, 64)
sendCont.AllPrize = strconv.FormatFloat(float64(quanTitCont.Allprize)/100, 'f', -1, 64)
sendCont.CappingVal = quanTitCont.CappingVal / 100
//获取实际值
shiJiZhi := publicmethod.MapOut[string]()
shiJiZhi["fl_evaluation_user"] = myLoginCont.Key
shiJiZhi["fl_evaluation_department"] = myLoginCont.MainDeparment
shiJiZhi["fl_evaluation_group"] = myLoginCont.Company
shiJiZhi["fl_duty_department"] = v.AcceptEvaluation
operationTime := time.Now().Unix()
if receivedValue.Time != "" {
strTime := fmt.Sprintf("%v-01 00:00:00", receivedValue.Time)
stringToTime, strToTimeErr := publicmethod.DateToTimeStamp(strTime)
if strToTimeErr == true {
operationTime = stringToTime
} else {
strTime = fmt.Sprintf("%v 00:00:00", receivedValue.Time)
stringToTime, strToTimeErr = publicmethod.DateToTimeStamp(strTime)
if strToTimeErr == true {
operationTime = stringToTime
}
}
}
years := publicmethod.ComputingTime(operationTime, 1)
quarter := publicmethod.ComputingTime(operationTime, 2)
months := publicmethod.ComputingTime(operationTime, 3)
switch v.Cycles {
case 1:
shiJiZhi["fl_year"] = years
shiJiZhi["fl_quarter"] = quarter
shiJiZhi["fl_month"] = months
shiJiZhi["fl_week"] = publicmethod.ComputingTime(operationTime, 4)
shiJiZhi["fl_day"] = publicmethod.ComputingTime(operationTime, 5)
case 2:
shiJiZhi["fl_year"] = years
shiJiZhi["fl_quarter"] = quarter
shiJiZhi["fl_month"] = months
shiJiZhi["fl_week"] = publicmethod.ComputingTime(operationTime, 4)
shiJiZhi["fl_day"] = publicmethod.ComputingTime(operationTime, 5)
case 3:
shiJiZhi["fl_year"] = years
shiJiZhi["fl_quarter"] = quarter
shiJiZhi["fl_month"] = months
shiJiZhi["fl_week"] = publicmethod.ComputingTime(operationTime, 4)
case 4:
shiJiZhi["fl_year"] = years
shiJiZhi["fl_quarter"] = quarter
shiJiZhi["fl_month"] = months
case 5:
shiJiZhi["fl_year"] = years
shiJiZhi["fl_quarter"] = quarter
case 6:
shiJiZhi["fl_year"] = years
default:
shiJiZhi["fl_year"] = years
shiJiZhi["fl_quarter"] = quarter
shiJiZhi["fl_month"] = months
shiJiZhi["fl_week"] = publicmethod.ComputingTime(operationTime, 4)
shiJiZhi["fl_day"] = publicmethod.ComputingTime(operationTime, 5)
}
sendCont.ReferTo = JudgeDingLiangIsTrue(v.Id, v.AcceptEvaluation, years, quarter, months, v.Cycles)
actualValue, shouDongScore := GetTimeIntervalDuty(shiJiZhi, v.Id) //实际值
sendCont.Actual = strconv.FormatFloat(actualValue/100, 'f', -1, 64)
// chuShuVal := actualValue - quanTitCont.Zeroprize
// beiChuShuVal := quanTitCont.Allprize - quanTitCont.Zeroprize
// if beiChuShuVal > 0 {
// sendCont.ReachScore = chuShuVal / beiChuShuVal
// } else {
// sendCont.ReachScore = 0
// }
var actual float64
actual, sendCont.ReachScore = postweb.GetAchieAndActual(actualValue, float64(sendCont.TargetWeight), quanTitCont.Zeroprize, quanTitCont.Allprize, quanTitCont.CappingVal)
if targetCont.ScoringMethod != 1 {
sendCont.ReachScore = publicmethod.DecimalEs(shouDongScore/100, 2)
}
// fmt.Printf("All--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", actualValue, sendCont.TargetWeight, quanTitCont.Zeroprize, quanTitCont.Allprize, quanTitCont.CappingVal, sendCont.ReachScore, actual)
if quanTitCont.Zeroprize == 0 && quanTitCont.Allprize == 0 {
sendCont.Reach = "未设置目标值"
} else {
dividend := quanTitCont.Allprize - quanTitCont.Zeroprize //被除数
if dividend == 0 {
sendCont.Reach = "未设置目标值"
} else {
// sendCont.Reach = fmt.Sprintf("(实际值-零奖值)/(全奖值-零奖值)")
actual = publicmethod.DecimalEs(actual*100, 2)
sendCont.Reach = fmt.Sprintf("%v%v", actual, "%")
if actualValue == 0 {
sendCont.Reach = "100%"
}
}
}
sendCont.Reason = ""
sendCont.DetailedTarget = strconv.FormatInt(v.DetailedTarget, 10)
// switch v.Cycles {
// case 5:
// banNian := []int64{3, 6, 9, 12}
// if publicmethod.IsInTrue[int64](months, banNian) {
// sendListCont = append(sendListCont, sendCont)
// }
// case 6:
// if months == 12 {
// sendListCont = append(sendListCont, sendCont)
// }
// case 7:
// banNian := []int64{6, 12}
// if publicmethod.IsInTrue[int64](months, banNian) {
// sendListCont = append(sendListCont, sendCont)
// }
// default:
// sendListCont = append(sendListCont, sendCont)
// }
sendListCont = append(sendListCont, sendCont)
}
}
publicmethod.Result(0, sendListCont, c)
}
// 判断定量指标是否已经提交
func JudgeDingLiangIsTrue(targetId, department int64, year, quarter, monthsss int64, types int) bool {
var idList []int64
// gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.FlowDataLogType{}).Select("`id`").Where("`targetid` = ? AND `department` = ?", targetId, department)
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.FlowDataLogType{}).Select("`id`").Where("`fld_evaluation_id` = ? AND `department` = ?", targetId, department)
// switch types {
// case 5:
// gormDb = gormDb.Where("`year` = ? AND `quarte` = ?", year, quarter)
// case 6:
// gormDb = gormDb.Where("`year` = ?", year)
// case 7:
// banNian := []int{1, 2, 3, 4, 5, 6}
// if monthsss > 6 {
// banNian = []int{7, 8, 9, 10, 11, 12}
// }
// gormDb = gormDb.Where("`year` = ? AND `month` IN ?", year, banNian)
// default:
// gormDb = gormDb.Where("`year` = ? AND `month` = ?", year, monthsss)
// }
/*
规则改变不管哪种统计类型每个月都要提交数据 季度计算未季度平均值在季度末参与计算
*/
gormDb = gormDb.Where("`year` = ? AND `month` = ?", year, monthsss)
err := gormDb.Find(&idList).Error
if err == nil && len(idList) > 0 {
return true
}
return false
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-15 10:23:22
@ 功能: 获取维度与指标权重
@ 参数
#planKey 方案编号
#dimensionId 维度
#targetId 指标
@ 返回值
#dimensionIdWeghit 维度权重
#targetIdWeghit 指标权重
@ 方法原型
#getPlanVersionWeghit(planKey, dimensionId, targetId string) (dimensionIdWeghit, targetIdWeghit int64)
*/
func getPlanVersionWeghit(planKey, dimensionId, targetId string) (dimensionIdWeghit, targetIdWeghit int64) {
var planVersionCont modelskpi.PlanVersio
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.PlanVersio{}).Select("`content`").Where("`key` = ?", planKey).First(&planVersionCont).Error
if err != nil {
return
}
var planVersioInfo []AddDutyNewCont
jsonErr := json.Unmarshal([]byte(planVersionCont.Content), &planVersioInfo)
if jsonErr != nil {
return
}
for _, v := range planVersioInfo {
if v.Id == dimensionId {
dimensionIdWeghit = int64(v.ZhiFraction)
for _, cv := range v.Child {
if cv.Id == targetId {
targetIdWeghit = cv.ReferenceScore
}
}
}
}
return
}
/**
@ 作者: 秦东
@ 时间: 2023-01-15 10:49:07
@ 功能: 判断全奖与零奖参数
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
// 判断全奖与零奖参数
func AllZreoConfig(cycles int) (monthInt int64) {
switch cycles {
case 4:
monthInt = publicmethod.ComputingTime(time.Now().Unix(), 3)
case 5:
monthInt = publicmethod.ComputingTime(time.Now().Unix(), 2)
default:
}
return
}
// 获取定量考核时间内审批通过的考核数据
func GetTimeIntervalDuty(whereData interface{}, schemeID int64) (actual, shouDongScore float64) {
// jsonStr, _ := json.Marshal(whereData)
// fmt.Printf("jsonStr------1------>%v\n", string(jsonStr))
actual = 0
//相关审批流
var flowLogList []modelskpi.FlowLog
err := overall.CONSTANT_DB_KPI.Where("`fl_reply` IN (2,3) AND FIND_IN_SET(?,`fl_evaluation_id`)", schemeID).Where(whereData).Find(&flowLogList).Error
if err != nil {
return
}
for _, v := range flowLogList {
ziDongScore, sdScore := GetSchemeFlowData(v.Key, schemeID)
actual = actual + ziDongScore
shouDongScore = shouDongScore + sdScore
}
return
}
// 获取指定审批流方案数据
func GetSchemeFlowData(flowKwy, schemeID int64) (weightSum, shouDongScore float64) {
weightSum = 0
overall.CONSTANT_DB_KPI.Model(&modelskpi.FlowLogData{}).Where("`fld_evaluation_id` = ? AND `fld_flow_log` = ?", schemeID, flowKwy).Pluck("COALESCE(SUM(fld_score), 0) as flscore", &weightSum)
// weightSum = 0
overall.CONSTANT_DB_KPI.Model(&modelskpi.FlowLogData{}).Where("`fld_evaluation_id` = ? AND `fld_flow_log` = ?", schemeID, flowKwy).Pluck("COALESCE(SUM(fld_scoring_score), 0) as scoring_score", &shouDongScore)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-23 16:35:22
@ 功能: 获取关联指标细则
@ 参数
#targetid 指标ID
#tableid 栏目Id
#bylaws 细则Id
#orgid 行政组织
#post 岗位
#types 类型1指标2子目标3细则
#level 级别1部门级2岗位级
@ 返回值
#bylawsId 相关ID
#err 信息
@ 方法原型
#GetTargetDetailsInfoList(targetid, tableid, bylaws, orgid, post int64, types, level int) (bylawsId []int64, err error)
*/
func GetTargetDetailsInfoList(targetid, tableid, bylaws, orgid, post int64, types, level int) (bylawsId []int64, err error) {
if types == 0 {
types = 3
}
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{})
switch types {
case 1:
gormDb = gormDb.Distinct(`target_id`)
case 2:
gormDb = gormDb.Distinct(`target_sun_id`)
default:
gormDb = gormDb.Distinct(`target_bylaws`)
}
gormDb = gormDb.Where("`state` = 1 AND `type` = ? AND `level` = ?", types, level)
if targetid != 0 {
gormDb = gormDb.Where("`target_id` = ?", targetid)
}
if tableid != 0 {
gormDb = gormDb.Where("`target_sun_id` = ?", tableid)
}
if bylaws != 0 {
gormDb = gormDb.Where("`target_bylaws` = ?", bylaws)
}
err = gormDb.Find(&bylawsId).Error
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-12 16:03:31
@ 功能: 提交定量考核
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SubmitQuantifyTarget(c *gin.Context) {
var receivedValue SubmitQuantTargetCont
c.ShouldBindJSON(&receivedValue)
if receivedValue.FlowworkId == "" {
publicmethod.Result(1, receivedValue, c, "未知工作流!不可进行提交")
return
}
if receivedValue.DepartmentId == "" {
publicmethod.Result(1, receivedValue, c, "未知行政组织!不可进行提交")
return
}
acceptDepartment, _ := strconv.ParseInt(receivedValue.DepartmentId, 10, 64)
if receivedValue.PlanVersionNumber == "" {
publicmethod.Result(1, receivedValue, c, "未知方案!不可进行提交")
return
}
operationTime := time.Now().Unix() //统一操作时间
occurrenceTime := operationTime
//计算发生时间
currentYears := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 1), 10)
currentQuarter := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 2), 10)
currentMonths := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 3), 10)
currentWeek := strconv.FormatInt(publicmethod.ComputingTime(operationTime, 4), 10)
if receivedValue.Time == "" {
publicmethod.Result(1, receivedValue, c, "未知考核时间!不可进行提交")
return
} else {
var dayTime publicmethod.DateTimeTotimes
dayTime.BaisStrToTime(receivedValue.Time)
if dayTime.Years != "" {
currentYears = dayTime.Years
}
if dayTime.Quarter != "" {
currentQuarter = dayTime.Quarter
}
if dayTime.Months != "" {
currentMonths = dayTime.Months
}
if dayTime.Week != "" {
currentWeek = dayTime.Week
}
occurrenceTime = dayTime.AllTime
}
currentYearsInt, _ := strconv.ParseInt(currentYears, 10, 64) //年
currentQuarterInt, _ := strconv.ParseInt(currentQuarter, 10, 64) //季度
currentMonthsInt, _ := strconv.ParseInt(currentMonths, 10, 64) //月
currentWeekInt, _ := strconv.ParseInt(currentWeek, 10, 64) //周
if len(receivedValue.List) < 1 {
publicmethod.Result(1, receivedValue, c, "未知考核项目!不可进行提交")
return
}
var errMsg []string
var dimIdList []string
var tarIdList []string
var allZreoConfig []FlowLogAllZreo
for _, v := range receivedValue.List {
if v.Id == "" {
errMsg = append(errMsg, "未知考核项目")
}
var allZreoConfigInfo FlowLogAllZreo
allZreoConfigInfo.Id = v.Id
allZreoConfigInfo.TargetId = v.Target
allZreoConfigInfo.TargetWeight = float64(v.TargetWeight)
var qualEvalCont modelskpi.QualitativeEvaluation
err := qualEvalCont.GetCont(map[string]interface{}{"`qe_id`": v.Id}, "qe_dimension", "qe_target")
if err != nil {
errMsg = append(errMsg, fmt.Sprintf("%v未知考核项目!不可进行提交", v.Targetname))
} else {
dimStr := strconv.FormatInt(qualEvalCont.Dimension, 10)
if !publicmethod.IsInTrue[string](dimStr, dimIdList) {
dimIdList = append(dimIdList, dimStr)
}
tarStr := strconv.FormatInt(qualEvalCont.Target, 10)
if !publicmethod.IsInTrue[string](tarStr, tarIdList) {
tarIdList = append(tarIdList, tarStr)
}
switch qualEvalCont.Cycles {
case 5:
var qualConfig modelskpi.QuantitativeConfig
conWhere := publicmethod.MapOut[string]()
conWhere["`departmentid`"] = acceptDepartment
conWhere["`dimension`"] = qualEvalCont.Dimension
conWhere["`target`"] = qualEvalCont.Target
conWhere["`year`"] = currentQuarterInt
conWhere["`timecopy`"] = currentMonthsInt
qualConfig.GetCont(conWhere, "zeroprize", "allprize", "capping_val")
allZreoConfigInfo.Zeroprize = qualConfig.Zeroprize
allZreoConfigInfo.Allprize = qualConfig.Allprize
allZreoConfigInfo.Capping = qualConfig.CappingVal
case 6:
var qualConfig modelskpi.QuantitativeConfig
conWhere := publicmethod.MapOut[string]()
conWhere["`departmentid`"] = acceptDepartment
conWhere["`dimension`"] = qualEvalCont.Dimension
conWhere["`target`"] = qualEvalCont.Target
conWhere["`year`"] = currentYearsInt
conWhere["`timecopy`"] = 1
qualConfig.GetCont(conWhere, "zeroprize", "allprize", "capping_val")
allZreoConfigInfo.Zeroprize = qualConfig.Zeroprize
allZreoConfigInfo.Allprize = qualConfig.Allprize
allZreoConfigInfo.Capping = qualConfig.CappingVal
default:
var qualConfig modelskpi.QuantitativeConfig
conWhere := publicmethod.MapOut[string]()
conWhere["`departmentid`"] = acceptDepartment
conWhere["`dimension`"] = qualEvalCont.Dimension
conWhere["`target`"] = qualEvalCont.Target
conWhere["`year`"] = currentYearsInt
conWhere["`timecopy`"] = currentMonthsInt
qualConfig.GetCont(conWhere, "zeroprize", "allprize", "capping_val")
allZreoConfigInfo.Zeroprize = qualConfig.Zeroprize
allZreoConfigInfo.Allprize = qualConfig.Allprize
allZreoConfigInfo.Capping = qualConfig.CappingVal
}
allZreoConfig = append(allZreoConfig, allZreoConfigInfo)
}
if v.Actual == "" {
errMsg = append(errMsg, fmt.Sprintf("%v未输入实际值", v.Targetname))
}
if v.Addtime == "" {
errMsg = append(errMsg, fmt.Sprintf("%v未输入检查时间", v.Targetname))
}
var waiBuTime publicmethod.DateTimeTotimes
waiBuTime.BaisStrToTime(v.Addtime)
where := publicmethod.MapOut[string]()
where["fld_year"] = waiBuTime.Years
where["fld_quarter"] = waiBuTime.Quarter
where["fld_month"] = waiBuTime.Months
where["fld_evaluation_id"] = v.Id
where["fl_duty_department"] = receivedValue.DepartmentId
fmt.Printf("where--->%v\n", where)
var dutyData modelskpi.DutyFlowData
err = dutyData.GetCont(where, "fld_id")
if err == nil {
errMsg = append(errMsg, fmt.Sprintf("%v已经提交过!请不要重复提交!", v.Targetname))
}
}
if len(errMsg) > 0 {
errMsgStr := strings.Join(errMsg, ";")
publicmethod.Result(1, receivedValue, c, errMsgStr)
return
}
uuid := publicmethod.GetUUid(6) //上报数据唯一识别码
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
myUserKey := strconv.FormatInt(myLoginCont.Key, 10)
//获取工作流
var workflowInfo currency_recipe.WorkflowEngine
jieguo := workflowInfo.InitWorkflow(receivedValue.FlowworkId, "", myUserKey, receivedValue.DepartmentId).SendData()
//处理工作流
var haveWorkflow workflowengine.OperateWorkflow
haveWorkflow.Step = 1 //操作哪一步
// haveWorkflow.OrderId = uuid //发起表单ID
// haveWorkflow.Attribute = qualEvalCont.Type //属性 1、定性;2、定量
haveWorkflow.OperationStatus = 2 //操作状态
var caoZuoRen workflowengine.ManipulatePeopleInfo
caoZuoRen.Key = strconv.FormatInt(myLoginCont.Key, 10) //操作人
caoZuoRen.OrgId = strconv.FormatInt(myLoginCont.AdminOrg, 10) //操作人行政组织
haveWorkflow.ManipulatePeople = caoZuoRen //操作人相关
haveWorkflow.WorkFlowList = jieguo.NodeContList //流程步进图
flowView := haveWorkflow.ManipulateWorkflow() //处理后的工作流
//审批主体信息
var evalProFlowView modelskpi.EvaluationProcess
evalProFlowView.OrderKey = uuid //发起表单key"`
evalProFlowView.Step = haveWorkflow.Step //当前执行到第几部"`
flowAllJson, _ := json.Marshal(flowView)
evalProFlowView.Content = string(flowAllJson) //流程步进值"`
nextNodeJson, _ := json.Marshal(haveWorkflow.NextNodeCont)
nextNodeStr := string(nextNodeJson)
evalProFlowView.NextContent = nextNodeStr //下一步内容"`
evalProFlowView.Time = operationTime //创建时间"`
evalProFlowView.State = 2 //1:起草,2:审批中;3:通过;4:驳回"`
evalProFlowView.RoleGroup = 0 //角色组"`
evalProFlowView.TypeClass = 2 //1、定性;2、定量"`
evalProFlowView.Participants = strings.Join(haveWorkflow.Participant, ",") //参与人"`
evalProFlowView.StartTime = operationTime //流程开始时间"`
evalProFlowView.NextStep = haveWorkflow.NextStep //下一步"`
evalProFlowView.NextExecutor = strings.Join(haveWorkflow.NextNodeContExecutor, ",") //下一步执行人"`
evalProFlowView.SetupDepartment = myLoginCont.MainDeparment //发起部门"`
evalProFlowView.Dimension = strings.Join(dimIdList, ",") //维度"`
evalProFlowView.Target = strings.Join(tarIdList, ",") //指标"`
evalProFlowView.AcceptDepartment = acceptDepartment //接受考核部门"`
evalProFlowView.HappenTime = occurrenceTime
flowKyeInt, _ := strconv.ParseInt(receivedValue.FlowworkId, 10, 64)
evalProFlowView.FlowKey = flowKyeInt //流程图唯一识别符
flowVersionInt, _ := strconv.ParseInt(jieguo.Version, 10, 64)
evalProFlowView.FlowVid = flowVersionInt //流程版本"`
evalProFlowView.EpOld = 2
evalProFlowView.Creater = myLoginCont.Key //发起人
evalProFlowView.Clique = myLoginCont.Company //流程归属公司
//定量数据流水值
var planIdList []string
var addFlowDataList []modelskpi.FlowLogData
for _, v := range receivedValue.List {
var flowDataCont modelskpi.FlowLogData
if !publicmethod.IsInTrue[string](v.Id, planIdList) {
planIdList = append(planIdList, v.Id)
}
planId, _ := strconv.ParseInt(v.Id, 10, 64)
flowDataCont.EvaluationPlan = planId //考核方案项目ID"`
flowDataCont.Key = uuid //识别标志"`
flowDataCont.Score = publicmethod.StrNumberToInt64(v.Actual, 100) //数据"`
flowDataCont.Content = v.Reason //描述"`
flowDataCont.Time = operationTime //创建时间"`
flowDataCont.ScoringMethod = v.ScoringMethod
reacVal := publicmethod.StrNumberToInt64(v.ReachScore, 100) //计分方式(1:自动;2:手动)"`
flowDataCont.ScoringScore = float64(reacVal) //手动分"`
flowDataCont.PlanVersion = v.PlanVersionNumber //版本号"`
flowDataCont.Year = currentYearsInt //年分"`
flowDataCont.Quarter = currentQuarterInt //季度"`
flowDataCont.Month = currentMonthsInt //月"`
flowDataCont.Week = currentWeekInt //周"`
flowDataCont.ToDay = 10 //天"`
tarInt, _ := strconv.ParseInt(v.Target, 10, 64)
flowDataCont.TargetId = tarInt //指标ID"`
addFlowDataList = append(addFlowDataList, flowDataCont)
}
//定量考核数据表
var workFlowLogCont modelskpi.FlowLog
workFlowLogCont.EvaluationPlan = strings.Join(planIdList, ",") //考核方案项目ID"`
// workFlowLogCont.Score = //数据"`
workFlowLogCont.Key = uuid //识别标志"`
// workFlowLogCont.Content = //描述"`
workFlowLogCont.Time = occurrenceTime //创建时间"`
workFlowLogCont.EiteTime = operationTime //修改时间"`
workFlowLogCont.EvaluationDepartment = myLoginCont.MainDeparment //测评部门"`
workFlowLogCont.EvaluationUser = myLoginCont.Key //测评人"`
workFlowLogCont.EvaluationGroup = myLoginCont.Company //测评集团"`
workFlowLogCont.Year = currentYearsInt //年分"`
workFlowLogCont.Quarter = currentQuarterInt //季度"`
workFlowLogCont.Month = currentMonthsInt //月"`
workFlowLogCont.Week = currentWeekInt //周"`
workFlowLogCont.ToDay = 10 //天"`
// workFlowLogCont.Enclosure = //附件"`
_, companyId, _, _, _ := publicmethod.GetOrgStructurees(acceptDepartment)
workFlowLogCont.DutyGroup = companyId //职责集团"`
workFlowLogCont.DutyDepartment = acceptDepartment //职责部门"`
workFlowLogCont.Reply = 2 //1状态(0:删除;1:起草;2:审批;3:通过)"`
workFlowLogCont.PlanVersion = receivedValue.PlanVersionNumber //版本号"`
baseJson, _ := json.Marshal(allZreoConfig)
workFlowLogCont.Baseline = string(baseJson) //基准线 "`
//审批记录
var stepsTotal int64
overall.CONSTANT_DB_KPI.Model(&modelskpi.OpenApprovalChangeLog{}).Where("`orderid` = ?", uuid).Count(&stepsTotal)
var flowLogCont modelskpi.OpenApprovalChangeLog
flowLogCont.Type = 1 //类型(1:部门;2:岗位)"`
flowLogCont.Title = haveWorkflow.CurrentNode.NodeName //节点名称"`
flowLogCont.Operator = myLoginCont.Key //操作人"`
flowLogCont.OrderId = uuid //订单ID"`
flowLogCont.OperatorTime = operationTime //操作时间"`
flowLogCont.Step = stepsTotal + 1 //操作第几步"`
flowLogCont.OperatorType = haveWorkflow.CurrentNode.State //操作状态(1:位操作;2:已操作)"`
flowLogCont.Msgid = "" //消息id,用于撤回应用消息"`
flowLogCont.ResponseCode = "" //仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,24小时内有效,且只能使用一次"`
flowLogCont.Stepper = haveWorkflow.CurrentNode.Step //步进器"`
flowLogCont.ChangeIsTrue = 1 //是否可变更(1:可变更;2:不可变更)"`
flowLogCont.Eiteyime = operationTime //变动时间"`
flowLogCont.YesOrNo = haveWorkflow.CurrentNode.State //未操作;1:同意;2:驳回;3:撤回"`
outPur := publicmethod.MapOut[string]()
outPur["evalProFlowView"] = evalProFlowView
outPur["workFlowLogCont"] = workFlowLogCont
outPur["addFlowDataList"] = addFlowDataList
outPur["flowLogCont"] = flowLogCont
gormDb := overall.CONSTANT_DB_KPI.Begin()
evalProFlowViewErr := gormDb.Create(&evalProFlowView).Error
workFlowLogContErr := gormDb.Create(&workFlowLogCont).Error
addFlowDataListErr := gormDb.Create(&addFlowDataList).Error
flowLogContErr := gormDb.Create(&flowLogCont).Error
var callbackMsg []byte //
var err error
var workwechatErr error
if evalProFlowViewErr == nil && workFlowLogContErr == nil && addFlowDataListErr == nil && flowLogContErr == nil {
addErr := gormDb.Commit().Error
if addErr == nil {
//下一个节点内容
if nextNodeStr != "" { //判断下个节点是否为空
if len(haveWorkflow.NextNodeCont.UserList) > 0 { //判断下个节点是够有审批人
var recipient []string //接收人
var sendWechatUserKey []string
for _, v := range haveWorkflow.NextNodeCont.UserList { //获取接收人得微信或企业微信Openid用作发送消息的唯一识别码
if !publicmethod.IsInTrue[string](v.Id, sendWechatUserKey) {
sendWechatUserKey = append(sendWechatUserKey, v.Id)
}
if v.Wechat != "" {
if !publicmethod.IsInTrue[string](v.Wechat, recipient) {
recipient = append(recipient, v.Wechat)
}
} else {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.Id}, "`wechat`", "`work_wechat`")
if userCont.Wechat != "" {
if !publicmethod.IsInTrue[string](userCont.Wechat, recipient) {
recipient = append(recipient, userCont.Wechat)
}
}
if userCont.WorkWechat != "" {
if !publicmethod.IsInTrue[string](userCont.WorkWechat, recipient) {
recipient = append(recipient, userCont.WorkWechat)
}
}
}
}
if len(recipient) > 0 { //判断是否有接收人
//开始组装消息内容
var sendMsg workwechat.SentMiniMessage
sendMsg.ToUser = strings.Join(recipient, "|") //收件人配置
var templateCard workwechat.TemplateCardMsgContMini //模版卡片主体
//头部左标题部分
nodeType := publicmethod.GetSetpNodeName(haveWorkflow.NextNodeCont.Type)
templateCard.Source.Desc = fmt.Sprintf("%v-%v", haveWorkflow.NextNodeCont.NodeName, nodeType)
//任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成
templateCard.TaskId = fmt.Sprintf("kpi_ratify_%v", uuid)
templateCard.ActionMenu.Desc = "恒信高科"
var rightHand workwechat.ActionListCont
rightHand.Text = "恒信高科"
rightHand.Key = fmt.Sprintf("kpi_head_%v", publicmethod.GetUUid(7))
templateCard.ActionMenu.ActionList = append(templateCard.ActionMenu.ActionList, rightHand)
//主内容框
templateCard.MainTitle.Title = fmt.Sprintf("考核周期:%v", publicmethod.UnixTimeToDay(occurrenceTime, 15))
//引用文献样式
var yinYongWenXian []string
for _, v := range receivedValue.List {
if v.ScoringMethod == 1 {
yinYongWenXian = append(yinYongWenXian, fmt.Sprintf("指标:%v\n实际值:%v\n达成率:%v\n得分:%v", v.Targetname, v.Actual, v.Reach, v.ReachScore))
} else {
var lsZeroprize float64
var lsAllprize float64
var lsCapping float64
for _, cv := range allZreoConfig {
if cv.TargetId == v.Target {
lsZeroprize = cv.Zeroprize
lsAllprize = cv.Allprize
lsCapping = cv.Capping
}
}
actualInt, _ := strconv.ParseInt(v.Actual, 10, 64)
scoreVal, _, _, _, _ := publicmethod.CalculateScore(v.TargetWeight, float64(actualInt)*100, lsAllprize, lsZeroprize, lsCapping, 2)
yinYongWenXian = append(yinYongWenXian, fmt.Sprintf("指标:%v\n实际值:%v\n达成率:%v\n得分:%v\n手动分:%v\n原因:%v", v.Targetname, v.Actual, v.Reach, scoreVal, v.ReachScore, v.Reason))
}
}
fmt.Printf("sendMsg->%v\ntemplateCard->%v\nyinYongWenXian->%v\n", sendMsg, templateCard, yinYongWenXian)
templateCard.QuoteArea.QuoteText = strings.Join(yinYongWenXian, "\n")
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
var userRecarCont modelshr.PersonArchives
userRecarCont.GetCont(map[string]interface{}{"`key`": myLoginCont.Key}, "`wechat`", "`work_wechat`", "`maindeparment`")
recipientWechat := userRecarCont.Wechat
if userRecarCont.WorkWechat != "" {
recipientWechat = userRecarCont.WorkWechat
}
var orgContInfo modelshr.AdministrativeOrganization
orgContInfo.GetCont(map[string]interface{}{"`id`": userRecarCont.MainDeparment}, "name")
var hcListCont1 workwechat.HorizontalContentListCont
hcListCont1.Type = 0
hcListCont1.Keyname = "提报部门:"
hcListCont1.Value = orgContInfo.Name
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont1)
var hcListCont3 workwechat.HorizontalContentListCont
hcListCont3.Keyname = "提报人:"
hcListCont3.Value = fmt.Sprintf("%v(%v)", myLoginCont.Name, myLoginCont.Number)
if recipientWechat != "" {
hcListCont3.Type = 3
hcListCont3.UserId = recipientWechat
} else {
hcListCont3.Type = 0
}
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont3)
//审批详情访问地址
jumpUrl := fmt.Sprintf("%v/#/pages/approval/departworkflowcont?id=%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl, evalProFlowView.Id)
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
var jmpCont1 workwechat.JumpListCont
jmpCont1.Type = 1
jmpCont1.Title = "前往处理"
jmpCont1.Url = jumpUrl
templateCard.JumpList = append(templateCard.JumpList, jmpCont1)
//整体卡片的点击跳转事件,text_notice必填本字段
templateCard.CardAction.Url = jumpUrl
sendMsg.TemplateCard = templateCard
callbackMsg, err = sendMsg.InitMes().SendMessage()
workwechatErr = workwechat.WriteUpdateWechatTempmsg(callbackMsg, sendMsg, 1, uuid, sendWechatUserKey)
var callbackCont publicmethod.WechatCallBack
json.Unmarshal(callbackMsg, &callbackCont)
}
}
}
outErr := publicmethod.MapOut[string]()
outErr["addErr"] = addErr
outErr["err"] = err
outErr["workwechatErr"] = workwechatErr
outErr["callbackMsg"] = string(callbackMsg)
publicmethod.Result(0, outErr, c)
} else {
addErr := gormDb.Rollback().Error
publicmethod.Result(104, addErr, c)
}
} else {
outErr := publicmethod.MapOut[string]()
addErr := gormDb.Rollback().Error
outErr["evalProFlowViewErr"] = evalProFlowViewErr
outErr["workFlowLogContErr"] = workFlowLogContErr
outErr["addFlowDataListErr"] = addFlowDataListErr
outErr["flowLogContErr"] = flowLogContErr
outErr["addErr"] = addErr
publicmethod.Result(1014, outErr, c)
}
// publicmethod.Result(0, outPur, c)
}

1613
api/version1/departmentseting/departmentpc/programme.go

File diff suppressed because it is too large

784
api/version1/departmentseting/departmentpc/qualitativekpi.go

File diff suppressed because it is too large

142
api/version1/departmentseting/departmentpc/rulesmatrix.go

@ -134,3 +134,145 @@ func GetRulesDepartment(target, sonTarget, bylaws int64, level int) (orgId []int
// fmt.Printf("orgId----------->%v----------->%v\n", orgId, snedId)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-13 15:17:31
@ 功能: 获取指定指标下的细则列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetTargetDetailsList(c *gin.Context) {
var receivedValue GetTarDetails
c.ShouldBindJSON(&receivedValue)
if receivedValue.TargetId == 0 {
publicmethod.Result(1, receivedValue, c, "未获取到指标ID!")
return
}
var idList []int64
var detCont modelskpi.DetailedTarget
gormDb := overall.CONSTANT_DB_KPI.Table(fmt.Sprintf("%s dt", detCont.TableName())).Distinct("dt.dt_id").Where("dt.dt_state BETWEEN 1 AND 2 AND dt.dt_parentid = ?", receivedValue.TargetId)
if receivedValue.Cycle != 0 {
gormDb = gormDb.Where("dt.`dt_cycle` = ?", receivedValue.Cycle)
}
if len(receivedValue.TestMethod) > 0 {
var sqlOrStr string
for ti, tv := range receivedValue.TestMethod {
if ti == 0 {
// gormDb = gormDb.Where("FIND_IN_SET(?,`dt_censor_type`)", tv)
sqlOrStr = fmt.Sprintf("FIND_IN_SET(%v,`dt_censor_type`)", tv)
} else {
// gormDb = gormDb.Or("FIND_IN_SET(?,`dt_censor_type`)", tv)
sqlOrStr = fmt.Sprintf("%v OR FIND_IN_SET(%v,`dt_censor_type`)", sqlOrStr, tv)
}
}
gormDb = gormDb.Where(sqlOrStr)
}
if len(receivedValue.OrgList) > 0 {
gormDb = gormDb.Joins("LEFT JOIN `target_department` `td` on td.target_id = dt.dt_parentid AND td.target_sun_id = dt.dt_parentid_sun AND td.target_bylaws = dt.dt_id").Where("td.`type` = 3 AND td.`state` BETWEEN 1 AND 2 AND td.`level` = 1 AND td.department_id IN ?", receivedValue.OrgList)
}
err := gormDb.Find(&idList).Error
if err != nil || len(idList) < 1 {
publicmethod.Result(107, err, c)
return
}
// return
var listCont []modelskpi.DetailedTarget
err = overall.CONSTANT_DB_KPI.Where("`dt_id` IN ?", idList).Order("dt_parentid desc, dt_parentid_sun").Find(&listCont).Error
if err != nil || len(listCont) < 1 {
publicmethod.Result(107, err, c)
return
}
var sendListCont []outputTargetDetails
jishuqi := 1
var lastSunTable int64
for _, v := range listCont {
var sendCont outputTargetDetails
sendCont.Id = v.Id
sendCont.Title = v.Title //指标细则"`
sendCont.Content = v.Content //指标说明"`
sendCont.ParentId = v.ParentId //归属指标栏目"`
if lastSunTable != v.ParentIdSun {
lastSunTable = v.ParentIdSun
jishuqi = 1
} else {
jishuqi = jishuqi + 1
}
sendCont.JiBuQi = jishuqi
sendCont.ParentIdSun = v.ParentIdSun //归属指标子栏目"`
sendCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
sendCont.AddTime = v.AddTime //制定时间"`
sendCont.MinScore = v.MinScore //最小分*100保存"`
sendCont.MaxScore = v.MaxScore //最大分*100保存"`
sendCont.Company = v.Company //单位"`
sendCont.AddReduce = v.AddReduce //1:减少;2:增加;3:无属性,现场确认加或减"`
sendCont.CensorType = v.CensorType //检查方式"`
sendCont.CensorCont = v.CensorCont //检查依据"`
sendCont.CensorRate = v.CensorRate //检查频次"`
sendCont.Cycles = v.Cycles //1:班;2:天;3:周;4:月;5:季度;6:年"`
sendCont.CycleAttres = v.CycleAttres //辅助计数"`
sendCont.Paretment = v.Paretment //接受考核的部门"`
sendCont.Reportary = v.Reportary //提报人"`
var sonTargetCont modelskpi.QualitativeTarget
sonTargetCont.GetCont(map[string]interface{}{"q_id": v.ParentIdSun}, "q_title")
sendCont.ColumnName = sonTargetCont.Title
if v.MinScore != 0 && v.MaxScore != 0 {
minScoreFloat64 := publicmethod.DecimalEs(float64(v.MinScore)/100, 2)
maxScoreFloat64 := publicmethod.DecimalEs(float64(v.MaxScore)/100, 2)
sendCont.Standard = fmt.Sprintf("%v-%v", minScoreFloat64, maxScoreFloat64)
} else if v.MinScore == 0 && v.MaxScore != 0 {
maxScoreFloat64 := publicmethod.DecimalEs(float64(v.MaxScore)/100, 2)
sendCont.Standard = fmt.Sprintf("%v", maxScoreFloat64)
} else if v.MinScore != 0 && v.MaxScore == 0 {
minScoreFloat64 := publicmethod.DecimalEs(float64(v.MinScore)/100, 2)
sendCont.Standard = fmt.Sprintf("%v", minScoreFloat64)
} else {
sendCont.Standard = "0"
}
sendListCont = append(sendListCont, sendCont)
}
publicmethod.Result(0, sendListCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-15 11:38:24
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetTargetColumnList(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil || receivedValue.Id == "" {
publicmethod.Result(100, receivedValue, c)
return
}
var columnContList []modelskpi.QualitativeTarget
err = overall.CONSTANT_DB_KPI.Where("`q_state` = 1 AND `q_parent_id` = ?", receivedValue.Id).Find(&columnContList).Error
if err != nil {
publicmethod.Result(107, err, c)
return
}
publicmethod.Result(0, columnContList, c)
}

502
api/version1/departmentseting/departmentpc/type.go

@ -1,6 +1,7 @@
package departmentpc
import (
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
"sync"
@ -11,7 +12,8 @@ import (
type ApiMethod struct{}
// 协程设置
var syncSeting = sync.WaitGroup{}
var SyncSeting = sync.WaitGroup{}
var SyncSetFiles = sync.WaitGroup{}
// 部门考核WEB端入口
func (a *ApiMethod) Index(c *gin.Context) {
@ -36,7 +38,11 @@ type departListQuery struct {
// 输出部门指标列表
type printDepartmentTarget struct {
modelskpi.EvaluationTarget
DimensionTitle string `json:"dimensiontitle"` //维度名称
DimensionTitle string `json:"dimensiontitle"` //维度名称
Relevantdepartmentsmap []publicWordKey `json:"relevantdepartmentsmap"` //关联部门
Reportmap []publicWordKey `json:"reportmap"` //提报人
DimensionStr string `json:"dimensionstr"` //维度
KeyStr string `json:"keystr"`
}
// 输出指标已经关联的部门
@ -102,10 +108,11 @@ type QualEvalSunList struct {
type getDepartTargetContType struct {
publicmethod.PagesTurn
TargetId string `json:"targetid"` //指标ID
DepartmentId string `json:"departmentid"` //部门ID
DepartmentId string `json:"departid"` //部门ID
ReportPerson string `json:"reportperson"` //上报人
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
TargetSunId string `json:"targetsunid"` //考核子栏目
// Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
TargetSunId string `json:"targetsunid"` //考核子栏目
Censorrate int `json:"censorrate"` //周期1:班;2:天;3:周;4:月;5:季度;6:年
}
// 输出定性指标详细内容列表
@ -155,8 +162,9 @@ type outCont struct {
type NewOutPutDetailedTarget struct {
publicmethod.PublicId
QualEvalSunList
ReportManList []printReportCont `json:"reportmanlist"` //上报人
DepartmentList []string `json:"departmentlist"` //接受考核的部门
ReportManList []printReportCont `json:"reportmanlist"` //上报人
DepartmentList []string `json:"departmentlist"` //接受考核的部门
DepartmentIdList []int64 `json:"departmentidlist"` //接受考核的部门
}
// 修改单一指标细则内容提交参数
@ -196,7 +204,8 @@ type depTarAboutPost struct {
// 循环体
type LoopStruct struct {
publicmethod.PublicId
Child []LoopStruct `json:"child"`
Child []LoopStruct `json:"child"`
ChildCopy []string `json:"childcopy"`
}
// 定性指标细则与部门矩阵参数
@ -222,3 +231,480 @@ type matrixZhuBiaoZhoo struct {
publicmethod.PublicId
publicmethod.PublicName
}
// 部门方案搜索列表
type DepartPrograList struct {
OrgId string `json:"orgid"` //行政组织
Year string `json:"year"` //年份
Version string `json:"version"` //版本号
}
// 输出部门方案
type SendDepartPrograList struct {
modelskpi.PlanVersio
GroupName string `json:"groupname"` //归属集团
DeaprtName string `json:"deaprtname"` //部门ID
Time string `json:"time"`
VersionCont []publicmethod.DepartmentProgrammeJson `json:"versioncont"` //方案内容
States bool `json:"states"` //
}
// 判断方案是否有执行中的任务
type judgePlanTask struct {
dingXingTask []map[string]interface{}
dingLiangTask []map[string]interface{}
mutext sync.RWMutex
}
// 读取锁数据
func (j *judgePlanTask) readPlanTaskData() ([]map[string]interface{}, []map[string]interface{}) {
j.mutext.RLock()
defer j.mutext.RUnlock()
return j.dingXingTask, j.dingLiangTask
}
// 并发输出
type bingFaOut struct {
Id int64 `json:"id" gorm:"primaryKey;column:sf_id;type:bigint(20) unsigned;not null;comment:Id"`
Key int64 `json:"key" gorm:"column:sf_key;type:bigint(20) unsigned;default:0;not null;comment:识别标志"`
EvaluationPlan int64 `json:"evaluationplan" gorm:"column:sf_evaluation_plan;type:bigint(20) unsigned;default:0;not null;comment:考核方案项目ID"`
OrderKey int64 `json:"orderkey" gorm:"column:ep_order_key;type:bigint(20) unsigned;default:0;not null;comment:发起表单key"`
State int `json:"state" gorm:"column:ep_state;type:int(2) unsigned;default:1;not null;comment:1:审批,2:通过;3:驳回;"`
}
type bingFaOutDingLiang struct {
Id int64 `json:"id" gorm:"primaryKey;column:fl_id;type:bigint(20) unsigned;not null;comment:Id;index"`
Key int64 `json:"key" gorm:"column:fl_key;type:bigint(20) unsigned;default:0;not null;comment:识别标志"`
EvaluationPlan string `json:"evaluationplan" gorm:"column:fl_evaluation_id;type:mediumtext unsigned;default:0;not null;comment:考核方案项目ID"`
Reply int `json:"reply" gorm:"column:fl_reply;type:int(2) unsigned;default:1;not null;comment:状态(0:删除;1:起草;2:审批;3:通过)"`
OrderKey int64 `json:"orderkey" gorm:"column:ep_order_key;type:bigint(20) unsigned;default:0;not null;comment:发起表单key"`
State int `json:"state" gorm:"column:ep_state;type:int(2) unsigned;default:1;not null;comment:1:审批,2:通过;3:驳回;"`
}
// 添加部门考核项目新
type AddDutyNewContGroup struct {
Group string `json:"group"` //集团
DepartmentId string `json:"orgid"` //部门
Year string `json:"year"` //年度
Child []AddDutyNewCont `json:"child"` //考核细则
}
type AddDutyNewCont struct {
Id string `json:"id"` //维度ID
Name string `json:"name"`
// Order int64 `json:"ordering"`
ZhiFraction int `json:"zhiFraction"`
Child []EvaluPross `json:"child"` //考核细则
}
// 指标
type EvaluPross struct {
Id string `json:"id"` //维度ID
Name string `json:"name"`
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位"`
ReferenceScore int64 `json:"referencescore"` //标准分值"`
Cycles int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年"`
CycleAttres int `json:"cycleattr"` //辅助计数"`
State int `json:"state"` //
Score int64 `json:"score"` //分数
QualEvalId string `json:"qeid"`
Status int `json:"status"` //1:使用;2:禁用;3:观察
}
// 指标细则关联考核人
type DutyAssEssTarget struct {
Id int64 `json:"id"`
Operator []string `json:"operator"` //考核执行人
Department []string `json:"department"` //部门
}
// 获取定量任务列表参数
type GetQuanTasks struct {
OrgId string `json:"orgid"` //行政组织Id
Title string `json:"title"`
Time string `json:"time"` //时间
publicmethod.PagesTurn
}
type GetQuanTasksIng struct {
OrgId string `json:"orgid"` //行政组织Id
Title string `json:"title"`
Time string `json:"time"` //时间
}
// 考核方案细则列表输出
type TargetContOutCont struct {
Id string `json:"id"` //指标ID
Type int `json:"type"` //1:定性考核;2:定量考核
Group string `json:"group"` //公司
GroupNAme string `json:"groupname"` //公司名称
DepartmentId string `json:"parentid"` //主部门
DepartmentName string `json:"parentname"` //主部门名称
Dimension string `json:"dimension"` //纬度
DimensionName string `json:"dimensionname"` //纬度名称
Target string `json:"target"` //指标
TargetName string `json:"targetname"` //指标名称
TargetSun string `json:"targetsun"` //栏目
TargetSunName string `json:"targetsunname"` //栏目名称
DetailedTarget string `json:"detailedtarget"` //细则
DetailedTargetName string `json:"detailedtargetname"` //细则名称
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位"`
ReferenceScore int64 `json:"referencescore"` //标准分值"`
Cycles int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年"`
CycleAttres int `json:"cycleattr"` //辅助计数"`
State int `json:"state"`
UserList []string `json:"userlist"` //执行人列表
UserListAry []QualEvalArrt `json:"userlistary"` //执行人列表
Actual string `json:"actual"` //实际值
ZeroPrize string `json:"zeroprize"` //零奖值
AllPrize string `json:"allprize"` //全奖奖值
Reach string `json:"reach"` //达成率公式
ReachScore float64 `json:"reachscore"` //手动分
CappingVal float64 `json:"cappingcal"` //封顶值
Reason string `json:"reason"` //说明
ScoringMethod int64 `json:"scoringmethod"` //计分方式(1:自动;2:手动)
DimensionWeight int64 `json:"dimensionweight"` //权重
TargetWeight int64 `json:"targetweight"` //权重
PlanVersionNumber string `json:"planversionnumber"` //版本号
ReferTo bool `json:"referto"` //是否提交
}
// 执行人列表输出
type QualEvalArrt struct {
Id string `json:"id"`
Name string `json:"name"`
}
// 新版部门指标列表
type NewDepartTarList struct {
publicmethod.PagesTurn
publicmethod.PublicName //指标名称
Dimension string `json:"dimension"` //维度
Attribute string `json:"attribute"` //性质 1:定性指标;2:定量指标
OrgIdList []string `json:"orgidlist"` //行政组织列表
}
// 通用指端
type publicWordKey struct {
Key string `json:"key"`
Number string `json:"number"`
Title string `json:"title"`
}
// 部门指标关联岗位
type depTarAboutPostEs struct {
publicmethod.PublicId
OrgList []LoopStructEs `json:"orglist"`
}
// 循环体
type LoopStructEs struct {
Id string `json:"id"`
Name string `json:"name"`
Number string `json:"number"`
Child []LoopStructEs `json:"child"`
ChildCopy []string `json:"childcopy"`
}
// 根据指标获取指标细则
type GetTarDetails struct {
TargetId int64 `json:"targetid"`
OrgList []int64 `json:"orglist` //行政组织
TestMethod []string `json:"testmethod"` //检查方式(1:现场检查;2:资料检查;3:事件触发)
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年;7:半年
}
// 考核细则输出
type outputTargetDetails struct {
modelskpi.DetailedTarget
ColumnName string `json:"columnname"`
Standard string `json:"standard"` //考核标准
JiBuQi int `json:"jibuqi"` //记不起
}
/*
新版指标细则处理过程相关切片
*/
type NewDetailsCont struct {
TargetId string `json:"targetid"` //指标ID
TableName string `json:"tablename"` //栏目名称
TargetOrgList []publicWordKey `json:"targetorglist"` //指标行政组织
DetailsList []DetailsListCont `json:"detailslist"` //细则列表
}
// 细则结构体
type DetailsListCont struct {
Title string `json:"title"` //考核内容
Standard string `json:"standard"` //考核标准
Unit string `json:"unit"` //单位
Types int `json:"types"` //操作类型(1:减分;2:加分;3:加减分)
InspeMethod []string `json:"inspemethod"` //检查方式(1:现场检查;2:资料审查;3:事件触发)
Cycle int `json:"cycle"` //检查周期1:班;2:天;3:周;4:月;5:季度;6:年;7:半年
Frequency int `json:"frequency"` //检查频率
Evidence string `json:"evidence"` //检查依据
Remarks string `json:"remarks"` //备注说明
Department []string `json:"department"` //被考核部门
Executor []string `json:"executor"` //执行人
}
// 统一关联数据基本信息
type UnifiedRelation struct {
DimensionId int64 `json:"dimensionid"`
TargetId int64 `json:"targetid"`
TableId int64 `json:"tableid"`
DibylawsId int64 `json:"bylawsid"`
Department []string `json:"department"` //被考核部门
Executor []string `json:"executor"` //执行人
}
// 编辑单一指标细则内容
type EditOneDetailsCont struct {
publicmethod.PublicId
DetailsListCont
}
// 根据栏目添加细则
type TableAddDetaCont struct {
TargetId string `json:"targetid"` //指标id
TableiId string `json:"tableid"` //栏目Id
DetailsList []DetailsListCont `detailslist` //细则列表
}
// 修改栏目信息
type EditTableInfo struct {
publicmethod.PublicId
Title string `json:"title"` //栏目名称
Departmentint []string `json:"departmentint"` //关联部门
UserList []string `json:"userlist"` //执行人
}
// 输出定性考核列表
type OutPutDingXingCont struct {
OrgId string `json:"orgid"` //行政组织Id
OrgName string `json:"orgname"` //行政组织名称
TargetId string `json:"targetid"` //指标ID
Title string `json:"title"`
MinusScore float64 `json:"minusscore"` //总减分
BonusPoints float64 `json:"bonuspoints"` //总加分
}
// 相关提报人定性考核细则
type BylawsAboutPeople struct {
OrgId string `json:"orgid"` //行政组织Id
TargetId string `json:"targetid"` //行政组织Id
Title string `json:"title"`
publicmethod.PagesTurn
}
// 输出相关考核项目
type OutPutBylawsCont struct {
publicmethod.PublicId //项目ID
ColumnTitle string `json:"columntitle"` //栏目名称
Title string `json:"title"` //考核项目
Content string `json:"content"` //考核内容
Standard string `json:"standard"` //标准
Unit string `json:"unit"` //单位
PlusMinusScore int `json:"plusminusscore"` //加减分
ScoreType int `json:"scoretype"` //1、定分;2、区间分;3、不定性分值
MaxScore float64 `json:"maxscore"` //最大分
MinScore float64 `json:"minscore"` //最小分
}
// 获取定性考核提交数据
type HaveQualityAssessData struct {
Orgid string `json:"orgid"` //接受考核的行政组织
ScoreFlowCont ScoreFlowInfo `json:"scoreflowcont"` //定性考核数据
FlowKey string `json:"flowkey"` //工作流识别符
FlowVersion string `json:"flowversion"` //使用的版本
UploadFiles []UploadFilesCont `json:"uploadfiles"` //附件文件
WorkFlowView []currency_recipe.NodeCont `json:"workflowview"` //工作流
}
// 定性考核提交参数
type ScoreFlowInfo struct {
ItemId string `json:"id"` //考核项目ID
Score float64 `json:"score"` //区间分数
Frequency int `json:"frequency"` //定分发生次数 frequency:1,
Time string `json:"time"` //发生时间
Correct int `json:"correct"` //是否需要整改 1:整改;2:不需要
DueTime string `json:"duetime"` //整改期限
Reason string `json:"reason"` //操作原因
Type int `json:"type"` //1:加分;2:减分
}
// 附件文件
type UploadFilesCont struct {
publicmethod.PublicName //文件名称
FileUrl string `json:"fileUrl"` //文件访问地址
PhysicsPath string `json:"physicspath"` //文件物理地址
Type int `json:"type"` //类型 1:图片;2:视频;3:office文档;4:压缩文件;5:其他文件
FileSize int64 `json:"fileSize"` //文件大小(单位:B)
Size string `json:"size"` //文件大小文字描述
Tag string `json:"tag"` //文件后缀
}
// 提交定量数据
type SubmitQuantTargetCont struct {
FlowworkId string `json:"flowworkid"` //流程编号
DepartmentId string `json:"departmentid"` //行政组织
PlanVersionNumber string `json:"planversionnumber"` //方案版本号
Time string `json:"time"` //提报时间
List []RationLogList `json:"list"` //提报数据列表
}
type RationLogList struct {
Id string `json:"id"`
Actual string `json:"actual"` //实际值
ScoringMethod int `json:"scoringmethod"` //计分方式(1:自动;2:手动)"`
ReachScore string `json:"reachscore"` //手动分
Unit string `json:"unit"` //单位
Target string `json:"target"` //指标
Targetname string `json:"targetname"` //指标名称
Reason string `json:"reason"` //原因
ReferenceScore int64 `json:"referencescore"` //标准分值"`
ZeroPrize string `json:"zeroprize"` //零奖值
AllPrize string `json:"allprize"` //全奖奖值
CappingVal float64 `json:"cappingcal"` //封顶值
TargetWeight int64 `json:"targetweight"` //权重
PlanVersionNumber string `json:"planversionnumber"` //版本号
Addtime string `json:"month"` //检查时间
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年;7:半年
Reach string `json:"reach"` //达成率
}
// 定量流水全奖值、零奖值、封顶值
type FlowLogAllZreo struct {
Id string `json:"id"`
TargetId string `json:"targetid"` //指标ID`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
TargetWeight float64 `json:"targetweight"` //封顶值"`
}
// 输出方案项目列表
type SchemeCont struct {
DimensionId string `json:"dimensionid"` //维度Id
DimensionName string `json:"dimensionname"` //维度名称
DimensionStandard float64 `json:"dimensionstandard"` //维度标准
TargetId string `json:"targetid"` //指标Id
TargetName string `json:"targetname"` //指标名称
TargetStandard float64 `json:"Targetstandard"` //指标标准
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位
Attribute int `json:"attribute"` //指标性质 1:定量;2:定性
State int `json:"state"` //状态 1:使用;2:禁用;3:观察
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年;7:半年
Frequency int `json:"frequency"` //频率
PlantVersion string `json:"plantversion"` //版本
OrgId string `json:"orgid"` //行政组织
}
// 查看行政组织定性考核细则列表
type LookTargetToBylaws struct {
publicmethod.PublicId //指标Id
OrgId string `json:"orgid"` //行政组织
PosId string `json:"posid"` //岗位ID
Type int `json:"type"` //类型(1:指标;2:子目标;3:细则)
Level int `json:"level"` //级别(1:部门级;2:岗位级)
}
// 输出查看行政组织定性考核细则列表
type SendTargetToBylaws struct {
TableId int64 `json:"tableid"`
TableName string `json:"tablename"`
TargetId string `json:"targetid"`
TargetName string `json:"targetname"`
Criterion string `json:"criterion"`
MaxScore float64 `json:"maxscore"` //最大分
MinScore float64 `json:"minscore"` //最小分
Unit string `json:"unit"` //单位
Content string `json:"content"` //指标说明
}
// 输出执行人
type RunManCont struct {
publicmethod.PublicId
publicmethod.PublicName
Number string `json:"number"`
Company string `json:"company"`
Department string `json:"department"`
Icon string `json:"icon"`
IconBase64 string `json:"iconbase64"`
}
// 编辑方案指标
type EditSchemeContTarget struct {
PlanVersionKey string `json:"planversionkey"` //版本号
TargetId string `json:"targetid"` //指标ID
OrgId string `json:"orgid"` //行政组织
Content string `json:"content"` //说明
State int `json:"state"` //状态
Operator []string `json:"operator"` //执行人
}
// 删除方案指标
type DelSchemeContTarget struct {
PlanVersionKey string `json:"planversionkey"` //版本号
TargetId string `json:"targetid"` //指标ID
OrgId string `json:"orgid"` //行政组织
}
// 输出复制行政组织方案指标内容
type CopySchemeCont struct {
OrgId string `json:"orgid"`
Year string `json:"year"`
Child []CopyDutyNewCont `json:"child"` //纬度
}
type CopyDutyNewCont struct {
Id string `json:"id"` //维度ID
Name string `json:"name"`
ZhiFraction int `json:"zhiFraction"`
Child []CopyEvaluPross `json:"child"` //指标
}
// 指标
type CopyEvaluPross struct {
Id string `json:"id"` //指标ID
Name string `json:"name"` //指标名称
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位"`
ReferenceScore int64 `json:"referencescore"` //标准分值"`
State int `json:"status"`
Istrue int `json:"istrue"` //是否允许修改
}
type DepartTargetList struct {
Id string `json:"id"`
Name string `json:"name"`
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位"`
ReferenceScore int64 `json:"referencescore"` //标准分值"`
State int `json:"state"`
IsTrue int `json:"istrue"` //是否允许修改
}
// 纬度列表
type dimListCont struct {
publicmethod.PublicId
publicmethod.PublicName
}
// 指标列表
type targetListInfo struct {
dimListCont
Dimension string `json:"dimension"`
}
// 输出新增方案
type outNewScheme struct {
dimListCont
ZhiFraction int `json:"zhiFraction"`
Child []outNewSchemeTar `json:"child"`
}
type outNewSchemeTar struct {
dimListCont
Referencescore int `json:"referencescore"`
}

1792
api/version1/departmentseting/departmentweb/department.go

File diff suppressed because it is too large

243
api/version1/departmentseting/departmentweb/type.go

@ -2,15 +2,258 @@ package departmentweb
import (
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
type ApiMethod struct{}
// 协程设置
var SyncSeting = sync.WaitGroup{}
var SyncSetinges = sync.WaitGroup{}
// 获取综合统计数值
type GetDttsb struct {
Target []GetDttsbCont
Actuality []GetDttsbCont
CompletionRate []GetDttsbCont
AxisLeftMax float64
AxisLeftMin float64
AxisRightMax float64
AxisRightMin float64
mutext sync.RWMutex
}
type GetDttsbCont struct {
Val float64
Sort int
}
// 读取数据
func (g *GetDttsb) readPlanTaskData() ([]GetDttsbCont, []GetDttsbCont, []GetDttsbCont, float64, float64, float64, float64) {
g.mutext.RLock()
defer g.mutext.RUnlock()
return g.Target, g.Actuality, g.CompletionRate, g.AxisLeftMax, g.AxisLeftMin, g.AxisRightMax, g.AxisRightMin
}
// 部门考核WEB端入口
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "部门考核WEB端入口"
publicmethod.Result(0, outputCont, c)
}
// 获取部门指标列表
type GetDepartTargetCont struct {
publicmethod.PublicId
Attribute int `json:"attribute"` //1:定性考核;2:定量考核
}
// 输出指标信息
type SendTargetCont struct {
publicmethod.PublicId
publicmethod.PublicName
}
// 根据部门、指标、年份统计每月的目标值、实际值、达成率
type BaseDepartTargetTime struct {
OrgId string `json:"orgid"` //行政组织
TargetId string `json:"targetid"` //指标ID
DateTime string `json:"datetime"` //时间
}
// 输出部门、指标、年份统计图目标值、实际值、达成率数据结构
type DrawEcharStatisticsCont struct {
Legend []string `json:"legend"` //项目名称
XAxisVal []string `json:"xaxis"` //X轴坐标值
YAxis []YaxisStruct `json:"yaxis"` //Y轴坐标值
Series []Seriescont `json:"series"` //图表数值
}
// Y轴属性
type YaxisStruct struct {
Type string `json:"type"` //坐标轴类型
publicmethod.PublicName //坐标轴名称。
Min float64 `json:"min"` //最小值
Max float64 `json:"max"` //最大值
FormAtter string `json:"formatter"` //单位
}
// 图表值
type Seriescont struct {
publicmethod.PublicName //名称
Type string `json:"type"` //图像类型
Tooltip string `json:"tooltip"` //单位
Data []float64 `json:"data"` //结果
}
// 定量流水全奖值、零奖值、封顶值
type FlowLogAllZreo struct {
Id string `json:"id"`
TargetId string `json:"targetid"` //指标ID`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
}
// 根据部门、指标、年份统计历史同比每月的目标值、实际值、达成率
type BaseDepartTargetTimeYOY struct {
OrgId string `json:"orgid"` //行政组织
TargetId string `json:"targetid"` //指标ID
DateTime []int `json:"datetime"` //时间
}
// 输出历史同比数据
type SendYOYData struct {
XAxisVal []string `json:"xaxis"` //X轴坐标值
YAxis YaxisStruct `json:"yaxis"` //Y轴坐标值
Series []Seriescont `json:"series"` //图表数值
}
// 协程获取每个年份数据
// 获取综合统计数值
type GeteveryYearDttsb struct {
Target []HistorMonthData
AxisMax float64
AxisMin float64
mutext sync.RWMutex
}
// 历史同比记录
type HistorMonthData struct {
Months int
MonthStr string
MonthDataList []float64
}
// 读取数据
func (g *GeteveryYearDttsb) readPlanTaskData() ([]HistorMonthData, float64, float64) {
g.mutext.RLock()
defer g.mutext.RUnlock()
return g.Target, g.AxisMax, g.AxisMin
}
// 通过时间获取组织总分
type OrgSecrcFormTime struct {
OrgId string `json:"orgid"` //行政组织
DateTimes string `json:"datetimes"` //时间
}
// 根据时间查询行政组织总成绩协程设置
type SyncOrgTimeAllScore struct {
OrgScore []SyncOTASVal
AxisMax float64
AxisMin float64
mutext sync.RWMutex
}
type SyncOTASVal struct {
OrgId int64 //行政组织ID
Score float64 //分
Months int //月
}
// 读取数据
func (s *SyncOrgTimeAllScore) readPlanTaskData() ([]SyncOTASVal, float64, float64) {
s.mutext.RLock()
defer s.mutext.RUnlock()
return s.OrgScore, s.AxisMax, s.AxisMin
}
// 按时间输出行政组织总成
type SendTimeOfOrgSumScore struct {
XAxisVal []string `json:"xaxis"` //X轴坐标值
YAxis YaxisOrgAllScore `json:"yaxis"` //Y轴坐标值
Series []float64 `json:"series"` //图表数值
}
type YaxisOrgAllScore struct {
Min float64 `json:"min"` //最小值
Max float64 `json:"max"` //最大值
}
// 考核方案
type SchemeInfo struct {
publicmethod.PublicId
publicmethod.PublicName
DimensionScore float64 `json:"dimensionscore"` //维度分数
Child []SchemeTarget `json:"child"` //方案指标
}
// 方案指标
type SchemeTarget struct {
publicmethod.PublicId
publicmethod.PublicName
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位"`
ReferenceScore int64 `json:"referencescore"` //标准分值"`
Cycles int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年"`
CycleAttres int `json:"cycleattr"` //辅助计数"`
State int `json:"state"`
Score int64 `json:"score"` //分数
QualEvalId string `json:"qeid"`
Status int `json:"status"` //1:启用;2:禁用;3:为观察指标
}
// 获取关键指标列表
type HingeTarget struct {
Id []string `json:"id"` //指标ID
OrgId []string `json:"orgid"` //行政组织
DateTime string `json:"datetime"` //时间
}
// 输出关键指标
type OutPutHingeTarget struct {
Id string `json:"id"`
Title string `json:"title"`
CharKey string `json:"CharKey"`
DataList []float64 `json:"datalist"`
XAxisVal []string `json:"xaxis"` //X轴坐标值
YAxis YaxisOrgAllScore `json:"yaxis"` //Y轴坐标值
}
// 获取行政组织月度成绩
type OrgMonthResult struct {
OrgId string `json:"orgid"` //行政组织
DateTime string `json:"datetime"` //时间
}
// 根据部门、指标、年份统计历史同比每月的目标值、实际值、达成率
type BaseDepartTimeYOY struct {
OrgId string `json:"orgid"` //行政组织
DateTime []int `json:"datetime"` //时间
}
// 相关提报人定性考核细则
type BylawsAboutPeopleDime struct {
OrgId string `json:"orgid"` //行政组织Id
TargetId string `json:"targetid"` //指标Id
}
// 输出栏目
type OutDimList struct {
publicmethod.PublicId
publicmethod.PublicName
BylawsAboutPeopleDime
}
// 根据栏目获取获取相关指标
type BaseTableGetTargetWeb struct {
publicmethod.PagesTurn
BylawsAboutPeopleDime
TableId string `json:"tableid"` //栏目Id
}
// 输出相关考核项目
type OutPutBylawsCont struct {
publicmethod.PublicId //项目ID
ColumnTitle string `json:"columntitle"` //栏目名称
Title string `json:"title"` //考核项目
Content string `json:"content"` //考核内容
Standard string `json:"standard"` //标准
Unit string `json:"unit"` //单位
PlusMinusScore int `json:"plusminusscore"` //加减分
ScoreType int `json:"scoretype"` //1、定分;2、区间分;3、不定性分值
MaxScore float64 `json:"maxscore"` //最大分
MinScore float64 `json:"minscore"` //最小分
}

147
api/version1/departmentseting/departmentweb/web.go

@ -0,0 +1,147 @@
package departmentweb
import (
"encoding/json"
"key_performance_indicators/api/version1/statistics"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-07-29 16:50:53
@ 功能: 按时间计算行政组织成绩
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (s *SyncOrgTimeAllScore) TallyUpOrgCalculateScore(orgCont modelshr.AdministrativeOrganization, year, month string) {
//锁操作
s.mutext.Lock()
defer s.mutext.Unlock()
yearInt, _ := strconv.ParseInt(year, 10, 64)
monthInt, _ := strconv.ParseInt(month, 10, 64)
//获取版本信息
planCont, err := publicmethod.GetPlanVresion(orgCont.Id, yearInt, monthInt)
var getPoints float64 //行政组织总分
if err == nil {
var planVersioInfo []SchemeInfo
jsonErr := json.Unmarshal([]byte(planCont.Content), &planVersioInfo)
if jsonErr == nil {
for _, v := range planVersioInfo { //维度
for _, sv := range v.Child { //指标
if sv.Status == 3 { //为观察指标
getPoints = getPoints + float64(sv.ReferenceScore)
} else {
var targetInfo modelskpi.EvaluationTarget
targetInfo.GetCont(map[string]interface{}{"et_id": sv.Id}, "et_type,et_cycle")
if sv.Cycles == 0 { //判断统计方式
sv.Cycles = targetInfo.Cycles
}
if targetInfo.Type == 1 { //定性考核
dingXingScore, _ := statistics.DingXingScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{monthInt}, sv.Id)
getPoints = getPoints + dingXingScore
} else { //定量考核
var dingLiangScore float64
switch sv.Cycles {
case 5: //季度指标
quarterList := []int64{3, 6, 9, 12}
if !publicmethod.IsInTrue[int64](monthInt, quarterList) {
dingLiangScore = float64(sv.ReferenceScore)
// fmt.Printf("季度指标--->%v--->%v--->%v\n", sv.Name, sv.Id, dingLiangScore)
} else {
switch monthInt {
case 3:
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{1, 2, 3}, sv.Id, sv.Cycles)
case 6:
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{4, 5, 6}, sv.Id, sv.Cycles)
case 9:
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{7, 8, 9}, sv.Id, sv.Cycles)
case 12:
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{10, 11, 12}, sv.Id, sv.Cycles)
default:
}
}
case 6: //年度指标
if monthInt == 12 {
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, sv.Id, sv.Cycles)
} else {
dingLiangScore = float64(sv.ReferenceScore)
// fmt.Printf("年度指标--->%v--->%v--->%v\n", sv.Name, sv.Id, dingLiangScore)
}
case 7: //半年指标
switch monthInt {
case 6:
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{1, 2, 3, 4, 5, 6}, sv.Id, sv.Cycles)
case 12:
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{7, 8, 9, 10, 11, 12}, sv.Id, sv.Cycles)
default:
dingLiangScore = float64(sv.ReferenceScore)
// fmt.Printf("半年指标--->%v--->%v--->%v\n", sv.Name, sv.Id, dingLiangScore)
}
default: //月度指标
dingLiangScore, _ = statistics.DingLiangScoreCalculation(orgCont.Id, yearInt, sv.ReferenceScore, []int64{monthInt}, sv.Id, sv.Cycles)
}
dingLiangScoreGd, _ := publicmethod.DecimalNew(dingLiangScore, 2)
getPoints = getPoints + dingLiangScoreGd
}
}
}
}
}
}
tayTime := time.Now().Unix()
currentYears := publicmethod.UnixTimeToDay(tayTime, 16)
currentMonth := publicmethod.UnixTimeToDay(tayTime, 17)
currentYearsInt, _ := strconv.Atoi(currentYears)
currentMonthInt, _ := strconv.Atoi(currentMonth)
yearsInt, _ := strconv.Atoi(year)
monthsInt, _ := strconv.Atoi(month)
if currentYearsInt == yearsInt && monthsInt > currentMonthInt {
getPoints = 0
}
if s.AxisMax < getPoints {
s.AxisMax = getPoints
}
if s.AxisMin == 0 {
s.AxisMin = getPoints
} else {
if s.AxisMin > getPoints {
s.AxisMin = getPoints
}
}
var orgScore SyncOTASVal
orgScore.OrgId = orgCont.Id
orgScore.Score = publicmethod.DecimalEs(getPoints, 2)
orgScore.Months, _ = strconv.Atoi(month)
s.OrgScore = append(s.OrgScore, orgScore)
SyncSeting.Done()
}
/**
@ 作者: 秦东
@ 时间: 2023-07-29 17:03:39
@ 功能: 计算行政组织月份得分
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
// func (){}

12
api/version1/empower/system_license.go

@ -2,6 +2,7 @@ package empower
import (
"key_performance_indicators/overall/publicmethod"
"strings"
"github.com/gin-gonic/gin"
)
@ -24,8 +25,10 @@ func (a *ApiMethod) ObtainAuthorization(c *gin.Context) {
publicmethod.Result(1, err, c, "未知身份!不可授权!")
return
}
menuIdAry, menuUrl, err := publicmethod.GetPostPower(context.AdminOrg, context.Position, receivedValue.System)
// jsonStr, _ := json.Marshal(context)
// fmt.Printf("jsonStr------>%v\n", string(jsonStr))
// menuIdAry, menuUrl, err := publicmethod.GetPostPower(context.AdminOrg, context.Position, receivedValue.System)
_, pointId, operation, _ := publicmethod.GetNewAccredit(receivedValue.System, context.Role, context.Key, context.AdminOrg, context.Position)
// var systemPermission modelssystempermission.Empower
// err = systemPermission.GetCont(map[string]interface{}{"`state`": 1, "`ordid`": context.AdminOrg, "`post_id`": context.Position, "`system`": receivedValue.System}, "`point_id`")
@ -40,7 +43,8 @@ func (a *ApiMethod) ObtainAuthorization(c *gin.Context) {
// return
// }
sendData := publicmethod.MapOut[string]()
sendData["powerid"] = menuIdAry
sendData["powerurl"] = menuUrl
sendData["powerid"] = strings.Split(pointId, ",")
sendData["poweroperationid"] = strings.Split(operation, ",")
sendData["powerurl"] = []string{}
publicmethod.Result(0, sendData, c)
}

8
api/version1/entry.go

@ -5,10 +5,14 @@ import (
"key_performance_indicators/api/version1/departmentseting/departmentpc"
"key_performance_indicators/api/version1/departmentseting/departmentweb"
"key_performance_indicators/api/version1/empower"
"key_performance_indicators/api/version1/flowchart"
"key_performance_indicators/api/version1/honoraryArchives"
"key_performance_indicators/api/version1/jurisdiction/jurisdictionpc"
"key_performance_indicators/api/version1/newsclass"
"key_performance_indicators/api/version1/postseting/postpc"
"key_performance_indicators/api/version1/postseting/postweb"
"key_performance_indicators/api/version1/statistics"
"key_performance_indicators/api/version1/systemapproval"
)
type ApiEntry struct {
@ -20,6 +24,10 @@ type ApiEntry struct {
BookImg bookimg.ApiMethod //图文信息管理
JurisdictionpcApi jurisdictionpc.ApiMethod //权限模块PC端
EmpowerApi empower.ApiMethod //系统授权
WorkFlowChat flowchart.ApiMethod //工作流
SystemAppExamine systemapproval.ApiMethod //系统审批处理
StatisticsApi statistics.ApiMethod //指标统计
NewsClassApi newsclass.ApiMethod //新闻类
}
var AppApiEntry = new(ApiEntry)

291
api/version1/flowchart/entry.go

@ -0,0 +1,291 @@
package flowchart
import (
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/overall/publicmethod"
"github.com/gin-gonic/gin"
)
// 工作流入口
type ApiMethod struct{}
// 系统授权配置
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "工作流入口"
publicmethod.Result(0, outputCont, c)
}
// 审批工作流全图
type ReviewFlow struct {
publicmethod.PublicId //考核项目ID
IsCorrection int `json:"iscorrection"` //是否整改 1:不整改;2:整改
PlusReduction int `json:"plusreduction"` //加减分 1:减少;2:增加;
PeopleList []string `json:"peopleList"` //被测评的人userKey
}
// 获取审批记录
type HaveApprovalRecord struct {
publicmethod.PagesTurn
State int `json:"state"` // 0:全部;1:审批中;2:驳回;3:归档;4:删除
NameorNumber string `json:"nameornumber"` //申请人姓名或工号
Title string `json:"title"` //标题
OrgId string `json:"orgid"` //行政组织
Years int `json:"years"`
Months int `json:"month"`
}
// 输出审批记录值
type OutPutFlowLog struct {
Id string `json:"id"` //
OrderKey string `json:"orderkey"` //发起表单key"`
Step int `json:"step"` //当前执行到第几部"`
Content string `json:"content"` //流程步进值"`
NextContent string `json:"nextcontent"` //下一步内容"`
Time int64 `json:"time"` //创建时间"`
State int `json:"state"` //1:草稿,2:审批中;3:驳回;4:归档;5:删除"`
RoleGroup string `json:"rolegroup"` //角色组"`
TypeClass int `json:"type"` //1、定性;2、定量"`
Participants string `json:"participants"` //参与人"`
StartTime int64 `json:"starttime"` //u流程开始时间"`
NextStep int `json:"nextstep"` //下一步"`
NextExecutor string `json:"nextexecutor"` //下一步执行人"`
SetupDepartment string `json:"setupdepartment"` //发起部门"`
Dimension string `json:"dimension"` //维度"`
Target string `json:"target"` //指标"`
DetailedTarget string `json:"detailedtarget"` //指标细则"`
AcceptDepartment string `json:"acceptdepartment"` //接受考核部门"`
HappenTime int64 `json:"happentime"` //发生时间"`
FlowKey string `json:"flowkey"` //工作流识别符"`
FlowVid string `json:"flowvid"` //当前工作流版本号"`
EpOld int `json:"epold"` //1:旧流程;2:新流程"`
Creater string `json:"creater"` //流程创始人"`
TargetTitle string `json:"targettitle"` //指标名称"`
BylawsTitle string `json:"bylawstitle"` //细则名称"`
Clique string `json:"clique"` //公司"`
DepartmentName string `json:"departmentname"` //接受考核部门名称
CreaterName string `json:"creatername"` //流程创始人"`
CurrentNode string `json:"currentnode"` //当前节点"`
CurrentNodeMan string `json:"currentnodeman"` //当前节点操作人"`
CreationDate string `json:"creationdate"` //创建日期"`
OccurrenceTime string `json:"occurrencetime"` //发生时间"`
}
// 输出工作流内容
type OutPutWorkflowCont struct {
publicmethod.PublicId //id
FlowNumber string `json:"flownumber"` //编号
IsOld int `json:"isold"` //1:旧流程;2:新流程
Attribute int `json:"attribute"` //属性:1:定性;2:定量
CreaterName string `json:"creatername"` //流程创始人"`
DepartmentName string `json:"departmentname"` //接受考核部门名称
DepartmentId int64 `json:"departmentid"` //接受考核部门Id
CreationDate string `json:"creationdate"` //发生日期"`
ReportingDate string `json:"reportingdate"` //提报日期"`
Actionable int `json:"actionable"` //本节点是否可操作(1:可操作;非1:不可操作)
OperateOtherNodes currency_recipe.NodeCont `json:"operateothernodes"` //允许操作的节点
SetExecutor int `json:"setexecutor"` //设置执行人 (1:可操作;非1:不可操作)
NodeStep int `json:"nodestep"` //当前步骤
NextStep int `json:"nextstep"` //下一步
//定性部分
DingXingList []DingxingCont `json:"dingxinglist"` //定性指标
//定量部分
DingLiangList []DingLiangCont `json:"dinglianglist"` //定量指标
//流程
WorkFlowList []currency_recipe.NodeCont `json:"workflowlist"` //流程步进树
WorkFlowListOld []OldWoekflow `json:"workflowlistold"` //流程步进树
//责任人
DivisionIsShow int `json:"divisionisshow"` //责任划分显示
DivisLoofOfEdit int `json:"divilookofedit"` //责任划分显示或编辑
DivisionList []DivisionListCont `json:"divisionlist"` //责任划分
//整改措施
RunType int `json:"runtype"` //是不是执行节点
MeasureIsShow int `json:"measureisshow"` //整改显示
MeasureList []MeasureCont `json:"measurelist"` //整改措施
}
// 责任划分
type DivisionListCont struct {
Type int `json:"type"` //类型
UserName string `json:"username"` //姓名
UserNumber string `json:"usernumber"` //工号
UserKey string `json:"userkey"` //识别符
Weight float64 `json:"weight"` //权重
}
// 整改措施
type MeasureCont struct {
UserName string `json:"username"` //姓名
UserNumber string `json:"usernumber"` //工号
UserKey string `json:"userkey"` //识别符
OrgNAme string `json:"orgname"` //行政组织
Cause string `json:"cause"` //整改内容
Enclosure []currency_recipe.EnclosureFormat `json:"enclosure"` //附件
Time string `json:"time"` //整改内容
}
// 允许操作的节点
type OperateOtherNodes struct {
}
type DingxingCont struct {
Dimension string `json:"dimension"` //维度"`
Target string `json:"target"` //指标"`
TableName string `json:"tablename"` //栏目"`
DetailedTarget string `json:"detailedtarget"` //指标细则"`
Standard string `json:"standard"` //考核标准
PlusMinusScore float64 `json:"plusminusscore"` //加减分
Cause string `json:"cause"` //原因
PlusReduction int `json:"plusreduction"` //加减分 1:减少;2:增加;
Enclosure []UploadFilesCont `json:"enclosure"` //附件
}
type DingLiangCont struct {
Dimension string `json:"dimension"` //维度"`
Target string `json:"target"` //指标"`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
Weight float64 `json:"weight"` //权重
ActualValue float64 `json:"actualvalue"` //实际值
CompletionRate float64 `json:"completionrate"` //完成率
TargetScore float64 `json:"targetscore"` //指标得分
CalculationMethod int `json:"calculationmethod"` //计算方式
Cause string `json:"cause"` //原因
}
// 定量考核基准线
type DingLiangJizhuxian struct {
publicmethod.PublicId
TargetId string `json:"targetid"` //指标ID
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
}
// 旧流程
type OldWoekflow struct {
Step int `json:"step"` //步骤
NodeName string `json:"nodename"` //
State int `json:"state"` //
Class int `json:"class"` //
Userlist []OldUserlist `json:"userlist"` //
}
// 就流程审批人
type OldUserlist struct {
publicmethod.PublicId
publicmethod.PublicName
Icon string `json:"icon"`
Wechat string `json:"wechat"`
Group int `json:"group"` //
GroupName string `json:"groupname"` //
DepartMentid int `json:"departmentid"` //
DepartmentName string `json:"departmentname"` //
Workshopid int `json:"workshopid"` //
WorkshopName string `json:"workshopname"` //
Postid int `json:"postid"` //
PostName string `json:"postname"` //
Tema int `json:"tema"` //
TemaName string `json:"temaname"` //
Log []OldLog `json:"log"` //
}
type OldLog struct {
State int `json:"state"` //
Time string `json:"time"` //
Enclosure string `json:"enclosure"` //
}
// 审批参数
type ExamAndApp struct {
publicmethod.PublicId //流程ID
Step int `json:"step"` //步数
YesOrNo int `json:"yesorno"` //1:未操作,2:同意;3:驳回
Cause string `json:"cause"` //意见
Enclosure []currency_recipe.EnclosureFormat `json:"enclosure"` //附件
SetExecutor int `json:"setexecutor"` //划分责任人 1:划分;非1:不划分
ExecutorList []ExecutorCont `json:"executorlist"` //责任人列表
CorrectiveAction CorrectiveActionCont `json:"correctiveaction"` //整改措施
}
// 整改措施
type CorrectiveActionCont struct {
IsTrue int `json:"istrue"` //步数
Content string `json:"content"` //意见
Enclosure []UploadFilesCont `json:"filelist"` //附件
}
// 附件文件
type UploadFilesCont struct {
publicmethod.PublicName //文件名称
FileUrl string `json:"fileUrl"` //文件访问地址
PhysicsPath string `json:"physicspath"` //文件物理地址
Type int `json:"type"` //类型 1:图片;2:视频;3:office文档;4:压缩文件;5:其他文件
FileSize int64 `json:"fileSize"` //文件大小(单位:B)
Size string `json:"size"` //文件大小文字描述
Tag string `json:"tag"` //文件后缀
}
// 责任人内容
type ExecutorCont struct {
Type int `json:"type"` //责任类型(1、主要责任人;2、互保责任人;3、责任班组;4、责任班组长;5、主管;6、三大员;7、厂长;8、主任)
UserKey string `json:"userkey"` //责任人Key
UserName string `json:"username"` //责任人姓名
UserNumber string `json:"usernumber"` //责任人编号
Weight string `json:"weight"` //占责比重
}
// 审批执行
type WorkFlowRuning struct {
OrderKey int64
List []currency_recipe.NodeCont //流程全图
Participant []string //参与人
Step int //下一步步进值
Executor publicmethod.AuthenticationPower `json:"sxecutor"` //当前执行人
YesOrNo int `json:"yesorno"` //1:未操作,2:同意;3:驳回
Cause string `json:"cause"` //意见
Enclosure []currency_recipe.EnclosureFormat `json:"enclosure"` //附件
NextStep int //下一步
NextNodeCont currency_recipe.NodeCont //下一节点
NextExecutor []string //下一步执行人
RunNode currency_recipe.NodeCont //当前执行中的节点
DesignatedOperator DesignatedOperatorCont `json:"designatedoperator"` //指定操作人员
CorrectiveAction CorreActionCont `json:"correctiveaction"` //整改措施
}
// 整改措施
type CorreActionCont struct {
IsTrue int `json:"istrue"` //步数
Content string `json:"content"` //意见
Annex []currency_recipe.EnclosureFormat `json:"annex"` //附件(流程)
}
// 指定操作人员
type DesignatedOperatorCont struct {
IsTrue bool `json:"isTrue"`
UserList []currency_recipe.UserListFlowAll `json:"userlist"` //节点操作人
}
// 返回发送消息数据
type CallBackSendMsgCont struct {
DimeContTitle string
TargetContTitle string
BylawsContTitle string
QuoteText string
}
// 返回发送消息数据
type CallBackSendMsgContLiang struct {
OccurrenceTime string
QuoteText string
}
// 定量流水全奖值、零奖值、封顶值
type FlowLogAllZreo struct {
Id string `json:"id"`
TargetId string `json:"targetid"` //指标ID`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
TargetWeight int64 `json:"targetweight"` //封顶值"`
}

429
api/version1/flowchart/flow.go

@ -0,0 +1,429 @@
package flowchart
import (
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
// 生成审批流程流
func (a *ApiMethod) ReviewWorkFlow(c *gin.Context) {
//获取登录人信息
context, err := publicmethod.LoginMyCont(c)
if err != nil {
publicmethod.Result(1, err, c, "未知身份!不可操作!")
return
}
var receivedValue ReviewFlow
c.ShouldBindJSON(&receivedValue)
if receivedValue.Id == "" {
publicmethod.Result(1, receivedValue, c, "参数错误!")
return
}
if receivedValue.IsCorrection == 0 {
receivedValue.IsCorrection = 2
}
if len(receivedValue.PeopleList) < 1 {
publicmethod.Result(1, receivedValue, c, "未知被考核人!请指定!")
return
}
//获取考核项性质
var qualEvalScheme modelskpi.QualitativeEvaluationScheme
err = qualEvalScheme.GetCont(map[string]interface{}{"id": receivedValue.Id})
if err != nil {
publicmethod.Result(107, err, c)
return
}
//抄送人
var sendCopyMan []publicmethod.UserListFlowAll
//流程图
var flowMap []publicmethod.FlowChartList
endStep := 3
//第一步:创建
var begin publicmethod.FlowChartList
begin.Step = 1 //步伐
begin.NodeName = publicmethod.GetSetpName(1) //节点名称
begin.State = 2 //状态 1、不点亮;2、点亮
begin.Class = 1 //节点类型 1、普通节点;2、运行中指定节点
begin.RunType = 1
beginUserList := append(begin.UserList, GetApproveUser(context.Wechat, context.WorkWechat))
for _, bv := range beginUserList {
begin.UserList = append(begin.UserList, bv)
if receivedValue.IsCorrection == 1 {
sendCopyMan = append(sendCopyMan, bv)
}
}
flowMap = append(flowMap, begin)
//第二步:本部门负责人审批
var stepTwo publicmethod.FlowChartList
stepTwo.Step = 2 //步伐
stepTwo.NodeName = publicmethod.GetSetpName(2) //节点名称
stepTwo.State = 1 //状态 1、不点亮;2、点亮
stepTwo.Class = 1 //节点类型 1、普通节点;2、运行中指定节点
if receivedValue.IsCorrection != 1 {
stepTwo.RunType = 2
} else {
stepTwo.RunType = 3
}
//获取审批人weChatOpenID
sendUserList, userErr := publicmethod.GetRefereeTeamWorkWechat(16182159043990656, context.MainDeparment)
if userErr == nil {
for iu := 0; iu < len(sendUserList); iu++ {
departListUser := GetApproveUser(sendUserList[iu], sendUserList[iu])
stepTwo.UserList = append(stepTwo.UserList, departListUser)
if receivedValue.IsCorrection != 1 {
sendCopyMan = append(sendCopyMan, departListUser)
}
}
}
flowMap = append(flowMap, stepTwo)
if qualEvalScheme.Attribute == 1 {
//定性
if receivedValue.IsCorrection != 1 {
//整改措施提交人
var stepThree publicmethod.FlowChartList
stepThree.Step = 3 //步伐
stepThree.NodeName = publicmethod.GetSetpName(4) //节点名称
stepThree.State = 1 //状态 1、不点亮;2、点亮
stepThree.Class = 2 //节点类型 1、普通节点;2、运行中指定节点
stepThree.RunType = 2
//主要责任人负责提交整改措施
if len(receivedValue.PeopleList) > 0 {
for ipv := 0; ipv < len(receivedValue.PeopleList); ipv++ {
var myUsCont modelshr.PersonArchives
meErr := myUsCont.GetCont(map[string]interface{}{"`key": receivedValue.PeopleList[ipv]}, "`wechat`", "`work_wechat`")
if meErr == nil {
appManList := GetApproveUser(myUsCont.Wechat, myUsCont.WorkWechat)
stepThree.UserList = append(stepThree.UserList, appManList)
sendCopyMan = append(sendCopyMan, appManList)
}
}
}
flowMap = append(flowMap, stepThree)
//发起人验收
var stepFour publicmethod.FlowChartList
stepFour.Step = 4
stepFour.NodeName = publicmethod.GetSetpName(5)
stepFour.State = 1
stepFour.Class = 1
stepFour.RunType = 2
stepFour.UserList = append(stepFour.UserList, GetApproveUser(context.Wechat, context.WorkWechat))
flowMap = append(flowMap, stepFour)
endStep = 5
} else {
if len(receivedValue.PeopleList) > 0 {
for ipv := 0; ipv < len(receivedValue.PeopleList); ipv++ {
var myUsCont modelshr.PersonArchives
meErr := myUsCont.GetCont(map[string]interface{}{"`key": receivedValue.PeopleList[ipv]}, "`wechat`", "`work_wechat`")
if meErr == nil {
appManList := GetApproveUser(myUsCont.Wechat, myUsCont.WorkWechat)
sendCopyMan = append(sendCopyMan, appManList)
}
}
}
}
}
//抄送
var stepCopy publicmethod.FlowChartList
stepCopy.Step = endStep
stepCopy.NodeName = publicmethod.GetSetpName(6)
stepCopy.State = 1
stepCopy.Class = 1
stepCopy.RunType = 3
stepCopy.UserList = sendCopyMan
flowMap = append(flowMap, stepCopy)
publicmethod.Result(0, flowMap, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-01 09:50:09
@ 功能: 获取人员信息
@ 参数
#wechat 微信Openid
#workWechat 企业微信ID
@ 返回值
#userCont 人员信息
*/
func GetApproveUser(wechat, workWechat string) (userCont publicmethod.UserListFlowAll) {
openId := wechat
if workWechat != "" {
openId = workWechat
}
var myCont modelshr.PersonArchives
err := overall.CONSTANT_DB_HR.Where("`wechat` = ? OR `work_wechat` = ?", openId, openId).First(&myCont).Error
if err == nil {
userCont.Id = strconv.FormatInt(myCont.Key, 10) //操作人ID
userCont.Name = myCont.Name //操作人姓名
userCont.Icon = myCont.Icon //操作人头像
userCont.Wechat = wechat //微信Openid
if workWechat != "" {
userCont.Wechat = workWechat
}
userCont.Company = myCont.Company //集团公司
if myCont.Company != 0 {
var companyCont modelshr.AdministrativeOrganization
companyCont.GetCont(map[string]interface{}{"`id`": myCont.Company}, "`name`")
userCont.CompanyName = companyCont.Name //分厂名称
}
userCont.DepartmentId = myCont.MainDeparment //分厂Id
if myCont.MainDeparment != 0 {
var departmentCont modelshr.AdministrativeOrganization
departmentCont.GetCont(map[string]interface{}{"`id`": myCont.MainDeparment}, "`name`")
userCont.DepartmentName = departmentCont.Name //分厂名称
}
userCont.WorkshopId = myCont.AdminOrg //工段Id
if myCont.AdminOrg != 0 {
var adminOrgCont modelshr.AdministrativeOrganization
adminOrgCont.GetCont(map[string]interface{}{"`id`": myCont.AdminOrg}, "`name`")
userCont.WorkshopName = adminOrgCont.Name //工段名称
}
userCont.PostId = myCont.JobId //职务Id
if myCont.JobId != 0 {
var dutiesCont modelshr.Duties
dutiesCont.GetCont(map[string]interface{}{"`id`": myCont.JobId}, "`name`")
userCont.PostName = dutiesCont.Name //职务名称
}
userCont.Tema = myCont.TeamId //班组Id
if myCont.TeamId != 0 {
var teamCont modelshr.TeamGroup
teamCont.GetCont(map[string]interface{}{"`id`": myCont.TeamId}, "`name`")
userCont.TemaName = teamCont.Name //班组名称
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-01 15:11:56
@ 功能: 创建流程图
@ 参数
#founderWechat 发起人微信或企业微信Openid
#founderDepartment 发起人部门
#reviewFlowParameter 创建流程参数
#isAdd 1创建2其他
@ 返回值
#flowMap 工作流
#err 系统信息
*/
func SetUpWorkFlow(founderWechat string, founderDepartment int64, reviewFlowParameter ReviewFlow, isAdd int) (flowMap []publicmethod.FlowChartList, err error) {
if reviewFlowParameter.IsCorrection == 0 {
reviewFlowParameter.IsCorrection = 2
}
if len(reviewFlowParameter.PeopleList) < 1 {
return
}
//获取考核项性质
var qualEvalScheme modelskpi.QualitativeEvaluationScheme
err = qualEvalScheme.GetCont(map[string]interface{}{"id": reviewFlowParameter.Id})
if err != nil {
return
}
//抄送人
var sendCopyMan []publicmethod.UserListFlowAll
var isTureCopyMan []string
//流程图
// var flowMap []publicmethod.FlowChartList
endStep := 1
//第一步:创建
var begin publicmethod.FlowChartList
begin.Step = endStep //步伐
begin.NodeName = publicmethod.GetSetpName(1) //节点名称
begin.State = 2 //状态 1、不点亮;2、点亮
begin.Class = 1 //节点类型 1、普通节点;2、运行中指定节点
begin.RunType = 1 //运行状态(1:开始;2:操作点;3:结束;4:抄送)
beginUserList := append(begin.UserList, GetApproveUser(founderWechat, founderWechat))
for _, bv := range beginUserList {
if isAdd == 1 {
var setLogList publicmethod.LogList
setLogList.State = 2
setLogList.TimeVal = publicmethod.UnixTimeToDay(time.Now().Unix(), 1)
bv.LogList = append(bv.LogList, setLogList)
}
begin.UserList = append(begin.UserList, bv)
if reviewFlowParameter.IsCorrection == 1 {
sendCopyMan = append(sendCopyMan, bv)
isTureCopyMan = append(isTureCopyMan, bv.Id)
}
}
var oenStep publicmethod.NodeRelationshipStruct
oenStep.FromNode = 0
oenStep.ToNode = 2
oenStep.RejectNode = 0
begin.NodeRelationship = oenStep
flowMap = append(flowMap, begin)
//第二步:本部门负责人审批
endStep = endStep + 1
var stepTwo publicmethod.FlowChartList
stepTwo.Step = endStep //步伐
stepTwo.NodeName = publicmethod.GetSetpName(2) //节点名称
stepTwo.State = 1 //状态 1、不点亮;2、点亮
stepTwo.Class = 1 //节点类型 1、普通节点;2、运行中指定节点
if reviewFlowParameter.IsCorrection == 1 {
stepTwo.RunType = 3
} else {
stepTwo.RunType = 2
}
//获取审批人weChatOpenID
sendUserList, userErr := publicmethod.GetRefereeTeamWorkWechat(16182159043990656, founderDepartment)
if userErr == nil {
for iu := 0; iu < len(sendUserList); iu++ {
departListUser := GetApproveUser(sendUserList[iu], sendUserList[iu])
stepTwo.UserList = append(stepTwo.UserList, departListUser)
if reviewFlowParameter.IsCorrection != 1 {
if publicmethod.IsInTrue[string](departListUser.Id, isTureCopyMan) == false {
sendCopyMan = append(sendCopyMan, departListUser)
isTureCopyMan = append(isTureCopyMan, departListUser.Id)
}
}
}
}
var twoFlowStep publicmethod.NodeRelationshipStruct
twoFlowStep.FromNode = endStep - 1
twoFlowStep.ToNode = endStep + 1
twoFlowStep.RejectNode = 1
stepTwo.NodeRelationship = twoFlowStep
flowMap = append(flowMap, stepTwo)
if qualEvalScheme.Attribute == 1 {
//定性
if reviewFlowParameter.IsCorrection != 1 {
//整改措施提交人
endStep = endStep + 1
var stepThree publicmethod.FlowChartList
stepThree.Step = endStep //步伐
stepThree.NodeName = publicmethod.GetSetpName(4) //节点名称
stepThree.State = 1 //状态 1、不点亮;2、点亮
stepThree.Class = 2 //节点类型 1、普通节点;2、运行中指定节点
stepThree.RunType = 2
//主要责任人负责提交整改措施
if len(reviewFlowParameter.PeopleList) > 0 {
for ipv := 0; ipv < len(reviewFlowParameter.PeopleList); ipv++ {
var myUsCont modelshr.PersonArchives
meErr := myUsCont.GetCont(map[string]interface{}{"`key": reviewFlowParameter.PeopleList[ipv]}, "`wechat`", "`work_wechat`")
if meErr == nil {
appManList := GetApproveUser(myUsCont.Wechat, myUsCont.WorkWechat)
stepThree.UserList = append(stepThree.UserList, appManList)
if publicmethod.IsInTrue[string](appManList.Id, isTureCopyMan) == false {
isTureCopyMan = append(isTureCopyMan, appManList.Id)
sendCopyMan = append(sendCopyMan, appManList)
}
}
}
}
var threeStep publicmethod.NodeRelationshipStruct
threeStep.FromNode = endStep - 1
threeStep.ToNode = endStep + 1
threeStep.RejectNode = 1
stepThree.NodeRelationship = threeStep
flowMap = append(flowMap, stepThree)
//发起人验收
endStep = endStep + 1
var stepFour publicmethod.FlowChartList
stepFour.Step = endStep
stepFour.NodeName = publicmethod.GetSetpName(5)
stepFour.State = 1
stepFour.Class = 1
stepFour.RunType = 3
stepFour.UserList = append(stepFour.UserList, GetApproveUser(founderWechat, founderWechat))
var fourStep publicmethod.NodeRelationshipStruct
fourStep.FromNode = endStep - 1
fourStep.ToNode = endStep + 1
fourStep.RejectNode = endStep - 1
stepFour.NodeRelationship = fourStep
flowMap = append(flowMap, stepFour)
// endStep = 5
} else {
if len(reviewFlowParameter.PeopleList) > 0 {
for ipv := 0; ipv < len(reviewFlowParameter.PeopleList); ipv++ {
var myUsCont modelshr.PersonArchives
meErr := myUsCont.GetCont(map[string]interface{}{"`key": reviewFlowParameter.PeopleList[ipv]}, "`wechat`", "`work_wechat`")
if meErr == nil {
appManList := GetApproveUser(myUsCont.Wechat, myUsCont.WorkWechat)
if publicmethod.IsInTrue[string](appManList.Id, isTureCopyMan) == false {
isTureCopyMan = append(isTureCopyMan, appManList.Id)
sendCopyMan = append(sendCopyMan, appManList)
}
}
}
}
}
}
//抄送
endStep = endStep + 1
var stepCopy publicmethod.FlowChartList
stepCopy.Step = endStep
stepCopy.NodeName = publicmethod.GetSetpName(6)
stepCopy.State = 1
stepCopy.Class = 3
stepCopy.UserList = sendCopyMan
stepCopy.RunType = 4
var endFlowStep publicmethod.NodeRelationshipStruct
endFlowStep.FromNode = endStep - 1
endFlowStep.ToNode = 0
endFlowStep.RejectNode = 0
stepCopy.NodeRelationship = endFlowStep
flowMap = append(flowMap, stepCopy)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-15 08:46:33
@ 功能: 获取节点操作人列表
@ 参数
#flowMap 流程结构体
#step 第几步
@ 返回值
#userKey 操作人key
#UserList 操作人列表
*/
func GetNodeOperator(flowMap []publicmethod.FlowChartList, step int) (userKey []string, UserList []publicmethod.UserListFlowAll) {
for _, v := range flowMap {
if v.Step == step {
UserList = v.UserList
if step > 0 {
for _, uv := range v.UserList {
if publicmethod.IsInTrue[string](uv.Id, userKey) == false {
userKey = append(userKey, uv.Id)
}
}
}
}
}
return
}

965
api/version1/flowchart/myworkflow.go

@ -0,0 +1,965 @@
package flowchart
import (
"encoding/json"
"fmt"
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/api/workwechat"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-04-08 10:09:31
@ 功能: 获取审批记录
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetApprovalRecord(c *gin.Context) {
var receivedValue HaveApprovalRecord
c.ShouldBindJSON(&receivedValue)
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.Page = 20
}
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
var flowList []modelskpi.ApprovalRecord
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.ApprovalRecord{})
switch receivedValue.State {
case 1:
gormDb = gormDb.Where("ep_state = ? ", 1)
case 2:
gormDb = gormDb.Where("ep_state = ? ", 2)
case 3:
gormDb = gormDb.Where("ep_state = ? ", 3)
case 4:
gormDb = gormDb.Where("ep_state = ? ", 4)
default:
gormDb = gormDb.Where("ep_state BETWEEN ? AND ?", 1, 4)
}
if receivedValue.Title != "" {
gormDb = gormDb.Where("target_title LIKE ? OR bylaws_title LIKE ?", "%"+receivedValue.Title+"%", "%"+receivedValue.Title+"%")
}
userIdentity := publicmethod.DetermineUserIdentity(myLoginCont.Key)
if myLoginCont.Role != "1" {
switch userIdentity.Level {
case 1:
gormDb = gormDb.Where("FIND_IN_SET(?,`ep_participants`)", myLoginCont.Key)
case 2:
gormDb = gormDb.Where("`ep_setup_department` IN ? OR `ep_accept_department` IN ?", userIdentity.OrgList, userIdentity.OrgList)
case 3:
gormDb = gormDb.Where("`ep_clique` = ? ", userIdentity.Group)
case 4:
gormDb = gormDb.Where("`ep_setup_department` IN ? OR `ep_accept_department` IN ?", userIdentity.OrgList, userIdentity.OrgList)
default:
}
}
if receivedValue.OrgId != "" {
gormDb = gormDb.Where("ep_accept_department = ? OR ep_setup_department = ?", receivedValue.OrgId, receivedValue.OrgId)
}
if receivedValue.Years != 0 {
if receivedValue.Months != 0 {
timeDay := fmt.Sprintf("%v-%v-01", receivedValue.Years, receivedValue.Months)
if receivedValue.Months <= 9 {
timeDay = fmt.Sprintf("%v-0%v-01", receivedValue.Years, receivedValue.Months)
}
startTime, endTime := publicmethod.GetAppointMonthStarAndEndTimeEs(timeDay)
gormDb = gormDb.Where("ep_happen_time BETWEEN ? AND ?", startTime, endTime)
} else {
startTime := publicmethod.DateToTimeStampOld(fmt.Sprintf("%v-01-01 00:00:00", receivedValue.Years))
endTime := publicmethod.DateToTimeStampOld(fmt.Sprintf("%v-12-31 23:59:59", receivedValue.Years))
gormDb = gormDb.Where("ep_happen_time BETWEEN ? AND ?", startTime, endTime)
}
}
jsonStr, _ := json.Marshal(userIdentity)
fmt.Printf("userIdentity------------>%v\n", string(jsonStr))
var total int64
totalErr := gormDb.Count(&total).Error
if totalErr != nil {
total = 0
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("ep_id DESC").Find(&flowList).Error
if err != nil {
publicmethod.Result(105, err, c)
return
}
var sendListCont []OutPutFlowLog
for _, v := range flowList {
var sendCont OutPutFlowLog
sendCont.Id = strconv.FormatInt(v.Id, 10) //
sendCont.OrderKey = strconv.FormatInt(v.OrderKey, 10) //发起表单key"`
sendCont.Step = v.Step //当前执行到第几部"`
sendCont.Content = v.Content //流程步进值"`
sendCont.NextContent = v.NextContent //下一步内容"`
sendCont.Time = v.Time //创建时间"`
sendCont.CreationDate = publicmethod.UnixTimeToDay(v.StartTime, 11)
sendCont.State = v.State //1:草稿,2:审批中;3:驳回;4:归档;5:删除"`
sendCont.RoleGroup = strconv.FormatInt(v.RoleGroup, 10) //角色组"`
sendCont.TypeClass = v.TypeClass //1、定性;2、定量"`
sendCont.Participants = v.Participants //参与人"`
sendCont.StartTime = v.StartTime //u流程开始时间"`
sendCont.NextStep = v.NextStep //下一步"`
sendCont.NextExecutor = v.NextExecutor //下一步执行人"`
sendCont.SetupDepartment = strconv.FormatInt(v.SetupDepartment, 10) //发起部门"`
sendCont.Dimension = v.Dimension //维度"`
sendCont.Target = v.Target //指标"`
sendCont.DetailedTarget = v.DetailedTarget //指标细则"`
sendCont.AcceptDepartment = strconv.FormatInt(v.AcceptDepartment, 10) //接受考核部门"`
sendCont.HappenTime = v.HappenTime //发生时间"`
sendCont.OccurrenceTime = publicmethod.UnixTimeToDay(v.HappenTime, 14)
sendCont.FlowKey = strconv.FormatInt(v.FlowKey, 10) //工作流识别符"`
sendCont.FlowVid = strconv.FormatInt(v.FlowVid, 10) //当前工作流版本号"`
sendCont.EpOld = v.EpOld //1:旧流程;2:新流程"`
sendCont.Creater = strconv.FormatInt(v.Creater, 10) //流程创始人"`
sendCont.TargetTitle = v.TargetTitle //指标名称"`
sendCont.BylawsTitle = v.BylawsTitle //细则名称"`
sendCont.Clique = strconv.FormatInt(v.Clique, 10) //公司"`
var accOrgCont modelshr.AdministrativeOrganization
accOrgCont.GetCont(map[string]interface{}{"`id`": v.AcceptDepartment}, "`name`")
sendCont.DepartmentName = accOrgCont.Name
if v.Creater != 0 {
var creaCont modelshr.PersonArchives
creaCont.GetCont(map[string]interface{}{"`key`": v.Creater}, "`name`")
sendCont.CreaterName = creaCont.Name
}
if v.EpOld == 2 {
if v.NextContent != "" {
var nextNode currency_recipe.NodeCont
jsonErr := json.Unmarshal([]byte(v.NextContent), &nextNode)
if jsonErr == nil {
sendCont.CurrentNode = nextNode.NodeName
if len(nextNode.UserList) > 0 {
var userNameCree []string
for _, uv := range nextNode.UserList {
if !publicmethod.IsInTrue[string](uv.Name, userNameCree) {
userNameCree = append(userNameCree, uv.Name)
}
}
sendCont.CurrentNodeMan = strings.Join(userNameCree, ",")
}
}
}
} else {
var flowLog []currency_recipe.NodeCont
jsonFlowErr := json.Unmarshal([]byte(v.NextContent), &flowLog)
// fmt.Printf("流程------>%v\n", flowLog)
if jsonFlowErr == nil {
for _, fv := range flowLog {
if fv.Step == v.NextStep {
sendCont.CurrentNode = fv.NodeName
if len(fv.UserList) > 0 {
var userNameCreeOld []string
for _, uvo := range fv.UserList {
if !publicmethod.IsInTrue[string](uvo.Name, userNameCreeOld) {
userNameCreeOld = append(userNameCreeOld, uvo.Name)
}
}
sendCont.CurrentNodeMan = strings.Join(userNameCreeOld, ",")
}
}
}
}
}
sendListCont = append(sendListCont, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, int64(total), int64(len(sendListCont)), sendListCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-08 16:47:22
@ 功能: 查看审批记录详情
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) LookWorkFlowCont(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, err, c)
return
}
//获取流程信息
var evalProCont modelskpi.EvaluationProcess
err = evalProCont.GetCont(map[string]interface{}{"ep_id": receivedValue.Id})
if err != nil {
publicmethod.Result(107, err, c)
return
}
var sendCont OutPutWorkflowCont
sendCont.Id = strconv.FormatInt(evalProCont.Id, 10)
sendCont.FlowNumber = strconv.FormatInt(evalProCont.OrderKey, 10)
sendCont.Attribute = evalProCont.TypeClass //1、定性;2、定量"`
sendCont.NextStep = evalProCont.NextStep
if evalProCont.Creater != 0 {
var creaCont modelshr.PersonArchives
creaCont.GetCont(map[string]interface{}{"`key`": evalProCont.Creater}, "`name`")
sendCont.CreaterName = creaCont.Name
}
sendCont.DepartmentId = evalProCont.AcceptDepartment
var accOrgCont modelshr.AdministrativeOrganization
accOrgCont.GetCont(map[string]interface{}{"`id`": evalProCont.AcceptDepartment}, "`name`")
sendCont.DepartmentName = accOrgCont.Name
sendCont.CreationDate = publicmethod.UnixTimeToDay(evalProCont.HappenTime, 11)
sendCont.ReportingDate = publicmethod.UnixTimeToDay(evalProCont.Time, 11)
sendCont.IsOld = evalProCont.EpOld
nextRunType := 1
if evalProCont.EpOld == 2 {
json.Unmarshal([]byte(evalProCont.Content), &sendCont.WorkFlowList)
if evalProCont.NextStep != 0 && evalProCont.NextStep <= len(sendCont.WorkFlowList) {
sendCont.NodeStep = evalProCont.Step
} else {
sendCont.NodeStep = len(sendCont.WorkFlowList)
}
if evalProCont.State < 4 && evalProCont.NextContent != "" {
var nextNodeCont currency_recipe.NodeCont
json.Unmarshal([]byte(evalProCont.NextContent), &nextNodeCont)
// sendCont.RunType = nextNodeCont.Type
nextRunType = nextNodeCont.Type
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
if len(nextNodeCont.UserList) > 0 {
for _, uv := range nextNodeCont.UserList {
myKeyStr := strconv.FormatInt(myLoginCont.Key, 10)
if uv.Id == myKeyStr {
sendCont.Actionable = 1
}
}
}
if len(sendCont.WorkFlowList) > 0 {
for _, av := range sendCont.WorkFlowList {
if av.CustomNode == nextNodeCont.NodeNumber {
sendCont.OperateOtherNodes = av
sendCont.SetExecutor = 1
}
}
}
}
} else {
json.Unmarshal([]byte(evalProCont.NextContent), &sendCont.WorkFlowListOld)
if evalProCont.NextStep != 0 && evalProCont.NextStep <= len(sendCont.WorkFlowListOld) {
sendCont.NodeStep = evalProCont.Step
} else {
sendCont.NodeStep = len(sendCont.WorkFlowListOld)
}
}
//定性部分
if evalProCont.TypeClass == 1 {
var scoreFlowList []modelskpi.ScoreFlow
overall.CONSTANT_DB_KPI.Model(&modelskpi.ScoreFlow{}).Select("sf_evaluation_plan,sf_plus_reduce_score,sf_score,sf_reason,sf_count,sf_target_id,sf_detailed_id,sf_enclosure").Where("sf_key = ?", evalProCont.OrderKey).Find(&scoreFlowList)
if len(scoreFlowList) > 0 {
for _, v := range scoreFlowList {
var dingXingCong DingxingCont
//获取指标信息
var targetCont modelskpi.EvaluationTarget
targetCont.GetCont(map[string]interface{}{"`et_id`": v.TargetId}, "`et_title`", "`et_dimension`")
dingXingCong.Target = targetCont.Title
//获取维度细信息
var dimeCont modelskpi.DutyClass
dimeCont.GetCont(map[string]interface{}{"`id`": targetCont.Dimension}, "`title`")
dingXingCong.Dimension = dimeCont.Title
//获取细则信息
var detailedTargetCont modelskpi.DetailedTarget
detailedTargetCont.GetCont(map[string]interface{}{"`dt_id`": v.DetailedId}, "`dt_title`", "`dt_parentid_sun`")
dingXingCong.DetailedTarget = detailedTargetCont.Title
//获取栏目信息
var tableCont modelskpi.QualitativeTarget
tableCont.GetCont(map[string]interface{}{"`q_id`": detailedTargetCont.ParentIdSun}, "`q_title`")
dingXingCong.TableName = tableCont.Title
//获取定性指标数据
var qualEvalView modelskpi.QualitativeEvaluationView
qualEvalView.GetCont(map[string]interface{}{"`qe_id`": v.EvaluationPlan}, "`qe_min_score`", "`qe_max_score`", "`qe_reference_score`")
if qualEvalView.MinScore > 0 && qualEvalView.MaxScore > 0 {
dingXingCong.Standard = fmt.Sprintf("%v-%v", qualEvalView.MinScore/100, qualEvalView.MaxScore/100) //标准
defen := float64(v.Score) / 100
dingXingCong.PlusMinusScore = publicmethod.DecimalEs(defen, 2)
} else if qualEvalView.MinScore > 0 && qualEvalView.MaxScore <= 0 {
dingXingCong.Standard = fmt.Sprintf("%v", qualEvalView.MinScore/100)
defen := (float64(v.Score) * float64(v.Count)) / 100
dingXingCong.PlusMinusScore = publicmethod.DecimalEs(defen, 2)
} else if qualEvalView.MinScore <= 0 && qualEvalView.MaxScore > 0 {
dingXingCong.Standard = fmt.Sprintf("%v", qualEvalView.MaxScore/100)
defen := (float64(v.Score) * float64(v.Count)) / 100
dingXingCong.PlusMinusScore = publicmethod.DecimalEs(defen, 2)
} else {
dingXingCong.Standard = "0"
defen := float64(v.Score) / 100
dingXingCong.PlusMinusScore = publicmethod.DecimalEs(defen, 2)
}
dingXingCong.Cause = v.Reason
dingXingCong.PlusReduction = v.PlusReduceScore
if v.Enclosure != "" {
json.Unmarshal([]byte(v.Enclosure), &dingXingCong.Enclosure)
}
sendCont.DingXingList = append(sendCont.DingXingList, dingXingCong)
}
}
} else {
//定量
var flowLogCont modelskpi.FlowLog
flcErr := flowLogCont.GetCont(map[string]interface{}{"`fl_key`": evalProCont.OrderKey}, "`fl_enclosure`", "`fl_planversion`", "`fl_baseline`")
if flcErr == nil {
var jiZhunZhi []DingLiangJizhuxian
json.Unmarshal([]byte(flowLogCont.Baseline), &jiZhunZhi)
var dingLiangLog []modelskpi.FlowLogData
overall.CONSTANT_DB_KPI.Model(&modelskpi.FlowLogData{}).Select("fld_evaluation_id,fld_score,fld_cont,fld_scoring_method,fld_scoring_score,fld_target_id").Where("fld_flow_log = ?", evalProCont.OrderKey).Find(&dingLiangLog)
if len(dingLiangLog) > 0 {
for _, v := range dingLiangLog {
var dingLiangInfo DingLiangCont
//获取指标信息
var targetCont modelskpi.EvaluationTarget
targetCont.GetCont(map[string]interface{}{"`et_id`": v.TargetId}, "`et_title`", "`et_dimension`")
dingLiangInfo.Target = targetCont.Title
//获取维度细信息
var dimeCont modelskpi.DutyClass
dimeCont.GetCont(map[string]interface{}{"`id`": targetCont.Dimension}, "`title`")
dingLiangInfo.Dimension = dimeCont.Title
var zeroprize float64
var allprize float64
var capping float64
if len(jiZhunZhi) > 0 {
for _, jzzv := range jiZhunZhi {
epId := strconv.FormatInt(v.EvaluationPlan, 10)
fmt.Printf("限定值---》%v\n", v.EvaluationPlan)
if jzzv.Id == epId {
dingLiangInfo.Zeroprize = publicmethod.DecimalEs(float64(jzzv.Zeroprize)/100, 2) //零奖值"`
dingLiangInfo.Allprize = publicmethod.DecimalEs(float64(jzzv.Allprize)/100, 2) //零奖值"`
dingLiangInfo.Capping = publicmethod.DecimalEs(float64(jzzv.Capping)/100, 2) //零奖值"`
zeroprize = float64(jzzv.Zeroprize)
allprize = float64(jzzv.Allprize)
capping = float64(jzzv.Capping)
}
}
}
var qualEvalView modelskpi.QualitativeEvaluationView
qualEvalView.GetCont(map[string]interface{}{"`qe_id`": v.EvaluationPlan}, "`qe_reference_score`")
dingLiangInfo.Weight = float64(qualEvalView.ReferenceScore) //权重
dingLiangInfo.ActualValue = publicmethod.DecimalEs(float64(v.Score)/100, 2) //实际值
// dingLiangInfo.CompletionRate = v.Score //完成率
if v.ScoringMethod == 1 {
dingLiangInfo.TargetScore, _, _, _, dingLiangInfo.CompletionRate = publicmethod.CalculateScore(qualEvalView.ReferenceScore, float64(v.Score), allprize, zeroprize, capping, 2)
} else {
dingLiangInfo.TargetScore = publicmethod.DecimalEs(float64(v.ScoringScore)/100, 2) //指标得分
}
//
dingLiangInfo.CalculationMethod = v.ScoringMethod
dingLiangInfo.Cause = v.Content
sendCont.DingLiangList = append(sendCont.DingLiangList, dingLiangInfo)
}
}
}
}
//获取责任划分
var dutyListCont []modelskpi.DivisionResponsibilities
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.DivisionResponsibilities{}).Select("df_type,df_user_name,df_user_key,df_weight,df_user_number").Where("df_sf_id = ?", evalProCont.OrderKey).Find(&dutyListCont).Error
if err == nil && len(dutyListCont) > 0 {
sendCont.DivisionIsShow = 1
for _, dlv := range dutyListCont {
var dutyCont DivisionListCont
dutyCont.Type = dlv.Type //类型
dutyCont.UserName = dlv.UserName //姓名
dutyCont.UserNumber = dlv.UserNumber //工号
dutyCont.UserKey = strconv.FormatInt(dlv.UserKey, 10) //识别码
dutyCont.Weight = publicmethod.DecimalEs(float64(dlv.Weight)/100, 2) //权重
sendCont.DivisionList = append(sendCont.DivisionList, dutyCont)
}
}
if sendCont.Actionable == 1 {
if sendCont.SetExecutor == 1 {
sendCont.DivisionIsShow = 1
sendCont.DivisLoofOfEdit = 1
} else {
sendCont.DivisLoofOfEdit = 2
}
if nextRunType == 3 {
sendCont.RunType = 1
} else {
sendCont.RunType = 2
}
} else {
sendCont.DivisLoofOfEdit = 2
sendCont.RunType = 2
}
// fmt.Printf("nextRunType------>%v\n", nextRunType)
//获取整改措施
var measureList []modelskpi.RectificationMeasures
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.RectificationMeasures{}).Select("rm_user_key,rm_state,rm_time,rm_content,rm_files").Where("depart_post = 1 AND rm_order = ?", evalProCont.OrderKey).Find(&measureList).Error
if err == nil && len(measureList) > 0 {
sendCont.MeasureIsShow = 1
for _, mlv := range measureList {
var measUser modelshr.PersonArchives
measUser.GetCont(map[string]interface{}{"`key`": mlv.UserKey}, "`name`", "`number`", "`admin_org`")
var measCont MeasureCont
measCont.UserName = measUser.Name //姓名
measCont.UserNumber = measUser.Number //工号
measCont.UserKey = strconv.FormatInt(mlv.UserKey, 10) //识别符
var orgCont modelshr.AdministrativeOrganization
orgCont.GetCont(map[string]interface{}{"`id`": measUser.AdminOrg}, "`name`")
measCont.OrgNAme = orgCont.Name //行政组织
measCont.Cause = mlv.Content //整改内容
if mlv.Enclosure != "" {
hjsdj := json.Unmarshal([]byte(mlv.Enclosure), &measCont.Enclosure)
fmt.Printf("hjsdj----------->%+v\n", hjsdj)
}
measCont.Time = publicmethod.UnixTimeToDay(mlv.Time, 1) //整改内容
sendCont.MeasureList = append(sendCont.MeasureList, measCont)
}
} else {
if sendCont.RunType == 1 {
sendCont.MeasureIsShow = 1
}
}
publicmethod.Result(0, sendCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-10 15:22:38
@ 功能: 审批操作
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) ExamineAndApprove(c *gin.Context) {
var receivedValue ExamAndApp
c.ShouldBindJSON(&receivedValue)
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.YesOrNo == 0 {
receivedValue.YesOrNo = 3
}
//获取登录人信息
myLoginCont, err := publicmethod.LoginMyCont(c)
if err != nil {
publicmethod.Result(1, err, c, "你没有权限进行此操作!或您的身份令牌已超时!")
return
}
//获取流程信息
var evalProCont modelskpi.EvaluationProcess
err = evalProCont.GetCont(map[string]interface{}{"ep_id": receivedValue.Id})
if err != nil {
publicmethod.Result(107, err, c)
return
}
if evalProCont.State == 4 {
publicmethod.Result(1, err, c, "流程已归档!不可进行审批!")
return
}
if evalProCont.State == 5 {
publicmethod.Result(1, err, c, "流程已锁定!不可进行任何操作!")
return
}
if evalProCont.NextStep == 0 {
publicmethod.Result(1, err, c, "流程已归档!不可进行审批!")
return
}
if evalProCont.NextStep != receivedValue.Step {
publicmethod.Result(1, err, c, "改节点已经被其他人操作!不可重复操作!")
return
}
if evalProCont.NextContent != "" {
var nextNodeInfo currency_recipe.NodeCont
jsonErr := json.Unmarshal([]byte(evalProCont.NextContent), &nextNodeInfo)
if jsonErr == nil {
isOk := false
for _, v := range nextNodeInfo.UserList {
myKeyStr := strconv.FormatInt(myLoginCont.Key, 10)
if myKeyStr == v.Id {
isOk = true
}
}
if !isOk {
publicmethod.Result(1, err, c, "你没有权限进行此操作!或您的身份令牌已超时!")
return
}
}
}
var workFlowList []currency_recipe.NodeCont
json.Unmarshal([]byte(evalProCont.Content), &workFlowList)
var runWorkflow WorkFlowRuning
runWorkflow.OrderKey = evalProCont.OrderKey
runWorkflow.List = workFlowList
runWorkflow.Step = evalProCont.NextStep
runWorkflow.Executor = myLoginCont
runWorkflow.YesOrNo = receivedValue.YesOrNo
runWorkflow.Cause = receivedValue.Cause
runWorkflow.Enclosure = receivedValue.Enclosure
//判断是否需要写入责任人
if receivedValue.SetExecutor == 1 {
if len(receivedValue.ExecutorList) > 0 {
//责任划分
var addDivisRespon []modelskpi.DivisionResponsibilities
for _, elv := range receivedValue.ExecutorList {
var userInfo modelshr.PersonArchives
userInfo.GetCont(map[string]interface{}{"key": elv.UserKey})
if elv.Type == 1 {
runWorkflow.DesignatedOperator.UserList = append(runWorkflow.DesignatedOperator.UserList, currency_recipe.SetOperator(userInfo))
}
var addDivCont modelskpi.DivisionResponsibilities
addDivCont.ScoreFlow = evalProCont.OrderKey //归属加减分关联值"`
addDivCont.Type = elv.Type //责任类型(1、主要责任人;2、互保责任人;3、责任班组;4、责任班组长;5、主管;6、三大员;7、厂长、主任)"`
addDivCont.UserName = userInfo.Name //责任人名"`
addDivCont.UserNumber = userInfo.Number //责任人工号"`
addDivCont.UserKey = userInfo.Key //责任人KEY"`
addDivCont.Department = userInfo.AdminOrg //责任人部门"`
addDivCont.Group = userInfo.Company //责任人集团"`
addDivCont.Tema = userInfo.TeamId //责任人班组"`
weightFloat64, _ := strconv.ParseFloat(elv.Weight, 64)
weightInt64, _ := strconv.ParseInt(strconv.FormatFloat(weightFloat64*100, 'f', -1, 64), 10, 64)
addDivCont.Weight = weightInt64 //比重"`*100
addDivCont.Time = time.Now().Unix() //创建时间"`
addDivCont.EiteTime = time.Now().Unix() //修改时间"`
addDivCont.DistributionUser = publicmethod.GetUUid(8) //分配任key"`
addDivCont.EvaluationDepartment = myLoginCont.MainDeparment //测评部门"`
addDivCont.EvaluationUser = myLoginCont.Key //测评人"`
addDivCont.EvaluationGroup = myLoginCont.Company //测评集团"`
addDivisRespon = append(addDivisRespon, addDivCont)
}
if len(runWorkflow.DesignatedOperator.UserList) > 0 {
runWorkflow.DesignatedOperator.IsTrue = true
} else {
runWorkflow.DesignatedOperator.IsTrue = false
}
if len(addDivisRespon) > 0 {
var delDivCont modelskpi.DivisionResponsibilities
delDivCont.DelCont(map[string]interface{}{"df_sf_id": evalProCont.OrderKey})
overall.CONSTANT_DB_KPI.Create(&addDivisRespon)
}
} else {
publicmethod.Result(1, err, c, "未划分责任人!请先划分责任人!")
return
}
}
//提交整改意见
if receivedValue.CorrectiveAction.IsTrue == 1 {
if receivedValue.CorrectiveAction.Content == "" {
publicmethod.Result(1, err, c, "请输入整改意见!")
return
} else {
runWorkflow.CorrectiveAction.IsTrue = 1
runWorkflow.CorrectiveAction.Content = receivedValue.CorrectiveAction.Content
var fileListCont []currency_recipe.EnclosureFormat
if len(receivedValue.CorrectiveAction.Enclosure) > 0 {
for _, ev := range receivedValue.CorrectiveAction.Enclosure {
var fileCont currency_recipe.EnclosureFormat
fileCont.FileName = ev.Name //附件名称
fileCont.FilePath = ev.FileUrl //附件地址
fileCont.Type = ev.Type //附件类型
fmt.Printf("副将---->%v\n---->%v\n", fileCont, ev)
runWorkflow.CorrectiveAction.Annex = append(runWorkflow.CorrectiveAction.Annex, fileCont)
fileListCont = append(fileListCont, fileCont)
}
}
var userInfo modelshr.PersonArchives
userInfo.GetCont(map[string]interface{}{"key": myLoginCont.Key})
var writeRectMeas modelskpi.RectificationMeasures
writeRectMeas.UserKey = userInfo.Key //整改人"`
writeRectMeas.Department = userInfo.AdminOrg //整改部门"`
writeRectMeas.Group = userInfo.Company //集团"`
writeRectMeas.OrderKey = evalProCont.OrderKey //订单ID"`
writeRectMeas.State = 2 //1:草果;2:审批中;3:不合格;4:合格"`
writeRectMeas.Time = time.Now().Unix() //创建时间"`
writeRectMeas.EiteTime = time.Now().Unix() //修改时间"`
writeRectMeas.Content = receivedValue.CorrectiveAction.Content //整改内容"`
if len(fileListCont) > 0 {
fileJson, _ := json.Marshal(fileListCont)
writeRectMeas.Enclosure = string(fileJson) //附件"`
}
writeRectMeas.DepartPost = 1 //1、部门;2:岗位"`
fmt.Printf("附件---->%v\n---->%v\n", fileListCont, writeRectMeas)
writeRectMeas.AddCont()
}
}
runWorkflow.ProcessOperation()
editWorkflow := publicmethod.MapOut[string]()
workflowAll, _ := json.Marshal(runWorkflow.List)
editWorkflow["ep_cont"] = string(workflowAll)
if len(runWorkflow.NextExecutor) > 0 {
editWorkflow["ep_next_executor"] = strings.Join(runWorkflow.NextExecutor, ",")
} else {
editWorkflow["ep_next_executor"] = ""
}
if runWorkflow.NextNodeCont.Step != 0 {
workflowNext, _ := json.Marshal(runWorkflow.NextNodeCont)
editWorkflow["ep_next_cont"] = string(workflowNext)
} else {
editWorkflow["ep_next_cont"] = ""
}
editWorkflow["ep_next_step"] = runWorkflow.NextStep
if len(runWorkflow.Participant) > 0 {
editWorkflow["ep_participants"] = strings.Join(runWorkflow.Participant, ",")
} else {
editWorkflow["ep_participants"] = ""
}
replyState := receivedValue.YesOrNo
if receivedValue.YesOrNo == 2 {
if runWorkflow.NextStep == 0 {
editWorkflow["ep_state"] = 4
replyState = 4
} else {
editWorkflow["ep_state"] = 2
replyState = 2
}
} else {
editWorkflow["ep_state"] = receivedValue.YesOrNo
replyState = receivedValue.YesOrNo
}
if runWorkflow.NextStep == 0 {
editWorkflow["ep_step"] = len(runWorkflow.List)
} else {
editWorkflow["ep_step"] = runWorkflow.Step
}
editWorkflow["ep_time"] = time.Now().Unix()
var evalProContEdit modelskpi.EvaluationProcess
err = evalProContEdit.EiteCont(map[string]interface{}{"ep_id": evalProCont.Id}, editWorkflow)
// uh := publicmethod.MapOut[string]()
// uh["editWorkflow"] = editWorkflow
// uh["runWorkflow"] = runWorkflow
if err != nil {
publicmethod.Result(104, err, c)
return
}
if evalProCont.TypeClass == 1 {
//定性
scoFlwWhe := publicmethod.MapOut[string]()
scoFlwWhe["sf_key"] = evalProCont.OrderKey
var seeScoreFlowCont modelskpi.ScoreFlow
scoErr := seeScoreFlowCont.GetCont(scoFlwWhe, "sf_id")
if scoErr == nil {
seeScoreFlowCont.EiteCont(scoFlwWhe, map[string]interface{}{"sf_reply": replyState})
}
} else {
flwWhe := publicmethod.MapOut[string]()
flwWhe["fl_key"] = evalProCont.OrderKey
//定量
var flowLogInfo modelskpi.FlowLog
flwErr := flowLogInfo.GetCont(flwWhe, "fl_id")
if flwErr == nil {
flowLogInfo.EiteCont(flwWhe, map[string]interface{}{"fl_reply": replyState})
}
}
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-10 16:52:14
@ 功能: 流程操作
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkFlowRuning) ProcessOperation() {
total := len(w.List) //获取流程总长度
if total > 0 { //流程存在内容
if w.Step <= total && w.Step != 0 { //判断流程起点及流程有无超出范围
w.NextStep = w.Step + 1 //获取下一步步进值
if w.NextStep >= total {
w.NextStep = 0
}
userKey := strconv.FormatInt(w.Executor.Key, 10) //当前操作人Key
for i, v := range w.List { //遍历匹配节点
if v.Step < w.Step { //当前节点之前的节点全部置操作
w.List[i].State = 2
for _, usv := range v.UserList { //获取已参与进来的人
if !publicmethod.IsInTrue[string](usv.Id, w.Participant) {
w.Participant = append(w.Participant, usv.Id)
}
}
}
if v.Step == w.Step { //当前节点
w.AddNodeOperator(v.NodeNumber)
w.List[i].State = 2 //节点置已操作
var atPresentWechat []string
var atPresent []string
for ui, uv := range v.UserList {
if !publicmethod.IsInTrue[string](uv.Id, w.Participant) {
w.Participant = append(w.Participant, uv.Id)
}
atPresent = append(atPresent, uv.Id)
atPresentWechat = append(atPresentWechat, uv.Wechat)
if uv.Id == userKey {
var userCarrLog currency_recipe.LogList
userCarrLog.State = w.YesOrNo //状态 1、未操作;2、通过;3、驳回
userCarrLog.Cause = w.Cause
userCarrLog.TimeVal = publicmethod.UnixTimeToDay(time.Now().Unix(), 1)
userCarrLog.Enclosure = w.Enclosure //附件
w.List[i].UserList[ui].LogList = append(w.List[i].UserList[ui].LogList, userCarrLog)
}
}
w.RunNode = v
w.WriteFlowLog()
if v.Type != 2 { //判断当前节点是不是操作
workwechat.UpdateWechatMsgCont(1, w.YesOrNo, w.OrderKey, userKey)
//判断同意还是驳回
if w.YesOrNo == 2 {
w.NodeYes(total)
} else {
w.NodeNot(total, v.GoBackNode)
}
} else {
for ui, _ := range v.UserList {
var userCarrLog currency_recipe.LogList
userCarrLog.State = w.YesOrNo //状态 1、未操作;2、通过;3、驳回
userCarrLog.Cause = w.Cause
userCarrLog.TimeVal = publicmethod.UnixTimeToDay(time.Now().Unix(), 1)
userCarrLog.Enclosure = w.Enclosure //附件
w.List[i].UserList[ui].LogList = append(w.List[i].UserList[ui].LogList, userCarrLog)
}
msgkkk, ksgEr := SendTogetherMsg(w.OrderKey, v, 1)
fmt.Printf("ProcessOperation--->%v\n--->%v\n", msgkkk, ksgEr)
//是抄送节点
w.ProcessOperation()
return
}
}
}
} else { //流程已结束
w.NextStep = 0
for i, v := range w.List {
w.List[i].State = 2
for _, usv := range v.UserList {
if !publicmethod.IsInTrue[string](usv.Id, w.Participant) {
w.Participant = append(w.Participant, usv.Id)
}
}
}
}
}
}
func (w *WorkFlowRuning) AddNodeOperator(nodeNumber string) {
if w.DesignatedOperator.IsTrue {
for i, v := range w.List {
if v.CustomNode == nodeNumber {
w.List[i].UserList = w.DesignatedOperator.UserList
}
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-11 09:32:38
@ 功能: 判断下一步要执行什么(拒绝)
@ 参数
#total 流程总步数
#nodeNumber 要退回的节点
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkFlowRuning) NodeNot(total int, nodeNumber string) {
if total <= 1 {
w.NextStep = 1
}
for _, nv := range w.List {
if nv.NodeNumber == nodeNumber {
w.NextStep = nv.Step
stepVal := nv.Step - 1
if stepVal < 1 {
w.Step = 1
} else {
w.Step = stepVal
}
break
}
}
w.NodeYes(total)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-11 09:26:41
@ 功能: 判断下一步要执行什么(同意)
@ 参数
#total 流程总步数
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkFlowRuning) NodeYes(total int) {
if w.NextStep <= total && w.NextStep != 0 {
for i, v := range w.List {
if v.Step == w.NextStep {
writeLog := false
if v.Type == 2 {
w.Step = w.NextStep
writeLog = true
w.List[i].State = 2
}
var nextZhiXingRen []string
var atPresentWechat []string
for ni, nv := range v.UserList {
if !publicmethod.IsInTrue[string](nv.Id, w.Participant) {
w.Participant = append(w.Participant, nv.Id)
}
if !publicmethod.IsInTrue[string](nv.Id, nextZhiXingRen) {
nextZhiXingRen = append(nextZhiXingRen, nv.Id) //下一步执行人
}
if !publicmethod.IsInTrue[string](nv.Wechat, atPresentWechat) {
atPresentWechat = append(atPresentWechat, nv.Wechat)
}
if writeLog { //参送节点直接发送信息
var userCarrLog currency_recipe.LogList
userCarrLog.State = 2 //状态 1、未操作;2、通过;3、驳回
userCarrLog.Cause = ""
userCarrLog.TimeVal = publicmethod.UnixTimeToDay(time.Now().Unix(), 1)
// userCarrLog.Enclosure = w.Enclosure //附件
w.List[i].UserList[ni].LogList = append(w.List[i].UserList[ni].LogList, userCarrLog)
}
}
w.NextNodeCont = v
w.NextExecutor = nextZhiXingRen
msgkkk, ksgEr := SendTogetherMsg(w.OrderKey, v, 1)
fmt.Printf("NodeYes--->%v\n--->%v\n", msgkkk, ksgEr)
if writeLog {
w.RunNode = v
w.WriteFlowLog()
w.ProcessOperation()
return
}
}
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-10 16:52:24
@ 功能: 审批记录新增
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkFlowRuning) WriteFlowLog() {
//审批记录
var stepsTotal int64
overall.CONSTANT_DB_KPI.Model(&modelskpi.OpenApprovalChangeLog{}).Where("`orderid` = ?", w.OrderKey).Count(&stepsTotal)
var flowLogCont modelskpi.OpenApprovalChangeLog
flowLogCont.Type = 1 //类型(1:部门;2:岗位)"`
flowLogCont.Title = w.RunNode.NodeName //节点名称"`
flowLogCont.Operator = w.Executor.Key //操作人"`
flowLogCont.OrderId = w.OrderKey //订单ID"`
flowLogCont.OperatorTime = time.Now().Unix() //操作时间"`
flowLogCont.Step = stepsTotal + 1 //操作第几步"`
flowLogCont.OperatorType = w.RunNode.State //操作状态(1:位操作;2:已操作)"`
flowLogCont.Msgid = "" //消息id,用于撤回应用消息"`
flowLogCont.ResponseCode = "" //仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,24小时内有效,且只能使用一次"`
flowLogCont.Stepper = w.RunNode.Step //步进器"`
flowLogCont.ChangeIsTrue = 1 //是否可变更(1:可变更;2:不可变更)"`
flowLogCont.Eiteyime = time.Now().Unix() //变动时间"`
flowLogCont.YesOrNo = w.YesOrNo //未操作;1:同意;2:驳回;3:撤回"`
flowLogCont.Idea = w.Cause
fileJson, _ := json.Marshal(w.Executor)
flowLogCont.Annex = string(fileJson)
flowLogCont.AddCont()
}

258
api/version1/flowchart/sendmsg.go

@ -0,0 +1,258 @@
package flowchart
import (
"encoding/json"
"fmt"
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/api/workwechat"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-04-23 14:29:55
@ 功能: 统一发送信息
@ 参数
#orderId 审批记录编号
#nodeCont 节点内容
#operate 操作1通过2驳回3抄送
@ 返回值
#
@ 方法原型
#
*/
func SendTogetherMsg(orderId int64, nodeCont currency_recipe.NodeCont, operate int) (callbackMsgStr string, err error) {
if orderId == 0 {
return
}
if len(nodeCont.UserList) <= 0 {
return
}
var recipient []string //接收人
var sendWechatUserKey []string
for _, v := range nodeCont.UserList { //获取接收人得微信或企业微信Openid用作发送消息的唯一识别码
if !publicmethod.IsInTrue[string](v.Id, sendWechatUserKey) {
sendWechatUserKey = append(sendWechatUserKey, v.Id)
}
if v.Wechat != "" {
if !publicmethod.IsInTrue[string](v.Wechat, recipient) {
recipient = append(recipient, v.Wechat)
}
} else {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.Id}, "`wechat`", "`work_wechat`")
if userCont.Wechat != "" {
if !publicmethod.IsInTrue[string](userCont.Wechat, recipient) {
recipient = append(recipient, userCont.Wechat)
}
}
if userCont.WorkWechat != "" {
if !publicmethod.IsInTrue[string](userCont.WorkWechat, recipient) {
recipient = append(recipient, userCont.WorkWechat)
}
}
}
}
if len(recipient) <= 0 {
return
}
var workflowCont modelskpi.EvaluationProcess
err = workflowCont.GetCont(map[string]interface{}{"ep_order_key": orderId})
if err != nil {
return
}
//开始组装消息内容
var sendMsg workwechat.SentMiniMessage
sendMsg.ToUser = strings.Join(recipient, "|") //收件人配置
var templateCard workwechat.TemplateCardMsgContMini //模版卡片主体
//头部左标题部分
nodeType := publicmethod.GetSetpNodeName(nodeCont.Type)
templateCard.Source.Desc = fmt.Sprintf("%v-%v", nodeCont.NodeName, nodeType)
//任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成
uuid := publicmethod.GetUUid(7) //上报数据唯一识别码
templateCard.TaskId = fmt.Sprintf("kpi_ratify_%v", uuid)
if workflowCont.TypeClass == 1 { //定性操作
msgCont, errs := SendMsgDingXing(orderId)
if errs != nil {
return
}
templateCard.MainTitle.Title = msgCont.DimeContTitle
templateCard.MainTitle.Desc = msgCont.TargetContTitle
templateCard.QuoteArea.Title = msgCont.BylawsContTitle
templateCard.QuoteArea.QuoteText = msgCont.QuoteText
} else { //定量操作
msgCont, errs := SendMsgDingLiang(workflowCont)
if errs != nil {
return
}
templateCard.MainTitle.Title = msgCont.OccurrenceTime
templateCard.QuoteArea.QuoteText = msgCont.QuoteText
}
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
var userRecarCont modelshr.PersonArchives
userRecarCont.GetCont(map[string]interface{}{"`key`": workflowCont.Creater}, "`number`", "`name`", "`wechat`", "`work_wechat`", "`maindeparment`")
recipientWechat := userRecarCont.Wechat
if userRecarCont.WorkWechat != "" {
recipientWechat = userRecarCont.WorkWechat
}
var orgContInfo modelshr.AdministrativeOrganization
orgContInfo.GetCont(map[string]interface{}{"`id`": userRecarCont.MainDeparment}, "name")
var hcListCont1 workwechat.HorizontalContentListCont
hcListCont1.Type = 0
hcListCont1.Keyname = "提报部门:"
hcListCont1.Value = orgContInfo.Name
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont1)
var hcListCont3 workwechat.HorizontalContentListCont
hcListCont3.Keyname = "提报人:"
hcListCont3.Value = fmt.Sprintf("%v(%v)", userRecarCont.Name, userRecarCont.Number)
if recipientWechat != "" {
hcListCont3.Type = 3
hcListCont3.UserId = recipientWechat
} else {
hcListCont3.Type = 0
}
templateCard.HorizontalContentList = append(templateCard.HorizontalContentList, hcListCont3)
//审批详情访问地址
jumpUrl := fmt.Sprintf("%v/#/pages/approval/departworkflowcont?id=%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl, workflowCont.Id)
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
var jmpCont1 workwechat.JumpListCont
jmpCont1.Type = 1
jmpCont1.Title = "前往处理"
jmpCont1.Url = jumpUrl
templateCard.JumpList = append(templateCard.JumpList, jmpCont1)
//整体卡片的点击跳转事件,text_notice必填本字段
templateCard.CardAction.Url = jumpUrl
sendMsg.TemplateCard = templateCard
callbackMsg, err := sendMsg.InitMes().SendMessage()
callbackMsgStr = string(callbackMsg)
workwechat.WriteUpdateWechatTempmsg(callbackMsg, sendMsg, 1, orderId, sendWechatUserKey)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-23 15:09:41
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func SendMsgDingLiang(workflowCont modelskpi.EvaluationProcess) (msgCont CallBackSendMsgContLiang, err error) {
msgCont.OccurrenceTime = fmt.Sprintf("考核周期:%v", publicmethod.UnixTimeToDay(workflowCont.HappenTime, 15))
var flowLogCont modelskpi.FlowLog
err = flowLogCont.GetCont(map[string]interface{}{"fl_key": workflowCont.OrderKey}, "fl_baseline")
if err != nil {
return
}
var allZreoConfig []FlowLogAllZreo
json.Unmarshal([]byte(flowLogCont.Baseline), &allZreoConfig)
var flogDataList []modelskpi.FlowLogData
err = overall.CONSTANT_DB_KPI.Where("fld_flow_log = ?", workflowCont.OrderKey).Find(&flogDataList).Error
if err != nil || len(flogDataList) < 1 {
return
}
var yinYongWenXian []string
for _, v := range flogDataList {
var targetCont modelskpi.EvaluationTarget
targetCont.GetCont(map[string]interface{}{"`et_id`": v.TargetId}, "`et_id`", "`et_title`")
var lsZeroprize float64
var lsAllprize float64
var lsCapping float64
var targetWeight int64
for _, cv := range allZreoConfig {
tarStrId := strconv.FormatInt(v.TargetId, 10)
if cv.TargetId == tarStrId {
lsZeroprize = cv.Zeroprize
lsAllprize = cv.Allprize
lsCapping = cv.Capping
targetWeight = cv.TargetWeight
}
}
scoreVal, _, _, _, _ := publicmethod.CalculateScore(targetWeight, float64(v.Score), lsAllprize, lsZeroprize, lsCapping, 2)
if v.ScoringMethod == 1 {
yinYongWenXian = append(yinYongWenXian, fmt.Sprintf("指标:%v\n实际值:%v\n达成率:%v\n得分:%v", targetCont.Title, publicmethod.DecimalEs(float64(v.Score)/100, 2), v.Content, scoreVal))
} else {
yinYongWenXian = append(yinYongWenXian, fmt.Sprintf("指标:%v\n实际值:%v\n达成率:%v\n得分:%v\n手动分:%v\n原因:%v", targetCont.Title, publicmethod.DecimalEs(float64(v.Score)/100, 2), v.Content, scoreVal, publicmethod.DecimalEs(float64(v.ScoringScore)/100, 2), v.Content))
}
}
msgCont.QuoteText = strings.Join(yinYongWenXian, "\n")
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-23 15:07:43
@ 功能: 定性操作
@ 参数
#orderId 流程ID
@ 返回值
#msgCont 返回值
#err 错误信息
@ 方法原型
#func SendMsgDingXing(orderId int64) (msgCont CallBackSendMsgCont, err error)
*/
func SendMsgDingXing(orderId int64) (msgCont CallBackSendMsgCont, err error) {
var scoreFlowCont modelskpi.ScoreFlow
err = scoreFlowCont.GetCont(map[string]interface{}{"sf_key": orderId})
if err != nil {
//指标
var targetCont modelskpi.EvaluationTarget
targetCont.GetCont(map[string]interface{}{"`et_id`": scoreFlowCont.TargetId}, "`et_id`", "`et_title`")
msgCont.TargetContTitle = targetCont.Title
var dimeCont modelskpi.DutyClass
dimeCont.GetCont(map[string]interface{}{"`id`": targetCont.Id}, "`title`")
msgCont.DimeContTitle = dimeCont.Title
var bylawsCont modelskpi.DetailedTarget
bylawsCont.GetCont(map[string]interface{}{"`dt_id`": scoreFlowCont.DetailedId}, "`dt_title`")
msgCont.BylawsContTitle = bylawsCont.Title
//1:加分;2:减分"`
if scoreFlowCont.PlusReduceScore == 1 {
if scoreFlowCont.Reason != "" {
msgCont.QuoteText = fmt.Sprintf("奖励: %v 分\n原因:%v\n发生时间:%v", publicmethod.DecimalEs(float64(scoreFlowCont.Score)/100, 2), scoreFlowCont.Reason, publicmethod.UnixTimeToDay(scoreFlowCont.HappenTime, 12))
} else {
msgCont.QuoteText = fmt.Sprintf("奖励: %v 分\n发生时间:%v", publicmethod.DecimalEs(float64(scoreFlowCont.Score)/100, 2), publicmethod.UnixTimeToDay(scoreFlowCont.HappenTime, 12))
}
} else {
if scoreFlowCont.Reason != "" {
msgCont.QuoteText = fmt.Sprintf("扣除: %v 分\n原因:%v\n发生时间:%v", publicmethod.DecimalEs(float64(scoreFlowCont.Score)/100, 2), scoreFlowCont.Reason, publicmethod.UnixTimeToDay(scoreFlowCont.HappenTime, 12))
} else {
msgCont.QuoteText = fmt.Sprintf("扣除: %v 分\n发生时间:%v", publicmethod.DecimalEs(float64(scoreFlowCont.Score)/100, 2), publicmethod.UnixTimeToDay(scoreFlowCont.HappenTime, 12))
}
}
}
return
}
//

16
api/version1/jurisdiction/jurisdictionpc/appsystem.go

@ -4,6 +4,7 @@ import (
"key_performance_indicators/models/modelssystempermission"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/gin-gonic/gin"
@ -85,7 +86,20 @@ func (a *ApiMethod) SystemList(c *gin.Context) {
publicmethod.Result(107, err, c)
return
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(systemAry)), systemAry, c)
var snedList []SendSystemList
for _, v := range systemAry {
var sendCont SendSystemList
sendCont.Id = v.Id //
sendCont.Title = v.Title //系统名称"`
sendCont.Coder = v.Coder //识别符"`
sendCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
sendCont.Time = v.Time //创建时间"`
sendCont.Sort = v.Sort //排序"`
sendCont.ApiUrl = v.ApiUrl //菜单访问权限列表"`
sendCont.Key = strconv.FormatInt(v.Id, 10)
snedList = append(snedList, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(snedList)), snedList, c)
}
// 获取单一系统详情

102
api/version1/jurisdiction/jurisdictionpc/people.go

@ -0,0 +1,102 @@
package jurisdictionpc
import (
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-03-21 11:06:07
@ 功能: 搜索人员
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SearchPeople(c *gin.Context) {
var receivedValue FlowGetRoleList
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 20
}
var listCont []modelshr.PersonArchives
gormDb := overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Where("`emp_type` BETWEEN ? AND ?", 1, 10)
if receivedValue.Name != "" {
gormDb = gormDb.Where("`name` LIKE ? OR `number` LIKE ?", "%"+receivedValue.Name+"%", "%"+receivedValue.Name+"%")
}
var total int64
gormDbTotal := gormDb
totalErr := gormDbTotal.Count(&total).Error
if totalErr != nil {
total = 0
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err = gormDb.Find(&listCont).Error
if err != nil {
publicmethod.Result(107, err, c)
return
}
var sendContList []EmployeesCont
for _, v := range listCont {
var sendCont EmployeesCont
sendCont.Id = strconv.FormatInt(v.Key, 10) //`json:"id"`
sendCont.EmployeeName = v.Name //`json:"employeeName"` //人员名称
sendCont.IsLeave = "0" //`json:"isLeave"` //行政组织名称
sendCont.Open = "false" //`json:"open"` //上级ID
sendCont.Icon = v.Icon //`json:"icon"` //头像
sendCont.IconToBase64 = v.IconPhoto //`json:"iconToBase64"` //头像
sendCont.Wechat = v.Wechat //微信Openid
if v.WorkWechat != "" {
sendCont.Wechat = v.WorkWechat //微信Openid
}
_, companyId, _, _, _ := publicmethod.GetOrgStructurees(v.AdminOrg)
if companyId != 0 {
var orgCont modelshr.AdministrativeOrganization
orgCont.GetCont(map[string]interface{}{"`id`": companyId}, "`name`")
sendCont.Departmentid = companyId //分厂Id
sendCont.DepartmentName = orgCont.Name //分厂名称
}
//获取岗位
if v.Position != 0 {
var postCont modelshr.Position
postCont.GetCont(map[string]interface{}{"`id`": v.Position}, "`name`")
sendCont.Postid = v.Position //职务Id
sendCont.PostName = postCont.Name //职务名称
}
if v.TeamId != 0 {
var teamCont modelshr.TeamGroup
teamCont.GetCont(map[string]interface{}{"`id`": v.TeamId}, "`name`")
sendCont.Tema = v.TeamId //班组Id
sendCont.TemaName = teamCont.Name //班组名称
}
sendContList = append(sendContList, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendContList)), sendContList, c)
}

233
api/version1/jurisdiction/jurisdictionpc/postpower.go

@ -0,0 +1,233 @@
package jurisdictionpc
import (
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelssystempermission"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-05-29 13:06:32
@ 功能: 给指定岗位授权
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GrantPostSystemPowers(c *gin.Context) {
var receivedValue editPowerStructNew
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.OrdId == "" || receivedValue.OrdId == "0" {
publicmethod.Result(1, receivedValue, c, "未知行政组织!不可进行配权")
return
}
if receivedValue.PostId == "" || receivedValue.PostId == "0" {
publicmethod.Result(1, receivedValue, c, "未知岗位!不可进行配权")
return
}
if receivedValue.SystemName == "" {
publicmethod.Result(1, receivedValue, c, "未知配权系统!不可进行配权")
return
}
if receivedValue.Level == 0 {
receivedValue.Level = 2
}
var orgIdList []int64
switch receivedValue.Level {
case 2: //本部门
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
_, _, departmentId, _, _ := publicmethod.GetOrgStructure(orgIdInt)
// orgIdList = publicmethod.GetDepartmentSun(departmentId, orgIdList)
var getSunOrg publicmethod.GetOrgAllSun
getSunOrg.GetOrgSun(departmentId)
orgIdList = getSunOrg.Id
orgIdList = append(orgIdList, departmentId)
case 3: //本分部
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
_, companyId, _, _, _ := publicmethod.GetOrgStructure(orgIdInt)
// orgIdList = publicmethod.GetDepartmentSun(companyId, orgIdList)
var getSunOrg publicmethod.GetOrgAllSun
getSunOrg.GetOrgSun(companyId)
orgIdList = getSunOrg.Id
orgIdList = append(orgIdList, companyId)
case 4: //指定行政组织
case 5: //所有
overall.CONSTANT_DB_HR.Model(&modelshr.AdministrativeOrganization{}).Select("`id`").Where("`state` = 1").Find(&orgIdList)
default: //本岗位
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
orgIdList = append(orgIdList, orgIdInt)
}
var orgIdListAry []string //行政组织
for _, v := range orgIdList {
orgIdListAry = append(orgIdListAry, strconv.FormatInt(v, 10))
}
orgIdListStr := strings.Join(orgIdListAry, ",")
addTime := time.Now().Unix()
var empowerCont modelssystempermission.Empower
err = empowerCont.GetCont(map[string]interface{}{"`ordid`": receivedValue.OrdId, "`post_id`": receivedValue.PostId, "`system`": receivedValue.SystemName}, "`id`")
if len(receivedValue.PowerList) > 0 {
var menuList []string //权限点位
var menuOperationList []string //操作点位
for _, v := range receivedValue.PowerList {
switch receivedValue.SystemName {
case "kpi":
if v.Attribute != 4 {
menuList = append(menuList, v.Key)
}
if v.Attribute == 4 {
menuOperationList = append(menuOperationList, v.Key)
}
case "cangchu":
menuList = append(menuList, v.Key)
default:
menuList = append(menuList, v.Key)
}
}
menuListStr := strings.Join(menuList, ",")
menuOperationListStr := strings.Join(menuOperationList, ",")
fmt.Printf("操作点位-------->%v-------->%v\n", menuOperationListStr, menuOperationList)
if err != nil {
ordIdInt64, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
empowerCont.OrdId = ordIdInt64 //行政组织"`
postIdInt64, _ := strconv.ParseInt(receivedValue.PostId, 10, 64)
empowerCont.PostId = postIdInt64 //岗位ID"`
empowerCont.System = receivedValue.SystemName //系统"`
empowerCont.PointId = menuListStr //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = time.Now().Unix() //创建时间"`
empowerCont.Level = receivedValue.Level
empowerCont.Operation = menuOperationListStr
empowerCont.Organization = orgIdListStr
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
} else {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": menuListStr, "`operation`": menuOperationListStr, "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1, "`organization`": orgIdListStr})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
} else {
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": "", "`operation`": "", "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1, "`organization`": orgIdListStr})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
}
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-30 14:59:12
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GrantRoleSystemPowers(c *gin.Context) {
var receivedValue editRolePowerStructNew
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.RoleId == "" || receivedValue.RoleId == "0" {
publicmethod.Result(1, receivedValue, c, "未知角色!不可进行配权")
return
}
if receivedValue.SystemName == "" {
publicmethod.Result(1, receivedValue, c, "未知配权系统!不可进行配权")
return
}
if receivedValue.Level == 0 {
receivedValue.Level = 2
}
addTime := time.Now().Unix()
var empowerCont modelssystempermission.RoleEmpower
err = empowerCont.GetCont(map[string]interface{}{"`role_id`": receivedValue.RoleId, "`system`": receivedValue.SystemName}, "`id`")
if len(receivedValue.PowerList) < 1 {
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": "", "`operation`": "", "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
} else {
var menuList []string //权限点位
var menuOperationList []string //操作点位
for _, v := range receivedValue.PowerList {
switch receivedValue.SystemName {
case "kpi":
if v.Attribute != 4 {
menuList = append(menuList, v.Key)
}
if v.Attribute == 4 {
menuOperationList = append(menuOperationList, v.Key)
}
case "cangchu":
menuList = append(menuList, v.Key)
default:
menuList = append(menuList, v.Key)
}
}
menuListStr := strings.Join(menuList, ",")
menuOperationListStr := strings.Join(menuOperationList, ",")
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": menuListStr, "`operation`": menuOperationListStr, "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
} else {
roleIdInt, _ := strconv.ParseInt(receivedValue.RoleId, 10, 64)
empowerCont.RoleId = roleIdInt //行政组织"`
empowerCont.System = receivedValue.SystemName //系统"`
empowerCont.PointId = menuListStr //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = addTime //创建时间"`
empowerCont.Level = receivedValue.Level //授权范围等级(1:本部门;2:本分部;3:所有)"`
empowerCont.Operation = menuOperationListStr //操作点位
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
}
publicmethod.Result(0, err, c)
}

874
api/version1/jurisdiction/jurisdictionpc/power.go

@ -1,7 +1,12 @@
package jurisdictionpc
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelAppPlatform"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelsschool"
"key_performance_indicators/models/modelsstorage"
"key_performance_indicators/models/modelssystempermission"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
@ -36,12 +41,40 @@ func (a *ApiMethod) EditPower(c *gin.Context) {
publicmethod.Result(1, err, c, "请至少指定一项权限!")
return
}
switch receivedValue.Level {
case 2: //本分部
if len(receivedValue.Organization) < 1 {
receivedValue.Organization = append(receivedValue.Organization, receivedValue.OrdId)
ordIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
_, companyId, _, _, _ := publicmethod.GetOrgStructure(ordIdInt)
var sonOrgId []int64
sonOrgId = publicmethod.GetDepartmentSun(companyId, sonOrgId)
if len(sonOrgId) > 0 {
for oi := 0; oi < len(sonOrgId); oi++ {
sonOrgIdStr := strconv.FormatInt(sonOrgId[oi], 10)
if publicmethod.IsInTrue[string](sonOrgIdStr, receivedValue.Organization) == false {
receivedValue.Organization = append(receivedValue.Organization, sonOrgIdStr)
}
}
}
}
case 3:
var orgAry []string
receivedValue.Organization = orgAry
default:
receivedValue.Level = 1
if len(receivedValue.Organization) < 1 {
var orgAry []string
orgAry = append(orgAry, receivedValue.OrdId)
receivedValue.Organization = orgAry
}
}
var empowerCont modelssystempermission.Empower
err = empowerCont.GetCont(map[string]interface{}{"`ordid`": receivedValue.OrdId, "`post_id`": receivedValue.PostId, "`system`": receivedValue.SystemName}, "`id`")
postIdStr := strings.Join(receivedValue.PointId, ",")
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`state`": 1, "`point_id`": postIdStr, "`time`": time.Now().Unix()})
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`state`": 1, "`point_id`": postIdStr, "`time`": time.Now().Unix(), "`level`": receivedValue.Level, "`organization`": strings.Join(receivedValue.Organization, ",")})
} else {
ordIdInt64, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
empowerCont.OrdId = ordIdInt64 //行政组织"`
@ -51,6 +84,8 @@ func (a *ApiMethod) EditPower(c *gin.Context) {
empowerCont.PointId = postIdStr //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = time.Now().Unix() //创建时间"`
empowerCont.Level = receivedValue.Level
empowerCont.Organization = strings.Join(receivedValue.Organization, ",")
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
}
if err != nil {
@ -93,7 +128,7 @@ func (a *ApiMethod) EditPower(c *gin.Context) {
// 相关系统菜单
func (a *ApiMethod) SystemAboutMenu(c *gin.Context) {
var receivedValue publicmethod.PublicName
var receivedValue GetSystemMenuPower
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
@ -104,7 +139,7 @@ func (a *ApiMethod) SystemAboutMenu(c *gin.Context) {
return
}
var systemPower modelssystempermission.Appsystem
err = systemPower.GetCont(map[string]interface{}{"`system`": receivedValue.Name})
err = systemPower.GetCont(map[string]interface{}{"`coder`": receivedValue.Name})
if err != nil {
publicmethod.Result(105, err, c)
return
@ -117,26 +152,847 @@ func (a *ApiMethod) SystemAboutMenu(c *gin.Context) {
publicmethod.Result(1, err, c, "该系统授权已经取消合作!")
return
}
var menuThree []powerThree
var menuThree []publicmethod.PowerThree
// fmt.Printf("ApiUrl------>%v\n", receivedValue)
if systemPower.ApiUrl != "" {
//api入口不为空的情况下采用get访问方式接收数据
htmlByte := publicmethod.CurlGet(systemPower.ApiUrl)
fmt.Printf("%v\n", string(htmlByte))
var jsonAry callBackUrlMenu
jsonErr := json.Unmarshal(htmlByte, &jsonAry)
if jsonErr != nil {
publicmethod.Result(1, jsonErr, c, "数据获取错误!")
return
}
if jsonAry.Code != 0 {
publicmethod.Result(1, jsonErr, c, jsonAry.Msg)
return
}
menuThree = jsonAry.Data
} else {
var pointInt []string
var operatIon []string
var systemEmpowerCont modelssystempermission.Empower
err = systemEmpowerCont.GetCont(map[string]interface{}{"`ordid`": receivedValue.OrdId, "`post_id`": receivedValue.PostId, "`system`": systemPower.Coder}, "`point_id`", `operation`)
if err == nil {
pointInt = strings.Split(systemEmpowerCont.PointId, ",")
operatIon = strings.Split(systemEmpowerCont.Operation, ",")
}
//api入口为空,采用系统内置获取授权菜单
switch systemPower.Coder {
case "cangchu":
menuThree = wmsMenuThree(pointInt, operatIon)
// fmt.Printf("ApiUrl----2-->%v\n", systemPower.ApiUrl)
default:
//获取绩效考核菜单树
menuThree = kpiMenuThree()
menuThree = kpiMenuThree(pointInt, operatIon)
// fmt.Printf("ApiUrl---1--->%v\n", systemPower.ApiUrl)
}
}
publicmethod.Result(0, menuThree, c)
}
// kpi菜单树
func kpiMenuThree() (menuThree []powerThree) {
var menuList []modelsschool.SystemMenu
err := overall.CONSTANT_DB_Master.Where("`m_steat` = 1").Find(&menuList).Error
/*
*
@ 作者: 秦东
@ 时间: 2022-11-06 16:02:56
@ 功能: kpi菜单树
@ 参数
#purview 以获得的权限
#operatIon 操作点位
@ 返回值
#
*/
func kpiMenuThree(purview, operatIon []string) (menuThree []publicmethod.PowerThree) {
var menuList []modelsschool.SystemMenuSchool
err := overall.CONSTANT_DB_Master.Where("`m_steat` = 1").Order("`m_sort` ASC").Order("`m_id` DESC").Find(&menuList).Error
lenSum := len(menuList)
// fmt.Printf("ApiUrl---3--->%v--->%v\n", err, lenSum)
if err != nil || lenSum < 1 {
return
}
var menuSmaillList []publicmethod.MenuContList
for i := 0; i < lenSum; i++ {
var menSmaiCont publicmethod.MenuContList
idStr := strconv.FormatInt(menuList[i].Id, 10)
menSmaiCont.Id = idStr
menSmaiCont.Name = menuList[i].Title
menSmaiCont.ParentId = strconv.FormatInt(menuList[i].ParentId, 10)
menSmaiCont.PathUrl = menuList[i].ApiUrl
menSmaiCont.Key = idStr
if len(purview) > 0 {
if publicmethod.IsInTrue[string](idStr, purview) == true {
menSmaiCont.IsTrue = true
// fmt.Printf("\n\npurview------>%v------>%v------>%v\n\n", idStr, purview, publicmethod.IsInTrue[string](idStr, purview))
}
}
menSmaiCont.Attribute = 1
menuSmaillList = append(menuSmaillList, menSmaiCont)
}
menuThree = publicmethod.GetMenuThreePeiQuan(1, "0", menuSmaillList, operatIon)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-06 16:02:56
@ 功能: 仓储菜单树
@ 参数
#purview 以获得的权限
#operatIon 操作点位
@ 返回值
#
*/
func wmsMenuThree(purview, operatIon []string) (menuThree []publicmethod.PowerThree) {
var menuList []modelsstorage.AccesstoAddress
err := overall.CONSTANT_DB_Storage.Where("`state` = 1").Find(&menuList).Error
lenSum := len(menuList)
if err != nil || lenSum < 1 {
return
}
var menuSmaillList []publicmethod.MenuContList
for i := 0; i < lenSum; i++ {
var menSmaiCont publicmethod.MenuContList
idStr := strconv.FormatInt(menuList[i].Id, 10)
menSmaiCont.Id = idStr
menSmaiCont.Name = menuList[i].Name
menSmaiCont.ParentId = strconv.FormatInt(int64(menuList[i].Menuparent), 10)
menSmaiCont.PathUrl = menuList[i].Url
// fmt.Printf("ApiUrl---1--->%v--->%v--->%v\n", idStr, purview, publicmethod.IsInTrue[string](idStr, purview))
if len(purview) > 0 {
if publicmethod.IsInTrue[string](idStr, purview) == true {
menSmaiCont.IsTrue = true
}
}
menSmaiCont.Key = idStr
menSmaiCont.Attribute = 1
menSmaiCont.MenuKey = fmt.Sprintf("m_%v", menuList[i].Id)
menuSmaillList = append(menuSmaillList, menSmaiCont)
}
menuThree = publicmethod.GetMenuThrees(1, "0", menuSmaillList)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-07 13:46:06
@ 功能: 编辑权限新版
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) EditPowerNew(c *gin.Context) {
var receivedValue editPowerStructNew
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.OrdId == "" || receivedValue.OrdId == "0" {
publicmethod.Result(1, receivedValue, c, "未知行政组织!不可进行配权")
return
}
if receivedValue.PostId == "" || receivedValue.PostId == "0" {
publicmethod.Result(1, receivedValue, c, "未知岗位!不可进行配权")
return
}
if receivedValue.SystemName == "" {
publicmethod.Result(1, receivedValue, c, "未知配权系统!不可进行配权")
return
}
if receivedValue.Level == 0 {
receivedValue.Level = 2
}
var orgIdList []int64
switch receivedValue.Level {
case 2: //本部门
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
_, _, departmentId, _, _ := publicmethod.GetOrgStructure(orgIdInt)
orgIdList = publicmethod.GetDepartmentSun(departmentId, orgIdList)
case 3: //本分部
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
_, companyId, _, _, _ := publicmethod.GetOrgStructure(orgIdInt)
orgIdList = publicmethod.GetDepartmentSun(companyId, orgIdList)
case 4: //指定行政组织
case 5: //所有
overall.CONSTANT_DB_HR.Model(&modelshr.AdministrativeOrganization{}).Select("`id`").Where("`state` = 1").Find(&orgIdList)
default: //本岗位
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
orgIdList = append(orgIdList, orgIdInt)
}
var orgIdListStr string //行政组织
if len(orgIdList) > 0 {
var orgIdListStrAry []string //
for _, ovl := range orgIdList {
idStr := strconv.FormatInt(ovl, 10)
if publicmethod.IsInTrue[string](idStr, orgIdListStrAry) == false {
orgIdListStrAry = append(orgIdListStrAry, idStr)
}
}
orgIdListStr = strings.Join(orgIdListStrAry, ",")
}
var menuList []string //权限点位
var menuOperationList []string //操作点位
addTime := time.Now().Unix()
var empowerCont modelssystempermission.Empower
err = empowerCont.GetCont(map[string]interface{}{"`ordid`": receivedValue.OrdId, "`post_id`": receivedValue.PostId, "`system`": receivedValue.SystemName}, "`id`")
if len(receivedValue.PowerList) < 1 {
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": "", "`operation`": "", "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1, "`organization`": orgIdListStr})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
} else {
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
empowerCont.OrdId = orgIdInt //行政组织"`
postIdInt, _ := strconv.ParseInt(receivedValue.PostId, 10, 64)
empowerCont.PostId = postIdInt //岗位ID"`
empowerCont.System = receivedValue.SystemName //系统"`
empowerCont.PointId = strings.Join(menuList, ",") //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = addTime //创建时间"`
empowerCont.Level = receivedValue.Level //授权范围等级(1:本部门;2:本分部;3:所有)"`
empowerCont.Organization = orgIdListStr //行政组织"`
empowerCont.Operation = strings.Join(menuOperationList, ",") //操作点位
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
} else {
var munePowerList empowerSync
for _, v := range receivedValue.PowerList {
// if v.Id == "1" {
syncSeting.Add(1)
go munePowerList.GetAllSunCont(v)
// }
}
syncSeting.Wait()
menuIdList, menuOperIdList := munePowerList.readDataLock()
// fmt.Printf("\n\n%v-------结果-------->%v\n", menuIdList, menuOperIdList)
// publicmethod.Result(0, receivedValue.PowerList, c)
// return
// outData := publicmethod.MapOut[string]()
// outData["menuIdList"] = menuIdList
// outData["menuOperIdList"] = menuOperIdList
// publicmethod.Result(0, outData, c)
menuIdListStr := strings.Join(menuIdList, ",")
menuOperIdListStr := strings.Join(menuOperIdList, ",")
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": menuIdListStr, "`operation`": menuOperIdListStr, "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1, "`organization`": orgIdListStr})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
} else {
orgIdInt, _ := strconv.ParseInt(receivedValue.OrdId, 10, 64)
empowerCont.OrdId = orgIdInt //行政组织"`
postIdInt, _ := strconv.ParseInt(receivedValue.PostId, 10, 64)
empowerCont.PostId = postIdInt //岗位ID"`
empowerCont.System = receivedValue.SystemName //系统"`
empowerCont.PointId = menuIdListStr //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = addTime //创建时间"`
empowerCont.Level = receivedValue.Level //授权范围等级(1:本部门;2:本分部;3:所有)"`
empowerCont.Organization = orgIdListStr //行政组织"`
empowerCont.Operation = menuOperIdListStr //操作点位
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
}
publicmethod.Result(0, receivedValue, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-07 15:34:48
@ 功能: 获取菜单所有操作
@ 参数
#
@ 返回值
#
*/
func (e *empowerSync) GetAllSunCont(menuList publicmethod.PowerThree) {
e.mutext.Lock()
defer e.mutext.Unlock()
if menuList.IsTrue == true {
if publicmethod.IsInTrue[string](menuList.Id, e.menuList) == false {
e.menuList = append(e.menuList, menuList.Id)
}
}
if len(menuList.MenuOperation) > 0 {
for _, v := range menuList.MenuOperation {
if v.IsTrue == true {
if publicmethod.IsInTrue[string](v.Id, e.menuOperationList) == false {
e.menuOperationList = append(e.menuOperationList, v.Id)
}
}
}
}
if len(menuList.Child) > 0 {
var menuId []string
var menuOperId []string
menuIdList, menuOperIdList := DiGuiMenuList(menuList.Child, menuId, menuOperId)
// // fmt.Printf("\n\nmenuIdList------%v----->%v\n\n", menuList.Id, menuList.Child)
// fmt.Printf("\n\nmenuOperIdList----%v------->%v------->%v\n\n", menuList.Id, menuIdList, menuOperIdList)
if len(menuIdList) > 0 {
for _, mv := range menuIdList {
if publicmethod.IsInTrue[string](mv, e.menuList) == false {
e.menuList = append(e.menuList, mv)
}
}
}
if len(menuOperIdList) > 0 {
for _, mvo := range menuOperIdList {
// fmt.Printf("menuOper--Fuji->%v---->%v\n", menuList.Id, mvo)
// e.menuOperationList = append(e.menuOperationList, mvo)
if publicmethod.IsInTrue[string](mvo, e.menuOperationList) == false {
e.menuOperationList = append(e.menuOperationList, mvo)
}
}
}
}
syncSeting.Done()
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-07 16:15:58
@ 功能: 递归菜单选择操作
@ 参数
#
@ 返回值
#
*/
func DiGuiMenuList(menuList []publicmethod.PowerThree, menuId, menuOperId []string) (menuIdList, menuOperIdList []string) {
// fmt.Printf("\n\nmenuIdList----222222--%v----->%v----->%v\n\n", menuId, menuOperId, menuList)
for _, v := range menuList {
// fmt.Printf("\n\nmenuIdList----33333--%v----->%v----->%v\n\n", menuId, menuOperId, v.IsTrue)
if v.IsTrue == true {
fmt.Printf("\n\nmenuIdList----444--%v----->%v----->%v\n\n", menuId, menuOperId, v.Id)
menuIdList = append(menuIdList, v.Id)
for _, menuCont := range menuId {
if publicmethod.IsInTrue[string](menuCont, menuIdList) == false {
menuIdList = append(menuIdList, menuCont)
}
}
}
if len(v.MenuOperation) > 0 {
for _, vm := range v.MenuOperation {
if vm.IsTrue == true {
menuOperIdList = append(menuOperIdList, vm.Id)
for _, menuContOper := range menuOperId {
if publicmethod.IsInTrue[string](menuContOper, menuOperIdList) == false {
menuOperIdList = append(menuOperIdList, menuContOper)
}
}
}
}
}
if len(v.Child) > 0 {
// fmt.Printf("menuOper--zijian->%v---->%v\n", v.Id, v.Id)
menuIdList, menuOperIdList = DiGuiMenuList(v.Child, menuIdList, menuOperIdList)
}
}
// fmt.Printf("menuOper--jieshuzhi->%v---->%v\n", menuIdList, menuOperIdList)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-09 13:28:39
@ 功能: 角色配权菜单
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) SystemRoleAboutMenu(c *gin.Context) {
var receivedValue GetSystemRoleMenuPower
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(101, err, c)
return
}
var systemPower modelssystempermission.Appsystem
err = systemPower.GetCont(map[string]interface{}{"`coder`": receivedValue.Name})
if err != nil {
publicmethod.Result(105, err, c)
return
}
if systemPower.State == 2 {
publicmethod.Result(1, err, c, "该系统授权已经禁用!")
return
}
if systemPower.State == 3 {
publicmethod.Result(1, err, c, "该系统授权已经取消合作!")
return
}
var menuThree []publicmethod.PowerThree
// fmt.Printf("ApiUrl------>%v\n", receivedValue)
if systemPower.ApiUrl != "" {
//api入口不为空的情况下采用get访问方式接收数据
htmlByte := publicmethod.CurlGet(systemPower.ApiUrl)
fmt.Printf("%v\n", string(htmlByte))
var jsonAry callBackUrlMenu
jsonErr := json.Unmarshal(htmlByte, &jsonAry)
if jsonErr != nil {
publicmethod.Result(1, jsonErr, c, "数据获取错误!")
return
}
if jsonAry.Code != 0 {
publicmethod.Result(1, jsonErr, c, jsonAry.Msg)
return
}
menuThree = jsonAry.Data
} else {
var pointInt []string
var operatIon []string
var systemEmpowerCont modelssystempermission.RoleEmpower
err = systemEmpowerCont.GetCont(map[string]interface{}{"`role_id`": receivedValue.RoleId, "`system`": systemPower.Coder}, "`point_id`", `operation`)
if err == nil {
pointInt = strings.Split(systemEmpowerCont.PointId, ",")
operatIon = strings.Split(systemEmpowerCont.Operation, ",")
}
//api入口为空,采用系统内置获取授权菜单
switch systemPower.Coder {
case "cangchu":
menuThree = wmsMenuThree(pointInt, operatIon)
// fmt.Printf("ApiUrl----2-->%v\n", systemPower.ApiUrl)
default:
//获取绩效考核菜单树
menuThree = kpiMenuThree(pointInt, operatIon)
// fmt.Printf("ApiUrl---1--->%v\n", systemPower.ApiUrl)
}
}
publicmethod.Result(0, menuThree, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-07 13:46:06
@ 功能: 编辑权限新版(角色)
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) EditRolePowerNew(c *gin.Context) {
var receivedValue editRolePowerStructNew
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.RoleId == "" || receivedValue.RoleId == "0" {
publicmethod.Result(1, receivedValue, c, "未知角色!不可进行配权")
return
}
if receivedValue.SystemName == "" {
publicmethod.Result(1, receivedValue, c, "未知配权系统!不可进行配权")
return
}
if receivedValue.Level == 0 {
receivedValue.Level = 2
}
var menuList []string //权限点位
var menuOperationList []string //操作点位
addTime := time.Now().Unix()
var empowerCont modelssystempermission.RoleEmpower
err = empowerCont.GetCont(map[string]interface{}{"`role_id`": receivedValue.RoleId, "`system`": receivedValue.SystemName}, "`id`")
if len(receivedValue.PowerList) < 1 {
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": "", "`operation`": "", "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
} else {
roleIdInt, _ := strconv.ParseInt(receivedValue.RoleId, 10, 64)
empowerCont.RoleId = roleIdInt //行政组织"`
empowerCont.System = receivedValue.SystemName //系统"`
empowerCont.PointId = strings.Join(menuList, ",") //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = addTime //创建时间"`
empowerCont.Level = receivedValue.Level //授权范围等级(1:本部门;2:本分部;3:所有)"`
empowerCont.Operation = strings.Join(menuOperationList, ",") //操作点位
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
} else {
var munePowerList empowerSync
for _, v := range receivedValue.PowerList {
// if v.Id == "1" {
syncSeting.Add(1)
go munePowerList.GetAllSunCont(v)
// }
}
syncSeting.Wait()
menuIdList, menuOperIdList := munePowerList.readDataLock()
// fmt.Printf("\n\n%v-------结果-------->%v\n", menuIdList, menuOperIdList)
// publicmethod.Result(0, receivedValue.PowerList, c)
// return
// outData := publicmethod.MapOut[string]()
// outData["menuIdList"] = menuIdList
// outData["menuOperIdList"] = menuOperIdList
// publicmethod.Result(0, outData, c)
menuIdListStr := strings.Join(menuIdList, ",")
menuOperIdListStr := strings.Join(menuOperIdList, ",")
if err == nil {
err = empowerCont.EiteCont(map[string]interface{}{"`id`": empowerCont.Id}, map[string]interface{}{"`point_id`": menuIdListStr, "`operation`": menuOperIdListStr, "`level`": receivedValue.Level, "`time`": addTime, "`state`": 1})
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
} else {
roleIdInt, _ := strconv.ParseInt(receivedValue.RoleId, 10, 64)
empowerCont.RoleId = roleIdInt //行政组织"`
empowerCont.System = receivedValue.SystemName //系统"`
empowerCont.PointId = menuIdListStr //权限点位"`
empowerCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
empowerCont.Time = addTime //创建时间"`
empowerCont.Level = receivedValue.Level //授权范围等级(1:本部门;2:本分部;3:所有)"`
empowerCont.Operation = menuOperIdListStr //操作点位
err = overall.CONSTANT_DB_System_Permission.Create(&empowerCont).Error
if err != nil {
publicmethod.Result(1, err, c, "权限配置失败")
return
}
}
}
publicmethod.Result(0, receivedValue, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-27 08:19:37
@ 功能: 系统权限菜单
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SystemAboutPowerMenu(c *gin.Context) {
var receivedValue GetSystemMenuPower
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(101, err, c)
return
}
var systemPower modelssystempermission.Appsystem
err = systemPower.GetCont(map[string]interface{}{"`coder`": receivedValue.Name})
if err != nil {
publicmethod.Result(105, err, c)
return
}
if systemPower.State == 2 {
publicmethod.Result(1, err, c, "该系统授权已经禁用!")
return
}
if systemPower.State == 3 {
publicmethod.Result(1, err, c, "该系统授权已经取消合作!")
return
}
var menuThree []publicmethod.PowerThree
// fmt.Printf("ApiUrl------>%v\n", receivedValue)
if systemPower.ApiUrl != "" {
//api入口不为空的情况下采用get访问方式接收数据
htmlByte := publicmethod.CurlGet(systemPower.ApiUrl)
// fmt.Printf("%v\n", string(htmlByte))
var jsonAry callBackUrlMenu
jsonErr := json.Unmarshal(htmlByte, &jsonAry)
if jsonErr != nil {
publicmethod.Result(1, jsonErr, c, "数据获取错误!")
return
}
if jsonAry.Code != 0 {
publicmethod.Result(1, jsonErr, c, jsonAry.Msg)
return
}
menuThree = jsonAry.Data
} else {
var pointInt []string
var operatIon []string
var systemEmpowerCont modelssystempermission.Empower
err = systemEmpowerCont.GetCont(map[string]interface{}{"`ordid`": receivedValue.OrdId, "`post_id`": receivedValue.PostId, "`system`": systemPower.Coder}, "`point_id`", `operation`)
if err == nil {
pointInt = strings.Split(systemEmpowerCont.PointId, ",")
operatIon = strings.Split(systemEmpowerCont.Operation, ",")
}
//api入口为空,采用系统内置获取授权菜单
switch systemPower.Coder {
case "cangchu":
menuThree = wmsMenuThree(pointInt, operatIon)
// fmt.Printf("ApiUrl----2-->%v\n", systemPower.ApiUrl)
case "kpi":
//获取绩效考核菜单树
menuThree = kpiPostMenuThree(pointInt, operatIon)
default:
menuThree = appSystemMenuThree(pointInt)
// fmt.Printf("ApiUrl---1--->%v\n", systemPower.ApiUrl)
}
}
publicmethod.Result(0, menuThree, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-27 08:27:24
@ 功能: 新KPI授权树
@ 参数
#purview 菜单权限
#operatIon 附属权限
@ 返回值
#
@ 方法原型
#
*/
func kpiPostMenuThree(purview, operatIon []string) (menuThree []publicmethod.PowerThree) {
var menuList []modelsschool.SystemMenuSchool
err := overall.CONSTANT_DB_Master.Where("`m_steat` = 1").Order("`m_sort` ASC").Order("`m_sort` ASC").Order("`m_id` DESC").Find(&menuList).Error
lenSum := len(menuList)
if err != nil || lenSum < 1 {
return
}
var menusOperaList []publicmethod.MenuContList
for _, mv := range menuList {
idStr := strconv.FormatInt(mv.Id, 10)
var menuMenuCtion publicmethod.MenuContList
menuMenuCtion.Id = idStr
menuMenuCtion.Name = mv.Title
menuMenuCtion.ParentId = strconv.FormatInt(mv.ParentId, 10)
menuMenuCtion.PathUrl = mv.ApiUrl
if publicmethod.IsInTrue[string](idStr, purview) == true {
menuMenuCtion.IsTrue = true
}
menuMenuCtion.Key = idStr
menuMenuCtion.MenuKey = fmt.Sprintf("m_%v", mv.Id)
menuMenuCtion.Attribute = 1
menusOperaList = append(menusOperaList, menuMenuCtion)
}
var operList []modelsschool.MenuOperation
overall.CONSTANT_DB_Master.Order("menu_id asc").Find(&operList)
if len(operList) > 0 {
for _, v := range operList {
idStr := strconv.FormatInt(v.OperId, 10)
var menuOperaCtion publicmethod.MenuContList
menuOperaCtion.Id = idStr
menuOperaCtion.Name = v.OperTitle
menuOperaCtion.ParentId = strconv.FormatInt(v.MenuId, 10)
menuOperaCtion.PathUrl = ""
if publicmethod.IsInTrue[string](idStr, operatIon) == true {
menuOperaCtion.IsTrue = true
}
menuOperaCtion.Key = idStr
menuOperaCtion.MenuKey = fmt.Sprintf("o_%v_%v", v.MenuId, v.OperId)
menuOperaCtion.Attribute = 4
menusOperaList = append(menusOperaList, menuOperaCtion)
}
}
menuThree = publicmethod.KpiMenuOperaTree("0", menusOperaList)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-27 10:30:36
@ 功能: 应用平台菜单
@ 参数
#purview 菜单权限
#operatIon 附属权限
@ 返回值
#
@ 方法原型
#
*/
func appSystemMenuThree(purview []string) (menuThree []publicmethod.PowerThree) {
var menusList []modelAppPlatform.Menus
err := overall.CONSTANT_DB_AppPlatform.Where("visible IN ?", []int{1, 2}).Find(&menusList).Error
if err != nil && len(menusList) < 1 {
return
}
var menusOperaList []publicmethod.MenuContList
for _, v := range menusList {
keyStr := strconv.FormatInt(v.Perm, 10)
idStr := strconv.Itoa(v.Id)
var menuOperaCtion publicmethod.MenuContList
menuOperaCtion.Id = idStr
menuOperaCtion.Key = keyStr
menuOperaCtion.Name = v.Name
menuOperaCtion.ParentId = strconv.Itoa(v.ParentId)
menuOperaCtion.PathUrl = ""
if publicmethod.IsInTrue[string](idStr, purview) == true {
menuOperaCtion.IsTrue = true
}
menuOperaCtion.MenuKey = fmt.Sprintf("m_%v", v.Perm)
menuOperaCtion.Attribute = v.Types
menusOperaList = append(menusOperaList, menuOperaCtion)
}
menuThree = publicmethod.KpiMenuOperaTree("0", menusOperaList)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-30 14:32:09
@ 功能:系统权限菜单(角色)
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SystemAboutPowerMenuRole(c *gin.Context) {
var receivedValue GetSystemRoleMenuPower
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(101, err, c)
return
}
var systemPower modelssystempermission.Appsystem
err = systemPower.GetCont(map[string]interface{}{"`coder`": receivedValue.Name})
if err != nil {
publicmethod.Result(105, err, c)
return
}
if systemPower.State == 2 {
publicmethod.Result(1, err, c, "该系统授权已经禁用!")
return
}
if systemPower.State == 3 {
publicmethod.Result(1, err, c, "该系统授权已经取消合作!")
return
}
var menuThree []publicmethod.PowerThree
if systemPower.ApiUrl != "" {
//api入口不为空的情况下采用get访问方式接收数据
htmlByte := publicmethod.CurlGet(systemPower.ApiUrl)
// fmt.Printf("%v\n", string(htmlByte))
var jsonAry callBackUrlMenu
jsonErr := json.Unmarshal(htmlByte, &jsonAry)
if jsonErr != nil {
publicmethod.Result(1, jsonErr, c, "数据获取错误!")
return
}
if jsonAry.Code != 0 {
publicmethod.Result(1, jsonErr, c, jsonAry.Msg)
return
}
menuThree = jsonAry.Data
} else {
var pointInt []string
var operatIon []string
var systemEmpowerCont modelssystempermission.RoleEmpower
err = systemEmpowerCont.GetCont(map[string]interface{}{"`role_id`": receivedValue.RoleId, "`system`": systemPower.Coder}, "`point_id`", `operation`)
if err == nil {
pointInt = strings.Split(systemEmpowerCont.PointId, ",")
operatIon = strings.Split(systemEmpowerCont.Operation, ",")
}
//api入口为空,采用系统内置获取授权菜单
switch systemPower.Coder {
case "cangchu":
menuThree = wmsMenuThree(pointInt, operatIon)
// fmt.Printf("ApiUrl----2-->%v\n", systemPower.ApiUrl)
case "kpi":
//获取绩效考核菜单树
menuThree = kpiPostMenuThree(pointInt, operatIon)
default:
menuThree = appSystemMenuThree(pointInt)
// fmt.Printf("ApiUrl---1--->%v\n", systemPower.ApiUrl)
}
}
publicmethod.Result(0, menuThree, c)
}

665
api/version1/jurisdiction/jurisdictionpc/systemrole.go

@ -0,0 +1,665 @@
package jurisdictionpc
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelssystempermission"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
//系统角色处理
func (a *ApiMethod) AddSystemRole(c *gin.Context) {
var receivedValue systemRole
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Sort == 0 {
receivedValue.Sort = 50
}
var systemRoleCont modelssystempermission.SystemRole
err = systemRoleCont.GetCont(map[string]interface{}{"`name`": receivedValue.Name}, "`id`")
if err == nil {
publicmethod.Result(103, systemRoleCont, c)
return
}
systemRoleCont.Name = receivedValue.Name
systemRoleCont.Sort = receivedValue.Sort
systemRoleCont.State = 1
systemRoleCont.Time = time.Now().Unix()
err = overall.CONSTANT_DB_System_Permission.Create(&systemRoleCont).Error
if err != nil {
publicmethod.Result(104, err, c)
return
}
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-09 08:30:04
@ 功能: 系统角色编辑
@ 参数
#Id 项目ID
#Name 角色名称
#Sort 角色排序
@ 返回值
#
*/
func (a *ApiMethod) EditSystemRole(c *gin.Context) {
var receivedValue editSystemRoleCont
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Sort == 0 {
receivedValue.Sort = 50
}
var systemRoleCont modelssystempermission.SystemRole
err = systemRoleCont.GetCont(map[string]interface{}{"`id`": receivedValue.Id}, "`name`")
if err != nil {
publicmethod.Result(107, err, c)
return
}
editCont := publicmethod.MapOut[string]()
if receivedValue.Sort != systemRoleCont.Sort {
editCont["`sort`"] = receivedValue.Sort
}
if systemRoleCont.Name != receivedValue.Name {
err = systemRoleCont.GetCont(map[string]interface{}{"`name`": receivedValue.Name}, "`id`")
if err == nil {
publicmethod.Result(103, systemRoleCont, c)
return
}
editCont["`name`"] = receivedValue.Name
}
if len(editCont) > 0 {
editCont["`time`"] = time.Now().Unix()
editCont["`state`"] = 1
err = systemRoleCont.EiteCont(map[string]interface{}{"`id`": receivedValue.Id}, editCont)
if err != nil {
publicmethod.Result(106, err, c)
return
}
}
publicmethod.Result(0, systemRoleCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-09 08:41:20
@ 功能: 角色列表
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) SystemRoleList(c *gin.Context) {
var receivedValue systemRoleContList
c.ShouldBindJSON(&receivedValue)
var systemRoleInfoList []modelssystempermission.SystemRole
gormDb := overall.CONSTANT_DB_System_Permission.Model(&modelssystempermission.SystemRole{}).Where("`state` BETWEEN ? AND ?", 1, 2)
if receivedValue.Name != "" {
gormDb = gormDb.Where("`name` LIKE ?", "%"+receivedValue.Name+"%")
}
err := gormDb.Order("`sort` ASC").Order("`id` DESC").Find(&systemRoleInfoList).Error
if err != nil {
publicmethod.Result(107, err, c)
return
}
var sendList []sendSystemRoleList
for _, v := range systemRoleInfoList {
var sendCont sendSystemRoleList
sendCont.Id = v.Id
sendCont.Name = v.Name //角色名称"`
sendCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
sendCont.Time = v.Time //创建时间"`
sendCont.Sort = v.Sort //排序"`
if v.State == 1 {
sendCont.IsTrue = true
} else {
sendCont.IsTrue = false
}
sendList = append(sendList, sendCont)
}
publicmethod.Result(0, sendList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-09 08:52:56
@ 功能: 编辑角色状态
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) EditSystemRoleState(c *gin.Context) {
var receivedValue publicmethod.PublicState
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.State == 0 {
receivedValue.State = 2
}
wheAry := publicmethod.MapOut[string]()
wheAry["`id`"] = receivedValue.Id
var systemRoleCont modelssystempermission.SystemRole
err = systemRoleCont.GetCont(wheAry, "`state`")
if err != nil {
publicmethod.Result(107, err, c)
return
}
if receivedValue.State != 3 {
editCont := publicmethod.MapOut[string]()
if receivedValue.State != systemRoleCont.State {
editCont["`state`"] = receivedValue.State
}
if len(editCont) > 0 {
editCont["`time`"] = time.Now().Unix()
err = systemRoleCont.EiteCont(wheAry, editCont)
}
} else {
if receivedValue.IsTrue != 1 {
editCont := publicmethod.MapOut[string]()
if receivedValue.State != systemRoleCont.State {
editCont["`state`"] = receivedValue.State
}
if len(editCont) > 0 {
editCont["`time`"] = time.Now().Unix()
err = systemRoleCont.EiteCont(wheAry, editCont)
}
} else {
err = systemRoleCont.DelCont(wheAry)
}
}
if err != nil {
publicmethod.Result(106, err, c)
return
}
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-05-30 11:20:46
@ 功能: 批量编辑系统角色状态
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EditSystemRoleStateBatch(c *gin.Context) {
var receivedValue BatchRoleStatus
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if len(receivedValue.Id) < 1 {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.State == 0 {
receivedValue.State = 2
}
if receivedValue.IsTrue == 0 {
receivedValue.IsTrue = 2
}
if receivedValue.State != 3 {
editCont := publicmethod.MapOut[string]()
editCont["`state`"] = receivedValue.State
editCont["`time`"] = time.Now().Unix()
err = overall.CONSTANT_DB_System_Permission.Model(&modelssystempermission.SystemRole{}).Where("id IN ?", receivedValue.Id).Updates(editCont).Error
} else {
if receivedValue.IsTrue != 1 {
editCont := publicmethod.MapOut[string]()
editCont["`state`"] = receivedValue.State
editCont["`time`"] = time.Now().Unix()
err = overall.CONSTANT_DB_System_Permission.Model(&modelssystempermission.SystemRole{}).Where("id IN ?", receivedValue.Id).Updates(editCont).Error
} else {
err = overall.CONSTANT_DB_System_Permission.Where("id IN ?", receivedValue.Id).Delete(&modelssystempermission.SystemRole{}).Error
if err == nil {
ClearOutUserRole(receivedValue.Id)
}
}
}
if err != nil {
publicmethod.Result(106, err, c)
return
}
publicmethod.Result(0, err, c)
}
// 清楚人员中已删除得角色信息
func ClearOutUserRole(roleId []string) {
if len(roleId) < 1 {
return
}
var manList []modelshr.PersonArchives
err := overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Select("`id`,`role`").Where("`role` != '' AND `role` is not null").Find(&manList).Error
if err != nil {
return
}
for _, v := range manList {
roleUserList := strings.Split(v.Role, ",")
if len(roleUserList) > 0 {
newRole := publicmethod.DelMergeStruct[string](roleUserList, roleId)
var editUSer modelshr.PersonArchives
editUSer.EiteCont(map[string]interface{}{"`id`": v.Id}, map[string]interface{}{"`role`": strings.Join(newRole, ","), "`eite_time`": time.Now().Unix()})
}
}
fmt.Printf("manList-->%v\n", len(manList))
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-16 08:02:47
@ 功能: 角色相关人员
@ 参数
#id 角色ID
#name 姓名或工号
@ 返回值
#
*/
func (a *ApiMethod) RoleAboutPeopleList(c *gin.Context) {
var receivedValue SystemRoleAboutPeopleList
c.ShouldBindJSON(&receivedValue)
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 20
}
if receivedValue.Id == "" {
publicmethod.Result(1, nil, c, "未知角色")
return
}
gormDb := overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Select("`id`,`number`,`name`,`icon`,`company`,`maindeparment`,`admin_org`,`position`,`job_id`,`key`,`wechat`,`work_wechat`,`icon_photo`").Where("`state` = 1 AND FIND_IN_SET(?,`role`)", receivedValue.Id)
if receivedValue.Name != "" {
gormDb = gormDb.Where("`name` LIKE ? OR `number` LIKE ?", "%"+receivedValue.Name+"%", "%"+receivedValue.Name+"%")
}
var total int64
totalErr := gormDb.Count(&total).Error
if totalErr != nil {
total = 0
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
var RoleManList []modelshr.PersonArchives
err := gormDb.Find(&RoleManList).Error
if err != nil {
publicmethod.Result(1, err, c, "当前角色没有使用人")
return
}
if len(RoleManList) < 1 {
publicmethod.Result(1, RoleManList, c, "当前角色没有使用人")
return
}
var sendData []SendSystemRoleAboutPeopleList
for _, v := range RoleManList {
var sendDataInfo SendSystemRoleAboutPeopleList
sendDataInfo.Id = strconv.FormatInt(v.Id, 10)
sendDataInfo.Number = v.Number
sendDataInfo.Name = v.Name
sendDataInfo.Company = strconv.FormatInt(v.Company, 10)
var comInfo modelshr.AdministrativeOrganization
comInfo.GetCont(map[string]interface{}{"`id`": v.Company}, "`name`")
sendDataInfo.CompanyName = comInfo.Name
sendDataInfo.Department = strconv.FormatInt(v.MainDeparment, 10)
var deparInfo modelshr.AdministrativeOrganization
deparInfo.GetCont(map[string]interface{}{"`id`": v.MainDeparment}, "`name`")
sendDataInfo.DepartmentName = deparInfo.Name
sendDataInfo.OrgId = strconv.FormatInt(v.AdminOrg, 10)
var orderInfo modelshr.AdministrativeOrganization
orderInfo.GetCont(map[string]interface{}{"`id`": v.AdminOrg}, "`name`")
sendDataInfo.OrgName = orderInfo.Name
sendDataInfo.DutiesId = strconv.FormatInt(v.Position, 10)
var postCont modelshr.Position
postCont.GetCont(map[string]interface{}{"`id`": v.Position}, "`name`")
sendDataInfo.DutiesName = postCont.Name
sendDataInfo.Wechat = v.Wechat
if v.WorkWechat != "" {
sendDataInfo.Wechat = v.WorkWechat
}
sendDataInfo.Key = strconv.FormatInt(v.Key, 10)
if v.MainDeparment != v.AdminOrg {
sendDataInfo.DepartMentTitle = fmt.Sprintf("%v/%v/%v", comInfo.Name, deparInfo.Name, orderInfo.Name)
} else {
sendDataInfo.DepartMentTitle = fmt.Sprintf("%v/%v", comInfo.Name, deparInfo.Name)
}
sendDataInfo.Icon = v.Icon
sendDataInfo.IconBase64 = v.IconPhoto
sendData = append(sendData, sendDataInfo)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendData)), sendData, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-16 11:53:58
@ 功能: 批量删除角色关联人员
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) BatchDeletToRoleAboutMan(c *gin.Context) {
var receivedValue BatchDeletAllRoleMan
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if len(receivedValue.ManKey) < 1 {
publicmethod.Result(101, receivedValue, c)
return
}
var manList []modelshr.PersonArchives
err = overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Select("`id`,`role`").Where("`key` IN ?", receivedValue.ManKey).Find(&manList).Error
if err != nil {
publicmethod.Result(107, err, c)
return
}
if len(manList) < 1 {
publicmethod.Result(107, manList, c)
return
}
for _, v := range manList {
syncSeting.Add(1)
go EditManRoleCont(receivedValue.Id, v)
}
syncSeting.Wait()
publicmethod.Result(0, nil, c)
}
// 编辑批量删除角色人员信息处理
func EditManRoleCont(roleId string, manCont modelshr.PersonArchives) {
defer syncSeting.Done()
roleList := strings.Split(manCont.Role, ",")
if publicmethod.IsInTrue[string](roleId, roleList) == true {
var editRoleList []string
for i := 0; i < len(roleList); i++ {
if roleList[i] != roleId {
editRoleList = append(editRoleList, roleList[i])
}
}
saveData := publicmethod.MapOut[string]()
if len(editRoleList) > 0 {
saveData["`role`"] = strings.Join(editRoleList, ",")
} else {
saveData["`role`"] = ""
}
saveData["`eite_time`"] = time.Now().Unix()
manCont.EiteCont(map[string]interface{}{"`id`": manCont.Id}, saveData)
}
}
/*
*
@ 作者: 秦东
@ 时间: 2022-11-19 08:30:26
@ 功能: 添加角色使用人员
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) AddRoleUser(c *gin.Context) {
var receivedValue ReceiveRoleAndPeople
c.ShouldBindJSON(&receivedValue)
if receivedValue.RoleId == "" {
publicmethod.Result(1, nil, c, "未知角色1")
return
}
if len(receivedValue.PeopleList) < 1 {
publicmethod.Result(1, nil, c, "请选择关联人员2")
return
}
var roleCont modelssystempermission.SystemRole
err := roleCont.GetCont(map[string]interface{}{"`id`": receivedValue.RoleId}, "`id`")
if err != nil {
publicmethod.Result(1, nil, c, "角色不存在")
return
}
var peopleId []string
for _, v := range receivedValue.PeopleList {
if v.IsMan == 2 && publicmethod.IsInTrue[string](v.Id, peopleId) == false {
peopleId = append(peopleId, v.Id)
}
}
if len(peopleId) < 1 {
publicmethod.Result(0, receivedValue.PeopleList, c, "数据处理完成!3")
return
}
var manList []modelshr.PersonArchives
err = overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Select("`key`,`role`").Where("`key` IN ?", peopleId).Find(&manList).Error
if err != nil || len(manList) < 1 {
publicmethod.Result(107, nil, c, "数据处理失败!4")
return
}
for _, m := range manList {
saveData := publicmethod.MapOut[string]()
if m.Role == "" {
saveData["`role`"] = receivedValue.RoleId
} else {
oldRoleList := strings.Split(m.Role, ",")
if publicmethod.IsInTrue[string](receivedValue.RoleId, oldRoleList) == false {
oldRoleList = append(oldRoleList, receivedValue.RoleId)
saveData["`role`"] = strings.Join(oldRoleList, ",")
}
}
if len(saveData) > 0 {
saveData["`eite_time`"] = time.Now().Unix()
var saveCont modelshr.PersonArchives
saveCont.EiteCont(map[string]interface{}{"`key`": m.Key}, saveData)
}
}
publicmethod.Result(0, nil, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-21 10:48:54
@ 功能: 系统角色列表(工作流专版)
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SystemRoleListFlow(c *gin.Context) {
var receivedValue FlowGetRoleList
c.ShouldBindJSON(&receivedValue)
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 20
}
var systemRoleInfoList []modelssystempermission.SystemRole
gormDb := overall.CONSTANT_DB_System_Permission.Model(&modelssystempermission.SystemRole{}).Where("`state` = ?", 1)
if receivedValue.Name != "" {
gormDb = gormDb.Where("`name` LIKE ?", "%"+receivedValue.Name+"%")
}
var total int64
gormDbTotal := gormDb
totalErr := gormDbTotal.Count(&total).Error
if totalErr != nil {
total = 0
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("`sort` ASC").Order("`id` DESC").Find(&systemRoleInfoList).Error
if err != nil {
publicmethod.Result(107, err, c)
return
}
var sendContList []OutPutRoleList
for _, v := range systemRoleInfoList {
var sendCont OutPutRoleList
sendCont.Code = strconv.FormatInt(v.Id, 10) //`json:"code"` //编号
sendCont.RoleId = strconv.FormatInt(v.Id, 10) //`json:"roleId"` //角色ID
sendCont.Scope = strconv.Itoa(v.Sort) //`json:"scope"` //范围
sendCont.RoleName = v.Name //`json:"roleName"` //角色名称
sendCont.Description = v.Name //`json:"description"` //描述
sendCont.Status = strconv.Itoa(v.State) //`json:"status"` //状态
sendContList = append(sendContList, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendContList)), sendContList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-28 14:05:00
@ 功能: 获取统一岗位
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetPositionUnify(c *gin.Context) {
var uniflList []modelshr.PositionUnify
err := overall.CONSTANT_DB_HR.Where("`state` = ?", 1).Find(&uniflList).Error
if err != nil {
publicmethod.Result(105, err, c)
return
}
var sendData []OutPutUnify
for _, v := range uniflList {
var sendCont OutPutUnify
sendCont.Id = v.Id
sendCont.Name = v.Name //职位名称"`
sendCont.Time = v.Time //创建时间"`
sendCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
sendCont.Content = v.Content //关联具体岗位ID"`
json.Unmarshal([]byte(v.Content), &sendCont.PositionListId)
sendData = append(sendData, sendCont)
}
publicmethod.Result(0, sendData, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-28 14:07:58
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SearchPositionUnify(c *gin.Context) {
var receivedValue publicmethod.PublicName
c.ShouldBindJSON(&receivedValue)
var uniflList []modelshr.PositionUnify
gormDb := overall.CONSTANT_DB_HR.Where("`state` = ?", 1)
if receivedValue.Name != "" {
gormDb = gormDb.Where("`name` LIKE ?", "%"+receivedValue.Name+"%")
}
err := gormDb.Find(&uniflList).Error
if err != nil {
publicmethod.Result(105, err, c)
return
}
var sendData []OutPutUnify
for _, v := range uniflList {
var sendCont OutPutUnify
sendCont.Id = v.Id
sendCont.Name = v.Name //职位名称"`
sendCont.Time = v.Time //创建时间"`
sendCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
sendCont.Content = v.Content //关联具体岗位ID"`
json.Unmarshal([]byte(v.Content), &sendCont.PositionListId)
sendData = append(sendData, sendCont)
}
publicmethod.Result(0, sendData, c)
}

193
api/version1/jurisdiction/jurisdictionpc/type.go

@ -1,13 +1,33 @@
package jurisdictionpc
import (
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelssystempermission"
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
type ApiMethod struct{}
// 协程设置
var syncSeting = sync.WaitGroup{}
// 授权协程操作
type empowerSync struct {
menuList []string
menuOperationList []string
mutext sync.RWMutex
}
// 读取岗位指标协程数据
func (d *empowerSync) readDataLock() ([]string, []string) {
d.mutext.RLock()
defer d.mutext.RUnlock()
return d.menuList, d.menuOperationList
}
// 权限配置
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
@ -17,10 +37,12 @@ func (a *ApiMethod) Index(c *gin.Context) {
// 添加权限参数
type appPowerStruct struct {
OrdId string `json:"ordid"` //岗位
PostId string `json:"postid"` //岗位
SystemName string `json:"systemname"` //系统识别符
PointId []string `json:"pointid"` //权限点位
OrdId string `json:"ordid"` //行政组织
PostId string `json:"postid"` //岗位
SystemName string `json:"systemname"` //系统识别符
PointId []string `json:"pointid"` //权限点位
Level int `json:"level"` //授权范围等级(1:本部门;2:本分部;3:所有)
Organization []string `json:"organization"` //行政组织ID
}
// 添加应用系统
@ -46,10 +68,171 @@ type editSystemCont struct {
addsystemapp
}
// 菜单列表
type menuContList struct {
publicmethod.PublicId
publicmethod.PublicName
ParentId string `json:"parentid"`
}
// 权限菜单树
type powerThree struct {
menuContList
Child []powerThree `json:"child"`
}
// 权限菜单树URL返回解析
type callBackUrlMenu struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data []publicmethod.PowerThree `json:"data"`
}
// 获取系统菜单权限
type GetSystemMenuPower struct {
publicmethod.PublicName //系统标识符
OrdId string `json:"ordid"` //行政组织
PostId string `json:"postid"` //岗位
}
type GetSystemRoleMenuPower struct {
publicmethod.PublicName //系统标识符
RoleId string `json:"roleid"` //行政组织
}
// 添加权限参数
type editPowerStructNew struct {
OrdId string `json:"ordid"` //行政组织
PostId string `json:"postid"` //岗位
SystemName string `json:"systemname"` //系统识别符
Level int `json:"level"` //授权范围等级(1:本岗位;2:本部门;3:本分部;4:指定行政组织;5:所有)
PowerList []publicmethod.PowerThree `json:"power"` //权限列表
}
// 系统角色通用
type systemRole struct {
publicmethod.PublicName
publicmethod.PublicSort
}
// 编辑系统角色
type editSystemRoleCont struct {
publicmethod.PublicId
systemRole
}
// 系统角色列表
type systemRoleContList struct {
publicmethod.PublicName
}
Child []powerThree `json:"child"`
// 输出列表
type sendSystemRoleList struct {
modelssystempermission.SystemRole
IsTrue bool `json:"istrue"`
}
// 编辑角色权限参数
type editRolePowerStructNew struct {
RoleId string `json:"roleid"` //行政组织
SystemName string `json:"systemname"` //系统识别符
Level int `json:"level"` //授权范围等级(1:本岗位;2:本部门;3:本分部;4:指定行政组织;5:所有)
PowerList []publicmethod.PowerThree `json:"power"` //权限列表
}
// 角色相关使用人列表
type SystemRoleAboutPeopleList struct {
publicmethod.PagesTurn
publicmethod.PublicId
publicmethod.PublicName
}
// 角色相关使用人列表输出
type SendSystemRoleAboutPeopleList struct {
publicmethod.PostPeople
Key string `json:"key"` //员工Key
DepartMentTitle string `json:"departmenttitle"` //部门
}
// 批量删除角色相关人员
type BatchDeletAllRoleMan struct {
publicmethod.PublicId //角色ID
ManKey []string `json:"mankey"` //要处理的人
}
// 接收要角色要添加的人员信息
type ReceiveRoleAndPeople struct {
RoleId string `json:"roleid"` //角色ID
PeopleList []OrgAndPeopleSmail `json:"peoplelist"` //人员列表
}
type OrgAndPeopleSmail struct {
Id string `json:"id"` //行政组织Id或人员Key
IsMan int `json:"isman"` //是部门还是个人(1:行政组织;2:人员)
}
// 接收行政组织加人员主体
type OrgAndPeople struct {
Id string `json:"id"` //行政组织Id或人员Key
Name string `json:"name"` //行政组织名称或人员名称
Number string `json:"number"` //行政组织编号或人员编号
Icon string `json:"icon"` //行政组织头像或人员头像
ParentId string `json:"parentId"` //上级
OrgId string `json:"orgId"` //所属行政组织
IsMan int `json:"isman"` //是部门还是个人(1:行政组织;2:人员)
Sort int `json:"sort"` //排序
Identify int `json:"identify"` //身份识别
AllName string `json:"all_name"` //全部名
// Child []OrgAndPeople `json:"child"` //子栏目
}
// 工作流获取角色列表
type FlowGetRoleList struct {
publicmethod.PublicName
publicmethod.PagesTurn
}
// 审批节点选人人员节点
type EmployeesCont struct {
Id string `json:"id"`
EmployeeName string `json:"employeeName"` //人员名称
IsLeave string `json:"isLeave"` //行政组织名称
Open string `json:"open"` //上级ID
Icon string `json:"icon"` //头像
IconToBase64 string `json:"iconToBase64"` //头像
Wechat string `json:"wechat"` //微信或企业微信
Departmentid int64 `json:"departmentid"` //部门ID
DepartmentName string `json:"departmentname"` //部门名称
Postid int64 `json:"postid"` //岗位ID
PostName string `json:"postname"` //岗位名称
Tema int64 `json:"tema"` //班组Id
TemaName string `json:"temaname"` //班组名称
}
// 工作流审批角色输出
type OutPutRoleList struct {
Code string `json:"code"` //编号
RoleId string `json:"roleId"` //角色ID
Scope string `json:"scope"` //范围
RoleName string `json:"roleName"` //角色名称
Description string `json:"description"` //描述
Status string `json:"status"` //状态
}
// 输出统一岗位
type OutPutUnify struct {
modelshr.PositionUnify
PositionListId []int64 `json:"positionListId` //关联岗位ID
}
// 输出系统列表
type SendSystemList struct {
modelssystempermission.Appsystem
Key string `json:"key"` //
}
// 批量编辑角色状态
type BatchRoleStatus struct {
Id []string `json:"id"` //
State int `json:"state"`
IsTrue int `json:"istrue"` //1:强制删除;非1:软删除
}

17
api/version1/newsclass/type.go

@ -0,0 +1,17 @@
package newsclass
import (
"key_performance_indicators/overall/publicmethod"
"github.com/gin-gonic/gin"
)
// 新闻类数据处理
type ApiMethod struct{}
// 系统内部审批处理
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "新闻类数据处理入口"
publicmethod.Result(0, outputCont, c)
}

1516
api/version1/postseting/postpc/details.go

File diff suppressed because it is too large

229
api/version1/postseting/postpc/scheme.go

@ -26,7 +26,7 @@ func (a *ApiMethod) GetSchemeList(c *gin.Context) {
receivedValue.PageSize = 20
}
var schemeList []modelskpi.PositionPlanVersio
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.PositionPlanVersio{}).Where("`state` BETWEEN ? AND ?", 1, 2)
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.PositionPlanVersio{})
if receivedValue.VersionNumber != "" {
gormDb = gormDb.Where("`key` LIKE ?", "%"+receivedValue.VersionNumber+"%")
}
@ -40,10 +40,10 @@ func (a *ApiMethod) GetSchemeList(c *gin.Context) {
if receivedValue.OrgId != "" {
gormDb = gormDb.Where("`orgid` = ?", receivedValue.OrgId)
}
if receivedValue.PostId != "" {
gormDb = gormDb.Where("`position` = ?", receivedValue.PostId)
if len(receivedValue.PostId) > 0 {
gormDb = gormDb.Where("`position` IN ?", receivedValue.PostId)
}
if receivedValue.Year != 0 {
if receivedValue.Year != "" {
gormDb = gormDb.Where("`years` = ?", receivedValue.Year)
}
if receivedValue.State != 0 {
@ -52,7 +52,7 @@ func (a *ApiMethod) GetSchemeList(c *gin.Context) {
gormDb = gormDb.Where("`state` BETWEEN ? AND ?", 1, 2)
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("`state` ASC").Order("`version` ASC").Order("`id` DESC").Find(&schemeList).Error
err := gormDb.Order("`orgid` ASC").Order("`position` ASC").Order("`state` ASC").Order("`years` ASC").Order("`version` ASC").Order("`id` DESC").Find(&schemeList).Error
var total int64
totalErr := gormDb.Count(&total).Error
if totalErr != nil {
@ -88,9 +88,9 @@ func (a *ApiMethod) GetSchemeList(c *gin.Context) {
comCont.GetCont(map[string]interface{}{"`id`": schemeList[i].OrgId}, "`name`")
sendDataCont.OrgName = comCont.Name //归属行政组织"`
var postContInfo modelshr.Position
postContInfo.GetCont(map[string]interface{}{"`id`": schemeList[i].Group}, "`name`")
postContInfo.GetCont(map[string]interface{}{"`id`": schemeList[i].Position}, "`name`")
sendDataCont.PostName = postContInfo.Name //`归属岗位"`
sendDataCont.TimeStr = publicmethod.UnixTimeToDay(schemeList[i].AddTime, 1)
sendData = append(sendData, sendDataCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendData)), sendData, c)
@ -98,12 +98,16 @@ func (a *ApiMethod) GetSchemeList(c *gin.Context) {
// 获取岗位相关指标
func (a *ApiMethod) GetPostAboutTarget(c *gin.Context) {
var receivedValue publicmethod.PublicId
var receivedValue targetFormPost
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, err, c)
return
}
//获取岗位相关信息
var postCont modelshr.Position
postContErr := postCont.GetCont(map[string]interface{}{"`id`": receivedValue.Id}, "`id`", "`duties`", "`administrative_organization`", "`superior`", "`department`")
@ -124,7 +128,7 @@ func (a *ApiMethod) GetPostAboutTarget(c *gin.Context) {
var postPlanSync postDimeTarSync
for _, v := range dimensionList {
syncSeting.Add(1)
go postPlanSync.GetPostTargent(postCont, v)
go postPlanSync.GetPostTargent(postCont, receivedValue.State, v)
}
syncSeting.Wait()
planAry := postPlanSync.readDataLock() //读取线程通道数据
@ -143,13 +147,22 @@ func (a *ApiMethod) GetPostAboutTarget(c *gin.Context) {
/*
@position 岗位信息
@dutyClass 维度信息
@classType 0全部1定性2定量
*/
func (p *postDimeTarSync) GetPostTargent(position modelshr.Position, dutyClass modelskpi.DutyClass) {
func (p *postDimeTarSync) GetPostTargent(position modelshr.Position, classType int, dutyClass modelskpi.DutyClass) {
p.mutext.Lock()
defer p.mutext.Unlock()
//获取相关指标
var postTargetList []modelskpi.PostTarget
postTarErr := overall.CONSTANT_DB_KPI.Model(&modelskpi.PostTarget{}).Where("`state` = 1 AND `dimension` = ? AND `rele_depart` = ? AND FIND_IN_SET(?,`departments_post`)", dutyClass.Id, position.AdministrativeOrganization, position.Id).Find(&postTargetList).Error
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.PostTarget{}).Where("`state` = 1 AND `dimension` = ? AND `rele_depart` = ? AND FIND_IN_SET(?,`departments_post`)", dutyClass.Id, position.AdministrativeOrganization, position.Id)
jsonposition, _ := json.Marshal(position)
fmt.Printf("获取相关指标%v--------------->%v--------------->%v\n", string(jsonposition), classType, dutyClass)
if classType != 0 {
gormDb = gormDb.Where("`type` = ?", classType)
}
postTarErr := gormDb.Find(&postTargetList).Error
// fmt.Printf("postTargetList---->%v\n", postTargetList)
if postTarErr == nil && len(postTargetList) > 0 {
var planCont postAboutDimeTar
@ -164,7 +177,8 @@ func (p *postDimeTarSync) GetPostTargent(position modelshr.Position, dutyClass m
targetCont.StandardScore = getPostDimeTarWeight(position.AdministrativeOrganization, position.Id, dutyClass.Id, v.Id, 2, 1) //标准分
targetCont.Unit = v.Unit //单位
targetCont.IsTrue = 2 //是否允许修改 1:不允许;2:允许
targetCont.State = 1 //状态 1:启用;2:禁用;3:观察
targetCont.Type = v.Type
targetCont.State = 1 //状态 1:启用;2:禁用;3:观察
planCont.Child = append(planCont.Child, targetCont)
}
@ -183,7 +197,7 @@ func (p *postDimeTarSync) GetPostTargent(position modelshr.Position, dutyClass m
@isQuote 1不是引用2引用部门
getPostDimeTarWeight(orgid, postid, dimensionid, targetid int64, hierarchy, isQuote int)
*/
func getPostDimeTarWeight(orgid, postid, dimensionid, targetid int64, hierarchy, isQuote int) int64 {
func getPostDimeTarWeight(orgid, postid, dimensionid, targetid int64, hierarchy, isQuote int) float64 {
if hierarchy == 0 {
hierarchy = 2
}
@ -462,7 +476,10 @@ func postSchemeTargetPost(versionNumber string, source, judgeState int, scheme [
var xizeXiecheng postShemeListCont
for _, v := range scheme { //解析维度
dimensionIdInt64, _ := strconv.ParseInt(v.Id, 10, 64) //转换维度ID
if len(v.Child) > 0 { //判断是否有指标
syncSetingRun.Add(1)
go xieChengWeight(0, orgid, postid, dimensionIdInt64, 0, 1, 1, v.Score) //添加维度分值记录
if len(v.Child) > 0 { //判断是否有指标
for _, cv := range v.Child { //解析指标
targetIdInt64, _ := strconv.ParseInt(cv.Id, 10, 64) //转换指标ID
var saveData modelskpi.QualitativeEvaluationScheme //方案内容结构体
@ -473,6 +490,9 @@ func postSchemeTargetPost(versionNumber string, source, judgeState int, scheme [
if departPostTargetInfo.ScoringMethod != 0 {
scoringMethod = departPostTargetInfo.ScoringMethod
}
syncSetingRun.Add(1)
go xieChengWeight(int64(cv.Type), orgid, postid, dimensionIdInt64, targetIdInt64, 2, 1, cv.Score)
if cv.Type != 1 { //定量考核
//判断该指标是否存在
whereLian := publicmethod.MapOut[string]()
@ -524,9 +544,11 @@ func postSchemeTargetPost(versionNumber string, source, judgeState int, scheme [
//获取该指标的岗位指标子栏目
var postSonTarget []modelskpi.PostSonTarget
overall.CONSTANT_DB_KPI.Model(&modelskpi.PostSonTarget{}).Select("`id`,`parent_id`").Where("`state` = 1 AND `depart` = ? AND `depart_post` = ? AND `parent_id` = ?", orgid, postid, targetIdInt64).Find(&postSonTarget)
fmt.Printf("postSonTarget--------->%v\n", postSonTarget)
if len(postSonTarget) > 0 {
for _, son_v := range postSonTarget {
fmt.Printf("son_v--------->%v\n", son_v)
syncSetinges.Add(1)
go xizeXiecheng.eidtPostSchemeInfo(versionNumber, companyId, departmentId, orgid, postid, dimensionIdInt64, son_v.ParentId, son_v.Id, cv.State, scoringMethod, judgeState)
}
@ -536,6 +558,7 @@ func postSchemeTargetPost(versionNumber string, source, judgeState int, scheme [
}
}
syncSetinges.Wait()
syncSetingRun.Wait()
writeData := xizeXiecheng.readDataLock()
if len(writeData) > 0 {
for _, wdv := range writeData {
@ -568,6 +591,7 @@ func (p *postShemeListCont) eidtPostSchemeInfo(versionNumber string, companyId,
//获取相关指标细则内容
var postTargetDetailsCont []modelskpi.PostTargetDetails
overall.CONSTANT_DB_KPI.Where("`state` = 1 AND `parentid` = ? AND `parentid_sun` = ? AND `paretment` = ? AND `paretment_post` = ?", targetId, sonTargetId, orgid, postid).Find(&postTargetDetailsCont)
fmt.Printf("postTargetDetailsCont--------->%v\n", postTargetDetailsCont)
if len(postTargetDetailsCont) > 0 {
for _, v := range postTargetDetailsCont {
var saveData modelskpi.QualitativeEvaluationScheme //方案内容结构体
@ -595,7 +619,10 @@ func (p *postShemeListCont) eidtPostSchemeInfo(versionNumber string, companyId,
eidtTargetCont["`punishmode`"] = v.Punishmode
eidtTargetCont["`maxmoney`"] = v.Maxmoney
eidtTargetCont["`minmoney`"] = v.Minmoney
eidtTargetCont["`add_reduce`"] = v.AddReduce
saveData.EiteCont(map[string]interface{}{"`id`": saveData.Id}, eidtTargetCont)
fmt.Printf("judgeLianErr--------->%v\n", saveData)
} else { //不存在需要新增
var saveData modelskpi.QualitativeEvaluationScheme //方案内容结构体
@ -605,7 +632,7 @@ func (p *postShemeListCont) eidtPostSchemeInfo(versionNumber string, companyId,
saveData.OrgId = orgid //归属行政组织"`
saveData.PostId = postid //归属岗位"`
saveData.Title = v.Title //考核项名称"`
saveData.DimensionId = departmentId //维度"`
saveData.DimensionId = dimensionId //维度"`
saveData.TargetId = targetId //指标"`
saveData.SonTargetId = sonTargetId //子栏目"`
saveData.DetailsId = v.Id //细则"`
@ -619,11 +646,12 @@ func (p *postShemeListCont) eidtPostSchemeInfo(versionNumber string, companyId,
saveData.CensorType = "2" //检查方式(1:现场检查;2:资料检查;3:事件触发)"`
saveData.Source = 1 //来源(1:岗位;2:部门引用)"`
saveData.RunState = runState //运行状态(1:启用;2:禁用;3:观察)
saveData.Punishmode = v.Punishmode //处罚方式 1:扣分;2:现金处罚;3:扣分加现金
saveData.Maxmoney = v.Maxmoney //最高罚款
saveData.Minmoney = v.Minmoney //最低罚款
saveData.Punishmode = v.Punishmode //处罚方式 1:扣分;2:现金处罚;3:扣分加现金
saveData.Maxmoney = v.Maxmoney //最高罚款
saveData.Minmoney = v.Minmoney //最低罚款
saveData.AddReduce = v.AddReduce //1:减少;2:增加;3:无属性,现场确认加或减"`
p.shememList = append(p.shememList, saveData)
fmt.Printf("judgeLianErr----saveData----->%v\n", saveData)
}
}
}
@ -648,7 +676,10 @@ func postSchemeTarget(versionNumber string, source, judgeState int, scheme []sch
var saveNewData []modelskpi.QualitativeEvaluationScheme
for _, v := range scheme { //解析维度
dimensionIdInt64, _ := strconv.ParseInt(v.Id, 10, 64) //转换维度ID
if len(v.Child) > 0 { //判断是否有指标
syncSetingRun.Add(1)
go xieChengWeight(0, orgid, postid, dimensionIdInt64, 0, 1, 2, v.Score) //添加维度分值记录
if len(v.Child) > 0 { //判断是否有指标
for _, cv := range v.Child { //解析指标
targetIdInt64, _ := strconv.ParseInt(cv.Id, 10, 64) //转换指标ID
var saveData modelskpi.QualitativeEvaluationScheme
@ -668,6 +699,8 @@ func postSchemeTarget(versionNumber string, source, judgeState int, scheme []sch
scoringMethod = departPostTargetInfo.ScoringMethod
}
}
syncSetingRun.Add(1)
go xieChengWeight(int64(cv.Type), orgid, postid, dimensionIdInt64, targetIdInt64, 2, 2, cv.Score)
if cv.Type != 1 { //定量考核
//判断该指标是否存在
whereLian := publicmethod.MapOut[string]()
@ -826,6 +859,7 @@ func postSchemeTarget(versionNumber string, source, judgeState int, scheme []sch
overall.CONSTANT_DB_KPI.Create(&saveNewData)
}
syncSetinges.Wait()
syncSetingRun.Wait()
}
/*
@ -1149,6 +1183,7 @@ func (a *ApiMethod) EditSchemeStateOfDel(c *gin.Context) {
publicmethod.Result(1, err, c, "未知系统参数!")
return
}
where := map[string]interface{}{"`id`": receivedValue.Id}
var oldSystemCont modelskpi.PositionPlanVersio
err = oldSystemCont.GetCont(where)
@ -1160,13 +1195,15 @@ func (a *ApiMethod) EditSchemeStateOfDel(c *gin.Context) {
saveData := publicmethod.MapOut[string]()
saveData["`state`"] = receivedValue.State
saveData["`eitetime`"] = time.Now().Unix()
err = oldSystemCont.EiteCont(where, saveData)
var editPostPlan modelskpi.PositionPlanVersio
err = editPostPlan.EiteCont(where, saveData)
} else {
// if receivedValue.IsTrue != 1 {
saveData := publicmethod.MapOut[string]()
saveData["`state`"] = receivedValue.State
saveData["`eitetime`"] = time.Now().Unix()
err = oldSystemCont.EiteCont(where, saveData)
var editPostPlan modelskpi.PositionPlanVersio
err = editPostPlan.EiteCont(where, saveData)
// } else {
// err = overall.CONSTANT_DB_System_Permission.Where(where).Delete(&oldSystemCont).Error
// }
@ -1192,12 +1229,13 @@ func editSchemeOther(schemeCont modelskpi.PositionPlanVersio, state int) {
saveData["`eitetime`"] = time.Now().Unix()
overall.CONSTANT_DB_KPI.Model(&modelskpi.QualitativeEvaluationScheme{}).Where("`company_id` = ? AND `department_id` = ? AND `org_id` = ? AND `post_id` = ? AND `version_number` <> ?", schemeCont.Group, schemeCont.Department, schemeCont.OrgId, schemeCont.Position, schemeCont.Key).Updates(saveData)
// 将本岗位下其他方案禁用
var oldSystemCont modelskpi.PositionPlanVersio
// var oldSystemCont modelskpi.PositionPlanVersio
saveDataOther := publicmethod.MapOut[string]()
saveDataOther["`state`"] = 2
saveDataOther["`eitetime`"] = time.Now().Unix()
where := map[string]interface{}{"`id`": schemeCont.Id}
oldSystemCont.EiteCont(where, saveDataOther)
// where := map[string]interface{}{"`id`": schemeCont.Id}
// oldSystemCont.EiteCont(where, saveDataOther)
overall.CONSTANT_DB_KPI.Model(&modelskpi.PositionPlanVersio{}).Where("`position` = ? AND `state` = 1 AND `id` <> ?", schemeCont.Position, schemeCont.Id).Updates(saveDataOther)
//开启本岗位方案详情
var qesCont modelskpi.QualitativeEvaluationScheme
qesCont.EiteCont(map[string]interface{}{"`version_number`": schemeCont.Key}, map[string]interface{}{"`state": 1})
@ -1210,3 +1248,144 @@ func editSchemeOther(schemeCont modelskpi.PositionPlanVersio, state int) {
}
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-25 15:04:05
@ 功能: 协程写入岗位维度或指标权重
@ 参数
#class 0维度1定性考核2定量考核"`
#orgid 行政组织"
#postid 岗位
#dimensionIdInt64 考核维度
#target 指标
#weight 权重
#hierarchy 1维度2指标
#quote 1不是引用2引用部门
xieChengWeight(class, orgid, postid, dimensionIdInt64, target, hierarchy, quote int64, weight float64)
syncSetingRun.Done()
@ 返回值
#
*/
func xieChengWeight(class, orgid, postid, dimensionIdInt64, target, hierarchy, quote int64, weight float64) {
defer syncSetingRun.Done()
var dimWeight modelskpi.DepartDimePostWeight
dimWeight.Type = class //1:定性考核;2:定量考核"`
dimWeight.Orgid = orgid //行政组织"`
dimWeight.Postid = postid //岗位"`
dimWeight.Dimension = dimensionIdInt64 //考核维度"`
dimWeight.Target = target //指标"`
dimWeight.Weight = weight //权重"`
dimWeight.Addtime = time.Now().Unix() //添加时间"`
dimWeight.Hierarchy = hierarchy //1:维度;2:指标"`
dimWeight.Quote = quote //1:不是引用;2:引用部门"`
dimWeight.WriteTargetWeight()
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-20 14:04:52
@ 功能: 获取岗位指标添加方案时使用
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) HavePostTarget(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(1, err, c, "未知岗位!请先选择岗位!")
return
}
var postCont modelshr.Position
err = postCont.GetCont(map[string]interface{}{"`id`": receivedValue.Id}, "administrative_organization")
if err != nil {
publicmethod.Result(1, err, c, "未知岗位!请先选择岗位!")
return
}
var targetId []int64
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Distinct("target_id").Where("`level` = 2 AND `state` = 1 AND `post_id` = ?", receivedValue.Id).Find(&targetId).Error
if err != nil && len(targetId) < 1 {
publicmethod.Result(105, err, c)
return
}
var postTargetListCont []modelskpi.PostTarget
err = overall.CONSTANT_DB_KPI.Where("`id` IN ?", targetId).Find(&postTargetListCont).Error
if err != nil && len(postTargetListCont) < 1 {
publicmethod.Result(105, err, c)
return
}
var postPlanScheme postScheme
postPlanScheme.OrgId = strconv.FormatInt(postCont.AdministrativeOrganization, 10)
postPlanScheme.PostId = receivedValue.Id
var dutyClassList []PostSchemeDiem
var dutyId []int64
var tarList []PostSchemeTar
for _, v := range postTargetListCont {
if !publicmethod.IsInTrue[int64](v.Dimension, dutyId) {
dutyId = append(dutyId, v.Dimension)
var dutyCont modelskpi.DutyClass
errs := dutyCont.GetCont(map[string]interface{}{"`id`": v.Dimension}, "`title`", `sort`)
if errs == nil {
var dyCont PostSchemeDiem
dyCont.Id = strconv.FormatInt(v.Dimension, 10)
dyCont.Name = dutyCont.Title
dyCont.Sort = dutyCont.Sort
dutyClassList = append(dutyClassList, dyCont)
}
}
var tarCont PostSchemeTar
tarCont.Id = strconv.FormatInt(v.Id, 10)
tarCont.Name = v.Title
tarCont.Content = "" //说明
tarCont.Score = 0 //分数
tarCont.State = 1 //状态:1:启用;2:禁用;3:观察
tarCont.Type = v.Type //1、定性指标;2、定量指标
tarCont.Dimension = strconv.FormatInt(v.Dimension, 10)
tarList = append(tarList, tarCont)
}
//根据维度序号排序
sort.Slice(dutyClassList, func(i, j int) bool {
return dutyClassList[i].Sort < dutyClassList[j].Sort
})
for _, dv := range dutyClassList {
var dyInfo schemeStructure
dyInfo.Id = dv.Id
dyInfo.Name = dv.Name
dyInfo.Sort = dv.Sort
dyInfo.Score = 0
for _, tv := range tarList {
if tv.Dimension == dv.Id {
var trInfo schemeTargetStructure
trInfo.Id = tv.Id
trInfo.Name = tv.Name
trInfo.Content = tv.Content //说明
trInfo.Score = tv.Score //分数
trInfo.State = tv.State //状态:1:启用;2:禁用;3:观察
trInfo.Type = tv.Type //1、定性指标;2、定量指标
dyInfo.Child = append(dyInfo.Child, trInfo)
}
}
postPlanScheme.PostChild = append(postPlanScheme.PostChild, dyInfo)
}
publicmethod.Result(0, postPlanScheme, c)
}

1247
api/version1/postseting/postpc/serpostconfig.go

File diff suppressed because it is too large

586
api/version1/postseting/postpc/targetpost.go

@ -53,21 +53,61 @@ func (a *ApiMethod) GetPostTarget(c *gin.Context) {
sendData.ScoringMethod = postTargetCont.ScoringMethod //计分方式(1:自动;2:手动)"`
sendData.VisibleRange = postTargetCont.VisibleRange //可见范围"`
sendData.VisibleGroup = postTargetCont.VisibleGroup //可见范围(集团)"`
_, sendData.RelevantPostsMan, _ = getTargetAboutPost(postTargetCont.ReleDepart, postTargetCont.Dimension, postTargetCont.Id, 2)
sendData.OtherPostTarget, sendData.PostName, _ = getOrgOfPostReport(postTargetCont.Dimension, postTargetCont.Id, 0, 0, postTargetCont.State, 1, 2)
// _, sendData.RelevantPostsMan, _ = getTargetAboutPost(postTargetCont.ReleDepart, postTargetCont.Dimension, postTargetCont.Id, 2)
publicmethod.Result(0, sendData, c)
}
/*
获取行政组织及岗位提报人
#dimensionId 维度
#targetId 指标
#sunTargetId 栏目
#targetBylawsId 细则
#state 状态
#typeInt 类型1指标2子目标3细则
#level 级别1部门级2岗位级
*/
func getOrgOfPostReport(dimensionId, targetId, sunTargetId, targetBylawsId int64, state, typeInt, level int) (postPeopleList []OtherPostTargetCont, postName string, err error) {
var tarDepartList []modelskpi.TargetDepartment
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Select("`department_id`,`post_id`").Where("`state` = ? AND `level` = ? AND `dimension_id` = ? AND `target_id` = ? AND `target_sun_id` = ? AND `target_bylaws` = ?", state, level, dimensionId, targetId, sunTargetId, targetBylawsId).Find(&tarDepartList).Error
var postIsAry []int64
if err == nil && len(tarDepartList) > 0 {
var postId int64
for _, v := range tarDepartList {
if publicmethod.IsInTrue[int64](v.PostId, postIsAry) == false {
postIsAry = append(postIsAry, v.PostId)
var postPeopleCont OtherPostTargetCont
postPeopleCont.OrgId = v.DepartmentId
postPeopleCont.PostId = v.PostId
_, postPeopleCont.Operator, _ = getTargetAboutPostMan(v.DepartmentId, v.PostId, dimensionId, targetId, level, typeInt)
postPeopleList = append(postPeopleList, postPeopleCont)
postId = v.PostId
}
}
if postId != 0 {
var postCont modelshr.Position
postCont.GetCont(map[string]interface{}{"`id`": postId}, "`name`")
postName = postCont.Name
}
}
return
}
/*
获取岗位指标相关岗位
@departmentId 部门Id
@dimensionId 维度
@targetId 指标
@level 级别1部门级2岗位级
@typeInt 级别1部门级2岗位级
@level 1指标2子目标3细则
func getTargetAboutPost(departmentId, dimensionId, targetId int64, level int) (postId []int64, postPeopleList []postPeople, err error)
*/
func getTargetAboutPost(departmentId, dimensionId, targetId int64, level int) (postId []int64, postPeopleList []postPeople, err error) {
func getTargetAboutPost(departmentId, dimensionId, targetId int64, typeInt, level int) (postId []int64, postPeopleList []postPeople, err error) {
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Distinct("`post_id`").Where("`state` = 1 AND `level` = ? AND `department_id` = ? AND `dimension_id` = ? AND `target_id` = ?", level, departmentId, dimensionId, targetId).Find(&postId).Error
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Distinct("`post_id`").Where("`state` = 1 AND `type` = ? AND `level` = ? AND `department_id` = ? AND `dimension_id` = ? AND `target_id` = ?", level, typeInt, departmentId, dimensionId, targetId).Find(&postId).Error
if len(postId) > 0 {
for i := 0; i < len(postId); i++ {
var postmanCont postPeople
@ -75,7 +115,7 @@ func getTargetAboutPost(departmentId, dimensionId, targetId int64, level int) (p
var postCont modelshr.Position
postCont.GetCont(map[string]interface{}{"`id`": postId[i]}, "`name`")
postmanCont.Name = postCont.Name
_, postmanCont.Operator, _ = getTargetAboutPostMan(departmentId, postId[i], dimensionId, targetId, level)
_, postmanCont.Operator, _ = getTargetAboutPostMan(departmentId, postId[i], dimensionId, targetId, typeInt, level)
postPeopleList = append(postPeopleList, postmanCont)
}
}
@ -88,10 +128,11 @@ func getTargetAboutPost(departmentId, dimensionId, targetId int64, level int) (p
@postid 岗位
@dimensionId 维度
@targetId 指标
@level 级别1部门级2岗位级
@type 级别1部门级2岗位级
@level 1指标2子目标3细则
*/
func getTargetAboutPostMan(departmentId, postid, dimensionId, targetId int64, level int) (peopleId []int64, postPeople []string, err error) {
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Distinct("`man_key`").Where("`state` = 1 AND `type` = ? AND `department_id` = ? AND `post_id` = ? AND `dimension_id` = ? AND `target_id` = ?", level, departmentId, postid, dimensionId, targetId).Find(&peopleId).Error
func getTargetAboutPostMan(departmentId, postid, dimensionId, targetId int64, typeInt, level int) (peopleId []int64, postPeople []string, err error) {
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Distinct("`man_key`").Where("`state` = 1 AND `type` = ? AND `type_level` = ? AND `department_id` = ? AND `post_id` = ? AND `dimension_id` = ? AND `target_id` = ?", typeInt, level, departmentId, postid, dimensionId, targetId).Find(&peopleId).Error
if len(peopleId) > 0 {
for i := 0; i < len(peopleId); i++ {
postPeople = append(postPeople, strconv.FormatInt(peopleId[i], 10))
@ -418,7 +459,7 @@ func (a *ApiMethod) GetTargetAboutDepartToPostMan(c *gin.Context) {
publicmethod.Result(107, err, c)
return
}
_, outData, _ := getTargetAboutPost(postTargetCont.ReleDepart, postTargetCont.Dimension, postTargetCont.Id, 2)
_, outData, _ := getTargetAboutPost(postTargetCont.ReleDepart, postTargetCont.Dimension, postTargetCont.Id, 2, 1)
publicmethod.Result(0, outData, c)
}
@ -470,7 +511,7 @@ func (a *ApiMethod) AddPostTargetCont(c *gin.Context) {
//获取指标信息
var getTargetCont modelskpi.PostTarget
getTargetCont.GetCont(map[string]interface{}{"`id`": receivedValue.TargetId})
_, postPeople, _ := getTargetAboutPost(deartmentIdInt, getTargetCont.Dimension, getTargetCont.Id, 2)
_, postPeople, _ := getTargetAboutPost(deartmentIdInt, getTargetCont.Dimension, getTargetCont.Id, 2, 3)
//指标子栏目
var sunTargetCont modelskpi.PostSonTarget
@ -482,7 +523,7 @@ func (a *ApiMethod) AddPostTargetCont(c *gin.Context) {
sunTargetCont.Time = time.Now().Unix() //创建时间"`
sunTargetCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
sunTargetCont.Depart = deartmentIdInt //关联部门"`
sunTargetCont.Depart = receivedValue.DepartmentId //关联部门"`
sunTargetCont.DepartPost = strings.Join(receivedValue.PostId, ",")
sunTargetErr := overall.CONSTANT_DB_KPI.Create(&sunTargetCont).Error
if sunTargetErr != nil {
@ -560,22 +601,22 @@ func (a *ApiMethod) AddPostTargetCont(c *gin.Context) {
}
var saveCont modelskpi.PostTargetDetails
saveCont.Title = lv.Title //指标细则"`
saveCont.Content = lv.Explain //备注说明"`
saveCont.ParentId = targetSunIdInt //归属指标栏目"`
saveCont.ParentIdSun = sunTargetCont.Id //归属指标子栏目"`
saveCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
saveCont.AddTime = time.Now().Unix() //制定时间"`
saveCont.MinScore = minScoreInt //最小分*100保存"`
saveCont.MaxScore = maxScoreInt //最大分*100保存"`
saveCont.Company = lv.Unit //单位"`
saveCont.AddReduce = lv.Class //1:减少;2:增加;3:无属性,现场确认加或减"`
saveCont.CensorType = strings.Join(lv.Inspect, ",") //检查方式"`
saveCont.CensorCont = lv.Evidence //客观证据"`
saveCont.CensorRate = lv.Frequency //检查频次"`
saveCont.Cycles = lv.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
saveCont.CycleAttres = lv.CycleAttr //辅助计数"`
saveCont.Paretment = deartmentIdInt //接受考核的部门"`
saveCont.Title = lv.Title //指标细则"`
saveCont.Content = lv.Explain //备注说明"`
saveCont.ParentId = targetSunIdInt //归属指标栏目"`
saveCont.ParentIdSun = sunTargetCont.Id //归属指标子栏目"`
saveCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
saveCont.AddTime = time.Now().Unix() //制定时间"`
saveCont.MinScore = minScoreInt //最小分*100保存"`
saveCont.MaxScore = maxScoreInt //最大分*100保存"`
saveCont.Company = lv.Unit //单位"`
saveCont.AddReduce = lv.Class //1:减少;2:增加;3:无属性,现场确认加或减"`
saveCont.CensorType = strings.Join(lv.Inspect, ",") //检查方式"`
saveCont.CensorCont = lv.Evidence //客观证据"`
saveCont.CensorRate = lv.Frequency //检查频次"`
saveCont.Cycles = lv.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
saveCont.CycleAttres = lv.CycleAttr //辅助计数"`
saveCont.Paretment = strconv.FormatInt(deartmentIdInt, 10) //接受考核的部门"`
// saveCont.ParetmentPost = strings.Join(requestData.PostId, ",") //接受考核的部门岗位"`
// saveCont.Reportary = strings.Join(lv.ReportAry, ",") //接受考核的部门岗位"`
@ -648,8 +689,9 @@ func addDetaonsCont(saveCont modelskpi.PostTargetDetails, postMan, targetPostMan
fmt.Printf("postMan------->%v--------targetPostMan------->%v--------departAny------->%v--------peopletAny------->%v\n", postMan, targetPostMan, departAny, peopletAny)
//关联部门岗位
if len(departAny) > 0 {
paretmentIdInt, _ := strconv.ParseInt(saveCont.Paretment, 10, 64)
syncSetinges.Add(1)
go EditTargetTableDimenAboutPostOfDepart(dimensionId, saveCont.ParentId, saveCont.ParentIdSun, saveCont.Id, saveCont.Paretment, departAny, 2, 1)
go EditTargetTableDimenAboutPostOfDepart(dimensionId, saveCont.ParentId, saveCont.ParentIdSun, saveCont.Id, paretmentIdInt, departAny, 2, 1)
}
//关联考核岗位和提报人
@ -664,8 +706,9 @@ func addDetaonsCont(saveCont modelskpi.PostTargetDetails, postMan, targetPostMan
}
}
postid, _ := strconv.ParseInt(dv.Id, 10, 64)
paretmentIdInts, _ := strconv.ParseInt(saveCont.Paretment, 10, 64)
syncSetinges.Add(1)
go DepartAboutPostTargetReport(dimensionId, saveCont.ParentId, saveCont.ParentIdSun, saveCont.Id, saveCont.Paretment, postid, operatorList, 2, 1)
go DepartAboutPostTargetReport(dimensionId, saveCont.ParentId, saveCont.ParentIdSun, saveCont.Id, paretmentIdInts, postid, operatorList, 2, 1)
}
syncSetinges.Wait()
@ -887,7 +930,8 @@ func (a *ApiMethod) EditSonTargetCont(c *gin.Context) {
postTarCont.GetCont(map[string]interface{}{"`id`": sonTarCont.ParentId}, "`dimension`")
if len(receivedValue.PostOfOperator) > 0 {
syncSeting.Add(1)
go postSonTargetAboutOrder(postTarCont.Dimension, sonTarCont.Depart, sonTarCont.ParentId, sonTarCont.Id, receivedValue.PostOfOperator)
departInt, _ := strconv.ParseInt(sonTarCont.Depart, 10, 64)
go postSonTargetAboutOrder(postTarCont.Dimension, departInt, sonTarCont.ParentId, sonTarCont.Id, receivedValue.PostOfOperator)
}
syncSeting.Wait()
@ -1064,7 +1108,7 @@ func (a *ApiMethod) DelSonTargetCont(c *gin.Context) {
xiZeWhere := publicmethod.MapOut[string]()
xiZeWhere["`parentid`"] = sonTarCont.ParentId
xiZeWhere["`parentid_sun`"] = sonTarCont.Id
xiZeWhere["`paretment`"] = sonTarCont.Depart
// xiZeWhere["`paretment`"] = sonTarCont.Depart
var postTarDetaCont modelskpi.PostTargetDetails
postTarDetaCont.EiteCont(xiZeWhere, map[string]interface{}{"`state`": 3, "`time`": time.Now().Unix()})
publicmethod.Result(0, err, c)
@ -1165,7 +1209,8 @@ func (a *ApiMethod) AddOneTargetD(c *gin.Context) {
saveCont.CensorRate = receivedValue.Frequency //检查频次"`
saveCont.Cycles = receivedValue.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
saveCont.CycleAttres = receivedValue.CycleAttr //辅助计数"`
saveCont.Paretment = sonTarCont.Depart //接受考核的部门"`
// saveCont.Paretment = strconv.FormatInt(sonTarCont.Depart, 10) //接受考核的部门"`
saveCont.Paretment = sonTarCont.Depart
// saveCont.ParetmentPost = strings.Join(requestData.PostId, ",") //接受考核的部门岗位"`
// saveCont.Reportary = strings.Join(receivedValue.ReportAry, ",") //接受考核的部门岗位"`
saveCont.Punishmode = receivedValue.PunishMode //处罚或奖励方式 1:分数;2:现金;3:分数加现金
@ -1175,7 +1220,8 @@ func (a *ApiMethod) AddOneTargetD(c *gin.Context) {
//获取指标信息
var getTargetCont modelskpi.PostTarget
getTargetCont.GetCont(map[string]interface{}{"`id`": sonTarCont.ParentId})
_, postPeople, _ := getTargetSonAboutPost(sonTarCont.Depart, getTargetCont.Dimension, getTargetCont.Id, sonTarCont.Id, 2)
departInt, _ := strconv.ParseInt(sonTarCont.Depart, 10, 64)
_, postPeople, _ := getTargetSonAboutPost(departInt, getTargetCont.Dimension, getTargetCont.Id, sonTarCont.Id, 2)
syncSeting.Add(1)
go addDetaonsCont(saveCont, receivedValue.RelevantPostsMan, postPeople, getTargetCont.Dimension)
@ -1225,7 +1271,7 @@ func getTargetSonAboutPost(departmentId, dimensionId, targetId, sonTargetId int6
postmanCont.Name = postCont.Name
_, postmanCont.Operator, _ = getSonTargetAboutPostMan(departmentId, postId[i], dimensionId, targetId, sonTargetId, level)
if len(postmanCont.Operator) < 1 {
_, postmanCont.Operator, _ = getTargetAboutPostMan(departmentId, postId[i], dimensionId, targetId, level)
_, postmanCont.Operator, _ = getTargetAboutPostMan(departmentId, postId[i], dimensionId, targetId, level, 1)
}
postPeopleList = append(postPeopleList, postmanCont)
}
@ -1273,6 +1319,7 @@ func (a *ApiMethod) EidtPostTarDetailsStrte(c *gin.Context) {
publicmethod.Result(1, detaErr, c, "该指标细则不存在!")
return
}
softDel := 1
if requestData.State != 3 {
saveData := publicmethod.MapOut[string]()
saveData["state"] = requestData.State
@ -1293,6 +1340,7 @@ func (a *ApiMethod) EidtPostTarDetailsStrte(c *gin.Context) {
return
}
} else {
softDel = 2
saveErr := detaCont.DelCont(where)
if saveErr != nil {
publicmethod.Result(1, saveErr, c, "编辑失败!")
@ -1300,6 +1348,11 @@ func (a *ApiMethod) EidtPostTarDetailsStrte(c *gin.Context) {
}
}
}
departmentpc.SyncSeting.Add(1)
go departmentpc.TarDepartState(detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, requestData.State, softDel, 2, 3) // 处理关联部门
departmentpc.SyncSeting.Add(1)
go departmentpc.TarAboutReport(detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, requestData.State, softDel, 2, 3) // 处理相关提报人
departmentpc.SyncSeting.Wait()
publicmethod.Result(0, detaCont, c)
}
@ -1423,6 +1476,7 @@ func (a *ApiMethod) EditDeatilsCont(c *gin.Context) {
var postTarCont modelskpi.PostTarget
postTarCont.GetCont(map[string]interface{}{"`id`": detaCont.ParentId}, "`dimension`")
dimensionId := postTarCont.Dimension
paretmentIdInt, _ := strconv.ParseInt(detaCont.Paretment, 10, 64)
var departAny []string
for _, v := range receivedValue.RelevantPostsMan {
if publicmethod.IsInTrue[string](v.Id, departAny) == false {
@ -1431,13 +1485,13 @@ func (a *ApiMethod) EditDeatilsCont(c *gin.Context) {
postid, _ := strconv.ParseInt(v.Id, 10, 64)
if len(v.Operator) > 0 {
syncSetinges.Add(1)
go DepartAboutPostTargetReport(dimensionId, detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, detaCont.Paretment, postid, v.Operator, 2, 1)
go DepartAboutPostTargetReport(dimensionId, detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, paretmentIdInt, postid, v.Operator, 2, 1)
}
}
//关联部门岗位
if len(departAny) > 0 {
syncSetinges.Add(1)
go EditTargetTableDimenAboutPostOfDepart(dimensionId, detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, detaCont.Paretment, departAny, 2, 1)
go EditTargetTableDimenAboutPostOfDepart(dimensionId, detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, paretmentIdInt, departAny, 2, 1)
}
syncSetinges.Wait()
@ -1476,24 +1530,79 @@ func (a *ApiMethod) GetDetailsCont(c *gin.Context) {
} else {
sendData.CashStandard = fmt.Sprintf("%v", publicmethod.DecimalEs(float64(detaCont.Maxmoney)/100, 2))
}
// paretmentIdInt, _ := strconv.ParseInt(detaCont.Paretment, 10, 64)
var postTarCont modelskpi.PostTarget
postTarCont.GetCont(map[string]interface{}{"`id`": detaCont.ParentId}, "`dimension`")
dimensionId := postTarCont.Dimension
// dimensionId := postTarCont.Dimension
sendData.Title = detaCont.Title
sendData.Unit = detaCont.Company //单位
sendData.Class = detaCont.AddReduce //1:减少;2:增加;3:无属性,现场确认加或减
sendData.Inspect = strings.Split(detaCont.CensorType, ",") //检查方式(1:现场检查;2:资料检查;3:事件触发)
sendData.Cycle = detaCont.Cycles //1:班;2:天;3:周;4:月;5:季度;6:年
sendData.CycleAttr = detaCont.CycleAttres //辅助计数
sendData.Frequency = detaCont.CensorRate //频次
sendData.Evidence = detaCont.CensorCont //客观证据
sendData.Explain = detaCont.Content //备注说明
_, sendData.RelevantPostsMan, _ = getTargetAboutPostDeta(detaCont.Paretment, dimensionId, detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, 2) //相关岗位与提报人
sendData.PunishMode = detaCont.Punishmode //处罚方式 1:扣分;2:现金处罚;3:扣分加现金
sendData.Unit = detaCont.Company //单位
sendData.Class = detaCont.AddReduce
var inspectInt []int
inspectStrList := strings.Split(detaCont.CensorType, ",")
for _, iv := range inspectStrList {
ivInt, _ := strconv.Atoi(iv)
inspectInt = append(inspectInt, ivInt)
} //1:减少;2:增加;3:无属性,现场确认加或减
sendData.InspectItn = inspectInt
sendData.Inspect = inspectStrList //检查方式(1:现场检查;2:资料检查;3:事件触发)
sendData.Cycle = detaCont.Cycles //1:班;2:天;3:周;4:月;5:季度;6:年
sendData.CycleAttr = detaCont.CycleAttres //辅助计数
sendData.Frequency = detaCont.CensorRate //频次
sendData.Evidence = detaCont.CensorCont //客观证据
sendData.Explain = detaCont.Content //备注说明
// _, sendData.RelevantPostsMan, _ = getTargetAboutPostDeta(paretmentIdInt, dimensionId, detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, 2) //相关岗位与提报人
sendData.RelevantPostsMan = GetPostReportList(detaCont.ParentId, detaCont.ParentIdSun, detaCont.Id, 3, 2)
sendData.PunishMode = detaCont.Punishmode //处罚方式 1:扣分;2:现金处罚;3:扣分加现金
publicmethod.Result(0, sendData, c)
}
// 获取关联岗位及提报人
/*
#targetId 指标ID
#tableId 栏目ID
#bylawsId 细则ID
#types 类型1指标2子目标3细则
#level 级别1部门级2岗位级
*/
func GetPostReportList(targetId, tableId, bylawsId int64, types, level int) (listCont []postPeople) {
var postTarDepartList []modelskpi.TargetDepartment
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Select("`department_id`,`post_id`").Where("`state` = 1 AND `type` = ? AND `level` = ? AND `target_id` = ? AND `target_sun_id` = ? AND `target_bylaws` = ?", types, level, targetId, tableId, bylawsId).Find(&postTarDepartList).Error
if err != nil {
return
}
for _, v := range postTarDepartList {
var contInfo postPeople
contInfo.Id = strconv.FormatInt(v.PostId, 10)
contInfo.OrgId = strconv.FormatInt(v.DepartmentId, 10)
contInfo.Operator = GetRepostList(targetId, tableId, bylawsId, v.DepartmentId, v.PostId, types, level)
listCont = append(listCont, contInfo)
}
return
}
// 获取提报人
/*
#targetId 指标ID
#tableId 栏目ID
#bylawsId 细则ID
#types 类型1指标2子目标3细则
#level 级别1部门级2岗位级
*/
func GetRepostList(targetId, tableId, bylawsId, orgId, postId int64, types, level int) (userKey []string) {
var mankey []int64
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Select("`man_key`").Where("`state` = 1 AND `type` = ? AND `type_level` = ? AND `target_id` = ? AND `target_sun_id` = ? AND `target_bylaws` = ? AND `department_id` = ? AND `post_id` = ?", level, types, targetId, tableId, bylawsId, orgId, postId).Find(&mankey).Error
if err != nil || len(mankey) < 1 {
return
}
for _, v := range mankey {
manKeyStr := strconv.FormatInt(v, 10)
if publicmethod.IsInTrue[string](manKeyStr, userKey) == false {
userKey = append(userKey, manKeyStr)
}
}
return
}
/*
获取岗位指标子细则相关岗位
@departmentId 部门Id
@ -1537,3 +1646,384 @@ func getTargetAboutPostDetalMan(departmentId, postid, dimensionId, targetId, son
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-10 11:00:59
@ 功能: 获取岗位指标列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetPostTargetList(c *gin.Context) {
var receivedValue GetPostTargetContList
c.ShouldBindJSON(&receivedValue)
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 20
}
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
var postTargetCont modelskpi.PostTarget
gormDb := overall.CONSTANT_DB_KPI.Table(fmt.Sprintf("%s pt", postTargetCont.TableName())).Where("pt.`state` BETWEEN 1 AND 2")
if receivedValue.Title != "" {
gormDb = gormDb.Where("pt.`title` LIKE ?", "%"+receivedValue.Title+"%")
}
if receivedValue.Dimension != "" {
gormDb = gormDb.Where("pt.`dimension` = ?", receivedValue.Dimension)
}
if receivedValue.Attribute != 0 {
gormDb = gormDb.Where("pt.`type` = ?", receivedValue.Attribute)
}
if len(receivedValue.PostIdList) > 0 {
gormDb = gormDb.Joins("JOIN target_department td ON pt.`id` = td.`target_id` AND td.`target_sun_id` = 0 AND td.`target_bylaws` = 0 AND td.`type` = 1 AND td.`state` BETWEEN 1 AND 2 AND td.`level` = 2 AND td.`post_id` IN ?", receivedValue.PostIdList)
}
var total int64
gormDbTotal := gormDb.Distinct("pt.id")
totalErr := gormDbTotal.Count(&total).Error
if totalErr != nil {
total = 0
}
var targetIdAry []int64
gormDb = gormDb.Distinct("pt.id")
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("pt.`id` DESC").Find(&targetIdAry).Error
if err != nil || len(targetIdAry) < 1 {
publicmethod.Result(105, err, c)
return
}
//获取指标信息列表
var postTargetList []modelskpi.PostTarget
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.PostTarget{}).Where("`id` IN ?", targetIdAry).Order("`id` DESC").Find(&postTargetList).Error
if err != nil {
publicmethod.Result(105, err, c)
return
}
var sendPostTargetContList []outPostTargetList
for _, v := range postTargetList {
var postTargetCont outPostTargetList
postTargetCont.Id = v.Id
postTargetCont.Title = v.Title //标题"`
postTargetCont.Type = v.Type //定性考核;2:定量考核"`
postTargetCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
postTargetCont.Time = v.Time //创建时间"`
postTargetCont.Share = v.Share //共用;2:私用"`
postTargetCont.ReleDepart = v.ReleDepart //相关部门"`
postTargetCont.DepartmentsPost = v.DepartmentsPost //相关岗位"`
postTargetCont.Dimension = v.Dimension //维度"`
postTargetCont.Key = v.Key //UUID"`
postTargetCont.Report = v.Report //上报人"`
postTargetCont.Unit = v.Unit //单位"`
postTargetCont.Cycle = v.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
postTargetCont.Cycleattr = v.Cycleattr //n辅助计数"`
postTargetCont.ScoringMethod = v.ScoringMethod //计分方式(1:自动;2:手动)"`
postTargetCont.VisibleRange = v.VisibleRange //可见范围"`
postTargetCont.VisibleGroup = v.VisibleGroup //可见范围(集团)"`
var dimCont modelskpi.DutyClass
dimCont.GetCont(map[string]interface{}{"`id`": v.Dimension}, "`title`")
postTargetCont.DimensionName = dimCont.Title
postTargetCont.PostAry = getSubimtPost(v.Id, 0, 0, 1, 2)
postTargetCont.ReportAry = getSubimtPostReport(v.Id, 0, 0, 2, 1)
sendPostTargetContList = append(sendPostTargetContList, postTargetCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendPostTargetContList)), sendPostTargetContList, c)
}
// 获取提报岗位
/*
#targetId 指标Id
#sunTargetId 栏目Id
#targetBylawsId 细则Id
#typeInt 类型1指标2子目标3细则
#level 级别1部门级2岗位级
*/
func getSubimtPost(targetId, sunTargetId, targetBylawsId int64, typeInt, level int) (postTargetListCont []idAndName) {
var postIdList []int64
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Distinct("`post_id`").Where("`state` = 1 AND `target_id` = ? AND `target_sun_id` = ? AND `target_bylaws` = ? AND `type` = ? AND `level` = ?", targetId, sunTargetId, targetBylawsId, typeInt, level).Find(&postIdList).Error
if err != nil {
return
}
if len(postIdList) > 0 {
for _, v := range postIdList {
var postTarInfo modelshr.Position
errPost := postTarInfo.GetCont(map[string]interface{}{"`id`": v}, "`name`")
if errPost == nil {
var contInfo idAndName
contInfo.Id = strconv.FormatInt(v, 10)
contInfo.Name = postTarInfo.Name
postTargetListCont = append(postTargetListCont, contInfo)
}
}
}
return
}
// 获取岗位指标提报人
/*
#targetId 指标Id
#sunTargetId 栏目Id
#targetBylawsId 细则Id
#typeInt 级别1部门级2岗位级
#level 类型1指标2子目标3细则
*/
func getSubimtPostReport(targetId, sunTargetId, targetBylawsId int64, typeInt, level int) (manContList []UserContList) {
var userKey []int64
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Distinct("`man_key`").Where("`state` = 1 AND `target_id` = ? AND `target_sun_id` = ? AND `target_bylaws` = ? AND `type` = ? AND `type_level` = ?", targetId, sunTargetId, targetBylawsId, typeInt, level).Find(&userKey).Error
if err != nil {
return
}
if len(userKey) > 0 {
for _, v := range userKey {
var postTarInfo modelshr.PersonArchives
errPost := postTarInfo.GetCont(map[string]interface{}{"`key`": v}, "`number`", "`name`", "`icon`", "`icon_photo`")
if errPost == nil {
var contInfo UserContList
contInfo.Id = strconv.FormatInt(v, 10)
contInfo.Name = postTarInfo.Name
contInfo.Icon = postTarInfo.Icon
contInfo.IconImg = postTarInfo.IconPhoto
manContList = append(manContList, contInfo)
}
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-10 14:45:00
@ 功能: 设置岗位指标状态
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SetPostTargetState(c *gin.Context) {
var receivedValue publicmethod.PublicState
c.ShouldBindJSON(&receivedValue)
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c, "参数错误!!")
return
}
if receivedValue.State == 0 {
receivedValue.State = 1
}
if receivedValue.IsTrue == 0 {
receivedValue.IsTrue = 2
}
where := publicmethod.MapOut[string]()
where["id"] = receivedValue.Id
var targetCont modelskpi.PostTarget
err := targetCont.GetCont(where, "id")
if err != nil {
publicmethod.Result(107, err, c)
return
}
softDel := 1
if receivedValue.State == 3 && receivedValue.IsTrue == 1 {
//强制删除
//判断该指标是否在使用中,使用中的只能软删除
var epIdList []int64
overall.CONSTANT_DB_KPI.Model(&modelskpi.PostWorkflowOrders{}).Select("`id`").Where("FIND_IN_SET(?,`target`)", receivedValue.Id).Find(&epIdList)
if len(epIdList) > 0 {
softDel = 1
} else {
softDel = 2
}
}
var editTargetState modelskpi.PostTarget
if softDel == 1 {
//软删除
editTargetState.EiteCont(where, map[string]interface{}{"`state`": receivedValue.State, "`time`": time.Now().Unix()})
} else {
//硬删除
editTargetState.DelCont(where)
}
syncSeting.Add(1)
go SunPostTargetState(targetCont.Id, receivedValue.State, softDel) //处理目标
syncSeting.Add(1)
go PostTargetDatailedState(targetCont.Id, 0, receivedValue.State, softDel) // 处理细则
syncSeting.Add(1)
go PostTarDepartState(targetCont.Id, 0, 0, receivedValue.State, softDel, 2, 1) // 处理关联部门
syncSeting.Add(1)
go PostTarAboutReport(targetCont.Id, 0, 0, receivedValue.State, softDel, 2, 1) // 处理相关提报人
syncSeting.Wait()
publicmethod.Result(0, err, c)
}
//处理相关提报人
/*
#parentId 指标ID
#sunID 栏目
#bylawsId 细则
#state 状态
#isTrue 1软删非1硬删除
#level 1:部门级2岗位级
#typeInt 1指标2子目标3细则
*/
func PostTarAboutReport(parentId, sunID, bylawsId int64, state, isTrue, level, typeInt int) {
defer syncSeting.Done()
if state == 0 {
state = 1
}
if isTrue == 0 {
isTrue = 1
}
if level == 0 {
level = 1
}
wheAry := publicmethod.MapOut[string]()
wheAry["type"] = level
wheAry["type_level"] = typeInt
if parentId != 0 {
wheAry["target_id"] = parentId
}
if sunID != 0 {
wheAry["target_sun_id"] = sunID
}
if bylawsId != 0 {
wheAry["target_bylaws"] = bylawsId
}
var tarDataCont modelskpi.TargetReport
if isTrue == 1 {
//软删除
if state != 1 {
tarDataCont.EiteCont(wheAry, map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
} else {
overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Where("`state` BETWEEN 1 AND 2").Where(wheAry).Updates(map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
}
} else {
tarDataCont.DelCont(wheAry)
}
}
// 处理关联部门
/*
#parentId 指标ID
#sunID 栏目
#bylawsId 细则
#state 状态
#isTrue 1软删非1硬删除
#level 1:部门级2岗位级
#typeInt 1指标2子目标3细则
*/
func PostTarDepartState(parentId, sunID, bylawsId int64, state, isTrue, level, typeInt int) {
defer syncSeting.Done()
if state == 0 {
state = 1
}
if isTrue == 0 {
isTrue = 1
}
wheAry := publicmethod.MapOut[string]()
wheAry["level"] = level
wheAry["type"] = typeInt
if parentId != 0 {
wheAry["target_id"] = parentId
}
if sunID != 0 {
wheAry["target_sun_id"] = sunID
}
if bylawsId != 0 {
wheAry["target_bylaws"] = bylawsId
}
var tarDataCont modelskpi.TargetDepartment
if isTrue == 1 {
//软删除
if state != 1 {
tarDataCont.EiteCont(wheAry, map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
} else {
overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetDepartment{}).Where("`state` BETWEEN 1 AND 2").Where(wheAry).Updates(map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
}
} else {
tarDataCont.DelCont(wheAry)
}
}
// 处理细则
/*
#ParentId 指标ID
#SunID 栏目
#state 状态
#isTrue 1软删非1硬删除
*/
func PostTargetDatailedState(ParentId, SunID int64, state, isTrue int) {
defer syncSeting.Done()
if state == 0 {
state = 1
}
if isTrue == 0 {
isTrue = 1
}
wheAry := publicmethod.MapOut[string]()
if ParentId != 0 {
wheAry["parentid"] = ParentId
}
if SunID != 0 {
wheAry["parentid_sun"] = SunID
}
var tarDataCont modelskpi.PostTargetDetails
if isTrue == 1 {
//软删除
if state != 1 {
tarDataCont.EiteCont(wheAry, map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
} else {
overall.CONSTANT_DB_KPI.Model(&modelskpi.PostTargetDetails{}).Where("`state` BETWEEN 1 AND 2").Where(wheAry).Updates(map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
}
} else {
tarDataCont.DelCont(wheAry)
}
}
// 处理目标
/*
#ParentId 指标ID
#state 状态
#isTrue 1软删非1硬删除
*/
func SunPostTargetState(ParentId int64, state, isTrue int) {
defer syncSeting.Done()
if state == 0 {
state = 1
}
if isTrue == 0 {
isTrue = 1
}
var sunTargetCont modelskpi.PostSonTarget
if isTrue == 1 {
//软删除
if state != 1 {
sunTargetCont.EiteCont(map[string]interface{}{"`parent_id`": ParentId}, map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
} else {
overall.CONSTANT_DB_KPI.Model(&modelskpi.PostSonTarget{}).Where("`state` BETWEEN 1 AND 2 AND `parent_id` = ?", ParentId).Updates(map[string]interface{}{"`state`": state, "`time`": time.Now().Unix()})
}
} else {
sunTargetCont.DelCont(map[string]interface{}{"`parent_id`": ParentId})
}
}

155
api/version1/postseting/postpc/teshutype.go

@ -0,0 +1,155 @@
package postpc
import (
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
)
// 搜索行政组织岗位
type SearchOrgPost struct {
OrgId string `json:"orgid"`
publicmethod.PublicName
}
// 输出行政组织岗位
type SendSearPost struct {
OrgId []int64 `json:"orgid"` //行政组织ID
PostId int64 `json:"postid"` //岗位ID
PostList []PostListCont `json:"postlist"`
}
type PostListCont struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
// 部门与岗位和提报人关系
type OrgPostPeople struct {
OrgId int64 `json:"orgid"`
PostPeople []PostPeopleList `json:"postpeople"`
}
type PostPeopleList struct {
PostId int64 `json:"postid"`
PeopleList []string `json:"peoplelist"`
}
// 获取岗位指标细则
type GetPostDetails struct {
TargetId string `json:"targetid"`
Inspect []string `json:"inspect"` //检查方式(1:现场检查;2:资料检查;3:事件触发)
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
PostList []string `json:"postlist"` //岗位
}
// 输出岗位细则
type OutPostDetailsCont struct {
modelskpi.PostTargetDetails
ColumnName string `json:"columnName"` //栏目名称
Standard string `json:"standard"` //考核标准
Forfeit string `json:"forfeit"` //罚金
JiBuQi int `json:"jibuqi"` //记不起
}
// 输出指标关联的部门和岗位
type OutTargetDepatPostMan struct {
OrgId []string `json:"orgid"` //行政组织id
PostId []string `json:"postid"` //岗位ID
OrgAndPostList []OrgPostCont `json:"organdpostlist"` //行政组织与岗位列表
}
// 行政组织与岗位结构体
type OrgPostCont struct {
publicmethod.PublicId
publicmethod.PublicName
Number string `json:"number"`
OrgId string `json:"orgid"`
KeyList []string `json:"keylist"` //已选择标识
Child *[]OrgPostCont `json:"child"`
}
// 根据指标添加岗位细则
type AddPostDetails struct {
TargetId string `json:"targetid"` //指标Id
TableName string `json:"tablename"` //栏目名称
DetailsList []DetailsCont `json:"detailslist"` //岗位细则列表
}
// 岗位细则结构体
type DetailsCont struct {
Title string `json:"title"` //考核内容
PunishType int `json:"punishtype"` //1:分数;2:现金;3:分数加现金
Standard string `json:"standard"` //考核标准
Unit string `json:"unit"` //计量单位
CashStandard string `json:"cashstandard"` //现金考核标准
Types int `json:"types"` //操作种类1:加分;2:减分;3:加减分
Inspemethod []string `json:"inspemethod"` //检查方式
Cycle int `json:"cycle"` //周期
Frequency int `json:"frequency"` //检查频次
Evidence string `json:"evidence"` //客观证据
Remarks string `json:"remarks"` //备注说明
PostandExport []OrgPostCont `json:"postandexport"` //相关岗位及提报人
}
// 行政组织与岗位
type OrgAndPostCont struct {
OrgId int64 `json:"orgid"`
PostId int64 `json:"postid"`
}
// 行政组织与岗位与提报人
type OrgAndPostManCont struct {
OrgAndPostCont
ManKey int64 `json:"mankey"`
}
// 提报人组合
type ReportAry struct {
OrgAndPostCont
ManKey []int64 `json:"mankey"`
}
// 编辑岗位细则结构体
type EditDetailsCont struct {
publicmethod.PublicId
Title string `json:"title"` //考核内容
PunishType int `json:"punishtype"` //1:分数;2:现金;3:分数加现金
Standard string `json:"standard"` //考核标准
Unit string `json:"unit"` //计量单位
CashStandard string `json:"cashstandard"` //现金考核标准
Types int `json:"types"` //操作种类1:加分;2:减分;3:加减分
Inspemethod []string `json:"inspemethod"` //检查方式
Cycle int `json:"cycle"` //周期
Frequency int `json:"frequency"` //检查频次
Evidence string `json:"evidence"` //客观证据
Remarks string `json:"remarks"` //备注说明
PostandExport []RelevantPostsMan `json:"relevantpostsman"` //相关岗位及提报人
}
// 相关行政组织岗位提报人
type RelevantPostsMan struct {
publicmethod.PublicId
OrgId string `json:"orgid"`
Operator []string `json:"operator"`
}
// 根据指标添加岗位细则
type AddTablePostDetails struct {
TargetId string `json:"targetid"` //指标Id
TableId string `json:"tableid"` //栏目名称
DetailsList []DetailsCont `json:"detailslist"` //岗位细则列表
}
type OutTableDepatPostMan struct {
publicmethod.PublicName
OrgId []string `json:"orgid"` //行政组织id
PostId []string `json:"postid"` //岗位ID
OrgAndPostList []OrgPostCont `json:"organdpostlist"` //行政组织与岗位列表
}
// 编辑栏目内容
type EditTableCont struct {
publicmethod.PublicId
Title string `json:"title"` //
PostandExport []OrgPostCont `json:"repostlist"` //
}

856
api/version1/postseting/postpc/teshuxuqiu.go

@ -0,0 +1,856 @@
package postpc
import (
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-01-12 15:21:20
@ 功能: 搜索行政组织岗位列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SearchOrgPostList(c *gin.Context) {
var receivedValue SearchOrgPost
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(1, err, c, "请输入要查询得岗位名称!")
return
}
var companyId int64 = 0
if receivedValue.OrgId != "" {
orgIdInt, _ := strconv.ParseInt(receivedValue.OrgId, 10, 64)
_, companyId, _, _, _ = publicmethod.GetOrgStructure(orgIdInt)
}
var postList []modelshr.Position
err = overall.CONSTANT_DB_HR.Where("`state` = 1 AND `name` LIKE ?", "%"+receivedValue.Name+"%").Find(&postList).Error
if err != nil {
publicmethod.Result(1, err, c, "没有相关岗位!")
return
}
var sendList []SendSearPost
for _, v := range postList {
_, companyIdPost, minDer, sunDer, workId := publicmethod.GetOrgStructure(v.AdministrativeOrganization)
var orgAry []int64
// if companyIdPost != 0 && publicmethod.IsInTrue[int64](companyIdPost, orgAry) == false {
// orgAry = append(orgAry, companyIdPost)
// }
if minDer != 0 && publicmethod.IsInTrue[int64](minDer, orgAry) == false {
orgAry = append(orgAry, minDer)
}
if sunDer != 0 && publicmethod.IsInTrue[int64](sunDer, orgAry) == false {
orgAry = append(orgAry, sunDer)
}
if workId != 0 && publicmethod.IsInTrue[int64](workId, orgAry) == false {
orgAry = append(orgAry, workId)
}
if v.AdministrativeOrganization != 0 && publicmethod.IsInTrue[int64](v.AdministrativeOrganization, orgAry) == false {
orgAry = append(orgAry, v.AdministrativeOrganization)
}
if companyId != 0 {
if companyIdPost == companyId {
var sendCont SendSearPost
sendCont.OrgId = orgAry
sendCont.PostId = v.Id
sendCont.PostList = GetWithOrgList(v.AdministrativeOrganization)
sendList = append(sendList, sendCont)
}
} else {
var sendCont SendSearPost
sendCont.OrgId = orgAry
sendCont.PostId = v.Id
sendCont.PostList = GetWithOrgList(v.AdministrativeOrganization)
sendList = append(sendList, sendCont)
}
}
// fmt.Printf("总数--->%v\n", len(sendList))
publicmethod.Result(0, sendList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-12 15:21:30
@ 功能: 获取同行政组织岗位
@ 参数
#orgId 行政组织ID
@ 返回值
#postList 岗位列表
@ 方法原型
#func GetWithOrgList(orgId int64) (postList []PostListCont)
*/
func GetWithOrgList(orgId int64) (postList []PostListCont) {
var postListCont []modelshr.Position
err := overall.CONSTANT_DB_HR.Model(&modelshr.Position{}).Select("`id`,`name`").Where("`state` = 1 AND `administrative_organization` = ?", orgId).Find(&postListCont).Error
if err != nil {
return
}
for _, v := range postListCont {
var postCont PostListCont
postCont.Id = v.Id
postCont.Name = v.Name
postList = append(postList, postCont)
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-13 10:44:16
@ 功能: 获取行政组织级联数组
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetOrgAry(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(1, err, c, "参数错误!")
return
}
idInt, _ := strconv.ParseInt(receivedValue.Id, 10, 64)
_, _, minDer, sunDer, workId := publicmethod.GetOrgStructure(idInt)
var orgAry []int64
if minDer != 0 && publicmethod.IsInTrue[int64](minDer, orgAry) == false {
orgAry = append(orgAry, minDer)
}
if sunDer != 0 && publicmethod.IsInTrue[int64](sunDer, orgAry) == false {
orgAry = append(orgAry, sunDer)
}
if workId != 0 && publicmethod.IsInTrue[int64](workId, orgAry) == false {
orgAry = append(orgAry, workId)
}
if idInt != 0 && publicmethod.IsInTrue[int64](idInt, orgAry) == false {
orgAry = append(orgAry, idInt)
}
publicmethod.Result(0, orgAry, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-12 09:03:40
@ 功能: 获取行政组织级联数组和岗位
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetOrgAndPostAry(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(1, err, c, "参数错误!")
return
}
idInt, _ := strconv.ParseInt(receivedValue.Id, 10, 64)
_, _, minDer, sunDer, workId := publicmethod.GetOrgStructure(idInt)
var orgAry []int64
if minDer != 0 && minDer != 309 && publicmethod.IsInTrue[int64](minDer, orgAry) == false {
orgAry = append(orgAry, minDer)
}
if sunDer != 0 && sunDer != 309 && publicmethod.IsInTrue[int64](sunDer, orgAry) == false {
orgAry = append(orgAry, sunDer)
}
if workId != 0 && workId != 309 && publicmethod.IsInTrue[int64](workId, orgAry) == false {
orgAry = append(orgAry, workId)
}
if idInt != 0 && idInt != 309 && publicmethod.IsInTrue[int64](idInt, orgAry) == false {
orgAry = append(orgAry, idInt)
}
//获取相关岗位
var postContList []modelshr.Position
overall.CONSTANT_DB_HR.Where("`state` = 1 AND administrative_organization = ?", idInt).Find(&postContList)
sendData := publicmethod.MapOut[string]()
sendData["orglist"] = orgAry
sendData["postlist"] = postContList
publicmethod.Result(0, sendData, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-13 11:00:48
@ 功能: 添加岗位指标
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) NewAddPostTarget(c *gin.Context) {
var receivedValue addPostTarget
c.ShouldBindJSON(&receivedValue)
if receivedValue.Title == "" {
publicmethod.Result(1, receivedValue, c, "请输入指标名称!")
return
}
if receivedValue.Type == 0 {
receivedValue.Type = 2
}
if receivedValue.ScoringMethod == 0 {
receivedValue.ScoringMethod = 1
}
// if receivedValue.RelevantDepartments == "" {
// publicmethod.Result(1, receivedValue, c, "请选择该指标归属部门!")
// return
// }
if len(receivedValue.OtherPostTarget) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择该指标归属岗位!")
return
}
if receivedValue.Dimension == "" {
publicmethod.Result(1, receivedValue, c, "请选择指标归属维度!")
return
}
if receivedValue.Unit == "" {
publicmethod.Result(1, receivedValue, c, "请输入该指标计算单位!")
return
}
if receivedValue.Cycle == 0 {
receivedValue.Cycle = 1
}
if receivedValue.CycleAttr == 0 {
receivedValue.CycleAttr = 1
}
orgPostManList := HandlingRelations(receivedValue.OtherPostTarget)
if len(orgPostManList) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择该指标归属岗位!")
return
}
for _, v := range orgPostManList {
var saveData modelskpi.PostTarget
saveData.Title = receivedValue.Title //标题"`
saveData.Type = receivedValue.Type //1:定性考核;2:定量考核"`
saveData.State = 1 //状态(1:启用;2:禁用;3:删除)"`
saveData.Time = time.Now().Unix() //创建时间"`
saveData.Share = 2 //1:共用;2:私用"`
dimensionId, _ := strconv.ParseInt(receivedValue.Dimension, 10, 64)
saveData.Dimension = dimensionId //维度"`
saveData.Key = publicmethod.GetUUid(1) //UUID"`
saveData.Unit = receivedValue.Unit //单位"`
saveData.Cycle = receivedValue.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
saveData.Cycleattr = receivedValue.CycleAttr //辅助计数"`
saveData.ScoringMethod = receivedValue.ScoringMethod //计分方式(1:自动;2:手动)"`
saveData.VisibleRange = strings.Join(receivedValue.VisibleRange, ",") //可见范围"`
saveData.VisibleGroup = strings.Join(receivedValue.VisibleGroup, ",") //可见范围(集团)"`
saveData.ReleDepart = v.OrgId //相关部门"`
var postList []string
var manList []string
for _, vp := range v.PostPeople {
postId := strconv.FormatInt(vp.PostId, 10)
if publicmethod.IsInTrue[string](postId, postList) == false {
postList = append(postList, postId)
}
for _, vm := range vp.PeopleList {
if publicmethod.IsInTrue[string](vm, manList) == false {
manList = append(manList, vm)
}
}
}
saveData.DepartmentsPost = strings.Join(postList, ",") //相关岗位"`
saveData.Report = strings.Join(manList, ",") //上报人"`
overall.CONSTANT_DB_KPI.Create(&saveData)
for _, vps := range v.PostPeople {
syncSetinges.Add(1)
go DepartAboutPostTargetReport(dimensionId, saveData.Id, 0, 0, v.OrgId, vps.PostId, vps.PeopleList, 2, receivedValue.Type)
}
//关联部门岗位
if len(postList) > 0 {
syncSetinges.Add(1)
go EditTargetTableDimenAboutPostOfDepart(dimensionId, saveData.Id, 0, 0, v.OrgId, postList, 2, receivedValue.Type)
}
}
syncSetinges.Wait()
publicmethod.Result(0, orgPostManList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-13 13:40:21
@ 功能: 判断岗位指标是否存在
@ 参数
#targetTitle 指标名称
#Attribute 1定性考核2定量考核
#dimId 维度Key
#departId 部门ID
#postId 岗位ID
@ 返回值
#targetCont 岗位指标
#err 状态
@ 方法原型
#JudgePostTargetIsTrue(targetTitle string, Attribute int, dimId, departId, postId int64) (targetCont modelskpi.PostTarget, err error)
*/
func JudgePostTargetIsTrue(targetTitle string, Attribute int, dimId, departId, postId int64) (targetCont modelskpi.PostTarget, err error) {
err = overall.CONSTANT_DB_KPI.Model(targetCont).Select("`id`").Where("`rele_depart` = ? AND `dimension` = ? AND `type` = ? AND `title` = ? AND FIND_IN_SET(?,`departments_post`)", departId, dimId, Attribute, targetTitle, postId).First(&targetCont).Error
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-01-13 11:10:25
@ 功能: 处理行政组织与岗位和相关提报人关系
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func HandlingRelations(orgPostPeo []OtherPostTargetCont) (orgHandPost []OrgPostPeople) {
fmt.Printf("orgPostPeo---->%v\n", orgPostPeo)
if len(orgPostPeo) < 1 {
return
}
for _, ov := range orgPostPeo { //循环提交得行政组织与岗位和提报人
isInAry := false
for hi, hv := range orgHandPost { //循环已经处理得数据
if ov.OrgId == hv.OrgId { //判断此行政组织是否已经存在
isInAry = true
for hvpi, hvp := range hv.PostPeople { //循环已经处理后的岗位及提报人
if hvp.PostId == ov.PostId { //判断岗位数据是否已经处理过类是得岗位
var manList []string
for _, hvpm := range hvp.PeopleList { //已经添加了的岗位提报人
manList = append(manList, hvpm)
}
for _, ovm := range ov.Operator {
if publicmethod.IsInTrue[string](ovm, manList) == false {
manList = append(manList, ovm)
}
} //新提报人
orgHandPost[hi].PostPeople[hvpi].PeopleList = manList
} else { //此行政组织为处理过相关岗位则新增
var postAndMan PostPeopleList
postAndMan.PostId = ov.PostId
postAndMan.PeopleList = ov.Operator
orgHandPost[hi].PostPeople = append(orgHandPost[hi].PostPeople, postAndMan)
}
}
}
}
//次行政组织不存在,执行新增操作
if isInAry == false {
var orgHandPostCont OrgPostPeople
orgHandPostCont.OrgId = ov.OrgId
var postAndMan PostPeopleList
postAndMan.PostId = ov.PostId
postAndMan.PeopleList = ov.Operator
orgHandPostCont.PostPeople = append(orgHandPostCont.PostPeople, postAndMan)
orgHandPost = append(orgHandPost, orgHandPostCont)
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-12 13:17:05
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) NewAddPostTargetCont(c *gin.Context) {
var receivedValue NewAddPostTargetInfo
c.ShouldBindJSON(&receivedValue)
if receivedValue.Title == "" {
publicmethod.Result(1, receivedValue, c, "请输入指标名称!")
return
}
if receivedValue.Type == 0 {
receivedValue.Type = 2
}
if receivedValue.ScoringMethod == 0 {
receivedValue.ScoringMethod = 1
}
var postIdList []string
var reportList []string
if len(receivedValue.OtherPostTarget) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择该指标归属岗位!")
return
} else {
for _, v := range receivedValue.OtherPostTarget {
if v.OrgId == 0 || v.PostId == 0 || len(v.Operator) < 1 {
publicmethod.Result(1, receivedValue, c, "关联岗位与提报人员信息不全!请补充")
return
}
postIdStr := strconv.FormatInt(v.PostId, 10)
if publicmethod.IsInTrue[string](postIdStr, postIdList) == false {
postIdList = append(postIdList, postIdStr)
}
if len(v.Operator) > 0 {
for _, ov := range v.Operator {
if publicmethod.IsInTrue[string](ov, reportList) == false {
reportList = append(reportList, ov)
}
}
}
}
}
if receivedValue.Dimension == "" {
publicmethod.Result(1, receivedValue, c, "请选择指标归属维度!")
return
}
if receivedValue.Unit == "" {
publicmethod.Result(1, receivedValue, c, "请输入该指标计算单位!")
return
}
if receivedValue.Cycle == 0 {
receivedValue.Cycle = 1
}
if receivedValue.CycleAttr == 0 {
receivedValue.CycleAttr = 1
}
var saveData modelskpi.PostTarget
saveData.Title = receivedValue.Title //标题"`
saveData.Type = receivedValue.Type //1:定性考核;2:定量考核"`
saveData.State = 1 //状态(1:启用;2:禁用;3:删除)"`
saveData.Time = time.Now().Unix() //创建时间"`
saveData.Share = 2 //1:共用;2:私用"`
dimensionId, _ := strconv.ParseInt(receivedValue.Dimension, 10, 64)
saveData.Dimension = dimensionId //维度"`
saveData.Key = publicmethod.GetUUid(1) //UUID"`
saveData.Unit = receivedValue.Unit //单位"`
saveData.Cycle = receivedValue.Cycle //1:班;2:天;3:周;4:月;5:季度;6:年"`
saveData.Cycleattr = receivedValue.CycleAttr //辅助计数"`
saveData.ScoringMethod = receivedValue.ScoringMethod //计分方式(1:自动;2:手动)"`
saveData.VisibleRange = strings.Join(receivedValue.VisibleRange, ",") //可见范围"`
saveData.VisibleGroup = strings.Join(receivedValue.VisibleGroup, ",") //可见范围(集团)"`
saveData.DepartmentsPost = strings.Join(postIdList, ",")
saveData.Report = strings.Join(reportList, ",")
err := overall.CONSTANT_DB_KPI.Create(&saveData).Error
if err != nil {
publicmethod.Result(104, receivedValue, c)
return
}
for _, v := range receivedValue.OtherPostTarget {
syncSeting.Add(1)
go DepartTargetAboutPost(dimensionId, saveData.Id, 0, 0, v.OrgId, v.PostId, 1, receivedValue.Type, 2)
var peopleListId []int64
for _, pv := range v.Operator {
peoId, _ := strconv.ParseInt(pv, 10, 64)
if publicmethod.IsInTrue[int64](peoId, peopleListId) == false {
peopleListId = append(peopleListId, peoId)
}
syncSeting.Add(1)
go BeparTargetAboutPostMan(dimensionId, saveData.Id, 0, 0, v.OrgId, v.PostId, peoId, 2, receivedValue.Type, 1)
}
if len(peopleListId) > 0 {
syncSeting.Add(1)
go ClearTargetDepartAboutPostMan(dimensionId, saveData.Id, 0, 0, v.OrgId, v.PostId, peopleListId, 2, receivedValue.Type, 1)
}
}
syncSeting.Wait()
publicmethod.Result(0, err, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-09 13:35:06
@ 功能: 部门指标关联岗位
@ 参数
#dimensionId 维度
#targetId 指标
#targetSunId 栏目
#targetBylaws 细则
#departmentId 部门
#postId 岗位
#typeInt 类型1指标2子目标3细则
#class 属性1定性考核2定量考核
#level 级别1部门级2岗位级
@ 返回值
#
@ 方法原型
#func DepartTargetAboutPost(dimensionId, targetId, targetSunId, targetBylaws, departmentId, postId int64, typeInt, class, level int)
*/
func DepartTargetAboutPost(dimensionId, targetId, targetSunId, targetBylaws, departmentId, postId int64, typeInt, class, level int) {
defer syncSeting.Done()
if typeInt == 0 {
typeInt = 1
}
if class == 0 {
class = 1
}
if level == 0 {
level = 1
}
var targetDeparCont modelskpi.TargetDepartment
err := targetDeparCont.GetCont(map[string]interface{}{"`level`": level, "`type`": typeInt, "`target_id`": targetId, "`target_sun_id`": targetSunId, "`target_bylaws`": targetBylaws, "`department_id`": departmentId, "`post_id`": postId})
if err != nil {
//不存在新增
var tarDepartCont modelskpi.TargetDepartment
tarDepartCont.Dimension = dimensionId
tarDepartCont.TargetId = targetId //指标ID"`
tarDepartCont.TargetSunId = targetSunId //子目标"`
tarDepartCont.TargetBylaws = targetBylaws //指标细则"`
tarDepartCont.Type = typeInt //类型(1:指标;2:子目标;3:细则)"`
tarDepartCont.DepartmentId = departmentId //部门ID"`
tarDepartCont.PostId = postId //岗位ID"`
tarDepartCont.State = 1 //状态(1:启用;2:禁用;3:删除)"`
tarDepartCont.Time = time.Now().Unix() //写入时间"`
tarDepartCont.Class = class //1:定性考核;2:定量考核"`
tarDepartCont.Level = level //级别(1:部门级;2:岗位级)"`
overall.CONSTANT_DB_KPI.Create(&tarDepartCont)
} else {
//存在修改状态
if targetDeparCont.State != 1 {
otherSaveData := publicmethod.MapOut[string]()
otherSaveData["`state`"] = 2
otherSaveData["`time`"] = time.Now().Unix()
var editTarDepartCont modelskpi.TargetDepartment
editTarDepartCont.EiteCont(map[string]interface{}{"`id`": targetDeparCont.Id}, otherSaveData)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-09 14:09:41
@ 功能: 处理部门指标关联岗位提报人关系
@ 参数
#
@ 返回值
#dimensionId 维度
#targetId 指标
#targetSunId 栏目
#targetBylaws 细则
#departmentId 部门
#postId 岗位
#typeInt 类型1公司级2部门级
#manKey 用户Key
#class 属性1定性考核2定量考核
#typeLevel 级别1指标2子目标3细则
@ 方法原型
#func BeparTargetAboutPostMan(dimensionId, targetId, targetSunId, targetBylaws, departmentId, postId, manKey int64, typeInt, class, typeLevel int)
*/
func BeparTargetAboutPostMan(dimensionId, targetId, targetSunId, targetBylaws, departmentId, postId, manKey int64, typeInt, class, typeLevel int) {
defer syncSeting.Done()
if typeInt == 0 {
typeInt = 1
}
if class == 0 {
class = 1
}
if typeLevel == 0 {
typeLevel = 1
}
var manCont modelshr.PersonArchives
manCont.GetCont(map[string]interface{}{"`key`": manKey}, "`maindeparment`")
var targetReporCont modelskpi.TargetReport
err := targetReporCont.GetCont(map[string]interface{}{"`type_level`": typeLevel, "`type`": typeInt, "`target_id`": targetId, "`target_sun_id`": targetSunId, "`target_bylaws`": targetBylaws, "`department_id`": departmentId, "`post_id`": postId, "man_key": manKey})
if err != nil {
//不存在,新增
var tarReportContAdd modelskpi.TargetReport
tarReportContAdd.Dimension = dimensionId //维度
tarReportContAdd.TargetId = targetId //指标ID"`
tarReportContAdd.TargetSunId = targetSunId //子目标"`
tarReportContAdd.TargetBylaws = targetBylaws //指标细则"`
tarReportContAdd.DepartmentId = departmentId //部门ID"`
tarReportContAdd.PostId = postId //岗位ID"`
tarReportContAdd.Type = typeInt //类型(1:公司级;2:部门级)"`
tarReportContAdd.State = 1 //状态(1:启用;2:禁用;3:删除)"`
tarReportContAdd.ReportPerson = manKey //上报人"`
tarReportContAdd.ManDepartment = manCont.MainDeparment //提报人所在部门"`
tarReportContAdd.Time = time.Now().Unix() //写入时间"`
tarReportContAdd.Class = class //1:定性考核;2:定量考核"`
tarReportContAdd.Level = typeLevel //1:指标;2:子目标;3:细则
overall.CONSTANT_DB_KPI.Create(&tarReportContAdd)
} else {
//存在编辑
if targetReporCont.State != 1 {
otherSaveData := publicmethod.MapOut[string]()
otherSaveData["`state`"] = 2
if manCont.MainDeparment != targetReporCont.ManDepartment {
otherSaveData["`man_department`"] = manCont.MainDeparment
}
otherSaveData["`time`"] = time.Now().Unix()
var editTarReportCont modelskpi.TargetReport
editTarReportCont.EiteCont(map[string]interface{}{"`id`": targetReporCont.Id}, otherSaveData)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-09 13:55:26
@ 功能: 清理部门指标不在关联的岗位提报人
@ 参数
#dimensionId 维度
#targetId 指标
#targetSunId 栏目
#targetBylaws 细则
#departmentId 部门
#postId 岗位
#manKey 岗位
#typeInt 级别1部门级2岗位级
#class 属性1定性考核2定量考核
#level 类型1指标2子目标3细则
@ 返回值
#
@ 方法原型
#ClearTargetDepartAboutPostMan(dimensionId, targetId, targetSunId, targetBylaws, departmentId, postId int64, manKey []int64, typeInt, class, level int)
*/
func ClearTargetDepartAboutPostMan(dimensionId, targetId, targetSunId, targetBylaws, departmentId, postId int64, manKey []int64, typeInt, class, level int) {
defer syncSeting.Done()
if typeInt == 0 {
typeInt = 1
}
if class == 0 {
class = 1
}
if level == 0 {
level = 1
}
//将不属于该指标细则的部门至禁用
otherSaveData := publicmethod.MapOut[string]()
otherSaveData["`state`"] = 2
otherSaveData["`time`"] = time.Now().Unix()
overall.CONSTANT_DB_KPI.Model(&modelskpi.TargetReport{}).Where("`target_id` = ? AND `target_sun_id` = ? AND `target_bylaws` = ? AND `department_id` = ? AND `post_id` = ? AND `type` = ? AND `type_level` = ?", targetId, targetSunId, targetBylaws, departmentId, postId, typeInt, level).Not(map[string]interface{}{"man_key": manKey}).Updates(&otherSaveData)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-02-12 16:08:11
@ 功能: 编辑岗位指标(新版)
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) NewEditPostTarget(c *gin.Context) {
var receivedValue NewEditPostTargetCont
c.ShouldBindJSON(&receivedValue)
if receivedValue.Id == "" {
publicmethod.Result(1, receivedValue, c, "参数错误!请重新提交!")
return
}
if receivedValue.Title == "" {
publicmethod.Result(1, receivedValue, c, "请输入指标名称!")
return
}
if receivedValue.Type == 0 {
receivedValue.Type = 2
}
if receivedValue.ScoringMethod == 0 {
receivedValue.ScoringMethod = 1
}
var postIdList []string
var reportList []string
if len(receivedValue.OtherPostTarget) < 1 {
publicmethod.Result(1, receivedValue, c, "请选择该指标归属岗位!")
return
} else {
for _, v := range receivedValue.OtherPostTarget {
if v.OrgId == 0 || v.PostId == 0 || len(v.Operator) < 1 {
publicmethod.Result(1, receivedValue, c, "关联岗位与提报人员信息不全!请补充")
return
}
postIdStr := strconv.FormatInt(v.PostId, 10)
if publicmethod.IsInTrue[string](postIdStr, postIdList) == false {
postIdList = append(postIdList, postIdStr)
}
if len(v.Operator) > 0 {
for _, ov := range v.Operator {
if publicmethod.IsInTrue[string](ov, reportList) == false {
reportList = append(reportList, ov)
}
}
}
}
}
if receivedValue.Dimension == "" {
publicmethod.Result(1, receivedValue, c, "请选择指标归属维度!")
return
}
if receivedValue.Unit == "" {
publicmethod.Result(1, receivedValue, c, "请输入该指标计算单位!")
return
}
if receivedValue.Cycle == 0 {
receivedValue.Cycle = 1
}
if receivedValue.CycleAttr == 0 {
receivedValue.CycleAttr = 1
}
wheAry := publicmethod.MapOut[string]()
wheAry["id"] = receivedValue.Id
var postTargetInfo modelskpi.PostTarget
err := postTargetInfo.GetCont(wheAry)
if err != nil {
publicmethod.Result(107, receivedValue, c)
return
}
editCont := publicmethod.MapOut[string]()
if receivedValue.Title != "" && postTargetInfo.Title != receivedValue.Title {
editCont["`title`"] = receivedValue.Title
}
if receivedValue.Type != postTargetInfo.Type {
editCont["`type`"] = receivedValue.Type
}
postStr := strings.Join(postIdList, ",")
if postStr != postTargetInfo.DepartmentsPost {
editCont["`departments_post`"] = postStr
}
reportStr := strings.Join(reportList, ",")
if reportStr != postTargetInfo.Report {
editCont["`report`"] = reportStr
}
if receivedValue.Dimension != "" {
dimensionInt, _ := strconv.ParseInt(receivedValue.Dimension, 10, 64)
if dimensionInt != postTargetInfo.Dimension {
editCont["`dimension`"] = dimensionInt
}
}
if receivedValue.Unit != "" && postTargetInfo.Unit != receivedValue.Unit {
editCont["`unit`"] = receivedValue.Unit
}
if receivedValue.Cycle != postTargetInfo.Cycle {
editCont["`cycle`"] = receivedValue.Cycle
}
if receivedValue.CycleAttr != postTargetInfo.Cycleattr {
editCont["`cycleattr`"] = receivedValue.CycleAttr
}
if len(editCont) > 0 {
editCont["`time`"] = time.Now().Unix()
editCont["`state`"] = 1
var editCont modelskpi.PostTarget
err = editCont.EiteCont(wheAry, editCont)
}
for _, v := range receivedValue.OtherPostTarget {
syncSeting.Add(1)
go DepartTargetAboutPost(postTargetInfo.Dimension, postTargetInfo.Id, 0, 0, v.OrgId, v.PostId, 1, postTargetInfo.Type, 2)
var peopleListId []int64
for _, pv := range v.Operator {
peoId, _ := strconv.ParseInt(pv, 10, 64)
if publicmethod.IsInTrue[int64](peoId, peopleListId) == false {
peopleListId = append(peopleListId, peoId)
}
syncSeting.Add(1)
go BeparTargetAboutPostMan(postTargetInfo.Dimension, postTargetInfo.Id, 0, 0, v.OrgId, v.PostId, peoId, 2, postTargetInfo.Type, 1)
}
if len(peopleListId) > 0 {
syncSeting.Add(1)
go ClearTargetDepartAboutPostMan(postTargetInfo.Dimension, postTargetInfo.Id, 0, 0, v.OrgId, v.PostId, peopleListId, 2, postTargetInfo.Type, 1)
}
}
syncSeting.Wait()
publicmethod.Result(0, err, c)
}

273
api/version1/postseting/postpc/type.go

@ -66,7 +66,7 @@ type postAboutTarget struct {
publicmethod.PublicId
publicmethod.PublicName //指标名称
Content string `json:"content"` //指标描述
StandardScore int64 `json:"standardscore"` //标准分
StandardScore float64 `json:"standardscore"` //标准分
Unit string `json:"unit"` //单位
IsTrue int `json:"istrue"` //是否允许修改 1:不允许;2:允许
State int `json:"state"` //状态 1:启用;2:禁用;3:观察
@ -131,13 +131,13 @@ type schemeDetailedStructure struct {
// 岗位考核方案列表
type postSchemeList struct {
publicmethod.PagesTurn
VersionNumber string `json:"versionnumber"` //版本号
CompanyId string `json:"companyid"` //归属公司"`
DepartmentId string `json:"departmentid"` //归属部门"`
OrgId string `json:"orgid"` //归属行政组织"`
PostId string `json:"postid"` //`归属岗位"`
Year int `json:"year"` //`年度"`
State int `json:"state"` //`状态(1:启用;2:禁用;3:删除)"`
VersionNumber string `json:"versionnumber"` //版本号
CompanyId string `json:"companyid"` //归属公司"`
DepartmentId string `json:"departmentid"` //归属部门"`
OrgId string `json:"orgid"` //归属行政组织"`
PostId []string `json:"postid"` //`归属岗位"`
Year string `json:"year"` //`年度"`
State int `json:"state"` //`状态(1:启用;2:禁用;3:删除)"`
}
// 输出岗位考核方案列表
@ -148,6 +148,7 @@ type sendPostSchemeList struct {
DepartmentName string `json:"departmentname"` //归属部门"`
OrgName string `json:"orgname"` //归属行政组织"`
PostName string `json:"postname"` //`归属岗位"`
TimeStr string `json:"timestr"` //`时间"`
}
// 输出考核方案详细内容
@ -159,30 +160,39 @@ type outShemeVersionCont struct {
// 岗位单一指标详细内容输出
type getPostOneTarget struct {
modelskpi.PostTarget
RelevantPostsMan []postPeople `json:"relevantpostsman"` //相关岗位
DimensionStr string `json:"dimensionstr" `
OtherPostTarget []OtherPostTargetCont `json:"otherposttarget"` //其他部门相关岗位提报
DimensionStr string `json:"dimensionstr" `
PostName string `json:"postname"`
}
// 岗位单一指标关联岗位及提报人
type postPeople struct {
publicmethod.PublicId
publicmethod.PublicName
OrgId string `json:"orgid"` //行政组织Id
Operator []string `json:"operator"` //考核执行人
}
// 添加岗位指标
type addPostTarget struct {
Title string `json:"title"` //名称
Type int `json:"type"` //1:定性考核;2:定量考核
ScoringMethod int `json:"scoringMethod"` //计分方式(1:自动;2:手动)
RelevantDepartments string `json:"relevantDepartments"` //相关部门
Dimension string `json:"dimension"` //维度
Unit string `json:"unit"` //单位
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
CycleAttr int `json:"cycleattr"` //辅助计数
VisibleRange []string `json:"visibleRange"` //可见范围
VisibleGroup []string `json:"visibleGroup"` //可见范围(集团)
RelevantPostsMan []postPeople `json:"relevantpostsman"` //相关岗位与提报人
Title string `json:"title"` //名称
Type int `json:"type"` //1:定性考核;2:定量考核
ScoringMethod int `json:"scoringMethod"` //计分方式(1:自动;2:手动)
RelevantDepartments string `json:"relevantDepartments"` //相关部门
Dimension string `json:"dimension"` //维度
Unit string `json:"unit"` //单位
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
CycleAttr int `json:"cycleattr"` //辅助计数
VisibleRange []string `json:"visibleRange"` //可见范围
VisibleGroup []string `json:"visibleGroup"` //可见范围(集团)
RelevantPostsMan []postPeople `json:"relevantpostsman"` //相关岗位与提报人
OtherPostTarget []OtherPostTargetCont `json:"otherposttarget"` //其他部门相关岗位提报
}
type OtherPostTargetCont struct {
OrgId int64 `json:"orgid"` //行政组织Id
PostId int64 `json:"postid"` //岗位Id
Operator []string `json:"operator"` //考核执行人
}
// 编辑岗位指标
@ -202,19 +212,21 @@ type addPostContTarget struct {
// 岗位指标细则
type postContList struct {
Title string `json:"title"` //考核内容
ReferenceScore string `json:"referencescore"` //考核标准
Unit string `json:"unit"` //单位
Class int `json:"class"` //1:减少;2:增加;3:无属性,现场确认加或减
Inspect []string `json:"inspect"` //检查方式(1:现场检查;2:资料检查;3:事件触发)
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
CycleAttr int `json:"cycleattr"` //辅助计数
Frequency int `json:"frequency"` //频次
Evidence string `json:"evidence"` //客观证据
Explain string `json:"explain"` //备注说明
RelevantPostsMan []postPeople `json:"relevantpostsman"` //相关岗位与提报人
PunishMode int `json:"punishmode"` //处罚方式 1:扣分;2:现金处罚;3:扣分加现金
CashStandard string `json:"cashstandard"` //现金标准
Title string `json:"title"` //考核内容
ReferenceScore string `json:"referencescore"` //考核标准
Unit string `json:"unit"` //单位
Class int `json:"class"` //1:减少;2:增加;3:无属性,现场确认加或减
Inspect []string `json:"inspect"` //检查方式(1:现场检查;2:资料检查;3:事件触发)
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
CycleAttr int `json:"cycleattr"` //辅助计数
Frequency int `json:"frequency"` //频次
Evidence string `json:"evidence"` //客观证据
Explain string `json:"explain"` //备注说明
RelevantPostsMan []postPeople `json:"relevantpostsman"` //相关岗位与提报人
PunishMode int `json:"punishmode"` //处罚方式 1:扣分;2:现金处罚;3:扣分加现金
CashStandard string `json:"cashstandard"` //现金标准
InspectItn []int `json:"inspectint"` //检查方式(1:现场检查;2:资料检查;3:事件触发)
PostManList []OrgPostCont `json:"postmanlist"` //关联岗位及提报人
}
// 查看岗位定性考核细则列表
@ -231,7 +243,7 @@ type lookPostTargetDeta struct {
// 输出岗位定性指标详细列表
type sendNaitonTargetDeiment struct {
modelskpi.PostTargetDetails
SonTargetTitle string `sontargettitle` //指标名称
SonTargetTitle string `json:"sontargettitle"` //指标名称
ReferenceScore string `json:"referencescore"` //考核标准
CashStandard string `json:"cashstandard"` //现金标准
}
@ -259,8 +271,9 @@ type idAndName struct {
type UserContList struct {
idAndName
Icon string `json:"icon"`
Number string `json:"number"`
Icon string `json:"icon"`
Number string `json:"number"`
IconImg string `json:"iconimg"`
}
// 岗位细则设定提报人关联
@ -281,3 +294,189 @@ type sonTargetAddDieastion struct {
publicmethod.PublicId
postContList
}
// 设定指标结算周期
type SetEvaluationObjectives struct {
Year int64 `json:"year"` //年度
// Group string `json:"group"` //集团
DepartMent string `json:"department"` //部门
PostId string `json:"postid"`
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //指标
Cycle int `json:"cycle"` //周期
CycleAdded []CycleAddedType `json:"cycleadded"`
}
// 周期列表
type CycleAddedType struct {
Id int64 `json:"id"`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
}
// 定量考核目标设定查询
type SelectQuantitativeConfig struct {
Title string `json:"title"` //指标标题
GroupId string `json:"groupid"`
DepartmentID string `json:"departmentid"`
OrgID string `json:"orgid"` //行政组织
PostId string `json:"postid"` //岗位
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //指标
Type int `json:"type"` //1、年度;2、季度;3、月度
Year int `json:"year"` //年度
Class int `json:"class"` //季度与月度辅助值
State int `json:"state"` //状态(1、启用;2、禁用;3、删除)
UserKey []string `json:"userkey"` //人员
}
// 输出
type OutQuantitativeConfig struct {
modelskpi.QuanPostConfigTarget
GroupTitle string `json:"grouptitle"` //公司
DepartmentTitle string `json:"departmenttitle"` //部门
PostTitle string `json:"posttitle"` //岗位
DimensionTitle string `json:"dimensiontitle"` //维度
DimensionId string `json:"dimensionid"` //维度
TargetTitle string `json:"targettitle"` //指标
DetailedTargetTitle string `json:"detailedtargenttitle"` //指标明细
IdStr string `json:"idstr"` //字符型Id
}
// 修改考核目标设定
type EiteQuantConfig struct {
Id string `json:"id"`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
}
// 删除考核目标设定
type DelQuantConfig struct {
Id string `json:"id"`
}
// 获取岗位指标列表
type targetFormPost struct {
publicmethod.PublicId //岗位Id
State int `json:"state"` //0:所有;1:定性;2:定量
}
// 删除指标设定的目标值
type newDelTargetConfig struct {
OrgID string `json:"orgid"` //行政组织
PostId string `json:"postid"` //岗位
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //指标
Type int `json:"type"` //1、年度;2、季度;3、月度
Year int `json:"year"` //年度
}
type OutQuanPeopleConfig struct {
modelskpi.QuanPeopleConfigTarget
GroupTitle string `json:"grouptitle"` //公司
DepartmentTitle string `json:"departmenttitle"` //部门
PostTitle string `json:"posttitle"` //岗位
DimensionTitle string `json:"dimensiontitle"` //维度
DimensionId string `json:"dimensionid"` //维度
TargetTitle string `json:"targettitle"` //指标
DetailedTargetTitle string `json:"detailedtargenttitle"` //指标明细
IdStr string `json:"idstr"` //字符型Id
UserName string `json:"username"` //姓名
MyKey string `json:"mykey"` //
}
// 设定人员指标结算周期
type SetEvaluationObjectivMan struct {
UserKey []string `json:"userkey"` //人员key列表
Year int64 `json:"year"` //年度
// Group string `json:"group"` //集团
DepartMent string `json:"department"` //部门
PostId string `json:"postid"`
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //指标
Cycle int `json:"cycle"` //周期
CycleAdded []CycleAddedType `json:"cycleadded"`
}
type SelectQuantitativeConfigMan struct {
Title string `json:"title"` //指标标题
GroupId string `json:"groupid"`
DepartmentID string `json:"departmentid"`
OrgID string `json:"orgid"` //行政组织
PostId string `json:"postid"` //岗位
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //指标
Type int `json:"type"` //1、年度;2、季度;3、月度
Year int `json:"year"` //年度
Class int `json:"class"` //季度与月度辅助值
State int `json:"state"` //状态(1、启用;2、禁用;3、删除)
UserKey string `json:"userkey"` //人员
}
// 删除人员指标设定的目标值
type newDelTargetManConfig struct {
OrgID string `json:"orgid"` //行政组织
PostId string `json:"postid"` //岗位
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //指标
Type int `json:"type"` //1、年度;2、季度;3、月度
Year int `json:"year"` //年度
UserKey string `json:"userkey"` //人员
}
// 获取岗位指标列表
type GetPostTargetContList struct {
publicmethod.PagesTurn
PostIdList []int64 `json:"postidlist"` //岗位列表
Title string `json:"title"` //指标名称
Dimension string `json:"dimension"` //维度
Attribute int `json:"attribute"` //属性:1:定性;2:定量
}
// 岗位考核输出
type outPostTargetList struct {
modelskpi.PostTarget
DimensionName string `json:"dimensionname"` //维度
DepartmentName string `json:"departmentname"` //部门
PostAry []idAndName `json:"postary"` //岗位
ReportAry []UserContList `json:"reportary"` //提报人
}
// 添加岗位指标新版
type NewAddPostTargetInfo struct {
Title string `json:"title"` //名称
Dimension string `json:"dimension"` //维度
Type int `json:"type"` //1:定性考核;2:定量考核
Unit string `json:"unit"` //单位
ScoringMethod int `json:"scoringMethod"` //计分方式(1:自动;2:手动)
Cycle int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年
CycleAttr int `json:"cycleattr"` //辅助计数
OtherPostTarget []OtherPostTargetCont `json:"otherposttarget"` //其他部门相关岗位提报
VisibleRange []string `json:"visibleRange"` //可见范围
VisibleGroup []string `json:"visibleGroup"` //可见范围(集团)
}
// 编辑岗位指标(新版)
type NewEditPostTargetCont struct {
publicmethod.PublicId
NewAddPostTargetInfo
}
// 岗位方案指标列表
type PostSchemeDiem struct {
publicmethod.PublicId //id
publicmethod.PublicName //名称
Sort int `json:"sort"` //排序
}
type PostSchemeTar struct {
publicmethod.PublicId //id
publicmethod.PublicName //名称
Content string `json:"content"` //说明
Score float64 `json:"score"` //分数
State int `json:"state"` //状态:1:启用;2:禁用;3:观察
Type int `json:"type"` //1、定性指标;2、定量指标
Dimension string `json:"dimension"`
}

749
api/version1/postseting/postweb/appflowlog.go

@ -0,0 +1,749 @@
package postweb
import (
"encoding/json"
"fmt"
"key_performance_indicators/middleware/wechatapp/wechatcallback"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"github.com/gin-gonic/gin"
)
// 岗位审批记录
func (a *ApiMethod) GetPostFlowLog(c *gin.Context) {
var receivedValue postFlowLog
c.ShouldBindJSON(&receivedValue)
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 20
}
//获取登录人信息
context, _ := publicmethod.LoginMyCont(c)
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.AppNewFlowLog{})
switch context.IsAdmin {
case 2:
case 3:
case 4:
default:
gormDb = gormDb.Where("FIND_IN_SET(?,`participants`)", context.Key)
gormDb = gormDb.Where("`department_id` = ?", context.MainDeparment)
}
var flowLogList []modelskpi.AppNewFlowLog
if receivedValue.Title != "" {
gormDb = gormDb.Where("`pt_title` LIKE ? OR `pst_title` LIKE ? OR `ptd_title` LIKE ?", "%"+receivedValue.Title+"%", "%"+receivedValue.Title+"%", "%"+receivedValue.Title+"%")
}
if receivedValue.OrgId != 0 {
gormDb = gormDb.Where("`org_id` = ?", receivedValue.OrgId)
}
if receivedValue.PostId != 0 {
gormDb = gormDb.Where("`post_id` = ?", receivedValue.PostId)
}
if receivedValue.DayTime != "" {
startTime, endTime := publicmethod.GetAppointMonthStarAndEndTime(receivedValue.DayTime)
gormDb = gormDb.Where("`start_time` BETWEEN ? AND ?", startTime, endTime)
}
if receivedValue.Years != 0 {
if receivedValue.Month != 0 {
timeDay := fmt.Sprintf("%v-%v-01", receivedValue.Years, receivedValue.Month)
if receivedValue.Month <= 9 {
timeDay = fmt.Sprintf("%v-0%v-01", receivedValue.Years, receivedValue.Month)
}
startTime, endTime := publicmethod.GetAppointMonthStarAndEndTimeEs(timeDay)
gormDb = gormDb.Where("start_time BETWEEN ? AND ?", startTime, endTime)
} else {
startTime, _ := publicmethod.DateToTimeStamp(fmt.Sprintf("%v-01-01 00:00:00", receivedValue.Years))
endTime, _ := publicmethod.DateToTimeStamp(fmt.Sprintf("%v-12-31 23:59:59", receivedValue.Years))
gormDb = gormDb.Where("start_time BETWEEN ? AND ?", startTime, endTime)
}
}
if receivedValue.State != 0 {
gormDb = gormDb.Where("`state` = ?", receivedValue.State)
} else {
gormDb = gormDb.Where("`state` BETWEEN ? AND ?", 1, 5)
}
if receivedValue.ApprovalState == 1 {
gormDb = gormDb.Where("NOT FIND_IN_SET(?,`next_executor`)", context.Key)
}
if receivedValue.ApprovalState == 2 {
gormDb = gormDb.Where("FIND_IN_SET(?,`next_executor`)", context.Key)
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Order("`state` ASC").Order("`id` DESC").Find(&flowLogList).Error
var total int64
totalErr := gormDb.Count(&total).Error
if totalErr != nil {
total = 0
}
if err != nil || len(flowLogList) < 1 {
publicmethod.Result(107, err, c)
return
}
var sendData []SendPostFlowLog
for _, v := range flowLogList {
var sendCont SendPostFlowLog
sendCont.OrderId = strconv.FormatInt(v.OrderId, 10) //订单Key
titleStr := v.PtTitle
if v.PstTitle != "" {
titleStr = v.PstTitle
}
if v.PtdTitle != "" {
titleStr = v.PtdTitle
}
sendCont.Title = titleStr //标题
switch v.State {
case 1:
sendCont.Result = "起草" //审批结果
sendCont.Statetype = 1 //审批状态
case 2:
sendCont.Result = "审批中"
sendCont.Statetype = 0
case 3:
sendCont.Result = "驳回"
sendCont.Statetype = 4
case 4:
sendCont.Result = "归档"
sendCont.Statetype = 3
case 5:
sendCont.Result = "废弃"
sendCont.Statetype = 3
case 6:
sendCont.Result = "删除"
sendCont.Statetype = 3
default:
sendCont.Result = "审批中"
sendCont.Statetype = 0
}
cyclesVal := v.PtCycle
cycleAttresVal := v.PtCycleattr
if v.PtdCycles != 0 {
cyclesVal = v.PtdCycles
}
if v.PtdCycleAttres != 0 {
cycleAttresVal = v.PtdCycleAttres
}
sendCont.Cycles = cyclesVal //1:班;2:天;3:周;4:月;5:季度;6:年"`
sendCont.CycleAttres = cycleAttresVal //辅助计数"`
sendCont.Year = v.Year //年分"`
sendCont.Quarter = v.Quarter //季度"`
sendCont.Month = v.Month //月"`
sendCont.Week = v.Week //周"`
if v.NextStep == 0 {
sendCont.Node = "归档"
} else {
//获取流程节点
_, flowCont, _ := wechatcallback.GetOneNodeCont(v.WorkFlow, v.Step)
sendCont.Node = flowCont.NodeName //当前节点
}
sendCont.Class = v.Class
sendCont.MonthDays = publicmethod.UnixTimeToDay(v.StartTime, 22) //提报日期
sendData = append(sendData, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendData)), sendData, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-27 16:43:56
@ 功能:获取审批流详情
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) LookFlowMap(c *gin.Context) {
var receivedValue LookFlowInfo
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Class == 0 {
receivedValue.Class = 1
}
//获取登录人信息
context, _ := publicmethod.LoginMyCont(c)
//获取审批流相关内容
var getFlowCont GetFlowLogCont
syncSeting.Add(1)
go getFlowCont.ReadMainFlowLog(receivedValue.Id) //获取审批主表
if receivedValue.Class == 1 {
//定性
syncSeting.Add(1)
go getFlowCont.ReadNatureFlowLog(receivedValue.Id) //获取审批主表
syncSeting.Wait()
mainFlowLog, natureFlowList, _ := getFlowCont.readDataLock() //读取线程通道数据
var sendDataCont SendPostDingXing
sendDataCont.OrderId = strconv.FormatInt(mainFlowLog.OrderId, 10)
sendDataCont.Title = GetNatureFlowTitle(mainFlowLog.Executor, mainFlowLog.DepartmentId, mainFlowLog.PostId, mainFlowLog.PersonLiable, mainFlowLog.Target, mainFlowLog.HappenTime, 1)
sendDataCont.FlowMapAll, _, _ = wechatcallback.GetOneNodeCont(mainFlowLog.WorkFlow, mainFlowLog.Step)
for _, v := range natureFlowList {
sendDataCont.List = append(sendDataCont.List, AnalysisDingXing(v))
}
sendDataCont.Isset = 1
var zhiXingRen []string
//判断当前人是否要审批
if mainFlowLog.NextStep > 1 {
if mainFlowLog.NextExecutor != "" {
err = json.Unmarshal([]byte(mainFlowLog.NextExecutor), &zhiXingRen)
if err == nil {
dangQianRen := strconv.FormatInt(context.Key, 10)
if publicmethod.IsInTrue[string](dangQianRen, zhiXingRen) == true {
sendDataCont.Isset = 2
}
}
}
}
//获取步进值
var oacl modelskpi.OpenApprovalChangeLog
clickStep, stepErr := oacl.GetMAx(mainFlowLog.OrderId, zhiXingRen)
if stepErr != nil {
sendDataCont.Stepper = 1
} else {
sendDataCont.Stepper = clickStep + 1
}
if mainFlowLog.EnclosureFormat != "" {
json.Unmarshal([]byte(mainFlowLog.EnclosureFormat), &sendDataCont.Enclosure)
}
publicmethod.Result(0, sendDataCont, c) //输出
} else {
//定量
syncSeting.Add(1)
go getFlowCont.ReadMeterMainFlowLog(receivedValue.Id) //获取审批主表
syncSeting.Wait()
mainFlowLog, _, meterFlowList := getFlowCont.readDataLock() //读取线程通道数据
var sendDataCont SendPostDingLiang
sendDataCont.OrderId = strconv.FormatInt(mainFlowLog.OrderId, 10)
sendDataCont.Title = GetNatureFlowTitle(mainFlowLog.Executor, mainFlowLog.DepartmentId, mainFlowLog.PostId, mainFlowLog.PersonLiable, mainFlowLog.Target, mainFlowLog.HappenTime, 2)
sendDataCont.FlowMapAll, _, _ = wechatcallback.GetOneNodeCont(mainFlowLog.WorkFlow, mainFlowLog.Step)
sendDataCont.Isset = 1
//判断当前人是否要审批
var zhiXingRen []string
if mainFlowLog.NextStep > 1 {
if mainFlowLog.NextExecutor != "" {
err = json.Unmarshal([]byte(mainFlowLog.NextExecutor), &zhiXingRen)
if err == nil {
dangQianRen := strconv.FormatInt(context.Key, 10)
if publicmethod.IsInTrue[string](dangQianRen, zhiXingRen) == true {
sendDataCont.Isset = 2
}
}
}
}
//获取步进值
var oacl modelskpi.OpenApprovalChangeLog
clickStep, stepErr := oacl.GetMAx(mainFlowLog.OrderId, zhiXingRen)
if stepErr != nil {
sendDataCont.Stepper = 1
} else {
sendDataCont.Stepper = clickStep + 1
}
if mainFlowLog.EnclosureFormat != "" {
json.Unmarshal([]byte(mainFlowLog.EnclosureFormat), &sendDataCont.Enclosure)
}
for _, v := range meterFlowList {
sendDataCont.List = append(sendDataCont.List, AnalysisDingLiang(v))
}
publicmethod.Result(0, sendDataCont, c) //输出
}
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-28 14:37:27
@ 功能: 解析定量输出结构体
@ 参数
#
@ 返回值
#
*/
func AnalysisDingLiang(natureCont modelskpi.PostMeteringFlow) (sendData DingLiangList) {
//获取指标
var targetCont modelskpi.PostTarget
targetCont.GetCont(map[string]interface{}{"`id`": natureCont.Target}, "`title`")
sendData.Title = targetCont.Title
sendData.Target = targetCont.Title
sendData.Content = natureCont.Reason
//解析考核基准线
var jinZhunXian baseLineType
err := json.Unmarshal([]byte(natureCont.Baseline), &jinZhunXian)
if err == nil {
sendData.ZeroPrize = publicmethod.DecimalEs(jinZhunXian.Zeroprize, 2) //零奖值
sendData.AllPrize = publicmethod.DecimalEs(jinZhunXian.Allprize, 2) //全奖值
sendData.CappingVal = jinZhunXian.Capping //封顶值
}
var shemeCont modelskpi.QualitativeEvaluationScheme
err = shemeCont.GetCont(map[string]interface{}{"`id`": natureCont.ShemeId})
//获取指标分
var departDimPostWeight modelskpi.DepartDimePostWeight
where := publicmethod.MapOut[string]()
where["`orgid`"] = shemeCont.OrgId
where["`postid`"] = shemeCont.PostId
where["`dimension`"] = shemeCont.DimensionId
where["`hierarchy`"] = 1
where["`is_quote`"] = shemeCont.Source
where["`target`"] = shemeCont.TargetId
departDimPostWeight.GetCont(where, "`weight`")
sendData.Weight = departDimPostWeight.Weight / 100
sendData.Score = natureCont.Score
sendData.Achievement, sendData.Actual = GetAchieAndActual(natureCont.Score, departDimPostWeight.Weight, sendData.ZeroPrize, sendData.AllPrize, sendData.CappingVal)
fmt.Printf("jinZhunXian----->%v\n", jinZhunXian)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-28 15:09:33
@ 功能: 计算达成率及得分
@ 参数
#score 实际分
#weight 指标权重
#zeroprize 零奖值
#allprize 全奖值
#cappingval 封顶值
@ 返回值
#achievement 达成率
#actual 得分
@ 函数原型
#GetAchieAndActual(score, weight, zeroprize, allprize, cappingval float64) (achievement, actual float64)
*/
func GetAchieAndActual(score, weight, zeroprize, allprize, cappingval float64) (achievement, actual float64) {
cappingval = cappingval / 100
// fmt.Printf("1--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
if zeroprize == 0 && allprize == 0 { //当全奖值与零奖值都为空时
if score != 0 { //判断实际值是否不为0
actual = weight
achievement = 100
}
// fmt.Printf("2--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
} else {
if allprize > zeroprize { //当全奖值大于零奖值时 正向计算
if score <= zeroprize { //实际数值小于零奖值时达成率与得分都为零
actual = 0
achievement = 0
// fmt.Printf("3--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
} else {
chuShu := score - zeroprize
beiChushu := allprize - zeroprize
if beiChushu != 0 { //判断除数不能为零
daChengLv := chuShu / beiChushu
achievement = publicmethod.DecimalEs(daChengLv, 3)
// fmt.Printf("4-1-->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>daChengLv:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, daChengLv)
if daChengLv*100 >= cappingval { //达成率大于等于封顶值
if cappingval > 0 {
deFen := weight * (cappingval / 100)
actual = publicmethod.DecimalEs(deFen, 2)
} else {
actual = weight
}
} else {
deFen := weight * daChengLv
actual = publicmethod.DecimalEs(deFen, 2)
}
// fmt.Printf("4--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
} else {
actual = 0
achievement = 0
// fmt.Printf("5--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
}
}
} else { //如果全奖值小于零奖值 执行一下操作
if score >= zeroprize { //实际结算值大于零奖值 那么达成率和实际得分都是0
actual = 0
achievement = 0
// fmt.Printf("6--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
} else {
chuShu := score - zeroprize
beiChushu := allprize - zeroprize
if beiChushu != 0 { //判断除数不能为零
daChengLv := chuShu / beiChushu
achievement = publicmethod.DecimalEs(daChengLv, 3)
if daChengLv < 0 {
actual = 0
achievement = 0
// fmt.Printf("7--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
} else {
if daChengLv*100 >= cappingval { //达成率大于等于封顶值
if cappingval > 0 {
deFen := weight * (cappingval / 100)
actual = publicmethod.DecimalEs(deFen, 2)
} else {
actual = weight
}
} else {
deFen := weight * daChengLv
actual = publicmethod.DecimalEs(deFen, 2)
}
// fmt.Printf("8--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
}
} else {
actual = 0
achievement = 0
// fmt.Printf("9--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
}
}
}
}
// fmt.Printf("10--->score:%v------>weight:%v------>zeroprize:%v------>allprize:%v------>cappingval:%v------>achievement:%v------>actual:%v\n", score, weight, zeroprize, allprize, cappingval, achievement, actual)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-28 11:06:45
@ 功能: 解析定性输出结构体
@ 参数
#natureCont 定性考核数据
@ 返回值
#sendData 展示数据
*/
func AnalysisDingXing(natureCont modelskpi.PostNatureFlow) (sendData DingXingList) {
var dimCont modelskpi.DutyClass
dimCont.GetCont(map[string]interface{}{"`id`": natureCont.Dimension}, "`title`")
//获取指标
var targetCont modelskpi.PostTarget
targetCont.GetCont(map[string]interface{}{"`id`": natureCont.Target}, "`title`")
//获取指标子栏目
var sunTargetCont modelskpi.PostSonTarget
sunTargetCont.GetCont(map[string]interface{}{"`id`": natureCont.SonTarget}, "`title`")
var detailsCont modelskpi.PostTargetDetails
detailsCont.GetCont(map[string]interface{}{"`id`": natureCont.Detailed}, "`title`", "`min_score`", "`max_score`", "`maxmoney`", "`minmoney`", "`punishmode`", "`company`")
sendData.Dimension = dimCont.Title //维度
sendData.Target = targetCont.Title //考核指标
sendData.Targetsun = sunTargetCont.Title //考核项目
sendData.Detailedtargent = detailsCont.Title //考核内容
var scoreStr string
if detailsCont.MinScore != 0 {
if detailsCont.MaxScore != 0 {
scoreStr = fmt.Sprintf("%v-%v%v", publicmethod.DecimalEs(float64(detailsCont.MinScore)/100, 2), publicmethod.DecimalEs(float64(detailsCont.MaxScore/100), 2), detailsCont.Company)
} else {
scoreStr = fmt.Sprintf("%v%v", publicmethod.DecimalEs(float64(detailsCont.MinScore/100), 2), detailsCont.Company)
}
} else {
if detailsCont.MaxScore != 0 {
scoreStr = fmt.Sprintf("%v%v", publicmethod.DecimalEs(float64(detailsCont.MaxScore/100), 2), detailsCont.Company)
}
}
sendData.Standard = scoreStr //考核标准(分)
var moneyStr string
if detailsCont.Minmoney != 0 {
if detailsCont.Maxmoney != 0 {
moneyStr = fmt.Sprintf("%v-%v元", publicmethod.DecimalEs(float64(detailsCont.Minmoney/100), 2), publicmethod.DecimalEs(float64(detailsCont.Maxmoney/100), 2))
} else {
moneyStr = fmt.Sprintf("%v元", publicmethod.DecimalEs(float64(detailsCont.Minmoney/100), 2))
}
} else {
if detailsCont.Maxmoney != 0 {
moneyStr = fmt.Sprintf("%v元", publicmethod.DecimalEs(float64(detailsCont.Maxmoney/100), 2))
}
}
sendData.StandardMoney = moneyStr //考核标准(钱)
addOrDec := "扣除"
if natureCont.AddOrDecrease == 1 {
addOrDec = "奖励"
}
sendData.Lanmuname = addOrDec //奖励OR扣除
sendData.ScoreVal = publicmethod.DecimalEs(natureCont.Score/100, 2) * float64(natureCont.HappenCount) //奖励或扣除的分数
sendData.MoneyVal = publicmethod.DecimalEs(natureCont.Money/100, 2) * float64(natureCont.HappenCountMoney) //奖励或扣除的钱
sendData.Reason = natureCont.Reason //考核原因
sendData.Unit = detailsCont.Company
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-28 10:44:57
@ 功能: 获取定性审批标题
@ 参数
#executor 执行人
#orgId 被执行人行政组织
#postId 被执行人岗位
#personLiable 被执行人KEY
#target 指标
#class 1定性,2:定量
@ 返回值
#
*/
func GetNatureFlowTitle(executor, orgId, postId, personLiable, target, happenTime int64, class int) (title string) {
//获取执行人
var exeUser modelshr.PersonArchives
exeUser.GetCont(map[string]interface{}{"`key`": executor}, "`name`")
//获取被执行人信息
var perUserCont modelshr.PersonArchives
perUserCont.GetCont(map[string]interface{}{"`key`": personLiable}, "`name`")
var orgCont modelshr.AdministrativeOrganization
orgCont.GetCont(map[string]interface{}{"`id`": orgId}, "`name`")
var postCont modelshr.Position
postCont.GetCont(map[string]interface{}{"`id`": postId}, "`name`")
//获取指标
var targetCont modelskpi.PostTarget
targetCont.GetCont(map[string]interface{}{"`id`": target}, "`title`")
timeStr := publicmethod.UnixTimeToDay(happenTime, 14)
if class != 1 {
timeStr = publicmethod.UnixTimeToDay(happenTime, 15)
}
title = fmt.Sprintf("%v提交\n%v%v%v\n%v考核数据", exeUser.Name, orgCont.Name, postCont.Name, perUserCont.Name, timeStr)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-27 17:03:13
@ 功能: 读取审批流主表
@ 参数
#orderId 订单ID
@ 返回值
#
*/
func (g *GetFlowLogCont) ReadMainFlowLog(orderId string) {
g.mutext.Lock()
defer g.mutext.Unlock()
var flowLogCont modelskpi.PostWorkflowOrders
err := flowLogCont.GetCont(map[string]interface{}{`order_id`: orderId})
if err == nil {
g.FlowCont = flowLogCont
}
syncSeting.Done()
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-28 08:10:31
@ 功能: 定性考核数据
@ 参数
#orderId 订单ID
@ 返回值
#
*/
func (g *GetFlowLogCont) ReadNatureFlowLog(orderId string) {
g.mutext.Lock()
defer g.mutext.Unlock()
var flowLogCont []modelskpi.PostNatureFlow
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.PostNatureFlow{}).Where("`order_id` = ?", orderId).Find(&flowLogCont).Error
if err == nil {
g.NatureFlow = flowLogCont
}
syncSeting.Done()
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-28 08:10:31
@ 功能: 定量考核数据
@ 参数
#orderId 订单ID
@ 返回值
#
*/
func (g *GetFlowLogCont) ReadMeterMainFlowLog(orderId string) {
g.mutext.Lock()
defer g.mutext.Unlock()
var flowLogCont []modelskpi.PostMeteringFlow
err := overall.CONSTANT_DB_KPI.Model(&modelskpi.PostMeteringFlow{}).Where("`order_id` = ?", orderId).Find(&flowLogCont).Error
if err == nil {
g.MeterFlow = flowLogCont
}
syncSeting.Done()
}
/*
*
@ 作者: 秦东
@ 时间: 2022-10-27 16:43:56
@ 功能:获取审批流详情-->整改措施专用岗位
@ 参数
#
@ 返回值
#
*/
func (a *ApiMethod) LookFlowMapCorra(c *gin.Context) {
var receivedValue LookFlowInfoCorra
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, receivedValue, c)
return
}
if receivedValue.Class == 0 {
receivedValue.Class = 1
}
//获取登录人信息
context, _ := publicmethod.LoginMyCont(c)
//获取审批流相关内容
var getFlowCont GetFlowLogCont
syncSeting.Add(1)
go getFlowCont.ReadMainFlowLog(receivedValue.Id) //获取审批主表
if receivedValue.Class == 1 {
//定性
syncSeting.Add(1)
go getFlowCont.ReadNatureFlowLog(receivedValue.Id) //获取审批主表
syncSeting.Wait()
mainFlowLog, natureFlowList, _ := getFlowCont.readDataLock() //读取线程通道数据
var sendDataCont SendPostDingXing
sendDataCont.OrderId = strconv.FormatInt(mainFlowLog.OrderId, 10)
sendDataCont.Title = GetNatureFlowTitle(mainFlowLog.Executor, mainFlowLog.DepartmentId, mainFlowLog.PostId, mainFlowLog.PersonLiable, mainFlowLog.Target, mainFlowLog.HappenTime, 1)
sendDataCont.FlowMapAll, _, _ = wechatcallback.GetOneNodeCont(mainFlowLog.WorkFlow, mainFlowLog.Step)
for _, v := range natureFlowList {
sendDataCont.List = append(sendDataCont.List, AnalysisDingXing(v))
}
sendDataCont.Isset = 1
var zhiXingRen []string
//判断当前人是否要审批
if mainFlowLog.NextStep > 1 {
if mainFlowLog.NextExecutor != "" {
err = json.Unmarshal([]byte(mainFlowLog.NextExecutor), &zhiXingRen)
if err == nil {
dangQianRen := strconv.FormatInt(context.Key, 10)
if publicmethod.IsInTrue[string](dangQianRen, zhiXingRen) == true {
// sendDataCont.Isset = 2
}
}
}
}
//获取挂号信息
//判断此号码是否可以使用
var setUpRegister modelskpi.Register
err := setUpRegister.GetCont(map[string]interface{}{"`number`": receivedValue.Num}, "`state`", "`id`")
if err != nil {
sendDataCont.Isset = 2
}
if setUpRegister.State != 1 {
sendDataCont.Isset = 2
}
//获取步进值
var oacl modelskpi.OpenApprovalChangeLog
clickStep, stepErr := oacl.GetMAx(mainFlowLog.OrderId, zhiXingRen)
if stepErr != nil {
sendDataCont.Stepper = 1
} else {
sendDataCont.Stepper = clickStep + 1
}
if mainFlowLog.EnclosureFormat != "" {
json.Unmarshal([]byte(mainFlowLog.EnclosureFormat), &sendDataCont.Enclosure)
}
publicmethod.Result(0, sendDataCont, c) //输出
} else {
//定量
syncSeting.Add(1)
go getFlowCont.ReadMeterMainFlowLog(receivedValue.Id) //获取审批主表
syncSeting.Wait()
mainFlowLog, _, meterFlowList := getFlowCont.readDataLock() //读取线程通道数据
var sendDataCont SendPostDingLiang
sendDataCont.OrderId = strconv.FormatInt(mainFlowLog.OrderId, 10)
sendDataCont.Title = GetNatureFlowTitle(mainFlowLog.Executor, mainFlowLog.DepartmentId, mainFlowLog.PostId, mainFlowLog.PersonLiable, mainFlowLog.Target, mainFlowLog.HappenTime, 2)
sendDataCont.FlowMapAll, _, _ = wechatcallback.GetOneNodeCont(mainFlowLog.WorkFlow, mainFlowLog.Step)
sendDataCont.Isset = 1
//判断当前人是否要审批
var zhiXingRen []string
if mainFlowLog.NextStep > 1 {
if mainFlowLog.NextExecutor != "" {
err = json.Unmarshal([]byte(mainFlowLog.NextExecutor), &zhiXingRen)
if err == nil {
dangQianRen := strconv.FormatInt(context.Key, 10)
if publicmethod.IsInTrue[string](dangQianRen, zhiXingRen) == true {
// sendDataCont.Isset = 2
}
}
}
}
//获取挂号信息
//判断此号码是否可以使用
var setUpRegister modelskpi.Register
err := setUpRegister.GetCont(map[string]interface{}{"`number`": receivedValue.Num}, "`state`", "`id`")
if err != nil {
sendDataCont.Isset = 2
}
if setUpRegister.State != 1 {
sendDataCont.Isset = 2
}
//获取步进值
var oacl modelskpi.OpenApprovalChangeLog
clickStep, stepErr := oacl.GetMAx(mainFlowLog.OrderId, zhiXingRen)
if stepErr != nil {
sendDataCont.Stepper = 1
} else {
sendDataCont.Stepper = clickStep + 1
}
if mainFlowLog.EnclosureFormat != "" {
json.Unmarshal([]byte(mainFlowLog.EnclosureFormat), &sendDataCont.Enclosure)
}
for _, v := range meterFlowList {
sendDataCont.List = append(sendDataCont.List, AnalysisDingLiang(v))
}
publicmethod.Result(0, sendDataCont, c) //输出
}
}

30
api/version1/postseting/postweb/flowmap.go

@ -0,0 +1,30 @@
package postweb
import (
"key_performance_indicators/api/version1/flowchart"
"key_performance_indicators/overall/publicmethod"
"github.com/gin-gonic/gin"
)
// 生产流程图
func (a *ApiMethod) GetFlowMap(c *gin.Context) {
var receivedValue CreateFlow
c.ShouldBindJSON(&receivedValue)
//获取登录人信息
context, _ := publicmethod.LoginMyCont(c)
//生成工作流
wechatOpenId := context.Wechat
if context.WorkWechat != "" {
wechatOpenId = context.WorkWechat
}
var reviewFlowCont flowchart.ReviewFlow
reviewFlowCont.Id = receivedValue.Id
reviewFlowCont.IsCorrection = receivedValue.IsCorrection
reviewFlowCont.PlusReduction = receivedValue.PlusReduction
reviewFlowCont.PeopleList = append(reviewFlowCont.PeopleList, receivedValue.PersonLiable)
flowMap, _ := flowchart.SetUpWorkFlow(wechatOpenId, context.MainDeparment, reviewFlowCont, 1)
publicmethod.Result(0, flowMap, c)
}

259
api/version1/postseting/postweb/postration.go

@ -3,11 +3,14 @@ package postweb
import (
"encoding/json"
"fmt"
"key_performance_indicators/api/version1/flowchart"
"key_performance_indicators/middleware/wechatapp/wechatsendmsg"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
@ -194,24 +197,97 @@ func (a *ApiMethod) SubmitRationPostCont(c *gin.Context) {
publicmethod.Result(107, err, c)
return
}
//获取指标单位
var targetUnit modelskpi.PostTarget
overall.CONSTANT_DB_KPI.Model(&modelskpi.PostTarget{}).Select("unit").Where(map[string]interface{}{"`id`": postShemeCont.TargetId}).First(&targetUnit)
//获取被考核人基本信息
var userCont modelshr.PersonArchives
err = userCont.GetCont(map[string]interface{}{"`key`": receivedValue.PersonLiable}, "`company`", "`maindeparment`", "`admin_org`", "`position`")
err = userCont.GetCont(map[string]interface{}{"`key`": receivedValue.PersonLiable}, "`company`", "`maindeparment`", "`admin_org`", "`position`", "`wechat`", "`work_wechat`", "`key`")
if err != nil {
publicmethod.Result(107, err, c)
return
}
yearVal := publicmethod.ComputingTime(currentTime, 1)
quarter := publicmethod.ComputingTime(currentTime, 2) //月"`
timecopy := publicmethod.ComputingTime(currentTime, 3) //月"`
week := publicmethod.ComputingTime(currentTime, 4) //月"`
//判断考核周期内时候已经提交过
var oldPostMeterFlowCont modelskpi.PostMeteringFlow
oldWhe := publicmethod.MapOut[string]()
oldWhe["`sheme_id`"] = receivedValue.Id
oldWhe["`person_liable`"] = userCont.Key
oldWhe["`org_id`"] = userCont.AdminOrg
oldWhe["`post_id`"] = userCont.Position
oldWhe["`year`"] = yearVal
oldWhe["`quarter`"] = quarter
oldWhe["`month`"] = timecopy
oldWhe["`week`"] = week
err = oldPostMeterFlowCont.GetCont(oldWhe, "`id`")
if err == nil {
publicmethod.Result(1, err, c, "您已经提报过该数据!请不要重复提报!")
return
}
//获取登录人信息
context, _ := publicmethod.LoginMyCont(c)
uuId := publicmethod.GetUUid(1)
//生成工作流
wechatOpenId := context.Wechat
if context.WorkWechat != "" {
wechatOpenId = context.WorkWechat
}
var reviewFlowCont flowchart.ReviewFlow
reviewFlowCont.Id = receivedValue.Id
reviewFlowCont.IsCorrection = 1
reviewFlowCont.PlusReduction = 1
reviewFlowCont.PeopleList = append(reviewFlowCont.PeopleList, receivedValue.PersonLiable)
flowMap, _ := flowchart.SetUpWorkFlow(wechatOpenId, context.MainDeparment, reviewFlowCont, 1)
var flowParticipants []string //流程参与人
userKeyStr := strconv.FormatInt(context.Key, 10)
flowParticipants = append(flowParticipants, userKeyStr)
var sendUserList []string
var sendTitle string
var operatorKey []string
//获取下一个节点审批人
for _, v := range flowMap {
if v.Step == 2 {
sendTitle = v.NodeName
for _, vu := range v.UserList {
// fmt.Printf("vu------------>%v\n", vu)
if publicmethod.IsInTrue[string](vu.Wechat, sendUserList) == false {
sendUserList = append(sendUserList, vu.Wechat)
}
if publicmethod.IsInTrue[string](vu.Id, operatorKey) == false {
operatorKey = append(operatorKey, vu.Id)
}
if publicmethod.IsInTrue[string](vu.Id, flowParticipants) == false {
flowParticipants = append(flowParticipants, vu.Id)
}
}
}
}
addTime := time.Now().Unix()
//流程列表
var flowCont modelskpi.PostWorkflowOrders
flowCont.OrderId = uuId //审批单ID"`
flowCont.Step = 1 //当前执行到第几步"`
flowCont.NextStep = 2 //下一步执行哪个步骤"`
flowCont.WorkFlow = "" //工作流(审批json字符串)"`
flowCont.OrderId = uuId //审批单ID"`
flowCont.Step = 1 //当前执行到第几步"`
flowCont.NextStep = 2 //下一步执行哪个步骤"`
flowCont.NextExecutor = strings.Join(operatorKey, ",")
sumStep := len(flowMap)
if sumStep-1 > 0 {
sumStep = sumStep - 1
} else {
sumStep = 1
}
flowCont.CountStep = sumStep
flowMapJson, _ := json.Marshal(flowMap)
flowCont.WorkFlow = string(flowMapJson) //工作流(审批json字符串)"`
flowCont.CompanyId = userCont.Company //公司"`
flowCont.DepartmentId = userCont.MainDeparment //部门"`
flowCont.OrgId = userCont.AdminOrg //行政组织"`
@ -223,16 +299,24 @@ func (a *ApiMethod) SubmitRationPostCont(c *gin.Context) {
flowCont.Detailed = postShemeCont.DetailsId //指标细则"`
flowCont.Executor = context.Key //执行人"`
flowCont.ExecutorDepartment = context.MainDeparment //执行人部门"`
flowCont.State = 3 //流程状态 1:草稿;2:驳回;3:审批中;4:归档;5:废弃;6:删除"`
flowCont.StartTime = time.Now().Unix() //流程开始时间"`
flowCont.Time = time.Now().Unix() //时间"`
flowCont.State = 2 //流程状态 1:草稿;2:审批中;3:驳回;4:归档;5:废弃;6:删除"`
flowCont.StartTime = addTime //流程开始时间"`
flowCont.Time = addTime //时间"`
flowCont.Participants = strings.Join(flowParticipants, ",")
flowCont.Year = yearVal //年"`
flowCont.Quarter = quarter //季度"`
flowCont.Month = timecopy //月"`
flowCont.Week = week //周"`
flowCont.PersonLiable = userCont.Key
flowCont.HappenTime = currentTime //发生时间"`
if len(receivedValue.Enclosure) > 0 {
jsonFileList, _ := json.Marshal(receivedValue.Enclosure)
flowCont.EnclosureFormat = string(jsonFileList) //附件"`
}
yearVal := publicmethod.ComputingTime(currentTime, 1)
timecopy := publicmethod.ComputingTime(currentTime, 3) //月"`
var baseLine baseLineType
//获取指标的全奖、零奖、封顶值
baseLine.Allprize, baseLine.Zeroprize, baseLine.Capping = GetPostTagetRewardSeting(postShemeCont.CompanyId, postShemeCont.OrgId, postShemeCont.PostId, postShemeCont.DimensionId, postShemeCont.TargetId, postShemeCont.DetailsId, yearVal, timecopy)
@ -246,26 +330,26 @@ func (a *ApiMethod) SubmitRationPostCont(c *gin.Context) {
//定量考核流水
var postMeterFlow modelskpi.PostMeteringFlow
postMeterFlow.OrderId = uuId // 审批单ID"`
postMeterFlow.ShemeId = postShemeCont.Id // 方案ID"`
postMeterFlow.ShemeVersion = postShemeCont.VersionNumber //方案版本编号"`
postMeterFlow.Dimension = postShemeCont.DimensionId //维度"`
postMeterFlow.Target = postShemeCont.TargetId //指标"`
postMeterFlow.Score = receivedValue.Score * 100 //分值(*100保存)"`
postMeterFlow.Reason = receivedValue.Reason //这样操作的原因"`
postMeterFlow.Year = yearVal //年"`
postMeterFlow.Quarter = publicmethod.ComputingTime(currentTime, 2) //季度"`
postMeterFlow.Month = publicmethod.ComputingTime(currentTime, 3) //月"`
postMeterFlow.Week = publicmethod.ComputingTime(currentTime, 4) //周"`
postMeterFlow.PersonLiable = userCont.Key //责任人"`
postMeterFlow.CompanyId = userCont.Company //公司"`
postMeterFlow.DepartmentId = userCont.MainDeparment //部门"`
postMeterFlow.OrgId = userCont.AdminOrg //行政组织"`
postMeterFlow.PostId = userCont.Position //岗位"`
postMeterFlow.Executor = context.Key //执行人"`
postMeterFlow.ExecutorDepartment = context.MainDeparment //执行人部门"`
postMeterFlow.HappenTime = currentTime //发生时间"`
postMeterFlow.Time = time.Now().Unix() //时间"`
postMeterFlow.OrderId = uuId // 审批单ID"`
postMeterFlow.ShemeId = postShemeCont.Id // 方案ID"`
postMeterFlow.ShemeVersion = postShemeCont.VersionNumber //方案版本编号"`
postMeterFlow.Dimension = postShemeCont.DimensionId //维度"`
postMeterFlow.Target = postShemeCont.TargetId //指标"`
postMeterFlow.Score = receivedValue.Score * 100 //分值(*100保存)"`
postMeterFlow.Reason = receivedValue.Reason //这样操作的原因"`
postMeterFlow.Year = yearVal //年"`
postMeterFlow.Quarter = quarter //季度"`
postMeterFlow.Month = timecopy //月"`
postMeterFlow.Week = week //周"`
postMeterFlow.PersonLiable = userCont.Key //责任人"`
postMeterFlow.CompanyId = userCont.Company //公司"`
postMeterFlow.DepartmentId = userCont.MainDeparment //部门"`
postMeterFlow.OrgId = userCont.AdminOrg //行政组织"`
postMeterFlow.PostId = userCont.Position //岗位"`
postMeterFlow.Executor = context.Key //执行人"`
postMeterFlow.ExecutorDepartment = context.MainDeparment //执行人部门"`
postMeterFlow.HappenTime = currentTime //发生时间"`
postMeterFlow.Time = addTime //时间"`
baseLineJson, _ := json.Marshal(baseLine)
postMeterFlow.Baseline = string(baseLineJson) //基准线"`
@ -273,14 +357,127 @@ func (a *ApiMethod) SubmitRationPostCont(c *gin.Context) {
if receivedValue.ScoringMethod != 1 {
postMeterFlow.ScoringScore = receivedValue.ScoringScore * 100 //手动分
}
//开启事务提交
gormDbAffair := overall.CONSTANT_DB_KPI
gormDbAffair := overall.CONSTANT_DB_KPI.Begin()
passorErr := gormDbAffair.Create(&flowCont).Error
flowErr := gormDbAffair.Create(&postMeterFlow).Error
// openAppChangeErr := gormDbAffair.Create(&openAppChangeLog).Error
if passorErr == nil && flowErr == nil {
addErr := gormDbAffair.Commit().Error
publicmethod.Result(0, addErr, c)
// fmt.Printf("callData---2--->%v--------err--------->%v--------->%v\n", sendUserList, sendTitle, flowMap)
if len(sendUserList) > 0 {
//项下一个审批节点发送审批通知
//头部信息
var sourceText wechatsendmsg.SourceText
sourceText.IconUrl = "https://docu.hxgk.group/images/2022_01/3f7a1120a559e9bee3991b85eb34d103.png"
sourceText.Desc = fmt.Sprintf("恒信高科-%v", sendTitle)
sourceText.DescColor = 1
//引用文献
var quoteAreaInfo wechatsendmsg.QuoteAreaCont
quoteAreaInfo.Type = 0
quoteAreaInfo.Title = "数据详细"
quoteAreaInfo.QuoteText = fmt.Sprintf("数值:%v%v\n备注:%v", receivedValue.Score, targetUnit.Unit, receivedValue.Reason)
//按钮
var buttonList []wechatsendmsg.ButtonListCont
var buttonList1 wechatsendmsg.ButtonListCont
buttonList1.Text = "批准"
buttonList1.Style = 1
buttonList1.Key = fmt.Sprintf("KPI_post_%v_%v_%v", uuId, 1, 2)
buttonList = append(buttonList, buttonList1)
var buttonList2 wechatsendmsg.ButtonListCont
buttonList2.Text = "驳回"
buttonList2.Style = 3
buttonList2.Key = fmt.Sprintf("KPI_post_%v_%v_%v", uuId, 2, 2)
buttonList = append(buttonList, buttonList2)
//二级标题+文本列表
var twoTitleTextList []wechatsendmsg.HorizontalContentListInfo
//发送人
var horizontalContentLis3 wechatsendmsg.HorizontalContentListInfo
horizontalContentLis3.KeyName = "申请人"
horizontalContentLis3.Value = "点击查看"
horizontalContentLis3.Type = 3
horizontalContentLis3.Userid = wechatOpenId
twoTitleTextList = append(twoTitleTextList, horizontalContentLis3)
//被考核人
if userCont.Wechat != "" || userCont.WorkWechat != "" {
weChatStrs := userCont.Wechat
if userCont.WorkWechat != "" {
weChatStrs = userCont.WorkWechat
}
var twoTitleTextCont wechatsendmsg.HorizontalContentListInfo
twoTitleTextCont.KeyName = "被考核人:"
twoTitleTextCont.Value = "点击查看"
twoTitleTextCont.Type = 3
twoTitleTextCont.Userid = weChatStrs
twoTitleTextList = append(twoTitleTextList, twoTitleTextCont)
}
//卡片跳转地址
var cardActionContStr wechatsendmsg.CardActionCont
cardActionContStr.Type = 1
jumpUrl := fmt.Sprintf("%v/#/pages/approval/postdingliang?orderid=%v&class=%v", overall.CONSTANT_CONFIG.Appsetup.WebUrl, uuId, 2)
cardActionContStr.Url = jumpUrl
// cardActionContStr.Url = fmt.Sprintf("http://new.hxgk.group/#/quantitativeList?id=%v", uuId)
var sendButtionMsg wechatsendmsg.SendButtonInteractionSimplify
sendButtionMsg.Touser = strings.Join(sendUserList, "|")
// sendButtionMsg.Touser = "KaiXinGuo" //指定接收消息的成员,成员ID列表;特殊情况:指定为
sendButtionMsg.Msgtype = "template_card"
agentIdInt, _ := strconv.ParseInt(overall.CONSTANT_CONFIG.WechatKpi.Agentid, 10, 64)
sendButtionMsg.Agentid = agentIdInt
sendButtionMsg.EnableDuplicateCheck = 0
sendButtionMsg.DuplicateCheckInterval = 1800
sendButtionMsg.EnableIdTrans = 0
sendButtionMsg.TemplateCard.CardType = "button_interaction"
sendButtionMsg.TemplateCard.Source = sourceText
sendButtionMsg.TemplateCard.TaskId = fmt.Sprintf("KPI_%v", uuId)
sendButtionMsg.TemplateCard.MainTitle.Title = postShemeCont.Title
sendButtionMsg.TemplateCard.MainTitle.Desc = postShemeCont.Content
sendButtionMsg.TemplateCard.QuoteArea = quoteAreaInfo
// sendButtionMsg.TemplateCard.SubTitleText = fmt.Sprintf("")
sendButtionMsg.TemplateCard.ButtonList = buttonList
sendButtionMsg.TemplateCard.HorizontalContentList = twoTitleTextList
sendButtionMsg.TemplateCard.CardAction = cardActionContStr
// sendButtionMsg.SendMsg("kpi")
callData, err := sendButtionMsg.SendMsg("kpi")
if err == nil {
if callData.Errcode == 0 {
// var operatorIsTrueCont modelskpi.OperatorIsTrue
// operatorIsTrueCont.OrderId = uuId //订单ID"`
// operatorIsTrueCont.Step = 1 //审批到第几步"`
// operatorIsTrueCont.State = 1 //:状态:1:可操作;2:不可操作"`
// operatorIsTrueCont.Time = addTime //操作时间"`
// operatorIsTrueCont.Msgid = callData.Msgid //:消息id,用于撤回应用消息"`
// operatorIsTrueCont.ResponseCode = callData.ResponseCode //仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,24小时内有效,且只能使用一次"`
// operatorIsTrueCont.Stepper = 1
// overall.CONSTANT_DB_KPI.Create(&operatorIsTrueCont)
var openAppChangeLog modelskpi.OpenApprovalChangeLog
openAppChangeLog.Type = 2
openAppChangeLog.Title = "创建申请"
openAppChangeLog.Operator = context.Key
openAppChangeLog.OrderId = uuId // 审批单ID"`
openAppChangeLog.OperatorTime = addTime
openAppChangeLog.Step = 1
openAppChangeLog.OperatorType = 2
openAppChangeLog.Msgid = callData.Msgid //:消息id,用于撤回应用消息"`
openAppChangeLog.ResponseCode = callData.ResponseCode //仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,24小时内有效,且只能使用一次"`
openAppChangeLog.Stepper = 1
openAppChangeLog.ChangeIsTrue = 1 //是否可变更(1:可变更;2:不可变更)"`
openAppChangeLog.Eiteyime = addTime
openAppChangeLog.YesOrNo = 1
overall.CONSTANT_DB_KPI.Create(&openAppChangeLog)
}
}
// jsonstr, _ := json.Marshal(sendButtionMsg)
// fmt.Printf("callData------>%v--------err--------->%v--------->%v\n", callData, err, targetUnit)
}
} else {
addErr := gormDbAffair.Rollback().Error
publicmethod.Result(104, addErr, c)

1461
api/version1/postseting/postweb/posttarget.go

File diff suppressed because it is too large

172
api/version1/postseting/postweb/type.go

@ -3,12 +3,30 @@ package postweb
import (
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
type ApiMethod struct{}
var syncSeting = sync.WaitGroup{}
// 获取审批详情
type GetFlowLogCont struct {
FlowCont modelskpi.PostWorkflowOrders //审批工作流
NatureFlow []modelskpi.PostNatureFlow //岗位定性考核流水
MeterFlow []modelskpi.PostMeteringFlow //岗位定量考核流水
mutext sync.RWMutex
}
// 读审批记录详情文件锁数据
func (g *GetFlowLogCont) readDataLock() (modelskpi.PostWorkflowOrders, []modelskpi.PostNatureFlow, []modelskpi.PostMeteringFlow) {
g.mutext.RLock()
defer g.mutext.RUnlock()
return g.FlowCont, g.NatureFlow, g.MeterFlow
}
// 岗位考核WEB端入口
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
@ -25,16 +43,21 @@ type getPostManTargetList struct {
// 输出定性指标指定人考核项目列表
type outPostManTargetList struct {
getPostManTargetList
Title string `json:"title"`
AddReduce int `json:"addreduce"` //1:减少;2:增加;3:无属性,现场确认加或减
UserKey string `json:"userkey"`
DimensionId string `json:"dimensionid"` //维度
Title string `json:"title"`
AddReduce int `json:"addreduce"` //1:减少;2:增加;3:无属性,现场确认加或减
UserKey string `json:"userkey"`
DimensionId string `json:"dimensionid"` //维度
Extrapoints float64 `json:"extrapoints"` //已加多少分
Scorereduction float64 `json:"scorereduction"` //已减多少分
Deduction float64 `json:"deduction"` //已扣款多少元
Reward float64 `json:"reward"` //已奖励多少元
}
// 输出定量考核项目
type outPostRation struct {
publicmethod.PublicId
publicmethod.PublicName
ShemeId string `json:"shemeid"`
Title string `json:"title"`
UserKey string `json:"userkey"`
DimensionId string `json:"dimensionid"` //维度
}
@ -45,6 +68,7 @@ type getNatureDimeList struct {
UserKey string `json:"userkey"`
DimensionId string `json:"dimensionid"` //维度
TargetId string `json:"targetid"`
Sontargetid string `json:"sontargetid"`
}
// 输出定性考核细则内容
@ -57,6 +81,9 @@ type outNatureDimeCont struct {
ScoreStr string `json:"scorestr"` //基础考核标准
MoneyStr string `json:"moneystr"` //现金
UserKey string `json:"userkey"`
Unity string `json:"unity"` //单位
ScoreState int `json:"scorestate"` //1、定分;2、区间分;3、不定性分值
MoneyState int `json:"moneystate"` //1、定钱;2、区间钱;3、不定性钱
}
// 岗位定性考核细致获取数据
@ -75,13 +102,16 @@ type outNatureDimePostCont struct {
ScoreStr string `json:"scorestr"` //基础考核标准
MoneyStr string `json:"moneystr"` //现金
UserKey string `json:"userkey"`
ScoreState int `json:"scorestate"` //1、定分;2、区间分;3、不定性分值
MoneyState int `json:"moneystate"` //1、定分;2、区间分;3、不定性分值
}
// 个人岗位定性考核提交数据参数
type sendMyEvaluationData struct {
publicmethod.PublicId //考核项ID
UserKey string `json:"userkey"` //接受考核人key
Count int `json:"count"` //计数
Count int `json:"count"` //计数(分)
MoneyCount int `json:"moneycount"` //计数器(钱)
HappenTime string `json:"happentime"` //发生时间.
Reason string `json:"reason"` //操作原因
Rectification int `json:"rectification"` //是否需要整改 1、需要整改;2:无需整改
@ -169,3 +199,133 @@ type baseLineType struct {
TargetId string `json:"targetid"`
AllZeroCappingWeight
}
// 获取子栏目列表
type getSonTarList struct {
publicmethod.PublicId
OrgId string `orgid`
PostId string `postid`
}
// 生产流程图
type CreateFlow struct {
Id string `json:"id"` //考核项目ID
IsCorrection int `json:"iscorrection"` //是否整改
PlusReduction int `json:"plusreduction"` //加减分
PersonLiable string `json:"personLiable" ` //责任人
}
// 获得岗位定量考核详情
type GetPostQuanClass struct {
publicmethod.PublicId
OrgId string `json:"orgid"` //行政组织
PostId string `json:"postid"` //岗位
Time string `json:"time"` // 考核时间
}
// 输出岗位定量考核详情
type sendPostQuanCont struct {
Content string `json:"content"` //指标说明
CompletionRate string `json:"completionRate"` //达成率
ZeroPrize float64 `json:"zeroprize"` //零奖值
AllPrize float64 `json:"allprize"` //全奖值
CappingPrize float64 `json:"cappingprize"` //封顶值
Weight float64 `json:"weight"` //指标权重
ScoringMethod int `json:"scoringmethod"` //计分方式(1:自动;2:手动)
}
// 岗位审批记录
type postFlowLog struct {
publicmethod.PagesTurn
Title string `json:"title"` //指标名
OrgId int64 `json:"orgid"` //行政组织
PostId int64 `json:"postid"` //岗位
DayTime string `json:"daytime"` //时间
State int `json:"state"` //状态:0:全部;1:起草;2:审批中;3:通过;4:驳回
ApprovalState int `json:"approvalstate" ` //审批:0:全部;1:已处理;2:未处理
Years int `json:"years"` //年
Month int `json:"month"` //月
}
// 输出岗位审批记录表
type SendPostFlowLog struct {
OrderId string `json:"orderid"` //订单Key
Title string `json:"title"` //标题
Result string `json:"result"` //审批结果
Statetype int `json:"statetype"` //审批状态
Cycles int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年"`
CycleAttres int `json:"cycleattr"` //辅助计数"`
Year int64 `json:"year"` //年分"`
Quarter int64 `json:"quarter"` //季度"`
Month int64 `json:"month"` //月"`
Week int64 `json:"week"` //周"`
Days int64 `json:"days"` //天
Node string `json:"node"` //当前节点
MonthDays string `json:"monthdays"` //提报日期
Class int `json:"class"` //1、定性;2、定量
}
// 查看审批流详情
type LookFlowInfo struct {
publicmethod.PublicId
Class int `json:"class"` //属性1、定性;2、定量
}
// 输出岗位定性
type SendPostDingXing struct {
OrderId string `json:"orderid"` //订单编号
Title string `json:"title"` //标题
List []DingXingList `json:"list"`
FlowMapAll []publicmethod.FlowChartList `json:"flowmapall"` //流程图
Isset int `json:"isset"` //本人是否需要审批
Enclosure []publicmethod.EnclosureFormat `json:"enclosure"` //附件
Stepper int `json:"stepper"` //步进器
}
// 定性考核
type DingXingList struct {
Dimension string `json:"dimension"` //维度
Target string `json:"target"` //考核指标
Targetsun string `json:"targetsun"` //考核项目
Detailedtargent string `json:"detailedtargent"` //考核内容
Standard string `json:"standard"` //考核标准(分)
StandardMoney string `json:"standardmoney"` //考核标准(钱)
Lanmuname string `json:"lanmuname"` //奖励OR扣除
ScoreVal float64 `json:"scoreval"` //奖励或扣除的分数
MoneyVal float64 `json:"moneyval"` //奖励或扣除的钱
Reason string `json:"reason"` //考核原因
Unit string `json:"unit"` //单位
}
// 输出岗位定量
type SendPostDingLiang struct {
OrderId string `json:"orderid"` //订单编号
Title string `json:"title"` //标题
List []DingLiangList `json:"list"`
FlowMapAll []publicmethod.FlowChartList `json:"flowmapall"` //流程图
Isset int `json:"isset"` //本人是否需要审批
Enclosure []publicmethod.EnclosureFormat `json:"enclosure"` //附件
Stepper int `json:"stepper"` //步进器
}
// 岗位定量考核
type DingLiangList struct {
Title string `json:"title"` //指标
Target string `json:"target"` //考核指标
ZeroPrize float64 `json:"zeroprize"` //零奖值
AllPrize float64 `json:"allprize"` //全奖值
CappingVal float64 `json:"cappingval"` //封顶值
Weight float64 `json:"weight"` //权重分
Score float64 `json:"score"` //实际值
Achievement float64 `json:"achievement"` //达成率
Actual float64 `json:"actual"` //指标得分
Content string `json:"content"` //说明
Unit string `json:"unit"` //说明
}
// 查看审批流详情 岗位整改措施专用
type LookFlowInfoCorra struct {
publicmethod.PublicId
Class int `json:"class"` //属性1、定性;2、定量
Num string `jsonL:"num"` //整改识别
}

564
api/version1/statistics/newpc.go

@ -0,0 +1,564 @@
package statistics
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-08-04 09:18:31
@ 功能: 汇总方案定量指标详情历史记录(新版)
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SummaryPlanRecord(c *gin.Context) {
var requestData detailedResultsLog
err := c.ShouldBindJSON(&requestData)
if err != nil {
response.Result(101, err, "数据获取失败!", c)
return
}
if requestData.TargetId == "" {
response.Result(102, err, "参数错误!请属入指标", c)
return
}
if requestData.Department == "" {
response.Result(103, err, "参数错误!请属入部门", c)
return
}
if requestData.Year == 0 {
requestData.Year = publicmethod.ComputingTime(time.Now().Unix(), 1)
}
if requestData.Months < 1 {
requestData.Months = 1
}
if requestData.Months > 12 {
requestData.Months = 12
}
orgId, _ := strconv.ParseInt(requestData.Department, 10, 64)
monthInt := int64(requestData.Months)
//获取当前时间考核方案
targetScore, attribute, cycles := GetTargetPlanScore("", requestData.TargetId, orgId, requestData.Year, monthInt)
// fmt.Printf("targetScore:%v\nattribute:%v\ncycles:%v\n", targetScore, attribute, cycles)
var sendList []dingLiangKaoHe
if err != nil {
response.Result(101, err, "数据获取失败!", c)
return
}
switch cycles {
case 5: //季度度指标
if publicmethod.IsInTrue[int64](monthInt, []int64{3, 6, 9, 12}) {
var fengDingZhi float64 = 0
var lingJiang float64 = 0
var quanJiang float64 = 0
isTrue := true
var dingLiangScore float64 = 0
switch monthInt {
case 3:
for i := 1; i <= 3; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 3 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
case 6:
for i := 4; i <= 6; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 6 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
case 9:
for i := 7; i <= 9; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 9 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
case 12:
for i := 10; i <= 12; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 12 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
default:
}
var secondCont dingLiangKaoHe
secondCont.MtOrAt = 1 //手动还是自动
secondCont.Cont = "平均分" //说明
secondCont.Nature = 1
secondCont.Zeroprize = lingJiang
secondCont.Allprize = quanJiang
secondCont.Capping = fengDingZhi
if attribute == 3 {
secondCont.Score = targetScore
} else {
var daChengLv float64 = 0
var pingJunXiShu float64 = 0
for _, j := range sendList {
daChengLv = daChengLv + j.CompletionRateAll
pingJunXiShu++
}
if pingJunXiShu > 0 {
pingJunZhi := daChengLv / pingJunXiShu
secondCont.Score = publicmethod.DecimalEs(GetQuantifyScore(targetScore, pingJunZhi, fengDingZhi), 2)
secondCont.CompletionRate = publicmethod.DecimalEs(pingJunZhi, 2)
} else {
secondCont.Score = targetScore
}
if !isTrue {
secondCont.Score = dingLiangScore
}
}
sendList = append(sendList, secondCont)
} else {
sendList, _ = GetDingLiangLog(orgId, requestData.Year, monthInt, requestData.TargetId, "")
}
case 6: //年度指标
isTrue := true
var dingLiangScore float64 = 0
var fengDingZhi float64 = 0
var lingJiang float64 = 0
var quanJiang float64 = 0
for i := 1; i <= 12; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 12 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
var secondCont dingLiangKaoHe
secondCont.MtOrAt = 1 //手动还是自动
secondCont.Cont = "平均分" //说明
secondCont.Nature = 1
secondCont.Zeroprize = lingJiang
secondCont.Allprize = quanJiang
secondCont.Capping = fengDingZhi
if attribute == 3 {
secondCont.Score = targetScore
} else {
var daChengLv float64 = 0
var pingJunXiShu float64 = 0
for _, j := range sendList {
daChengLv = daChengLv + j.CompletionRateAll
pingJunXiShu++
}
if pingJunXiShu > 0 {
pingJunZhi := daChengLv / pingJunXiShu
secondCont.Score = publicmethod.DecimalEs(GetQuantifyScore(targetScore, pingJunZhi, fengDingZhi), 2)
secondCont.CompletionRate = publicmethod.DecimalEs(pingJunZhi, 2)
} else {
secondCont.Score = targetScore
}
if !isTrue {
secondCont.Score = dingLiangScore
}
}
sendList = append(sendList, secondCont)
case 7: //半年指标
isTrue := true
var dingLiangScore float64 = 0
var fengDingZhi float64 = 0
var lingJiang float64 = 0
var quanJiang float64 = 0
if publicmethod.IsInTrue[int64](monthInt, []int64{1, 2, 3, 4, 5, 6}) {
for i := 1; i <= 6; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 6 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
} else {
for i := 7; i <= 12; i++ {
sendListIng, _ := GetDingLiangLog(orgId, requestData.Year, int64(i), requestData.TargetId, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
if i == 12 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
lingJiang = v.Zeroprize
quanJiang = v.Allprize
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
}
var secondCont dingLiangKaoHe
secondCont.MtOrAt = 1 //手动还是自动
secondCont.Cont = "平均分" //说明
secondCont.Nature = 1
secondCont.Zeroprize = lingJiang
secondCont.Allprize = quanJiang
secondCont.Capping = fengDingZhi
if attribute == 3 {
secondCont.Score = targetScore
} else {
var daChengLv float64 = 0
var pingJunXiShu float64 = 0
for _, j := range sendList {
daChengLv = daChengLv + j.CompletionRateAll
pingJunXiShu++
}
if pingJunXiShu > 0 {
pingJunZhi := daChengLv / pingJunXiShu
secondCont.Score = publicmethod.DecimalEs(GetQuantifyScore(targetScore, pingJunZhi, fengDingZhi), 2)
secondCont.CompletionRate = publicmethod.DecimalEs(pingJunZhi, 2)
} else {
secondCont.Score = targetScore
}
if !isTrue {
secondCont.Score = dingLiangScore
}
}
sendList = append(sendList, secondCont)
default:
sendList, _ = GetDingLiangLog(orgId, requestData.Year, monthInt, requestData.TargetId, "")
// chushu := len(sendList)
// var dingLiangScore float64 = 0
// if chushu > 0 {
// isTrue := true
// for _, v := range sendList {
// dingLiangScore = dingLiangScore + v.Score
// if v.MtOrAt == 2 {
// dingLiangScore = v.Score
// isTrue = false
// }
// }
// if isTrue {
// dingLiangScore, _ = publicmethod.DecimalNew(dingLiangScore/float64(chushu), 2)
// statisCont.Score = dingLiangScore
// } else {
// statisCont.Score = dingLiangScore
// }
// } else {
// targetScore, _, _ := GetTargetPlanScore("", cv.Id, orgId, requestData.Year, monthInt)
// statisCont.Score = targetScore
// }
}
response.Result(0, sendList, "查询完成!", c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-08-05 08:47:01
@ 功能: 计算定量指标分值
@ 参数
#targetScore 指标分
#completionRate 达成率
#capping 封顶值
@ 返回值
#
@ 方法原型
#
*/
func GetQuantifyScore(targetScore, completionRate, capping float64) (score float64) {
// fmt.Printf("targetScore:---》%v\ncompletionRate:---》%v\ncapping:---》%v\n", targetScore, completionRate, capping)
if capping != 0 {
if completionRate >= capping {
score = targetScore * (capping / 100)
} else {
score = targetScore * (completionRate / 100)
}
} else {
score = targetScore * (completionRate / 100)
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-08-07 10:42:04
@ 功能: 方案得分明细(new)
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) NewSummaryDetails(c *gin.Context) {
var requestData detailedResults
err := c.ShouldBindJSON(&requestData)
if err != nil {
response.Result(101, err, "数据获取失败!", c)
return
}
if requestData.Department == "" {
response.Result(102, err, "参数错误!请属入部门", c)
return
}
if requestData.Year == 0 {
requestData.Year = publicmethod.ComputingTime(time.Now().Unix(), 1)
}
if requestData.Months < 1 {
requestData.Months = 1
}
if requestData.Months > 12 {
requestData.Months = 12
}
orgId, _ := strconv.ParseInt(requestData.Department, 10, 64)
planVersion, _ := publicmethod.GetPlanVresion(orgId, requestData.Year, int64(requestData.Months))
var planVersioInfo []AddDutyNewCont
json.Unmarshal([]byte(planVersion.Content), &planVersioInfo)
var lookStatistics []detailedResultsList
for _, v := range planVersioInfo { //维度
for _, cv := range v.Child { //指标
// if cv.Id == "120" {
var statisCont detailedResultsList
statisCont.DimensionId = v.Id //维度Id
statisCont.DimensionName = v.Name //维度名称
statisCont.DimensionWeight = int64(v.ZhiFraction) //维度权重
statisCont.TargetId = cv.Id //指标ID
statisCont.TargetName = cv.Name //指标名称
statisCont.TargetCont = cv.Content //指标名称
statisCont.Targetweight = cv.ReferenceScore //指标权重
statisCont.GroupId = strconv.FormatInt(planVersion.Group, 10) //集团Id
statisCont.Versio = planVersion.Key
var groupCont modelshr.AdministrativeOrganization
groupCont.GetCont(map[string]interface{}{"`id`": planVersion.Group}, "name")
statisCont.GroupName = groupCont.Name //集团名称
statisCont.DepartmentId = strconv.FormatInt(planVersion.Department, 10) //部门ID
var departCont modelshr.AdministrativeOrganization
departCont.GetCont(map[string]interface{}{"`id`": planVersion.Department}, "name")
statisCont.DepartmentName = departCont.Name //部门名称
var evalTargetCont modelskpi.EvaluationTarget //指标信息
if cv.Id != "" && cv.Id != "0" {
targetErr := evalTargetCont.GetCont(map[string]interface{}{"`et_id`": cv.Id}, "et_type")
if targetErr == nil {
monthInt := int64(requestData.Months)
if evalTargetCont.Type == 1 { //定性指标
statisCont.Score, statisCont.ExecutiveDepartment = DingXingScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{monthInt}, cv.Id)
} else { //定量指标
var sendList []dingLiangKaoHe
var dingLiangScore float64 = 0
switch cv.Cycles {
case 5: //季度指标
var fengDingZhi float64 = 0
isTrue := true
switch monthInt {
case 3:
for i := 1; i <= 3; i++ {
sendListIng, orgNameList := GetDingLiangLog(orgId, requestData.Year, int64(i), cv.Id, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
statisCont.ExecutiveDepartment = append(statisCont.ExecutiveDepartment, orgNameList...)
if i == 3 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
case 6:
for i := 4; i <= 6; i++ {
sendListIng, orgNameList := GetDingLiangLog(orgId, requestData.Year, int64(i), cv.Id, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
statisCont.ExecutiveDepartment = append(statisCont.ExecutiveDepartment, orgNameList...)
if i == 6 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
case 9:
for i := 7; i <= 9; i++ {
sendListIng, orgNameList := GetDingLiangLog(orgId, requestData.Year, int64(i), cv.Id, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
statisCont.ExecutiveDepartment = append(statisCont.ExecutiveDepartment, orgNameList...)
if i == 9 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
case 12:
for i := 10; i <= 12; i++ {
sendListIng, orgNameList := GetDingLiangLog(orgId, requestData.Year, int64(i), cv.Id, fmt.Sprintf("%v月份实际分值", i))
sendList = append(sendList, sendListIng...)
statisCont.ExecutiveDepartment = append(statisCont.ExecutiveDepartment, orgNameList...)
if i == 12 {
for _, v := range sendListIng {
fengDingZhi = v.Capping
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
}
}
default:
isTrue = true
}
if isTrue {
targetScore, attribute, _ := GetTargetPlanScore("", cv.Id, orgId, requestData.Year, monthInt)
if attribute == 3 {
statisCont.Score = targetScore
} else {
var daChengLv float64 = 0
var pingJunXiShu float64 = 0
for _, j := range sendList {
daChengLv = daChengLv + j.CompletionRateAll
pingJunXiShu++
}
if pingJunXiShu > 0 {
pingJunZhi := daChengLv / pingJunXiShu
statisCont.Score = publicmethod.DecimalEs(GetQuantifyScore(targetScore, pingJunZhi, fengDingZhi), 2)
} else {
statisCont.Score = targetScore
}
}
} else {
statisCont.Score = dingLiangScore
}
default:
sendList, statisCont.ExecutiveDepartment = GetDingLiangLog(orgId, requestData.Year, monthInt, cv.Id, "")
chushu := len(sendList)
if chushu > 0 {
isTrue := true
for _, v := range sendList {
dingLiangScore = dingLiangScore + v.Score
if v.MtOrAt == 2 {
dingLiangScore = v.Score
isTrue = false
}
}
if isTrue {
dingLiangScore, _ = publicmethod.DecimalNew(dingLiangScore/float64(chushu), 2)
statisCont.Score = dingLiangScore
} else {
statisCont.Score = dingLiangScore
}
} else {
targetScore, _, _ := GetTargetPlanScore("", cv.Id, orgId, requestData.Year, monthInt)
statisCont.Score = targetScore
}
}
}
}
}
statisCont.Type = evalTargetCont.Type //1:定性;2:定量
statisCont.Unit = cv.Unit //单位
statisCont.Cycle = cv.Cycles //周期
statisCont.Cycleattr = cv.CycleAttres //辅助参数
lookStatistics = append(lookStatistics, statisCont)
// }
}
}
response.Result(0, lookStatistics, "查询完成", c)
}

231
api/version1/statistics/orgMonths.go

@ -0,0 +1,231 @@
package statistics
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"sort"
"strconv"
"time"
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-11-08 11:22:10
@ 功能: 行政组织年度成绩单
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) OrgTargetAnnualStatistics(c *gin.Context) {
//获取登录人信息
context, _ := publicmethod.LoginMyCont(c)
var requestData OrgAnnualStatistics
c.ShouldBindJSON(&requestData)
//获取行政组织
var orgList []modelshr.AdministrativeOrganization
gromDb := overall.CONSTANT_DB_HR.Model(&modelshr.AdministrativeOrganization{}).Select("`id`,`name`,`sort`").Where("ispower = 1 AND state = 1 AND organization_type > 2")
if requestData.OrgId != "" {
gromDb = gromDb.Where("superior = ?", requestData.OrgId)
} else {
gromDb = gromDb.Where("superior = ?", context.Company)
}
err := gromDb.Find(&orgList).Error
if err != nil && len(orgList) < 1 {
response.Result(102, err, "没有查询到数据", c)
return
}
var orgAry []modelshr.AdministrativeOrganization
for _, ov := range orgList {
if ov.Id != 163 && ov.Id != 281 {
//获取下级行政组织是否有主行政部门
sunOrgList, orgSunErr := getSunOrgList(ov.Id, "`id`", "`name`", "`sort`")
if orgSunErr == nil && len(sunOrgList) > 0 {
orgAry = append(orgAry, sunOrgList...)
} else {
orgAry = append(orgAry, ov)
}
}
}
//计算要查询的年份
currentYear := publicmethod.ComputingTime(time.Now().Unix(), 1) //当前年
todayYear := currentYear //今年
if requestData.Years != "" {
yearInt64, _ := strconv.ParseInt(requestData.Years, 10, 64)
currentYear = yearInt64
}
//计算月
var monthTody []int64
if currentYear == todayYear {
monthTodyIng := publicmethod.ComputingTime(time.Now().Unix(), 3)
var montInt64 int64
for montInt64 = 1; montInt64 <= monthTodyIng; montInt64++ {
monthTody = append(monthTody, montInt64)
}
} else {
var montInt64All int64
for montInt64All = 1; montInt64All <= 12; montInt64All++ {
monthTody = append(monthTody, montInt64All)
}
}
//保证月份不为负数
if len(monthTody) < 1 {
monthTody = append(monthTody, 1)
}
var sendList SendOrgAnnualStatistics
var orgTranscriptList OrgTranscript
for _, v := range monthTody {
sendList.XAxis = append(sendList.XAxis, fmt.Sprintf("%v月", v))
}
for _, v := range orgAry {
sendList.Legend = append(sendList.Legend, v.Name)
syncProcess.Add(1)
go orgTranscriptList.CalculateGrades(v, currentYear, monthTody)
}
syncProcess.Wait()
readStatisticsData := orgTranscriptList.readTranscriptData() //读取通道数据
if len(readStatisticsData) > 0 {
sendList.MaxScore = readStatisticsData[0].MaxScore
sendList.MinScore = readStatisticsData[0].MinScore
}
//根据维度序号排序
sort.Slice(readStatisticsData, func(i, j int) bool {
return readStatisticsData[i].Scort < readStatisticsData[j].Scort
})
for _, v := range readStatisticsData {
if sendList.MaxScore <= v.MaxScore {
sendList.MaxScore = v.MaxScore
}
if sendList.MinScore >= v.MinScore {
sendList.MinScore = v.MinScore
}
}
if sendList.MaxScore > 0 {
if sendList.MaxScore > 1 {
sendList.MaxScore = sendList.MaxScore + 1
} else {
sendList.MaxScore = sendList.MaxScore + 0.1
}
} else {
if sendList.MaxScore < -1 {
sendList.MaxScore = sendList.MaxScore + 1
} else {
sendList.MaxScore = sendList.MaxScore + 0.1
}
}
if sendList.MinScore > 0 {
if sendList.MinScore > 1 {
sendList.MinScore = sendList.MinScore - 1
} else {
sendList.MinScore = sendList.MinScore - 0.1
}
} else {
if sendList.MinScore < -1 {
sendList.MinScore = sendList.MinScore - 1
} else {
sendList.MinScore = sendList.MinScore - 0.1
}
}
sendList.Series = readStatisticsData
publicmethod.Result(0, sendList, c)
}
func (o *OrgTranscript) CalculateGrades(orgInfo modelshr.AdministrativeOrganization, currentYear int64, months []int64) {
//锁操作
o.mutext.Lock()
defer o.mutext.Unlock()
var orgSictesCont SeriesList
orgSictesCont.Name = orgInfo.Name
orgSictesCont.Scort = orgInfo.Sort
// var monthOrgScore OrgTranscriptScore
var everyMonthScore countEveryDepartmentMonthScore
for _, v := range months {
planCont, err := publicmethod.GetPlanVresion(orgInfo.Id, currentYear, v)
// fmt.Printf("planCont:%v\n%v\n", planCont, err)
if err == nil {
var planVersioInfo []AddDutyNewCont
jsonErr := json.Unmarshal([]byte(planCont.Content), &planVersioInfo)
if jsonErr == nil {
syncProcessDepartTarget.Add(1)
//按月份计算
go everyMonthScore.everyMonthCalculateNew(orgInfo.Id, currentYear, v, planVersioInfo)
}
}
}
syncProcessDepartTarget.Wait()
everyMonthScoreList := everyMonthScore.readMyDayData()
if len(everyMonthScoreList) > 0 {
orgSictesCont.MaxScore = everyMonthScoreList[0].Score
orgSictesCont.MinScore = everyMonthScoreList[0].Score
}
sort.Slice(everyMonthScoreList, func(i, j int) bool {
return everyMonthScoreList[i].MonthVal < everyMonthScoreList[j].MonthVal
})
// fmt.Printf("层级:%v\n", everyMonthScoreList)
for _, v := range everyMonthScoreList {
if orgSictesCont.MaxScore <= v.Score {
orgSictesCont.MaxScore = v.Score
}
if orgSictesCont.MinScore > v.Score {
orgSictesCont.MinScore = v.Score
}
orgSictesCont.DataList = append(orgSictesCont.DataList, v.Score)
}
o.ScoreStatistics = append(o.ScoreStatistics, orgSictesCont)
syncProcess.Done()
}
/*
*
@ 作者: 秦东
@ 时间: 2023-11-08 13:09:27
@ 功能: 计算行政组织每月成绩
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
// func (o *OrgTranscriptScore) CalculateGrades(orgId, years, months int64) {
// o.mutext.Lock()
// defer o.mutext.Unlock()
// var scoreInfo MonthOrgScore
// scoreInfo.Months = months
// planCont, err := publicmethod.GetPlanVresion(orgId, years, months)
// if err == nil {
// var planVersioInfo []AddDutyNewCont
// jsonErr := json.Unmarshal([]byte(planCont.Content), &planVersioInfo)
// }
// o.ScoreList = append(o.ScoreList, scoreInfo)
// syncProcessDepartTarget.Done()
// }

140
api/version1/statistics/orgstatistics.go

@ -0,0 +1,140 @@
package statistics
import (
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-08-17 16:44:24
@ 功能: 行政组织成绩单新版
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) OrgTranscriptNew(c *gin.Context) {
//获取登录人信息
context, err := publicmethod.LoginMyCont(c)
if err != nil {
publicmethod.Result(1, err, c, "您无权进行此操作!")
return
}
var requestData TranscriptTable
c.ShouldBindJSON(&requestData)
//获取当前访问人的公司组织架构
var orgList []modelshr.AdministrativeOrganization
gromDb := overall.CONSTANT_DB_HR.Model(&modelshr.AdministrativeOrganization{}).Select("`id`,`name`,`sort`").Where("ispower = 1 AND state = 1 AND organization_type > 2")
if requestData.Group != "" {
gromDb = gromDb.Where("superior = ?", requestData.Group)
} else {
gromDb = gromDb.Where("superior = ?", context.Company)
}
if requestData.Department != "" {
gromDb = gromDb.Where("`id` = ?", requestData.Department)
}
err = gromDb.Find(&orgList).Error
if err != nil {
response.Result(102, err, "没有查询到数据", c)
return
}
if len(orgList) <= 0 {
response.Result(103, err, "没有查询到数据", c)
return
}
var orgAry []modelshr.AdministrativeOrganization //行政组织列表
for _, ov := range orgList {
if ov.Id != 163 && ov.Id != 281 {
sunOrgList, orgSunErr := getSunOrgList(ov.Id, "`id`", "`name`", "`sort`")
if orgSunErr == nil && len(sunOrgList) > 0 {
orgAry = append(orgAry, sunOrgList...)
} else {
orgAry = append(orgAry, ov)
}
}
}
//计算要查询的年份
currentYear := publicmethod.ComputingTime(time.Now().Unix(), 1) //当前年
todayYear := currentYear //今年
if requestData.Year != "" {
yearInt64, _ := strconv.ParseInt(requestData.Year, 10, 64)
currentYear = yearInt64
}
//计算月
var monthTody []int64
if len(requestData.Month) < 1 {
if currentYear == todayYear {
monthTodyIng := publicmethod.ComputingTime(time.Now().Unix(), 3)
var montInt64 int64
for montInt64 = 1; montInt64 <= monthTodyIng; montInt64++ {
monthTody = append(monthTody, montInt64)
}
} else {
var montInt64All int64
for montInt64All = 1; montInt64All <= 12; montInt64All++ {
monthTody = append(monthTody, montInt64All)
}
}
} else {
for _, mmv := range requestData.Month {
monthTody = append(monthTody, int64(mmv))
}
}
//保证月份不为负数
if len(monthTody) < 1 {
monthTody = append(monthTody, 1)
}
/*
设定协程
遍历行政组织并发计算
*/
var orgTranscript TranscriptTableData
for _, v := range orgAry {
// if v.Id == 362 {
syncProcess.Add(1)
go orgTranscript.StaticticsOrgTimeResult(v, currentYear, monthTody)
// }
}
syncProcess.Wait()
}
/*
*
@ 作者: 秦东
@ 时间: 2023-08-18 08:16:52
@ 功能: 计算每个行政组织得分
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (t *TranscriptTableData) EveryOrgCensusResult(orgCont modelshr.AdministrativeOrganization, year int64, month []int64) {
//锁操作
t.mutext.Lock()
defer t.mutext.Unlock()
syncProcess.Done() //结束本协程
}

1594
api/version1/statistics/pc.go

File diff suppressed because it is too large

151
api/version1/statistics/pcplant.go

@ -0,0 +1,151 @@
package statistics
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-07-29 15:21:47
@ 功能: 方案得分明细
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) SummaryDetails(c *gin.Context) {
var requestData detailedResults
err := c.ShouldBindJSON(&requestData)
if err != nil {
response.Result(101, err, "数据获取失败!", c)
return
}
if requestData.Department == "" {
response.Result(102, err, "参数错误!请属入部门", c)
return
}
if requestData.Year == 0 {
requestData.Year = publicmethod.ComputingTime(time.Now().Unix(), 1)
}
if requestData.Months < 1 {
requestData.Months = 1
}
if requestData.Months > 12 {
requestData.Months = 12
}
orgId, _ := strconv.ParseInt(requestData.Department, 10, 64)
planVersion, _ := publicmethod.GetPlanVresion(orgId, requestData.Year, int64(requestData.Months))
var planVersioInfo []AddDutyNewCont
json.Unmarshal([]byte(planVersion.Content), &planVersioInfo)
var lookStatistics []detailedResultsList
for _, v := range planVersioInfo { //维度
for _, cv := range v.Child { //指标
// if cv.Id == "12" {
var statisCont detailedResultsList
statisCont.GroupId = strconv.FormatInt(planVersion.Group, 10) //集团Id
statisCont.Versio = planVersion.Key
var groupCont modelshr.AdministrativeOrganization
groupCont.GetCont(map[string]interface{}{"`id`": planVersion.Group}, "name")
statisCont.GroupName = groupCont.Name //集团名称
statisCont.DepartmentId = strconv.FormatInt(planVersion.Department, 10) //部门ID
var departCont modelshr.AdministrativeOrganization
departCont.GetCont(map[string]interface{}{"`id`": planVersion.Department}, "name")
statisCont.DepartmentName = departCont.Name //部门名称
statisCont.DimensionId = v.Id //维度Id
statisCont.DimensionName = v.Name //维度名称
statisCont.DimensionWeight = int64(v.ZhiFraction) //维度权重
statisCont.TargetId = cv.Id //指标ID
statisCont.TargetName = cv.Name //指标名称
statisCont.TargetCont = cv.Content //指标名称
statisCont.Targetweight = cv.ReferenceScore //指标权重
var evalTargetCont modelskpi.EvaluationTarget //指标信息
if cv.Id != "" && cv.Id != "0" {
targetErr := evalTargetCont.GetCont(map[string]interface{}{"`et_id`": cv.Id}, "et_type")
monthInt := int64(requestData.Months)
if targetErr == nil {
if evalTargetCont.Type == 1 {
//定性指标
statisCont.Score, statisCont.ExecutiveDepartment = DingXingScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{monthInt}, cv.Id)
} else {
//定量指标
var dingLiangScore float64
var orgList []string
//定量考核
switch cv.Cycles {
case 5: //季度指标
quarterList := []int64{3, 6, 9, 12}
if !publicmethod.IsInTrue[int64](monthInt, quarterList) {
dingLiangScore = float64(cv.ReferenceScore)
// fmt.Printf("季度指标--->%v--->%v--->%v\n", cv.Name, cv.Id, dingLiangScore)
} else {
switch monthInt {
case 3:
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{1, 2, 3}, cv.Id, cv.Cycles)
case 6:
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{4, 5, 6}, cv.Id, cv.Cycles)
case 9:
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{7, 8, 9}, cv.Id, cv.Cycles)
case 12:
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{10, 11, 12}, cv.Id, cv.Cycles)
default:
}
}
case 6: //年度指标
if monthInt == 12 {
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, cv.Id, cv.Cycles)
} else {
dingLiangScore = float64(cv.ReferenceScore)
// fmt.Printf("年度指标--->%v--->%v--->%v\n", cv.Name, cv.Id, dingLiangScore)
}
case 7: //半年指标
switch monthInt {
case 6:
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{1, 2, 3, 4, 5, 6}, cv.Id, cv.Cycles)
case 12:
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{7, 8, 9, 10, 11, 12}, cv.Id, cv.Cycles)
default:
dingLiangScore = float64(cv.ReferenceScore)
// fmt.Printf("半年指标--->%v--->%v--->%v\n", cv.Name, cv.Id, dingLiangScore)
}
default: //月度指标
dingLiangScore, orgList = DingLiangScoreCalculation(orgId, requestData.Year, cv.ReferenceScore, []int64{monthInt}, cv.Id, cv.Cycles)
}
dingLiangScoreGd, _ := publicmethod.DecimalNew(dingLiangScore, 2)
statisCont.Score = dingLiangScoreGd
statisCont.ExecutiveDepartment = orgList
fmt.Printf("定量指标---->%v\n---->%v\n", dingLiangScoreGd, orgList)
}
}
}
statisCont.Type = evalTargetCont.Type //1:定性;2:定量
statisCont.Unit = cv.Unit //单位
statisCont.Cycle = cv.Cycles //周期
statisCont.Cycleattr = cv.CycleAttres //辅助参数
lookStatistics = append(lookStatistics, statisCont)
// }
}
}
response.Result(0, lookStatistics, "查询完成", c)
}

283
api/version1/statistics/type.go

@ -0,0 +1,283 @@
package statistics
import (
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
type ApiMethod struct{}
// 携程设置
// var syncSeting = sync.WaitGroup{}
var syncProcess = sync.WaitGroup{}
/*
*
@ 作者: 秦东
@ 时间: 2023-07-27 10:11:58
@ 功能: 统计入口
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "统计入口"
publicmethod.Result(0, outputCont, c)
}
// 绩效考核成绩表
type TranscriptTable struct {
Group string `json:"group"`
Department string `json:"department"`
Year string `year`
Month []int `json:"month"`
}
// 绩效考核成绩表结果
type TranscriptTableDateList struct {
DepartmentId string `json:"departmentid"`
Department string `json:"department"`
Sort int `json:"sort"`
A float64 `json:"a"`
B float64 `json:"b"`
C float64 `json:"C"`
D float64 `json:"d"`
E float64 `json:"e"`
F float64 `json:"f"`
G float64 `json:"g"`
H float64 `json:"h"`
I float64 `json:"i"`
J float64 `json:"J"`
K float64 `json:"K"`
L float64 `json:"L"`
}
// 计算得分性质
type defenfenxi struct {
Title string `json:"title"`
TimeClass string `json:"timeclass"`
Month int64 `json:"month"`
Stroce float64 `json:"stroce"`
State int `json:"state"`
}
// 成绩表
type TranscriptTableData struct {
ScoreStatistics []TranscriptTableDateList
Defen []defenfenxi
mutext sync.RWMutex
}
// 读取成绩表锁数据
func (t *TranscriptTableData) readTranscriptData() []TranscriptTableDateList {
t.mutext.RLock()
defer t.mutext.RUnlock()
return t.ScoreStatistics
}
type countEveryDepartmentMonthScore struct {
outData []everyDepartmentScore
mutext sync.RWMutex
}
// 部门月分数
type everyDepartmentScore struct {
MonthVal int64 `json:"monthval"`
Score float64 `json:"score"`
}
// 读取锁数据
func (c *countEveryDepartmentMonthScore) readMyDayData() []everyDepartmentScore {
c.mutext.RLock()
defer c.mutext.RUnlock()
return c.outData
}
var syncProcessDepartTarget = sync.WaitGroup{} //获取指标相关参数
// 方案回显
type AddDutyNewCont struct {
Id string `json:"id"` //维度ID
Name string `json:"name"`
// Order int64 `json:"ordering"`
ZhiFraction int `json:"zhiFraction"`
Child []EvaluPross `json:"child"` //考核细则
}
// 指标
type EvaluPross struct {
Id string `json:"id"` //维度ID
Name string `json:"name"`
Content string `json:"content"` //指标说明
Unit string `json:"unit"` //单位"`
ReferenceScore int64 `json:"referencescore"` //标准分值"`
Cycles int `json:"cycle"` //1:班;2:天;3:周;4:月;5:季度;6:年"`
CycleAttres int `json:"cycleattr"` //辅助计数"`
State int `json:"state"`
Score int64 `json:"score"` //分数
QualEvalId string `json:"qeid"`
Status int `json:"status"`
}
// 定量流水全奖值、零奖值、封顶值
type FlowLogAllZreo struct {
Id string `json:"id"`
TargetId string `json:"targetid"` //指标ID`
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
}
// 图标维度输出
type TranscriptTableDateListChars struct {
XLine []string `json:"xline"`
Cylindrical []string `json:"cylindrical"`
YLine []YlineData `json:"cylindricaldata"`
}
type YlineData struct {
Name string `json:"name"`
Data []float64 `json:"data"`
}
// 行政组织级统计
type orgShierTongji struct {
A []float64 `json:"a"`
B []float64 `json:"b"`
C []float64 `json:"C"`
D []float64 `json:"d"`
E []float64 `json:"e"`
F []float64 `json:"f"`
G []float64 `json:"g"`
H []float64 `json:"h"`
I []float64 `json:"i"`
J []float64 `json:"J"`
K []float64 `json:"K"`
L []float64 `json:"L"`
}
// 查询成绩表月份明细
type detailedResults struct {
Department string `json:"department"` //部门
Year int64 `json:"year"` //年
Months int `json:"month"` //月份
}
// 查询成绩表月份明细历史
type detailedResultsLog struct {
TargetId string `json:"targetid"` //指标ID
detailedResults
}
// 定量考核基础参数
type dingLiangKaoHe struct {
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
Actual float64 `json:"actual"` //实际值
CompletionRate float64 `json:"completionrate"` //达成率
CompletionRateAll float64 `json:"completionrateall"` //达成率
Score float64 `json:"score"` //得分
MtOrAt int `json:"mtorat"` //手动还是自动
Cont string `json:"count"` //说明
Nature int `json:"nature"` //性质
}
// 输出考核方案月份详情表
type detailedResultsList struct {
GroupId string `json:"group"` //集团Id
GroupName string `json:"groupname"` //集团名称
DepartmentId string `json:"departmentid"` //部门ID
DepartmentName string `json:"departmentname"` //部门名称
DimensionId string `json:"dimensionid"` //维度Id
DimensionName string `json:"dimensionname"` //维度名称
DimensionWeight int64 `json:"dimensionweight"` //维度权重
TargetId string `json:"targetid"` //指标ID
TargetName string `json:"targetname"` //指标名称
TargetCont string `json:"targetCont"` //指标说明
Targetweight int64 `json:"targetweight"` //指标权重
Type int `json:"type"` //1:定性;2:定量
Unit string `json:"unit"` //单位
Cycle int `json:"cycle"` //周期
Cycleattr int `json:"cycleattr"` //辅助参数
ExecutiveDepartment []string `json:"executivedepartment"` //执行部门
Score float64 `json:"score"` //得分
Versio string `json:"versio"` //版本号码
}
// 定量考核基础参数(新版)
type dingLiangKaoHeNew struct {
Zeroprize float64 `json:"zeroprize"` //零奖值"`
Allprize float64 `json:"allprize"` //全奖值"`
Capping float64 `json:"capping"` //封顶值"`
Actual float64 `json:"actual"` //实际值
Score float64 `json:"score"` //手动得分
CompletionRate float64 `json:"completionrate"` //达成率
TargetScore float64 `json:"target_score"` //指标分
MtOrAt int `json:"mtorat"` //手动还是自动
Nature int `json:"nature"` //1、使用;2:禁用;3:观察
}
// 行政组织年度成绩单
type OrgAnnualStatistics struct {
OrgId string `json:"orgid"`
Years string `json:"years"`
}
// 输出行政组织年度统计成绩单
type SendOrgAnnualStatistics struct {
Legend []string `json:"legend"`
XAxis []string `json:"xAxis"`
MaxScore float64 `json:"maxscore"`
MinScore float64 `json:"minscore"`
Series []SeriesList `json:"series"`
}
type SeriesList struct {
Name string `json:"name"`
Scort int `json:"scort"`
MaxScore float64 `json:"maxscore"`
MinScore float64 `json:"minscore"`
DataList []float64 `json:"datalist"`
}
// 政组织年度统计成绩表
type OrgTranscript struct {
ScoreStatistics []SeriesList
mutext sync.RWMutex
}
// 读取政组织年度统计锁数据
func (t *OrgTranscript) readTranscriptData() []SeriesList {
t.mutext.RLock()
defer t.mutext.RUnlock()
return t.ScoreStatistics
}
// 计算月份结果
type MonthOrgScore struct {
Months int64
Score float64
}
// 计算月份结果(协程)
type OrgTranscriptScore struct {
ScoreList []MonthOrgScore
mutext sync.RWMutex
}
// 读取政组织年度统计锁数据
func (t *OrgTranscriptScore) readTranscriptData() []MonthOrgScore {
t.mutext.RLock()
defer t.mutext.RUnlock()
return t.ScoreList
}

29
api/version1/systemapproval/entry.go

@ -0,0 +1,29 @@
package systemapproval
import (
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
// 系统内部审批处理
type ApiMethod struct{}
// 协程设置
var syncSeting = sync.WaitGroup{}
// 系统内部审批处理
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "系统内部审批处理入口"
publicmethod.Result(0, outputCont, c)
}
// 审批参数
type AppFlowData struct {
OrderId string `json:"orderid"` //订单ID
YesOrNo int `json:"yesorno"` //1:批准;2:驳回
Content string `json:"content"` //审批意见
Stepper int `json:"stepper"` //步进器
}

1022
api/version1/systemapproval/post_nature.go

File diff suppressed because it is too large

705
api/workflow/currency_recipe/general_method.go

@ -0,0 +1,705 @@
package currency_recipe
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
)
//工作流解析函数
/*
*
@ 作者: 秦东
@ 时间: 2023-03-29 09:03:15
@ 功能: 初始化方法
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkflowEngine) InitWorkflow(fields ...string) *WorkflowEngine {
if w.Id == "" {
if len(fields) > 0 {
for i, v := range fields {
switch i {
case 0:
w.Id = v
case 1:
w.VersionId = v
case 2:
w.Applicant = v
case 3:
w.AcceptOrg = v
default:
}
}
}
}
if w.Id != "" {
var workflowInfo modelskpi.WorkFlowVersion
var err error
if w.VersionId != "" {
err = workflowInfo.GetCont(map[string]interface{}{"`key`": w.Id, "`version`": w.VersionId})
} else {
err = workflowInfo.GetCont(map[string]interface{}{"`key`": w.Id, "`state`": 1})
w.VersionId = workflowInfo.Version
}
if err == nil {
json.Unmarshal([]byte(workflowInfo.Content), &w.WorkflowCont)
}
}
// fmt.Printf("工作流接卸--->%v\n", w)
return w
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-29 09:26:47
@ 功能: 输出工作流
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkflowEngine) SendData() (sendCont SendOneWorkflow) {
var nodeInfo []NodeCont
nodeInfo, sendCont.IsTrue, sendCont.Msg = w.promoter()
sendCont.NodeContList = RectificationNode(nodeInfo)
sendCont.Version = w.VersionId
// sjkdjk, _ := json.Marshal(w)
// fmt.Printf("输出工作流--->%v\n", string(sjkdjk))
return
}
// 整流
func RectificationNode(nodeInfo []NodeCont) (nodeInfoOk []NodeCont) {
for i := 0; i < len(nodeInfo); i++ {
nextId := i + 1
if nextId < len(nodeInfo) {
nodeInfo[i].ArriveNode = nodeInfo[nextId].NodeNumber
nodeInfo[nextId].FromNode = nodeInfo[i].NodeNumber
}
}
nodeInfoOk = nodeInfo
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-29 09:42:16
@ 功能: 判断发起人
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (w *WorkflowEngine) promoter() (nodeList []NodeCont, isTrue bool, msg string) {
if w.Applicant == "" {
isTrue = false
msg = "未知申请人!流程不成立!"
return
}
err := w.ApplicantCont.GetCont(map[string]interface{}{"`key`": w.Applicant})
if err != nil {
isTrue = false
msg = "未知申请人!流程不成立!"
return
}
if len(w.WorkflowCont.FlowPermission) > 0 {
isTrue, msg = JudgeHaveApply(w.ApplicantCont, w.WorkflowCont.FlowPermission)
if !isTrue {
return
}
}
nodeConfig := w.WorkflowCont.NodeConfig
w.Step = 1
w.StarNodeNumber = nodeConfig.NodeNumber
//流程线
var nodeCont NodeCont
nodeCont.Step = w.Step //步伐
nodeCont.Type = nodeConfig.Type
nodeCont.NodeNumber = nodeConfig.NodeNumber //节点编号
nodeCont.NodeName = nodeConfig.NodeName //节点名称
nodeCont.State = 1 //状态 1、不点亮;2、点亮
nodeCont.GoBackNode = w.StarNodeNumber //可得返回节点
// nodeCont.UserList []UserListFlowAll //节点操作人
nodeCont.UserList = append(nodeCont.UserList, SetOperator(w.ApplicantCont))
nodeList = append(nodeList, nodeCont)
// var childNode *PublicChildNode
fmt.Printf("nodeConfig.ChildNode-->%v\n", nodeConfig.ChildNode)
childNode := nodeConfig.ChildNode
acceptOrgId, _ := strconv.ParseInt(w.AcceptOrg, 10, 64)
// nodeListCont, isTrues, msgs := childNode.AnalysisNode(w.Step, childNode.Attribute, w.StarNodeNumber, w.ApplicantCont, acceptOrgId)
// nodeList = append(nodeList, nodeListCont)
// isTrue = isTrues
// msg = msgs
// isTrue = true
if childNode != nil {
listNode := childNode.CircularParsing(w.Step, childNode.Attribute, w.StarNodeNumber, w.ApplicantCont, acceptOrgId, w.JudCond)
if len(listNode) > 1 {
for _, v := range listNode {
nodeList = append(nodeList, v)
}
}
}
// fmt.Printf("childNode.NodeContList-->%v\n", listNode)
isTrue = true
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-29 14:00:06
@ 功能: 解析下级节点(废弃)
@ 参数
#step 执行到第几步
#sendBackNode 开始节点编号
#applicantCont 申请人信息
#acceptorg 接受行政组织
#attribute 1申请人为基线2目标人为基线
@ 返回值
#
@ 方法原型
#func (p *PublicChildNode) AnalysisNode(step int, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64) (nodeList NodeCont, isTrue bool, msg string)
*/
func (p *PublicChildNode) AnalysisNode(step int, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64) (nodeList NodeCont, isTrue bool, msg string) {
step++
// fmt.Printf("%v\n",)
switch p.Type { //节点类型
case 1, 3: //审批
//流程线
nodeList.Step = step //步伐
nodeList.NodeNumber = p.NodeNumber //节点编号
nodeList.NodeName = p.NodeName //节点名称
nodeList.FromNode = p.FromNode //来源节点
nodeList.State = 1 //状态 1、不点亮;2、点亮
if p.SendBackNode == "beginnode" {
nodeList.GoBackNode = sendBackNode //可得返回节点
} else {
nodeList.GoBackNode = p.SendBackNode
}
nodeList.ExamineMode = p.ExamineMode
nodeList.NoHanderAction = p.NoHanderAction
//判断审批人设置
switch p.Settype {
case 1: //指定成员
isOk := false
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "1" {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.TargetID})
nodeList.UserList = append(nodeList.UserList, SetOperator(userCont))
isOk = true
}
}
}
if isOk {
isTrue = true
} else {
isTrue = false
msg = "未设置审批人"
}
case 2: //主管
var gainUser GainLeveDirector
gainUser.Step = 0
gainUser.Leve = p.DirectorLevel
if attribute == "1" {
gainUser.GainLeveDirector(applicantCont.AdminOrg)
} else {
gainUser.GainLeveDirector(acceptorg)
}
if len(gainUser.UserList) > 0 {
for _, v := range gainUser.UserList {
nodeList.UserList = append(nodeList.UserList, SetOperator(v))
}
} else {
isTrue = false
msg = "未设置审批人"
}
case 3: //行政岗位
if len(p.NodeUserList) > 0 {
var userList []modelshr.PersonArchives
if attribute == "1" {
userList = BaseOrgGainOperator(applicantCont.AdminOrg, p.NodeUserList)
} else {
userList = BaseOrgGainOperator(acceptorg, p.NodeUserList)
}
if len(userList) > 0 {
for _, v := range userList {
nodeList.UserList = append(nodeList.UserList, SetOperator(v))
}
} else {
isTrue = false
msg = "未设置审批人"
}
} else {
isTrue = false
msg = "未设置审批人"
}
case 4: //发起人自选
nodeList.RunType = 0
nodeList.RunScope = 0
switch p.SelectRange {
case 1: //全公司
nodeList.RunType = 1
nodeList.RunScope = 1
case 2: //指定成员
isOk := false
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "1" {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.TargetID})
nodeList.UserList = append(nodeList.UserList, SetOperator(userCont))
isOk = true
}
}
}
if isOk {
isTrue = true
} else {
isTrue = false
msg = "未设置审批人"
}
case 3: //指定角色
var roleId []string
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "2" {
if !publicmethod.IsInTrue[string](v.TargetID, roleId) {
roleId = append(roleId, v.TargetID)
}
}
}
}
// fmt.Printf("指定角色-->")
isOk := false
if len(roleId) > 0 {
for _, v := range roleId {
var userContList []modelshr.PersonArchives
err := overall.CONSTANT_DB_HR.Where("`emp_type` BETWEEN ? AND ? AND FIND_IN_SET(?,`role`)", 1, 10, v).Find(&userContList).Error
if err == nil && len(userContList) > 0 {
for _, uvr := range userContList {
nodeList.UserList = append(nodeList.UserList, SetOperator(uvr))
}
isOk = true
}
}
}
if isOk {
isTrue = true
} else {
isTrue = false
msg = "未设置审批人"
}
case 4: //本部门
nodeList.RunType = 1
nodeList.RunScope = 2
default:
isTrue = false
msg = "未设置审批人"
}
case 5: //发起人自己
nodeList.RunType = 2
nodeList.RunScope = 0
nodeList.UserList = append(nodeList.UserList, SetOperator(applicantCont))
case 7: //联系多层主管
var gainUser GainLeveDirector
gainUser.Step = 0
if p.ExamineEndDirectorLevel == 1 {
gainUser.Leve = 10
} else {
gainUser.Leve = p.ExamineEndDirectorLevel
}
// gainUser.Leve = 1
if attribute == "1" {
gainUser.GainLeveDirectoSseries(applicantCont.AdminOrg)
} else {
gainUser.GainLeveDirectoSseries(acceptorg)
}
if len(gainUser.UserList) > 0 {
for _, v := range gainUser.UserList {
nodeList.UserList = append(nodeList.UserList, SetOperator(v))
}
} else {
isTrue = false
msg = "未设置审批人"
}
case 8:
nodeList.RunType = 3
nodeList.RunScope = 0
nodeList.CustomNode = p.CustomNode
nodeList.ExecutionAddress = p.ExecutionAddress
default:
isTrue = false
msg = "未设置审批人"
}
case 2: //抄送
//流程线
nodeList.Step = step //步伐
nodeList.NodeNumber = p.NodeNumber //节点编号
nodeList.NodeName = p.NodeName //节点名称
nodeList.FromNode = p.FromNode //来源节点
nodeList.State = 1 //状态 1、不点亮;2、点亮
nodeList.RunType = 4
nodeList.RunScope = p.CcSelfSelectFlag
if p.SendBackNode == "beginnode" {
nodeList.GoBackNode = sendBackNode //可得返回节点
} else {
nodeList.GoBackNode = p.SendBackNode
}
isOk := false
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "1" {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.TargetID})
nodeList.UserList = append(nodeList.UserList, SetOperator(userCont))
isOk = true
}
}
}
if isOk {
isTrue = true
} else {
isTrue = false
msg = "未设置审批人"
}
// case 3: //执行人
case 4: //路由
case 5: //条件
default:
}
return
}
// // 获取节点审批人
// func GetNodeApprover(nodeKey string, nodeList []NodeCont) (UserList []UserListFlowAll) {
// lf len(nodeList) > 0{
// }
// return
// }
//根据行政岗位识别操作人
/*
#orgId 行政组织Id
#performAction 节点操作设定
*/
func BaseOrgGainOperator(orgId int64, performAction []NodeUserListCont) (userList []modelshr.PersonArchives) {
if len(performAction) > 0 {
//获取行政组织所有行政组织上级和下级
allOrg := publicmethod.HaveAllOrgRelation(orgId)
fmt.Printf("获取行政组织所有行政组织上级和下级--->%v--->%v--->%v\n", allOrg, orgId, performAction)
// postOftoOrg := make(map[string][]int64, 0)
var gainDirector GainLeveDirector
for _, v := range performAction {
if v.Type == "position" {
gainDirector.GetPostBaseOrg(v.TargetID, allOrg, orgId)
// postOftoOrg[v.TargetID] = GetPostBaseOrg(v.TargetID)
}
}
userList = gainDirector.UserList
}
return
}
// 获取职务关联得行政组织
/*
#unifyPosId 统一职务名称ID
#orgList 行政组织ID列表
#myOrgId 任务行政组织
*/
func (g *GainLeveDirector) GetPostBaseOrg(unifyPosId string, orgList []int64, myOrgId int64) {
var positionInfo modelshr.PositionUnify
err := positionInfo.GetCont(map[string]interface{}{"`id`": unifyPosId}, "`content`")
if err != nil {
return
}
fmt.Printf("获取职务关联得行政组织-2-->%v-->%v-->%v\n", unifyPosId, positionInfo, myOrgId)
var posIdStr []int64
err = json.Unmarshal([]byte(positionInfo.Content), &posIdStr)
if err != nil {
return
}
//获取相关职务数据
var posCont []modelshr.PostDutiesJob
err = overall.CONSTANT_DB_HR.Model(&modelshr.PostDutiesJob{}).Select("`id`,`name`,`adm_org`,`weight`").Where("`id` IN ?", posIdStr).Find(&posCont).Error
fmt.Printf("获取职务关联得行政组织-1-->%v\n", posCont)
if err != nil || len(posCont) < 1 {
fmt.Printf("获取职务关联得行政组织-1-11111->%v\n", err)
return
}
var orgIdList []int64
var orgPosId []JudgeOrgOfPosition
fmt.Printf("获取职务关联得行政组织-1-11112333111->%v\n", err)
for _, v := range posCont { //组织岗位与行政组织关系
if !publicmethod.IsInTrue[int64](v.AdministrativeOrganization, orgIdList) {
orgIdList = append(orgIdList, v.AdministrativeOrganization)
var orgPosIdCont JudgeOrgOfPosition
orgPosIdCont.Name = v.Name
orgPosIdCont.OrgId = v.AdministrativeOrganization
orgPosIdCont.PositionId = v.Id
orgPosIdCont.Weight = v.Weight
orgPosId = append(orgPosId, orgPosIdCont)
}
}
jieguo := publicmethod.Intersect[int64](orgList, orgIdList) //获取交集,判断是否有相关职位
fmt.Printf("获取交集,判断是否有相关职位-1-->%v-->%v-->%v-->%v\n", jieguo, orgList, orgIdList, orgPosId)
//获取相关岗位人员
var myIdList []int64
if len(jieguo) > 0 {
for _, ovp := range orgPosId {
if publicmethod.IsInTrue[int64](ovp.OrgId, jieguo) {
var userInfoList []modelshr.PersonArchives
gormDb := overall.CONSTANT_DB_HR.Where("`position` = ? AND `admin_org` = ? AND `emp_type` BETWEEN ? AND ?", ovp.PositionId, ovp.OrgId, 1, 10)
if ovp.Weight >= 8 {
gormDb = gormDb.Where("`person_in_charge` = 1 AND FIND_IN_SET(?,`responsible_department`)", myOrgId)
}
err = gormDb.Find(&userInfoList).Error
if err == nil && len(userInfoList) > 0 {
for _, usev := range userInfoList {
if !publicmethod.IsInTrue[int64](usev.Id, g.UserId) {
g.UserId = append(g.UserId, usev.Id)
myIdList = append(myIdList, usev.Id)
}
g.UserList = append(g.UserList, usev)
}
}
jsonCont, _ := json.Marshal(userInfoList)
fmt.Printf("负责人列表--sssss->%v--->%v\n", g.UserId, string(jsonCont))
}
}
}
//获取指定的负责范围
// for _, ovpnew := range orgPosId {
// if publicmethod.IsInTrue[int64](ovpnew.OrgId, jieguo) {
var userInfoListEs []modelshr.PersonArchives
gormDb := overall.CONSTANT_DB_HR.Where("`position` IN ? AND `person_in_charge` = 1 AND FIND_IN_SET(?,`responsible_department`) AND `emp_type` BETWEEN ? AND ?", posIdStr, myOrgId, 1, 10)
err = gormDb.Find(&userInfoListEs).Error
if err == nil && len(userInfoListEs) > 0 {
for _, usev := range userInfoListEs {
fmt.Printf("负责人列表-1111-->%v--->%v--->%v\n", g.UserId, !publicmethod.IsInTrue[int64](usev.Id, g.UserId), myIdList)
if !publicmethod.IsInTrue[int64](usev.Id, g.UserId) {
fmt.Printf("负责人列表-1222--%v\n", usev.Id)
g.UserList = append(g.UserList, usev)
}
}
}
jsonCont, _ := json.Marshal(userInfoListEs)
fmt.Printf("负责人列表--->%v--->%v\n", g.UserId, string(jsonCont))
// }
// }
}
// 获取第几级主管
/*
#orgId 行政组织Id
*/
func (g *GainLeveDirector) GainLeveDirector(orgId int64) {
var orgCont modelshr.AdministrativeOrganization
err := orgCont.GetCont(map[string]interface{}{"`id`": orgId}, "`superior`")
if err == nil {
//获取改行政组织下的负责人
var userCont []modelshr.PersonArchives
errs := overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Where("`person_in_charge` = 1 AND FIND_IN_SET(?,`responsible_department`)", orgId).Find(&userCont).Error
if errs == nil {
g.Step++
if g.Step == g.Leve {
for _, v := range userCont {
g.UserList = append(g.UserList, v)
}
} else if g.Step < g.Leve {
g.GainLeveDirector(orgCont.Superior)
}
} else {
g.GainLeveDirector(orgCont.Superior)
}
}
}
// 获取连续多级主管
/*
#orgId 行政组织Id
*/
func (g *GainLeveDirector) GainLeveDirectoSseries(orgId int64) {
if orgId > 0 {
var orgCont modelshr.AdministrativeOrganization
err := orgCont.GetCont(map[string]interface{}{"`id`": orgId}, "`superior`")
if err == nil {
//获取改行政组织下的负责人
var userCont []modelshr.PersonArchives
errs := overall.CONSTANT_DB_HR.Model(&modelshr.PersonArchives{}).Where("`person_in_charge` = 1 AND FIND_IN_SET(?,`responsible_department`)", orgId).Find(&userCont).Error
if errs == nil {
g.Step++
if g.Step <= g.Leve {
for _, v := range userCont {
g.UserList = append(g.UserList, v)
}
g.GainLeveDirectoSseries(orgCont.Superior)
}
} else {
g.GainLeveDirectoSseries(orgCont.Superior)
}
}
}
}
// 判断发起人是否具备使用该流程权限
func JudgeHaveApply(applicant modelshr.PersonArchives, FlowPermission []FlowPermissionStruct) (isTrue bool, msg string) {
if len(FlowPermission) < 1 {
isTrue = true
return
}
//获取申请人所有行政组织上级
var getAllOrg publicmethod.GetOrgAllParent
getAllOrg.GetOrgParentAllId(applicant.AdminOrg)
// fmt.Printf("所有行政组织--->%v\n", getAllOrg.Id)
havePurview := false
for _, v := range FlowPermission {
// fmt.Printf("所有行政组织--1->%v---------->%v\n", v.Type, v)
switch v.Type {
case "1": //个人
keyStr := strconv.FormatInt(applicant.Key, 10)
if v.TargetId == keyStr {
havePurview = true
}
case "2":
var roleAry []string
jsonErr := json.Unmarshal([]byte(applicant.Role), &roleAry)
if jsonErr == nil {
if len(roleAry) > 0 {
if publicmethod.IsInTrue[string](v.TargetId, roleAry) == true {
havePurview = true
}
}
}
case "3":
if len(getAllOrg.Id) > 0 {
targetIdInt, errInt := strconv.ParseInt(v.TargetId, 10, 64)
if errInt == nil {
if publicmethod.IsInTrue[int64](targetIdInt, getAllOrg.Id) == true {
havePurview = true
}
}
}
default:
}
}
if !havePurview {
isTrue = false
msg = "你没有发起此流程得权限!"
} else {
isTrue = true
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-29 11:48:12
@ 功能: 操作人记录信息
@ 参数
#userCont 人员信息
@ 返回值
#userNode 操作信息
@ 方法原型
#
*/
func SetOperator(userCont modelshr.PersonArchives) (userNode UserListFlowAll) {
userNode.Id = strconv.FormatInt(userCont.Key, 10) //操作人ID
userNode.Name = userCont.Name //操作人姓名
userNode.Icon = userCont.Icon //操作人头像
userNode.IconBase64 = userCont.IconPhoto
userNode.Wechat = userCont.Wechat //微信Openid
if userCont.WorkWechat != "" {
userNode.Wechat = userCont.WorkWechat //微信Openid
}
_, companyId, _, _, _ := publicmethod.GetOrgStructurees(userCont.AdminOrg)
if companyId != 0 {
var orgCont modelshr.AdministrativeOrganization
orgCont.GetCont(map[string]interface{}{"`id`": companyId}, "`name`")
userNode.DepartmentId = companyId //分厂Id
userNode.DepartmentName = orgCont.Name //分厂名称
}
//获取岗位
if userCont.Position != 0 {
var postCont modelshr.Position
postCont.GetCont(map[string]interface{}{"`id`": userCont.Position}, "`name`")
userNode.PostId = userCont.Position //职务Id
userNode.PostName = postCont.Name //职务名称
}
if userCont.TeamId != 0 {
var teamCont modelshr.TeamGroup
teamCont.GetCont(map[string]interface{}{"`id`": userCont.TeamId}, "`name`")
userNode.Tema = userCont.TeamId //班组Id
userNode.TemaName = teamCont.Name //班组名称
}
return
}
// 判断下一步操作
func (n *JudgeNextNodeCont) JudgeNextNode(step int) {
// for _, v := range n.NodeContList{
// }
}

558
api/workflow/currency_recipe/structural_analysis.go

@ -0,0 +1,558 @@
package currency_recipe
import (
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"sort"
"strconv"
"strings"
)
/**
@ 作者: 秦东
@ 时间: 2023-03-31 08:11:58
@ 功能:
@ 参数
#step 步进值
#attribute 1申请人为基线2目标人为基线
#sendBackNode 开始节点编号
#applicantCont 申请人信息
#acceptorg 接受行政组织
@ 返回值
#NodeContList 节点列表
@ 方法原型
#func (p *PublicChildNode) CircularParsing(step int, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64) (NodeContList []NodeCont)
*/
func (p *PublicChildNode) CircularParsing(step int, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64, judgingCondition []JudgingCondition) (NodeContList []NodeCont) {
// fmt.Printf("循环接卸--NodeName->%v---NodeNumber->%v---Attribute->%v---attribute->%v---Type->%v---Settype->%v-----SelectRange->%v---NodeUserList->%v\n", p.NodeName, p.NodeNumber, p.Attribute, attribute, p.Type, p.Settype, p.SelectRange, p.NodeUserList)
step++
var nodeCont NodeCont
nodeCont.Step = step //步伐
nodeCont.NodeNumber = p.NodeNumber //节点编号
nodeCont.NodeName = p.NodeName //节点名称
nodeCont.FromNode = p.FromNode
nodeCont.Type = p.Type
// nodeCont.ArriveNode = p.GotoNode
nodeCont.State = 1 //状态 1、不点亮;2、点亮
if p.SendBackNode == "beginnode" {
nodeCont.GoBackNode = sendBackNode //可得返回节点
} else {
nodeCont.GoBackNode = p.SendBackNode
}
nodeCont.ExamineMode = p.ExamineMode
nodeCont.NoHanderAction = p.NoHanderAction
switch p.Type { //节点类型
case 1, 3: //审批&执行人
//判断审批人设置
switch p.Settype {
case 1: //指定成员
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "1" {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.TargetID})
nodeCont.UserList = append(nodeCont.UserList, SetOperator(userCont))
}
}
}
case 2: //主管
var gainUser GainLeveDirector
gainUser.Step = 0
gainUser.Leve = p.DirectorLevel
if p.Attribute == "1" {
gainUser.GainLeveDirector(applicantCont.AdminOrg)
} else {
gainUser.GainLeveDirector(acceptorg)
}
if len(gainUser.UserList) > 0 {
for _, v := range gainUser.UserList {
nodeCont.UserList = append(nodeCont.UserList, SetOperator(v))
}
}
case 3: //行政岗位
if len(p.NodeUserList) > 0 {
var userList []modelshr.PersonArchives
if p.Attribute == "1" {
userList = BaseOrgGainOperator(applicantCont.AdminOrg, p.NodeUserList)
} else {
userList = BaseOrgGainOperator(acceptorg, p.NodeUserList)
}
if len(userList) > 0 {
for _, v := range userList {
nodeCont.UserList = append(nodeCont.UserList, SetOperator(v))
}
}
}
case 4: //发起人自选
nodeCont.RunType = 0
nodeCont.RunScope = 0
switch p.SelectRange {
case 1: //全公司
nodeCont.RunType = 1
nodeCont.RunScope = 1
case 2: //指定成员
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "1" {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.TargetID})
nodeCont.UserList = append(nodeCont.UserList, SetOperator(userCont))
}
}
}
case 3: //指定角色
var roleId []string
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "2" {
if !publicmethod.IsInTrue[string](v.TargetID, roleId) {
roleId = append(roleId, v.TargetID)
}
}
}
}
// fmt.Printf("指定角色-->")
if len(roleId) > 0 {
for _, v := range roleId {
var userContList []modelshr.PersonArchives
err := overall.CONSTANT_DB_HR.Where("`emp_type` BETWEEN ? AND ? AND FIND_IN_SET(?,`role`)", 1, 10, v).Find(&userContList).Error
if err == nil && len(userContList) > 0 {
for _, uvr := range userContList {
nodeCont.UserList = append(nodeCont.UserList, SetOperator(uvr))
}
}
}
}
case 4: //本部门
nodeCont.RunType = 1
nodeCont.RunScope = 2
default:
}
case 5: //发起人自己
nodeCont.RunType = 2
nodeCont.RunScope = 0
nodeCont.UserList = append(nodeCont.UserList, SetOperator(applicantCont))
case 7: //联系多层主管
var gainUser GainLeveDirector
gainUser.Step = 0
if p.ExamineEndDirectorLevel == 1 {
gainUser.Leve = 10
} else {
gainUser.Leve = p.ExamineEndDirectorLevel
}
// gainUser.Leve = 1
if attribute == "1" {
gainUser.GainLeveDirectoSseries(applicantCont.AdminOrg)
} else {
gainUser.GainLeveDirectoSseries(acceptorg)
}
if len(gainUser.UserList) > 0 {
for _, v := range gainUser.UserList {
nodeCont.UserList = append(nodeCont.UserList, SetOperator(v))
}
}
case 8:
nodeCont.RunType = 3
nodeCont.RunScope = 0
nodeCont.CustomNode = p.CustomNode
nodeCont.ExecutionAddress = p.ExecutionAddress
default:
}
NodeContList = append(NodeContList, nodeCont)
if p.ChildNode != nil {
// listCont := p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode)
NodeContList = append(NodeContList, p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)...)
}
case 2: //抄送
if nodeCont.GoBackNode == "" {
nodeCont.GoBackNode = sendBackNode //可得返回节点
}
nodeCont.RunType = 4
nodeCont.RunScope = p.CcSelfSelectFlag
if len(p.NodeUserList) > 0 {
for _, v := range p.NodeUserList {
if v.Type == "1" {
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": v.TargetID})
nodeCont.UserList = append(nodeCont.UserList, SetOperator(userCont))
}
}
}
NodeContList = append(NodeContList, nodeCont)
if p.ChildNode != nil {
// listCont := p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode)
NodeContList = append(NodeContList, p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)...)
}
case 4: //路由
step = step - 1
if step < 1 {
step = 1
}
if p.ConditionNodes != nil {
//根据维度序号排序
sort.Slice(p.ConditionNodes, func(i, j int) bool {
return p.ConditionNodes[i].PriorityLevel < p.ConditionNodes[j].PriorityLevel
})
lastStrp := step
for _, pv := range p.ConditionNodes {
listContNode, isOk := pv.ResolveRouting(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)
// fmt.Printf("提交满足---->%v---->%v\n", isOk, listContNode)
if isOk && len(listContNode) > 0 {
// for _, lcnv := range listContNode {
// NodeContList = append(NodeContList, lcnv)
// }
// if pv.ChildNode != nil{
// NodeContListEnd := pv.ChildNode.CircularParsing(step, pv.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)
// NodeContList = append(NodeContList, NodeContListEnd...)
// }
// fmt.Printf("提交满足--12213-->%v---->%v\n", isOk, listContNode)
lastStrp = lastStrp + len(listContNode)
NodeContList = append(NodeContList, listContNode...)
break
}
}
if p.ChildNode != nil {
// listCont := p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode)
// NodeContListEnd := append(NodeContList, p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)...)
NodeContListEnd := p.ChildNode.CircularParsing(lastStrp, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)
// for _, nclev := range NodeContListEnd {
// NodeContList = append(NodeContList, nclev)
// }
if len(NodeContListEnd) > 0 {
NodeContList = append(NodeContList, NodeContListEnd...)
}
}
} else {
if p.ChildNode != nil {
// listCont := p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode)
NodeContList = append(NodeContList, p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)...)
}
}
case 5: //条件
default:
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-31 08:14:04
@ 功能: 解析路由得判断条件
@ 参数
#step 步进值
#attribute 1申请人为基线2目标人为基线
#sendBackNode 开始节点编号
#applicantCont 申请人信息
#acceptorg 接受行政组织
#judgingCondition 判断条件
@ 返回值
#NodeContList 节点列表
#isTrue 条件满足
@ 方法原型
#func (p *PublicChildNode) ResolveRouting(step int, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64, judgingCondition []JudgingCondition) (NodeContList []NodeCont, isTrue bool)
*/
func (p *PublicChildNode) ResolveRouting(step int, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64, judgingCondition []JudgingCondition) (NodeContList []NodeCont, isTrue bool) {
// fmt.Printf("条件名称----->%v----->%v\n", p.NodeName, p.NodeNumber)
if len(p.ConditionList) > 0 {
var areYourOk []InterimCondition
for _, c := range p.ConditionList {
// jsondf, _ := json.Marshal(c)
// fmt.Printf("can-www-->%v\n", string(jsondf))
var areYourOkCont InterimCondition
areYourOkCont.Class = strconv.Itoa(c.Type)
switch areYourOkCont.Class {
case "1": //发起人
areYourOkCont.TsTrue = true
areYourOkCont.IsOk = JudgePeopleIsTrue(p.NodeUserList, p.Attribute, applicantCont, acceptorg)
case "3": //关联数据库
areYourOkCont.TsTrue = true
if len(judgingCondition) < 1 {
areYourOkCont.IsOk = true
} else {
areYourOkCont.IsOk = true
}
case "4": //自定义表单
areYourOkCont.TsTrue = true
if len(judgingCondition) < 1 {
areYourOkCont.IsOk = false
} else {
for _, jv := range judgingCondition {
if jv.Class == 1 {
areYourOkCont.IsOk = JudgeCustomConditions(c.Condition, jv.MyCustom)
}
}
}
default:
}
areYourOk = append(areYourOk, areYourOkCont)
}
// jsonStr, _ := json.Marshal(p.ChildNode)
// fmt.Printf("判断提交结果-----》%v-----》%v\n", areYourOk, judgingCondition)
areYourOkLen := len(areYourOk)
jiShuQi := 0
for i := 0; i < areYourOkLen; i++ {
if areYourOk[i].IsOk && areYourOk[i].TsTrue {
jiShuQi++
}
}
if jiShuQi == areYourOkLen {
isTrue = true
if p.ChildNode != nil {
NodeContList = p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)
}
} else {
isTrue = false
}
return
}
if len(judgingCondition) < 1 && len(p.ConditionList) < 1 {
isTrue = true
if p.ChildNode != nil {
NodeContList = p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)
}
return
}
if len(p.ConditionList) < 1 {
isTrue = true
if p.ChildNode != nil {
NodeContList = p.ChildNode.CircularParsing(step, p.Attribute, sendBackNode, applicantCont, acceptorg, judgingCondition)
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-31 13:09:39
@ 功能: 判断自定义条件
@ 参数
#condition 节点设定条件
#myCondition 自定义条件
@ 返回值
#isOk 条件是否通过
@ 方法原型
#func JudgeCustomConditions(condition []ConditionStruct, myCondition []CustomFields) (isOk bool)
*/
func JudgeCustomConditions(condition []ConditionStruct, myCondition []CustomFields) (isOk bool) {
// fmt.Printf("判断自定义条件--》%v--->%v\n", condition, myCondition)
if len(condition) < 1 || len(myCondition) < 1 {
isOk = false
return
}
var isTrue []InterimCondition
for _, v := range condition {
var isTrueCont InterimCondition
isTrueCont.Class = v.WordField
isTrueCont.TsTrue = true
for _, mv := range myCondition {
if v.WordField == mv.WordField {
switch v.OptType { //["", "<", ">", "≤", "=", "≥","in","not in"][optType] 计算符号 1-8
case "1":
if mv.LeftVal < v.Factor.LeftVal {
isTrueCont.IsOk = true
} else {
isTrueCont.IsOk = false
}
case "2":
if mv.LeftVal > v.Factor.LeftVal {
isTrueCont.IsOk = true
} else {
isTrueCont.IsOk = false
}
case "3":
if mv.LeftVal <= v.Factor.LeftVal {
isTrueCont.IsOk = true
} else {
isTrueCont.IsOk = false
}
case "4":
if mv.LeftVal == v.Factor.LeftVal {
isTrueCont.IsOk = true
} else {
isTrueCont.IsOk = false
}
case "5":
if mv.LeftVal >= v.Factor.LeftVal {
isTrueCont.IsOk = true
} else {
isTrueCont.IsOk = false
}
case "6":
guoDuoLeft := false
guoDuoRight := false
if v.Factor.LeftOptType == "1" {
if mv.LeftVal < v.Factor.LeftVal {
guoDuoLeft = true
} else {
guoDuoLeft = false
}
} else {
if mv.LeftVal <= v.Factor.LeftVal {
guoDuoLeft = true
} else {
guoDuoLeft = false
}
}
if v.Factor.RightOptType == "1" {
if mv.RightVal < v.Factor.RightVal {
guoDuoRight = true
} else {
guoDuoRight = false
}
} else {
if mv.RightVal <= v.Factor.RightVal {
guoDuoRight = true
} else {
guoDuoRight = false
}
}
if guoDuoLeft && guoDuoRight {
isTrueCont.IsOk = true
} else {
isTrueCont.IsOk = false
}
case "7":
isTrueCont.IsOk = strings.Contains(v.Factor.LeftVal, mv.LeftVal)
case "8":
baohan := strings.Contains(v.Factor.LeftVal, mv.LeftVal)
isTrueCont.IsOk = !baohan
default:
}
isTrue = append(isTrue, isTrueCont)
}
}
}
if len(isTrue) < 1 {
isOk = false
} else {
countIsTrue := len(isTrue)
trueSum := 0
for i := 0; i < countIsTrue; i++ {
if isTrue[i].IsOk && isTrue[i].TsTrue {
trueSum++
}
}
if trueSum == countIsTrue {
isOk = true
} else {
isOk = false
}
}
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-31 10:47:41
@ 功能: 判断人员信息是否符合要求
@ 参数
#condition 节点设定条件发起人相关
#attribute 1申请人为基线2目标人为基线
#applicantCont 申请人信息
#acceptorg 接受行政组织
@ 返回值
#isOk 条件是否通过
@ 方法原型
#func JudgePeopleIsTrue(condition []NodeUserListCont, attribute, sendBackNode string, applicantCont modelshr.PersonArchives, acceptorg int64) (isOk bool)
*/
func JudgePeopleIsTrue(condition []NodeUserListCont, attribute string, applicantCont modelshr.PersonArchives, acceptorg int64) (isOk bool) {
isOk = false
var panDing []InterimCondition
for _, v := range condition {
var panDingCont InterimCondition
panDingCont.Class = v.Type
switch v.Type {
case "1":
myKey := strconv.FormatInt(applicantCont.Key, 10)
if v.TargetID == myKey {
panDingCont.IsOk = true
} else {
panDingCont.IsOk = false
}
panDingCont.TsTrue = true
case "2":
if applicantCont.Role != "" {
myRole := strings.Split(applicantCont.Role, ",")
if publicmethod.IsInTrue[string](v.TargetID, myRole) {
panDingCont.IsOk = true
} else {
panDingCont.IsOk = false
}
} else {
panDingCont.IsOk = false
}
panDingCont.TsTrue = true
case "3":
allOrg := publicmethod.HaveAllOrgRelation(applicantCont.AdminOrg)
targetIdInt, _ := strconv.ParseInt(v.TargetID, 10, 64)
if publicmethod.IsInTrue[int64](targetIdInt, allOrg) {
panDingCont.IsOk = true
} else {
panDingCont.IsOk = false
}
panDingCont.TsTrue = true
default:
isOk = false
}
panDing = append(panDing, panDingCont)
// fmt.Printf("角色哈哈哈哈--->%v--->%v\n", v, panDingCont)
}
if len(panDing) < 1 {
isOk = false
} else {
for _, v := range panDing {
if v.TsTrue && v.IsOk {
isOk = true
break
}
}
}
// fmt.Printf("角色哈哈哈哈-1-->%v\n", panDing)
return
}

247
api/workflow/currency_recipe/type.go

@ -0,0 +1,247 @@
package currency_recipe
import (
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall/publicmethod"
)
// 工作流引擎
type WorkflowEngine struct {
Id string `json:"id"` //版本识别符
VersionId string `json:"versionid"` //版本Id
WorkflowCont FlowStructIng `json:"workflowcont"` //流程主体
Applicant string `json:"applicant"` //申请人
ApplicantCont modelshr.PersonArchives `json:"applicantcont"` //申请人信息
Step int `json:"step"` //计步器
StarNodeNumber string `json:"starnodenumber"` //开始节点
AcceptOrg string `json:"acceptorg"` //接受考核行政组织
JudCond []JudgingCondition `json:"judgingcondition` //关联条件
}
// 工作流结构体
type FlowStructIng struct {
TableId string `json:"tableId"` //流程ID
WorkFlowDef WorkFlowDefStruct `json:"workFlowDef"` //工作流程定义
DirectorMaxLevel int `json:"directorMaxLevel"` //审批主管最大层级
FlowPermission []FlowPermissionStruct `json:"flowPermission"` //发起人
NodeConfig PublicChildNode `json:"nodeConfig"` //流程结构体
}
// 工作流程定义
type WorkFlowDefStruct struct {
publicmethod.PublicName //流程名称
}
// 流程发起权限
type FlowPermissionStruct struct {
Type string `json:"type"` // 1、人员 2、 3、行政组织
TargetId string `json:"targetId"` //人员Key或行政组织ID
publicmethod.PublicName //人名或行政组织名称
Icon string `json:"icon"` //人员头像URL
IconToBase64 string `json:"iconToBase64"` //人员头像 base64加密
}
// 通用字段
type PublicChildNode struct {
NodePublicStruct
Error bool `json:"error"` //当前审批是否通过校验
PriorityLevel int `json:"priorityLevel"` // 条件优先级
Settype int `json:"settype"` // 审批人设置 1指定成员 2主管 4发起人自选 5发起人自己 7连续多级主管 8:指定审批节点自选
SelectMode int `json:"selectMode"` //审批人数 1选一个人 2选多个人
SelectRange int `json:"selectRange"` //选择范围 1.全公司 2指定成员 3指定角色 4:指定部门
DirectorLevel int `json:"directorLevel"` //审批终点 最高层主管数
ExamineMode int `json:"examineMode"` //多人审批时采用的审批方式 1依次审批 2会签
NoHanderAction int `json:"noHanderAction"` //审批人为空时 1自动审批通过/不允许发起 2转交给审核管理员
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"` //审批终点 第n层主管
NodeUserList []NodeUserListCont `json:"nodeUserList"` //操作人
CcSelfSelectFlag int `json:"ccSelfSelectFlag"` //允许发起人自选抄送人
ConditionList []ConditionListCont `json:"conditionList"` //当审批单同时满足以下条件时进入此流程
ChildNode *PublicChildNode `json:"childNode"`
ConditionNodes []PublicChildNode `json:"conditionNodes"` //条件节点
SendBackNode string `json:"sendBackNode"` //退回到哪个节点
DataBaseCondition []DataBaseConditionStruct `json:"databasecondition"` //关联数据库操作
CustomNode string `json:"customNode"` //由哪个节点指定本节点审批人
ExecutionAddress string `json:"executionaddress"` //执行节点跳转页面
}
// 基础结构
type NodePublicStruct struct {
NodeNumber string `json:"nodeNumber"` //节点编号
NodeName string `json:"nodeName"` //节点名称
Type int `json:"type"` // 0 发起人 1审批 2抄送 3执行人 4路由 5条件
FromNode string `json:"fromNode"` //来源节点
GotoNode []string `json:"gotoNode"` //去向节点
Attribute string `json:"attribute"` // 1:申请人为基线;2:目标人为基线
}
// 操作人
type NodeUserListCont struct {
TargetID string `json:"targetId"`
Type string `json:"type"` // 1、人员 2、 3、行政组织,4:
Name string `json:"name"`
Icon string `json:"icon"` //人员头像URL
IconToBase64 string `json:"iconToBase64"` //人员头像 base64加密
}
// 当审批单同时满足以下条件时进入此流程
type ConditionListCont struct {
ColumnID string `json:"columnId"` //
Type int `json:"type"` //1:发起人;2:关联数据表;3:自定义字段
ConditionEn string `json:"conditionEn"`
ConditionCn string `json:"conditionCn"`
OptType string `json:"optType"` //["", "<", ">", "≤", "=", "≥"][optType] 计算符号
Zdy1 string `json:"zdy1"` //左侧自定义内容
Zdy2 string `json:"zdy2"` //右侧自定义内容
Opt1 string `json:"opt1"` //左侧符号 < ≤
Opt2 string `json:"opt2"` //右侧符号 < ≤
ColumnDbname string `json:"columnDbname"` //条件字段名称
ColumnType string `json:"columnType"` //条件字段类型
ShowType string `json:"showType"` //checkBox多选 其他
ShowName string `json:"showName"` //展示名
FixedDownBoxValue string `json:"fixedDownBoxValue"` //多选数组
DataBaseCondition []string `json:"databaseCondition"` //自定义数据库条件
Condition []ConditionStruct `json:"condition"` //自定义字段
}
// 关联数据库执行条件
type DataBaseConditionStruct struct {
DataBaseName string `json:"databasename"` //数据库
TableKey string `json:"tablekey"` //数据表
WordList []WordListCont `json:"wordlist"` //规则列表
}
// 自定义条件字段
type ConditionStruct struct {
WordField string `json:"wordfield"` //字段名称
OptType string `json:"optType"` //["", "<", ">", "≤", "=", "≥","in","not in"][optType] 计算符号 1-8
Factor FactorStruct `json:"factor"` //等式
}
// 等式
type FactorStruct struct {
LeftOptType string `json:"leftoptType"` //左侧等式符号
LeftVal string `json:"leftval"` //左侧等式值
RightOptType string `json:"rightoptType"` //右侧等式符号
RightVal string `json:"rightval"` //右侧等式值
}
// 关联数据规则列表
type WordListCont struct {
Key string `json:"key"` //字段
Type string `json:"type"` //等式类行 1:小于;2:大于;3:小于等于;4:等于;5:大于等于;6:介于两数之间;in:包含;notin:不包含
Comment string `json:"comment"` //字段描述
Notation string `json:"notation"` //符号
Equation EquationStruct `json:"equation"` //等式关系
}
// 等式关系
type EquationStruct struct {
LeftNotation string `json:"leftnotation"` //左侧等式符号
LetfVal string `json:"letfval"` //左侧等式值
RightNotation string `json:"rightnotation"` //右侧等式符号
RightVal string `json:"rightval"` //右侧等式符号
}
// 输出单条结构工作流
type SendOneWorkflow struct {
IsTrue bool `json:"istrue"` //是否允许
Msg string `json:"msg"` //错误信息
CurrentNode string `json:"currentnode"` //当前节点
CurrentUserKey string `json:"currentuserkey"` //当前操作人
CurrentUserOrg string `json:"currentuserorg"` //当前操作人行政组织
Step int `json:"step"` //当前第几步
NodeContList []NodeCont `json:"nodecontlist"` //审批节点列表
Version string `json:"version"` //b版本
}
// 节点信息
type NodeCont struct {
Step int `json:"step"` //步伐
Type int `json:"type"` //节点类型 0:发起人;1:审批;2:抄送;3:执行节点;4:路由;5:条件;
NodeNumber string `json:"nodenumber"` //节点编号
NodeName string `json:"nodename"` //节点名称
State int `json:"state"` //状态 1、不点亮;2、点亮
FromNode string `json:"fromnode"` //来至哪个节点
ArriveNode string `json:"arrivenode"` //到哪个节点
GoBackNode string `json:"gobacknode"` //可得返回节点
ExamineMode int `json:"examinemode"` //多人审批时采用的审批方式 1依次审批 2会签 3:非会签
NoHanderAction int `json:"nohanderaction"` //审批人为空时 1自动审批通过/不允许发起 2转交给审核管理员
UserList []UserListFlowAll `json:"userlist"` //节点操作人
RunType int `json:"runtype"` //运行时选择 0:禁闭;1:发起人自选,2:发起人自己,3:有选中得节点指定,4:抄送节点
RunScope int `json:"runscope"` //运行时选择范围 0:不可选,1:本公司;2:本部门;当RunType = 4时:1:自选;非1:不可自选
CustomNode string `json:"customNode"` //由哪个节点指定本节点审批人
ExecutionAddress string `json:"executionaddress"` //执行节点跳转页面
JudgeList bool `json:"judgelist"` //是否可自己选中操作人
}
// 节点操作人
type UserListFlowAll struct {
Id string `json:"id"` //操作人ID
Name string `json:"name"` //操作人姓名
Icon string `json:"icon"` //操作人头像
IconBase64 string `json:"iconbase64"` //操作人头像
Wechat string `json:"wechat"` //微信Openid
DepartmentId int64 `json:"departmentid"` //分厂Id
DepartmentName string `json:"departmentname"` //分厂名称
PostId int64 `json:"postid"` //职务Id
PostName string `json:"postname"` //职务名称
Tema int64 `json:"tema"` //班组Id
TemaName string `json:"temaname"` //班组名称
LogList []LogList `json:"log"` //操作记录
}
// 节点操作人操作记录
type LogList struct {
State int `json:"state"` //状态 1、未操作;2、通过;3、驳回
TimeVal string `json:"time"`
Cause string `json:"cause"` //审批意见
Enclosure []EnclosureFormat `json:"enclosure"` //附件
}
// 附件格式
type EnclosureFormat struct {
FileName string `json:"filename"` //附件名称
FilePath string `json:"filepath"` //附件地址
Type int `json:"type"` //附件类型
}
// 获取第几级主管
type GainLeveDirector struct {
Step int `json:"step"` //
Leve int `json:"leve"`
UserList []modelshr.PersonArchives
UserId []int64
}
// 判断事那个行政组织得相关岗位
type JudgeOrgOfPosition struct {
publicmethod.PublicName
OrgId int64
PositionId int64
Weight int64
}
// 判断条件
type JudgingCondition struct {
Class int `json:"class"` //类型 1:自定义判断条件;2:关联数据库
DataBaseCont DataBaseConditionStruct `json:"dataBaseCont"` //数据库判断条件
MyCustom []CustomFields `json:"mycustom"` //自定义字段
}
// 自定义字段
type CustomFields struct {
WordField string `json:"wordfield"` //字段名称
LeftVal string `json:"leftval"` //左侧等式值
RightVal string `json:"rightval"` //右侧等式值
}
// 临时条件
type InterimCondition struct {
Class string `json:"class"` //类型
IsOk bool `json:"isok"` //符合与不符合
TsTrue bool `json:"istrue"` //操作与为操作
}
type JudgeNextNodeCont struct {
NodeContList []NodeCont `json:"nodecontlist"` //审批节点列表
}

11
api/workflow/entry.go

@ -0,0 +1,11 @@
package workflow
import (
"key_performance_indicators/api/workflow/workflowengine"
)
type ApiEntry struct {
WorkFlowApi workflowengine.ApiMethod
}
var AppApiEntry = new(ApiEntry)

150
api/workflow/workflowengine/class.go

@ -0,0 +1,150 @@
package workflowengine
import "key_performance_indicators/overall/publicmethod"
//当审批单同时满足以下条件时进入此流程
type ConditionListCont struct {
ColumnID string `json:"columnId"` //
Type int `json:"type"` //1:发起人;2:关联数据表;3:自定义字段
ConditionEn string `json:"conditionEn"`
ConditionCn string `json:"conditionCn"`
OptType string `json:"optType"` //["", "<", ">", "≤", "=", "≥"][optType] 计算符号
Zdy1 string `json:"zdy1"` //左侧自定义内容
Zdy2 string `json:"zdy2"` //右侧自定义内容
Opt1 string `json:"opt1"` //左侧符号 < ≤
Opt2 string `json:"opt2"` //右侧符号 < ≤
ColumnDbname string `json:"columnDbname"` //条件字段名称
ColumnType string `json:"columnType"` //条件字段类型
ShowType string `json:"showType"` //checkBox多选 其他
ShowName string `json:"showName"` //展示名
FixedDownBoxValue string `json:"fixedDownBoxValue"` //多选数组
DataBaseCondition []string `json:"databaseCondition"` //自定义数据库条件
Condition []ConditionStruct `json:"condition"` //自定义字段
}
//自定义条件字段
type ConditionStruct struct {
WordField string `json:"wordfield"` //字段名称
OptType string `json:"optType"` //["", "<", ">", "≤", "=", "≥","in","not in"][optType] 计算符号 1-8
Factor FactorStruct `json:"factor"` //等式
}
//等式
type FactorStruct struct {
LeftOptType string `json:"leftoptType"` //左侧等式符号
LeftVal string `json:"leftval"` //左侧等式值
RightOptType string `json:"rightoptType"` //右侧等式符号
RightVal string `json:"rightval"` //右侧等式值
}
//操作人
type NodeUserListCont struct {
TargetID string `json:"targetId"`
Type string `json:"type"` // 1、人员 2、 3、行政组织,4:
Name string `json:"name"`
Icon string `json:"icon"` //人员头像URL
IconToBase64 string `json:"iconToBase64"` //人员头像 base64加密
}
//通用字段
type PublicChildNode struct {
NodePublicStruct
Error bool `json:"error"` //当前审批是否通过校验
PriorityLevel int `json:"priorityLevel"` // 条件优先级
Settype int `json:"settype"` // 审批人设置 1指定成员 2主管 4发起人自选 5发起人自己 7连续多级主管 8:指定审批节点自选
SelectMode int `json:"selectMode"` //审批人数 1选一个人 2选多个人
SelectRange int `json:"selectRange"` //选择范围 1.全公司 2指定成员 2指定角色
DirectorLevel int `json:"directorLevel"` //审批终点 最高层主管数
ExamineMode int `json:"examineMode"` //多人审批时采用的审批方式 1依次审批 2会签
NoHanderAction int `json:"noHanderAction"` //审批人为空时 1自动审批通过/不允许发起 2转交给审核管理员
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"` //审批终点 第n层主管
NodeUserList []NodeUserListCont `json:"nodeUserList"` //操作人
CcSelfSelectFlag int `json:"ccSelfSelectFlag"` //允许发起人自选抄送人
ConditionList []ConditionListCont `json:"conditionList"` //当审批单同时满足以下条件时进入此流程
ChildNode *PublicChildNode `json:"childNode"`
ConditionNodes *[]PublicChildNode `json:"conditionNodes"` //条件节点
SendBackNode string `json:"sendBackNode"` //退回到哪个节点
DataBaseCondition []DataBaseConditionStruct `json:"databasecondition"` //关联数据库操作
CustomNode string `json:"customNode"` //由哪个节点指定本节点审批人
ExecutionAddress string `json:"executionaddress"` //执行节点跳转页面
}
//关联数据库执行条件
type DataBaseConditionStruct struct {
DataBaseName string `json:"databasename"` //数据库
TableKey string `json:"tablekey"` //数据表
WordList []WordListCont `json:"wordlist"` //规则列表
}
//关联数据规则列表
type WordListCont struct {
Key string `json:"key"` //字段
Type string `json:"type"` //等式类行 1:小于;2:大于;3:小于等于;4:等于;5:大于等于;6:介于两数之间;in:包含;notin:不包含
Comment string `json:"comment"` //字段描述
Notation string `json:"notation"` //符号
Equation EquationStruct `json:"equation"` //等式关系
}
//等式关系
type EquationStruct struct {
LeftNotation string `json:"leftnotation"` //左侧等式符号
LetfVal string `json:"letfval"` //左侧等式值
RightNotation string `json:"rightnotation"` //右侧等式符号
RightVal string `json:"rightval"` //右侧等式符号
}
//基础结构
type NodePublicStruct struct {
NodeNumber string `json:"nodeNumber"` //节点编号
NodeName string `json:"nodeName"` //节点名称
Type int `json:"type"` // 0 发起人 1审批 2抄送 3执行人 4路由 5条件
FromNode string `json:"fromNode"` //来源节点
GotoNode []string `json:"gotoNode"` //去向节点
Attribute string `json:"attribute"` // 1:申请人为基线;2:目标人为基线
}
//工作流结构体
type FlowStructIng struct {
TableId string `json:"tableId"` //流程ID
WorkFlowDef WorkFlowDefStruct `json:"workFlowDef"` //工作流程定义
DirectorMaxLevel int `json:"directorMaxLevel"` //审批主管最大层级
FlowPermission []FlowPermissionStruct `json:"flowPermission"` //发起人
NodeConfig PublicChildNode `json:"nodeConfig"` //流程结构体
}
//流程发起权限
type FlowPermissionStruct struct {
Type string `json:"type"` // 1、人员 2、 3、行政组织
TargetId string `json:"targetId"` //人员Key或行政组织ID
publicmethod.PublicName //人名或行政组织名称
Icon string `json:"icon"` //人员头像URL
IconToBase64 string `json:"iconToBase64"` //人员头像 base64加密
}
//输出全部节点信息
type outAllNodeCont struct {
AllCont []NodePublicStruct `json:"allcont"`
AllNumber []string `json:"allnumber"`
}
//判断上级操作节点
type JudgePrintNode struct {
publicmethod.PublicId
AllCont []NodePublicStruct `json:"allcont"`
}
//输出上级操作节点
type OutputPrintNode struct {
AllCont []NodePublicStruct `json:"allcont"`
Total int `json:"total"` //总数
}
//分支条件
type BranchingCondition struct {
ColumnId string `json:"columnId"` //条件id columnId == 0 为发起人
ShowType string `json:"showType"` //columnType == "String" && showType == "checkBox"为多选
ShowName string `json:"showName"` //名称
ColumnName string `json:"columnName"` //columnName 条件自定义字段
ColumnType string `json:"columnType"` //columnType == "Double"为区间
FixedDownBoxValue string `json:"fixedDownBoxValue"` //fixedDownBoxValue 匹配 columnType == "String" && showType == "checkBox"时子选项内容
}

21
api/workflow/workflowengine/entry.go

@ -0,0 +1,21 @@
package workflowengine
import (
"key_performance_indicators/overall/publicmethod"
"sync"
"github.com/gin-gonic/gin"
)
// 工作流引擎
type ApiMethod struct{}
// 协程设置
var syncSeting = sync.WaitGroup{}
// 系统内部审批处理
func (a *ApiMethod) Index(c *gin.Context) {
outputCont := publicmethod.MapOut[string]()
outputCont["index"] = "工作流引擎入口"
publicmethod.Result(0, outputCont, c)
}

120
api/workflow/workflowengine/es.go

@ -0,0 +1,120 @@
package workflowengine
type JSONData struct {
TableID string `json:"tableId"`
WorkFlowDef struct {
Name string `json:"name"`
} `json:"workFlowDef"`
DirectorMaxLevel int `json:"directorMaxLevel"`
FlowPermission []interface{} `json:"flowPermission"`
NodeConfig struct {
NodeName string `json:"nodeName"`
Type int `json:"type"`
PriorityLevel int `json:"priorityLevel"`
Settype int `json:"settype"`
SelectMode int `json:"selectMode"`
SelectRange int `json:"selectRange"`
DirectorLevel int `json:"directorLevel"`
ExamineMode int `json:"examineMode"`
NoHanderAction int `json:"noHanderAction"`
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"`
CcSelfSelectFlag int `json:"ccSelfSelectFlag"`
ConditionList []interface{} `json:"conditionList"`
NodeUserList []interface{} `json:"nodeUserList"`
ChildNode struct {
NodeName string `json:"nodeName"`
Error bool `json:"error"`
Type int `json:"type"`
Settype int `json:"settype"`
SelectMode int `json:"selectMode"`
SelectRange int `json:"selectRange"`
DirectorLevel int `json:"directorLevel"`
ExamineMode int `json:"examineMode"`
NoHanderAction int `json:"noHanderAction"`
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"`
ChildNode struct {
NodeName string `json:"nodeName"`
Type int `json:"type"`
PriorityLevel int `json:"priorityLevel"`
Settype int `json:"settype"`
SelectMode int `json:"selectMode"`
SelectRange int `json:"selectRange"`
DirectorLevel int `json:"directorLevel"`
ExamineMode int `json:"examineMode"`
NoHanderAction int `json:"noHanderAction"`
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"`
CcSelfSelectFlag int `json:"ccSelfSelectFlag"`
ConditionList []interface{} `json:"conditionList"`
NodeUserList []interface{} `json:"nodeUserList"`
ChildNode struct {
NodeName string `json:"nodeName"`
Type int `json:"type"`
CcSelfSelectFlag int `json:"ccSelfSelectFlag"`
ChildNode interface{} `json:"childNode"`
NodeUserList []interface{} `json:"nodeUserList"`
Error bool `json:"error"`
} `json:"childNode"`
ConditionNodes []struct {
NodeName string `json:"nodeName"`
Type int `json:"type"`
PriorityLevel int `json:"priorityLevel"`
Settype int `json:"settype"`
SelectMode int `json:"selectMode"`
SelectRange int `json:"selectRange"`
DirectorLevel int `json:"directorLevel"`
ExamineMode int `json:"examineMode"`
NoHanderAction int `json:"noHanderAction"`
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"`
CcSelfSelectFlag int `json:"ccSelfSelectFlag"`
ConditionList []struct {
ColumnID int `json:"columnId"`
Type int `json:"type"`
ConditionEn string `json:"conditionEn"`
ConditionCn string `json:"conditionCn"`
OptType string `json:"optType"`
Zdy1 string `json:"zdy1"`
Zdy2 string `json:"zdy2"`
Opt1 string `json:"opt1"`
Opt2 string `json:"opt2"`
ColumnDbname string `json:"columnDbname"`
ColumnType string `json:"columnType"`
ShowType string `json:"showType"`
ShowName string `json:"showName"`
FixedDownBoxValue string `json:"fixedDownBoxValue"`
} `json:"conditionList"`
NodeUserList []struct {
TargetID int `json:"targetId"`
Type int `json:"type"`
Name string `json:"name"`
} `json:"nodeUserList"`
ChildNode struct {
NodeName string `json:"nodeName"`
Type int `json:"type"`
PriorityLevel int `json:"priorityLevel"`
Settype int `json:"settype"`
SelectMode int `json:"selectMode"`
SelectRange int `json:"selectRange"`
DirectorLevel int `json:"directorLevel"`
ExamineMode int `json:"examineMode"`
NoHanderAction int `json:"noHanderAction"`
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"`
CcSelfSelectFlag int `json:"ccSelfSelectFlag"`
ConditionList []interface{} `json:"conditionList"`
NodeUserList []struct {
TargetID int `json:"targetId"`
Type int `json:"type"`
Name string `json:"name"`
} `json:"nodeUserList"`
ChildNode interface{} `json:"childNode"`
ConditionNodes []interface{} `json:"conditionNodes"`
Error bool `json:"error"`
} `json:"childNode"`
ConditionNodes []interface{} `json:"conditionNodes"`
Error bool `json:"error"`
} `json:"conditionNodes"`
} `json:"childNode"`
NodeUserList []interface{} `json:"nodeUserList"`
} `json:"childNode"`
ConditionNodes []interface{} `json:"conditionNodes"`
} `json:"nodeConfig"`
}

297
api/workflow/workflowengine/flowhandle.go

@ -0,0 +1,297 @@
package workflowengine
import (
"encoding/json"
"fmt"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strings"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-03-06 13:35:25
@ 功能: 判断是否显示指定审批节点自选选项及可选节点
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) JudgeOptionalNode(c *gin.Context) {
var receivedValue PublicChildNode
c.ShouldBindJSON(&receivedValue)
var alc outAllNodeCont
alc.sendAllNode(receivedValue)
publicmethod.Result(0, alc, c)
}
// 递归输出所有节点
func (o *outAllNodeCont) sendAllNode(val PublicChildNode) {
var cont NodePublicStruct
cont.NodeName = val.NodeName
cont.NodeNumber = val.NodeNumber
cont.Type = val.Type
cont.FromNode = val.FromNode
cont.GotoNode = val.GotoNode
if publicmethod.IsInTrue[string](val.NodeNumber, o.AllNumber) == false {
o.AllCont = append(o.AllCont, cont)
o.AllNumber = append(o.AllNumber, val.NodeNumber)
}
if val.ChildNode != nil {
o.sendAllNode(*val.ChildNode)
}
if val.ConditionNodes != nil && len(*val.ConditionNodes) > 0 {
for _, v := range *val.ConditionNodes {
o.sendAllNode(v)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-06 14:53:49
@ 功能: 获取所有父级审批节点
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetAllParentNode(c *gin.Context) {
var receivedValue JudgePrintNode
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, err, c)
return
}
var sendCont OutputPrintNode
if len(receivedValue.AllCont) < 1 {
sendCont.Total = 0
publicmethod.Result(0, sendCont, c)
return
}
var outCont outAllNodeCont
outCont.SeekFromNodeCont(receivedValue.Id, receivedValue.AllCont)
var daoXun []NodePublicStruct
contLen := len(outCont.AllCont)
if contLen > 0 {
for i := contLen - 1; i >= 0; i-- {
daoXun = append(daoXun, outCont.AllCont[i])
}
}
sendCont.AllCont = daoXun
sendCont.Total = len(outCont.AllCont)
publicmethod.Result(0, sendCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-07 08:35:59
@ 功能: 递归查找所有上级审批点
@ 参数
#parentNumber 来源节点编号
#allListCont 所有可操作节点
@ 返回值
#outAllNodeCont 结果集
@ 方法原型
#func (o *outAllNodeCont) SeekFromNodeCont(parentNumber string, allListCont []NodePublicStruct)
*/
func (o *outAllNodeCont) SeekFromNodeCont(parentNumber string, allListCont []NodePublicStruct) {
for _, v := range allListCont {
if v.NodeNumber == parentNumber {
if v.Type == 1 || v.Type == 3 {
if !publicmethod.IsInTrue[string](v.NodeNumber, o.AllNumber) {
o.AllCont = append(o.AllCont, v)
o.AllNumber = append(o.AllNumber, v.NodeNumber)
}
}
if v.FromNode != "" {
o.SeekFromNodeCont(v.FromNode, allListCont)
}
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-08 16:00:58
@ 功能: 判断条件
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) JudgingCondition(c *gin.Context) {
var sendListCont []BranchingCondition
//自定义判断条件
var customConditions BranchingCondition
customConditions.ColumnId = "99143260231966110" //条件id columnId == 0 为发起人
customConditions.ShowType = "input" //columnType == "String" && showType == "checkBox"为多选
customConditions.ShowName = "自定义判断条件" //名称
customConditions.ColumnName = "customConditions" //columnName 条件自定义字段
customConditions.ColumnType = "custom" //columnType == "Double"为区间
sendListCont = append(sendListCont, customConditions)
//数据库表
var datatableList []DataBaseCont
var dataBaseCont DataBaseCont
dataBaseCont.Key = "hr_new"
dataBaseCont.Name = "HR数据库"
datatableList = append(datatableList, dataBaseCont)
var dataBaseCont1 DataBaseCont
dataBaseCont1.Key = "perform"
dataBaseCont1.Name = "绩效考核数据库"
datatableList = append(datatableList, dataBaseCont1)
var dataBaseTable BranchingCondition
dataBaseTable.ColumnId = "99143260231966720" //条件id columnId == 0 为发起人
dataBaseTable.ShowType = "datatable" //columnType == "String" && showType == "checkBox"为多选
dataBaseTable.ShowName = "关联数据表" //名称
dataBaseTable.ColumnName = "datatablelist" //columnName 条件自定义字段
dataBaseTable.ColumnType = "datatable" //columnType == "Double"为区间
//
datatableListStr, _ := json.Marshal(datatableList)
dataBaseTable.FixedDownBoxValue = string(datatableListStr) //fixedDownBoxValue 匹配 columnType == "String" && showType == "checkBox"时子选项内容
sendListCont = append(sendListCont, dataBaseTable)
publicmethod.Result(0, sendListCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-22 14:14:05
@ 功能: 获取数据表结构
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetDataBaseTable(c *gin.Context) {
var receivedValue publicmethod.PublicName
err := c.ShouldBindJSON(&receivedValue)
if err != nil || receivedValue.Name == "" {
receivedValue.Name = "perform"
}
gormDb := overall.CONSTANT_DB_KPI
switch receivedValue.Name {
case "perform":
gormDb = overall.CONSTANT_DB_KPI
case "hr_new":
gormDb = overall.CONSTANT_DB_HR
default:
gormDb = overall.CONSTANT_DB_KPI
}
tables := make([]string, 0)
// tableint := publicmethod.MapOut[string]()
gormDb.Raw("SHOW TABLES").Scan(&tables)
// gormDb.Raw("SHOW TABLES").Scan(&tableint)
var datatableList []DataBaseCont
for _, v := range tables {
var tableCont DataBaseCont
tableCont.Key = v
tableCont.Name = v
datatableList = append(datatableList, tableCont)
}
// sendData := publicmethod.MapOut[string]()
// sendData["tables"] = tables
// sendData["tableint"] = tableint
publicmethod.Result(0, datatableList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-22 14:32:05
@ 功能: 获取数据表结构
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetDataBaseTableCont(c *gin.Context) {
var receivedValue DataBaseInfo
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.DataBaseName == "" {
publicmethod.Result(1, err, c, "未知数据库")
return
}
if receivedValue.TablesName == "" {
publicmethod.Result(1, err, c, "未知数据表")
return
}
gormDb := overall.CONSTANT_DB_KPI
switch receivedValue.DataBaseName {
case "perform":
gormDb = overall.CONSTANT_DB_KPI
case "hr_new":
gormDb = overall.CONSTANT_DB_HR
default:
gormDb = overall.CONSTANT_DB_KPI
}
sqlStr := fmt.Sprintf("SHOW FULL COLUMNS FROM %v", receivedValue.TablesName)
var tableList []OutPutDataBaseTable
gormDb.Raw(sqlStr).Scan(&tableList)
for i, v := range tableList {
if strings.Contains(v.Type, "int") || strings.Contains(v.Type, "float") || strings.Contains(v.Type, "double") || strings.Contains(v.Type, "decimal") {
tableList[i].Type = "int"
}
if strings.Contains(v.Type, "char") || strings.Contains(v.Type, "text") || strings.Contains(v.Type, "year") || strings.Contains(v.Type, "time") || strings.Contains(v.Type, "date") {
tableList[i].Type = "string"
}
}
publicmethod.Result(0, tableList, c)
}

66
api/workflow/workflowengine/shiyan.go

@ -0,0 +1,66 @@
package workflowengine
import (
"key_performance_indicators/overall/publicmethod"
"strconv"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-01-18 09:43:42
@ 功能: 实验用
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) ShiyanData(c *gin.Context) {
// jsonStr := `{"tableId":"1","workFlowDef":{"name":"合同审批"},"directorMaxLevel":4,"flowPermission":[],"nodeConfig":{"nodeName":"发起人","type":0,"priorityLevel":0,"settype":0,"selectMode":0,"selectRange":0,"directorLevel":0,"examineMode":0,"noHanderAction":0,"examineEndDirectorLevel":0,"ccSelfSelectFlag":0,"conditionList":[],"nodeUserList":[],"childNode":{"nodeName":"审核人","error":false,"type":1,"settype":2,"selectMode":0,"selectRange":0,"directorLevel":1,"examineMode":1,"noHanderAction":2,"examineEndDirectorLevel":0,"childNode":{"nodeName":"路由","type":4,"priorityLevel":1,"settype":1,"selectMode":0,"selectRange":0,"directorLevel":1,"examineMode":1,"noHanderAction":2,"examineEndDirectorLevel":1,"ccSelfSelectFlag":1,"conditionList":[],"nodeUserList":[],"childNode":{"nodeName":"抄送人","type":2,"ccSelfSelectFlag":1,"childNode":null,"nodeUserList":[],"error":false},"conditionNodes":[{"nodeName":"条件1","type":3,"priorityLevel":1,"settype":1,"selectMode":0,"selectRange":0,"directorLevel":1,"examineMode":1,"noHanderAction":2,"examineEndDirectorLevel":1,"ccSelfSelectFlag":1,"conditionList":[{"columnId":0,"type":1,"conditionEn":"","conditionCn":"","optType":"","zdy1":"","zdy2":"","opt1":"","opt2":"","columnDbname":"","columnType":"","showType":"","showName":"","fixedDownBoxValue":""}],"nodeUserList":[{"targetId":85,"type":1,"name":"天旭"}],"childNode":{"nodeName":"审核人","type":1,"priorityLevel":1,"settype":1,"selectMode":0,"selectRange":0,"directorLevel":1,"examineMode":1,"noHanderAction":2,"examineEndDirectorLevel":1,"ccSelfSelectFlag":1,"conditionList":[],"nodeUserList":[{"targetId":2515744,"type":1,"name":"哈哈哈哈"}],"childNode":null,"conditionNodes":[],"error":false},"conditionNodes":[],"error":false},{"nodeName":"条件2","type":3,"priorityLevel":2,"settype":1,"selectMode":0,"selectRange":0,"directorLevel":1,"examineMode":1,"noHanderAction":2,"examineEndDirectorLevel":1,"ccSelfSelectFlag":1,"conditionList":[],"nodeUserList":[],"childNode":null,"conditionNodes":[],"error":false}]},"nodeUserList":[]},"conditionNodes":[]}}`
// jsonStrSmaill := `{
// "tableId": "1",
// "workFlowDef": {
// "name": "合同审批"
// },
// "directorMaxLevel": 4,
// "flowPermission": {},
// "nodeConfig": {
// "nodeName": "发起人",
// "type": 0,
// "priorityLevel": 0,
// "settype": 0,
// "selectMode": 0,
// "selectRange": 0,
// "directorLevel": 0,
// "examineMode": 0,
// "noHanderAction": 0,
// "examineEndDirectorLevel": 0,
// "ccSelfSelectFlag": 0,
// "conditionList": {},
// "nodeUserList": {},
// "conditionNodes": {}
// }
// }`
var workFlowStruct FlowStructIng
workFlowStruct.TableId = strconv.FormatInt(publicmethod.GetUUid(2), 10)
workFlowStruct.WorkFlowDef.Name = "自定义工作流"
workFlowStruct.NodeConfig.NodeNumber = strconv.FormatInt(publicmethod.GetUUid(5), 10)
workFlowStruct.NodeConfig.NodeName = "发起人"
workFlowStruct.DirectorMaxLevel = 4
// err := json.Unmarshal([]byte(jsonStrSmaill), &workFlowStruct)
outData := publicmethod.MapOut[string]()
outData["workFlowStruct"] = workFlowStruct
// outData["err"] = err
publicmethod.Result(0, workFlowStruct, c)
}

179
api/workflow/workflowengine/type.go

@ -0,0 +1,179 @@
package workflowengine
import (
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall/publicmethod"
)
// 工作流结构体
type FlowStruct struct {
TableId string `json:"tableId"` //流程ID
WorkFlowDef WorkFlowDefStruct `json:"workFlowDef"` //工作流程定义
DirectorMaxLevel int `json:"directorMaxLevel"` //审批主管最大层级
FlowPermission []string `json:"flowPermission"` //发起人
NodeConfig NodeConfigStruct `json:"nodeConfig"` //流程结构体
}
// 工作流程定义
type WorkFlowDefStruct struct {
publicmethod.PublicName //流程名称
}
// 流程结构体
type NodeConfigStruct struct {
PublicNodeWord
ChildNode PublicNodeWord `json:"childNode"` //流程标准结构
}
// 流程结构体通用字段
type PublicNodeWord struct {
IsTrue bool `json:"error"` //当前审批是否通过校验
NodeName string `json:"nodeName"` //节点名称
Attribute string `json:"attribute"` //节点名称操作识别
Type int `json:"type"` // 0 发起人 1审批 2抄送 3条件 4路由
PriorityLevel int `json:"priorityLevel"` //条件优先级 0,1,2,3,4,5,6,7,8,9,10
Settype int `json:"settype"` // 审批人设置 1指定成员 2主管 4发起人自选 5发起人自己 7连续多级主管
SelectMode int `json:"selectMode"` //审批人数 0不选 1选一个人 2选多个人
SelectRange int `json:"selectRange"` //选择范围 0 1.全公司 2指定成员 2指定角色
DirectorLevel int `json:"directorLevel"` //审批终点 最高层主管数
ExamineMode int `json:"examineMode"` //多人审批时采用的审批方式 1依次审批 2会签
NoHanderAction int `json:"noHanderAction"` //审批人为空时 1自动审批通过/不允许发起 2转交给审核管理员
ExamineEndDirectorLevel int `json:"examineEndDirectorLevel"` //审批终点 第n层主管
CcSelfSelectFlag int `json:"ccSelfSelectFlag"` //允许发起人自选抄送人
ConditionList []ConditionListStruct `json:"conditionList"` //当审批单同时满足以下条件时进入此流程
NodeUserList []NodeUserListType `json:"nodeUserList"` //操作人
}
// 审批条件结构体
type ConditionListStruct struct {
ColumnId string `json:"columnId"` //发起人
OptType string `json:"optType"` //运算符 ["", "<", ">", "≤", "=", "≥"][optType]
Zdy1 string `json:"zdy1"` //自定义内容
Zdy2 string `json:"zdy2"` //自定义内容
Opt1 string `json:"opt1"` //左侧符号 < ≤
Opt2 string `json:"opt2"` //右侧符号 < ≤
ColumnDbname string `json:"columnDbname"` //条件字段名称
ColumnType string `json:"columnType"` //条件字段类型
ShowType string `json:"showType"` //checkBox多选 其他
ShowName string `json:"showName"` //展示名
FixedDownBoxValue string `json:"fixedDownBoxValue"` //多选数组
}
// 操作人
type NodeUserListType struct {
TargetId string `json:"targetId"` //操作人Key
publicmethod.PublicName //操作人姓名
}
// 输出数据库列表
type DataBaseCont struct {
Key string `json:"key"` //数据库识别符
publicmethod.PublicName //数据库名称
}
// 数据表结构
type DataBaseInfo struct {
DataBaseName string `json:"databasename"`
TablesName string `json:"tablesname"`
}
// 输出数据库表格字段
type OutPutDataBaseTable struct {
Field string `json:"field"` //字段名
Key string `json:"key"` //是否有索引;PRI表示是主键的一部分;UNI表示该列是UNIQUE索引的一部分;MUL表示某个给定值允许出现多次
Type string `json:"type"` //字段类型
Default string `json:"default"` //默认值
Null string `json:"null"` //是否可以为空
Extra string `json:"extra"` //表示可以获取的与给定列有关的附加信息
Privileges string `json:"privileges"` //可执行操作
Comment string `json:"comment"` //字段描述
}
// 获取工作流列表
type GetWorkFlow struct {
publicmethod.PublicName
publicmethod.PagesTurn
}
// 接收发布工作流数据
type PublishWorkFlowCont struct {
Flowid string `json:"flowid"` //工作流ID
publicmethod.PublicName //工作流名称
Describe string `json:"describe"` //描述
Flowcont FlowStructIng `json:"flowcont"` //流程主体
WeChat int `json:"wechat"` //关联企业微信
}
// 输出工作流列表
type WorkFlowList struct {
modelskpi.WorkFlowCont
Key string `json:"key"`
}
// 查看工作流
type LookWorkFlow struct {
publicmethod.PublicId //工作流编号
Version string `json:"version"` //版本
}
// 编辑工作流
type EditWorkFlowInfo struct {
PublishWorkFlowCont
VersionId string `json:"versionid"` //版本ID
}
// 获取工作流
type GetWorkFlowInfoIng struct {
FlowWorkId string `json:"flowworkid"` //
OrgId string `json:"orgid"` //接受考核得行政组织
Condition []MyCondition `json:"condition"`
}
// 自定义条件
type MyCondition struct {
Words string `json:"words"` //字段
Price string `json:"price"` //值
}
// 操作工作流
type OperateWorkflow struct {
Step int `json:"step"` //操作哪一步
NextStep int //下一步
OrderId int64 `json:"orderid"` //发起表单ID
Attribute int `json:"attribute"` //属性 1、定性;2、定量
OperationStatus int `json:"operationstatus"` //操作状态
ManipulatePeople ManipulatePeopleInfo //操作人相关
UploadFiles []currency_recipe.EnclosureFormat
WorkFlowList []currency_recipe.NodeCont //流程步进图
EndFlow bool //流程是否结束
Participant []string //参与人
NextNodeCont currency_recipe.NodeCont //下一个节点
NextNodeContExecutor []string //下一步执行人
CurrentNode currency_recipe.NodeCont //当前节点
}
// 附件文件
type UploadFilesCont struct {
publicmethod.PublicName //文件名称
FileUrl string `json:"fileUrl"` //文件访问地址
PhysicsPath string `json:"physicspath"` //文件物理地址
Type int `json:"type"` //类型 1:图片;2:视频;3:office文档;4:压缩文件;5:其他文件
FileSize int64 `json:"fileSize"` //文件大小(单位:B)
Size string `json:"size"` //文件大小文字描述
Tag string `json:"tag"` //文件后缀
}
// 操作人信息
type ManipulatePeopleInfo struct {
Key string `json:"key"` //操作人
OrgId string `json:"orgid"` //操作人行政组织
}
// 指标相关
type TargetInfo struct {
TargeiId int64
TableId int64
BylawsId int64
}

544
api/workflow/workflowengine/workflow.go

@ -0,0 +1,544 @@
package workflowengine
import (
"encoding/json"
"fmt"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-03-24 14:41:00
@ 功能: 获取工作流列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetWorkFlowList(c *gin.Context) {
var receivedValue GetWorkFlow
c.ShouldBindJSON(&receivedValue)
if receivedValue.Page == 0 {
receivedValue.Page = 1
}
if receivedValue.PageSize == 0 {
receivedValue.PageSize = 20
}
var listCont []modelskpi.WorkFlowCont
gormDb := overall.CONSTANT_DB_KPI.Model(&modelskpi.WorkFlowCont{}).Where("`state` = 1 AND `vstate` = 1")
if receivedValue.Name != "" {
gormDb = gormDb.Where("`name` LIKE ?", "%"+receivedValue.Name+"%")
}
var total int64
totalErr := gormDb.Count(&total).Error
if totalErr != nil {
total = 0
}
gormDb = publicmethod.PageTurningSettings(gormDb, receivedValue.Page, receivedValue.PageSize)
err := gormDb.Find(&listCont).Error
if err != nil || len(listCont) < 1 {
publicmethod.Result(107, err, c)
return
}
var sendListCont []WorkFlowList
for _, v := range listCont {
var sendCont WorkFlowList
sendCont.Id = v.Id //Id"`
sendCont.Name = v.Name //维度"`
sendCont.Content = v.Content //关联部门"`
sendCont.Version = v.Version //维度"`
sendCont.Describe = v.Describe //描述"`
sendCont.State = v.State //状态(1:启用;2:禁用;3:删除)"`
sendCont.VersionState = v.VersionState //状态(1:启用;2:禁用;3:删除)"`
sendCont.Time = v.Time //写入时间"`
sendCont.VersionId = v.VersionId //附表ID
sendCont.OpenWechat = v.OpenWechat
sendCont.Key = strconv.FormatInt(v.Id, 10)
sendListCont = append(sendListCont, sendCont)
}
publicmethod.ResultList(0, receivedValue.Page, receivedValue.PageSize, total, int64(len(sendListCont)), sendListCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-25 10:42:01
@ 功能: 发布工作流
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) PublishWorkFlow(c *gin.Context) {
var receivedValue PublishWorkFlowCont
c.ShouldBindJSON(&receivedValue)
if receivedValue.Name == "" {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.Flowid == "" {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.WeChat == 0 {
receivedValue.WeChat = 1
}
flowContStr, err := json.Marshal(receivedValue.Flowcont)
if err != nil {
publicmethod.Result(1, err, c, "您提交的流程格式不正确!")
return
}
// hjsdahkf := publicmethod.MapOut[string]()
// hjsdahkf["flowContStr"] = string(flowContStr)
// hjsdahkf["Flowcont"] = receivedValue.Flowcont
// publicmethod.Result(1, hjsdahkf, c, "您提交的流程格式不正确!")
// return
flowKey, _ := strconv.ParseInt(receivedValue.Flowid, 10, 64)
var workFlowCont modelskpi.WorkFlow
var workFlowVerSion modelskpi.WorkFlowVersion
//判断是否已经存在
where := publicmethod.MapOut[string]()
where["`key`"] = receivedValue.Flowid
err = workFlowVerSion.GetCont(where, "`id`")
dayTime := time.Now().Unix()
if err == nil {
//已经存在此流程编号新增流程版本
var totalFlowVersion int64
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.WorkFlowVersion{}).Select("`id`").Count(&totalFlowVersion).Error
if err != nil {
totalFlowVersion = 1
} else {
totalFlowVersion = totalFlowVersion + 1
}
stateVersion := 1
where["`state`"] = 1
err = workFlowVerSion.GetCont(where, "`id`")
if err == nil {
stateVersion = 2
}
workFlowVerSion.Id = flowKey //流程标号
workFlowVerSion.Content = string(flowContStr) //工作流主体
workFlowVerSion.Version = strconv.FormatInt(totalFlowVersion, 10) //版本
workFlowVerSion.Time = dayTime //写入时间"`
workFlowVerSion.State = stateVersion //状态(1:启用;2:禁用;3:删除)"`
err := overall.CONSTANT_DB_KPI.Create(&workFlowVerSion).Error
if err == nil {
publicmethod.Result(0, err, c)
} else {
publicmethod.Result(104, err, c)
}
} else {
workFlowCont.Id = flowKey //流程标号
workFlowCont.Name = receivedValue.Name //
workFlowCont.Time = dayTime //写入时间"`
workFlowCont.Describe = receivedValue.Describe //描述
workFlowCont.State = 1
workFlowCont.OpenWechat = receivedValue.WeChat
workFlowVerSion.Key = flowKey //流程标号
workFlowVerSion.Content = string(flowContStr) //工作流主体
workFlowVerSion.Version = "1" //版本
workFlowVerSion.Time = dayTime //写入时间"`
workFlowVerSion.State = 1 //状态(1:启用;2:禁用;3:删除)"`
//写入数据
gormDb := overall.CONSTANT_DB_KPI.Begin()
flowContErr := gormDb.Create(&workFlowCont).Error
flowVersion := gormDb.Create(&workFlowVerSion).Error
if flowContErr == nil && flowVersion == nil {
addErr := gormDb.Commit().Error
publicmethod.Result(0, addErr, c)
} else {
addErr := gormDb.Rollback().Error
publicmethod.Result(104, addErr, c)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-25 15:12:44
@ 功能: 编辑主流程状态
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EditWorkFlowState(c *gin.Context) {
var receivedValue publicmethod.PublicState
c.ShouldBindJSON(&receivedValue)
if receivedValue.Id == "" {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.State == 0 {
receivedValue.State = 1
}
if receivedValue.IsTrue == 0 {
receivedValue.IsTrue = 2
}
where := publicmethod.MapOut[string]()
where["`id`"] = receivedValue.Id
var workFlowCont modelskpi.WorkFlow
err := workFlowCont.GetCont(where)
if err != nil {
publicmethod.Result(104, err, c)
return
}
if receivedValue.IsTrue != 1 {
saveData := publicmethod.MapOut[string]()
saveData["`state`"] = receivedValue.State
saveData["`time`"] = time.Now().Unix()
err = workFlowCont.EiteCont(where, saveData)
publicmethod.Result(0, err, c)
} else {
if receivedValue.State != 3 {
saveData := publicmethod.MapOut[string]()
saveData["`state`"] = receivedValue.State
saveData["`time`"] = time.Now().Unix()
err = workFlowCont.EiteCont(where, saveData)
publicmethod.Result(0, err, c)
} else {
gormDb := overall.CONSTANT_DB_KPI.Begin()
delContErr := gormDb.Where("`id` = ?", receivedValue.Id).Delete(&workFlowCont).Error
delVersiontErr := gormDb.Where("`key` = ?", receivedValue.Id).Delete(&modelskpi.WorkFlowVersion{}).Error
if delContErr == nil && delVersiontErr == nil {
addErr := gormDb.Commit().Error
publicmethod.Result(0, addErr, c)
} else {
addErr := gormDb.Rollback().Error
publicmethod.Result(104, addErr, c)
}
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-25 15:40:10
@ 功能: 查看工作流
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) LookWorkFlowCont(c *gin.Context) {
var receivedValue LookWorkFlow
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(1, err, c, "未知流程")
return
}
if receivedValue.Version == "" {
publicmethod.Result(1, err, c, "wei")
return
}
where := publicmethod.MapOut[string]()
where["`id`"] = receivedValue.Id
where["`version`"] = receivedValue.Version
var workFlowCont modelskpi.WorkFlowCont
err = workFlowCont.GetCont(where)
if err != nil {
publicmethod.Result(107, err, c)
return
}
var sendCont PublishWorkFlowCont
sendCont.Flowid = strconv.FormatInt(workFlowCont.Id, 10)
sendCont.Name = workFlowCont.Name
sendCont.Describe = workFlowCont.Describe
// sendCont.Flowcont = json.Unmarshal()
err = json.Unmarshal([]byte(workFlowCont.Content), &sendCont.Flowcont)
fmt.Printf("err ---->%v\n", err)
publicmethod.Result(0, sendCont, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-25 16:30:22
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) InitializeWorkFlow(c *gin.Context) {
var workFlowStruct FlowStructIng
workFlowStruct.TableId = strconv.FormatInt(publicmethod.GetUUid(2), 10)
workFlowStruct.WorkFlowDef.Name = "自定义工作流"
workFlowStruct.NodeConfig.NodeNumber = strconv.FormatInt(publicmethod.GetUUid(5), 10)
workFlowStruct.NodeConfig.NodeName = "发起人"
workFlowStruct.DirectorMaxLevel = 4
// err := json.Unmarshal([]byte(jsonStrSmaill), &workFlowStruct)
outData := publicmethod.MapOut[string]()
outData["workFlowStruct"] = workFlowStruct
// outData["err"] = err
publicmethod.Result(0, workFlowStruct, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-27 15:17:50
@ 功能: 获取流程版本列表
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetWorkFlowVersionList(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, err, c)
return
}
var flowVersionList []modelskpi.WorkFlowVersion
err = overall.CONSTANT_DB_KPI.Where("`key` = ? AND `state` BETWEEN ? AND ?", receivedValue.Id, 1, 2).Order("id asc").Find(&flowVersionList).Error
if err != nil {
publicmethod.Result(107, err, c)
return
}
publicmethod.Result(0, flowVersionList, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-28 08:55:54
@ 功能:编辑流程主体
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) EditWorkFlowCont(c *gin.Context) {
var receivedValue EditWorkFlowInfo
c.ShouldBindJSON(&receivedValue)
if receivedValue.Flowid == "" {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.Name == "" {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.VersionId == "" {
publicmethod.Result(100, receivedValue, c)
return
}
if receivedValue.WeChat == 0 {
receivedValue.WeChat = 1
}
flowContStr, err := json.Marshal(receivedValue.Flowcont)
if err != nil {
publicmethod.Result(1, err, c, "您提交的流程格式不正确!")
return
}
flowKey, _ := strconv.ParseInt(receivedValue.Flowid, 10, 64)
var workFlowCont modelskpi.WorkFlowCont
//判断是否已经存在
where := publicmethod.MapOut[string]()
where["`id`"] = receivedValue.Flowid
err = workFlowCont.GetCont(where, "`id`")
dayTime := time.Now().Unix()
if err != nil {
publicmethod.Result(107, err, c)
return
}
saveMainData := publicmethod.MapOut[string]()
if workFlowCont.Name != receivedValue.Name {
saveMainData["`name`"] = receivedValue.Name
}
if workFlowCont.Describe != receivedValue.Describe {
saveMainData["`describe`"] = receivedValue.Describe
}
if workFlowCont.OpenWechat != receivedValue.WeChat {
saveMainData["`open_wechat`"] = receivedValue.WeChat
}
if len(saveMainData) > 0 {
saveMainData["`time`"] = dayTime
var editWorkFlowMain modelskpi.WorkFlow
editWorkFlowMain.EiteCont(where, saveMainData)
}
whereVersion := publicmethod.MapOut[string]()
whereVersion["`id`"] = receivedValue.VersionId
var workVersion modelskpi.WorkFlowVersion
err = workVersion.GetCont(whereVersion)
if err != nil {
var totalFlowVersion int64
err = overall.CONSTANT_DB_KPI.Model(&modelskpi.WorkFlowVersion{}).Select("`id`").Count(&totalFlowVersion).Error
if err != nil {
totalFlowVersion = 1
} else {
totalFlowVersion = totalFlowVersion + 1
}
stateVersion := 1
whersse := publicmethod.MapOut[string]()
whersse["`state`"] = 1
whersse["`key`"] = flowKey
var workFlowVeIstrue modelskpi.WorkFlowVersion
err = workFlowVeIstrue.GetCont(whersse, "`id`")
if err == nil {
stateVersion = 2
}
vid, _ := strconv.ParseInt(receivedValue.VersionId, 10, 64)
var workFlowVerSion modelskpi.WorkFlowVersion
workFlowVerSion.Id = vid
workFlowVerSion.Key = flowKey //流程标号
workFlowVerSion.Content = string(flowContStr) //工作流主体
workFlowVerSion.Version = strconv.FormatInt(totalFlowVersion, 10) //版本
workFlowVerSion.Time = dayTime //写入时间"`
workFlowVerSion.State = stateVersion //状态(1:启用;2:禁用;3:删除)"`
err := overall.CONSTANT_DB_KPI.Create(workFlowVerSion).Error
if err == nil {
publicmethod.Result(0, err, c)
} else {
publicmethod.Result(104, err, c)
}
} else {
saveVersion := publicmethod.MapOut[string]()
saveVersion["`content`"] = string(flowContStr)
saveVersion["`time`"] = dayTime
err = workVersion.EiteCont(whereVersion, saveVersion)
if err == nil {
publicmethod.Result(0, err, c)
} else {
publicmethod.Result(104, err, c)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2023-03-29 08:22:36
@ 功能:
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) StartUsingVersion(c *gin.Context) {
var receivedValue publicmethod.PublicId
err := c.ShouldBindJSON(&receivedValue)
if err != nil {
publicmethod.Result(100, err, c)
return
}
if receivedValue.Id == "" {
publicmethod.Result(101, err, c)
return
}
where := publicmethod.MapOut[string]()
where["`id`"] = receivedValue.Id
var versionCont modelskpi.WorkFlowVersion
err = versionCont.GetCont(where)
if err != nil {
publicmethod.Result(1, err, c, "未知版本!不可操作!")
return
}
var oldVersionCont modelskpi.WorkFlowVersion
err = oldVersionCont.EiteCont(map[string]interface{}{"`key`": versionCont.Key}, map[string]interface{}{"`state`": 2})
if err == nil {
var newVersionCont modelskpi.WorkFlowVersion
newVersionCont.EiteCont(where, map[string]interface{}{"`state`": 1})
}
publicmethod.Result(0, err, c)
}

207
api/workflow/workflowengine/workflowapi.go

@ -0,0 +1,207 @@
package workflowengine
import (
"key_performance_indicators/api/workflow/currency_recipe"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/overall/publicmethod"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-04-03 15:06:49
@ 功能: 获取工作流
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) GetWorkFlowFullView(c *gin.Context) {
var receivedValue GetWorkFlowInfoIng
c.ShouldBindJSON(&receivedValue)
if receivedValue.FlowWorkId == "" {
publicmethod.Result(1, receivedValue, c, "未知流程")
return
}
if receivedValue.OrgId == "" {
publicmethod.Result(1, receivedValue, c, "未知流程")
return
}
// ohjf, _ := strconv.ParseInt(receivedValue.OrgId, 10, 64)
// var getAllOrg publicmethod.GetOrgAllParent
// // getAllOrg.GetOrgParentAllId(departmentId)
// getAllOrg.GetOrgSonAllId(ohjf)
// fmt.Printf("%v\n", getAllOrg.Id)
// return
//获取登录人信息
myLoginCont, _ := publicmethod.LoginMyCont(c)
myKey := strconv.FormatInt(myLoginCont.Key, 10)
var workflowInfo currency_recipe.WorkflowEngine
if len(receivedValue.Condition) > 0 {
//条件设定
var tijiao1 currency_recipe.JudgingCondition
tijiao1.Class = 1
//自定义判断
var zdyPd []currency_recipe.CustomFields
for _, v := range receivedValue.Condition {
var zdyPdCont currency_recipe.CustomFields
zdyPdCont.WordField = v.Words
zdyPdCont.LeftVal = v.Price
zdyPd = append(zdyPd, zdyPdCont)
}
tijiao1.MyCustom = zdyPd
workflowInfo.JudCond = append(workflowInfo.JudCond, tijiao1)
}
jieguo := workflowInfo.InitWorkflow(receivedValue.FlowWorkId, "", myKey, receivedValue.OrgId).SendData()
// sjkdjk, _ := json.Marshal(receivedValue)
// fmt.Printf("初始化条件---》%v/n", string(sjkdjk))
// return
if !jieguo.IsTrue {
publicmethod.Result(1, jieguo, c, "未能获取到流程!")
} else {
jieguo.Step = 1
for _, v := range jieguo.NodeContList {
if v.Step == 1 {
jieguo.CurrentNode = v.NodeNumber
break
}
}
jieguo.Version = workflowInfo.VersionId
jieguo.CurrentUserKey = myKey
var cureeUserCont modelshr.PersonArchives
cureeUserCont.GetCont(map[string]interface{}{"`key`": myKey}, "`admin_org`")
jieguo.CurrentUserOrg = strconv.FormatInt(cureeUserCont.AdminOrg, 10)
publicmethod.Result(0, jieguo, c)
}
// senfdsd := publicmethod.MapOut[string]()
// senfdsd["jieguo"] = jieguo
// senfdsd["workflowInfo"] = workflowInfo
// publicmethod.Result(0, senfdsd, c)
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-07 11:03:01
@ 功能: 验证工作流
@ 参数
#workflowInfo 工作流列表
@ 返回值
#isTrue 是否合格
@ 方法原型
#func JudgeWorkflowIsTrue(workflowInfo []currency_recipe.NodeCont) (isTrue bool)
*/
func JudgeWorkflowIsTrue(workflowInfo []currency_recipe.NodeCont) (isTrue bool) {
isTrue = true
if len(workflowInfo) < 1 {
isTrue = false
} else {
for _, v := range workflowInfo {
if v.JudgeList {
if len(v.UserList) < 1 {
isTrue = false
break
}
}
}
}
return
}
// 写工作流
func (o *OperateWorkflow) ManipulateWorkflow() (WorkFlowList []currency_recipe.NodeCont) {
workflowLength := len(o.WorkFlowList)
nextSet := o.Step + 1
o.NextStep = nextSet
o.EndFlow = false
if nextSet > workflowLength {
o.EndFlow = true
o.NextStep = 0
return
}
for i, v := range o.WorkFlowList {
if v.Step < o.Step {
o.WorkFlowList[i].State = 2
for _, usv := range v.UserList {
if !publicmethod.IsInTrue[string](usv.Id, o.Participant) {
o.Participant = append(o.Participant, usv.Id)
}
}
}
if v.Step == o.Step {
o.WorkFlowList[i].State = 2
for ui, uv := range v.UserList {
if uv.Id == o.ManipulatePeople.Key {
var userCarrLog currency_recipe.LogList
userCarrLog.State = o.OperationStatus //状态 1、未操作;2、通过;3、驳回
userCarrLog.TimeVal = publicmethod.UnixTimeToDay(time.Now().Unix(), 1)
userCarrLog.Enclosure = o.UploadFiles //附件
o.WorkFlowList[i].UserList[ui].LogList = append(o.WorkFlowList[i].UserList[ui].LogList, userCarrLog)
// fmt.Printf("测样---3333--->%v---》%v---》%v\n", v.NodeName, userCarrLog, v.NodeName)
}
if !publicmethod.IsInTrue[string](uv.Id, o.Participant) {
o.Participant = append(o.Participant, uv.Id)
}
}
o.CurrentNode = v
// fmt.Printf("测样---22222》%v---》%v---》%v\n", v.NodeName, v, v.NodeName)
}
//判断下一步要执行什么
if nextSet <= workflowLength {
if v.Step == nextSet {
// fmt.Printf("测样---1111》%v---》%v---》%v\n", workflowLength, nextSet, v.NodeName)
writeLog := false
if v.Type == 2 {
o.Step = nextSet
WorkFlowList = o.ManipulateWorkflow()
writeLog = true
o.WorkFlowList[i].State = 2
}
var nextZhiXingRen []string
for ni, nv := range v.UserList {
if !publicmethod.IsInTrue[string](nv.Id, o.Participant) {
o.Participant = append(o.Participant, nv.Id) //参与人
}
if !publicmethod.IsInTrue[string](nv.Id, nextZhiXingRen) {
nextZhiXingRen = append(nextZhiXingRen, nv.Id) //下一步执行人
}
if writeLog { //参送节点直接发送信息
var userCsCarrLog currency_recipe.LogList
userCsCarrLog.State = 2 //状态 1、未操作;2、通过;3、驳回
userCsCarrLog.TimeVal = publicmethod.UnixTimeToDay(time.Now().Unix(), 1)
userCsCarrLog.Enclosure = o.UploadFiles //附件
o.WorkFlowList[i].UserList[ni].LogList = append(o.WorkFlowList[i].UserList[ni].LogList, userCsCarrLog)
}
}
o.NextNodeContExecutor = nextZhiXingRen
o.NextNodeCont = v
}
}
}
// if o.WorkFlowList[88].State != nil {
// }
// fmt.Printf("测样---》%v---》%v", workflowLength, o.WorkFlowList[workflowLength-1])
WorkFlowList = o.WorkFlowList
return
}

190
api/workwechat/entry.go

@ -0,0 +1,190 @@
package workwechat
//消息推送 touser,toparty,totag这三个参数在实际应用中必有一个不为空
/*
发送文本消息
*/
type SentMessage struct {
MessageMain
TemplateCard TemplateCardMsgCont `json:"template_card"` //模板卡片消息 参数
}
//发送简化消息
type SentMiniMessage struct {
MessageMain
TemplateCard TemplateCardMsgContMini `json:"template_card"` //模板卡片消息 参数
}
//简化消息主题
type TemplateCardMsgContMini struct {
TemplatePublic
ActionMenu ActionMenuCont `json:"action_menu"` //卡片右上角更多操作按钮
QuoteArea QuoteAreaCont `json:"quote_area"` //引用文献样式
HorizontalContentList []HorizontalContentListCont `json:"horizontal_content_list"` //二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
CardAction CardActionCont `json:"card_action"` //整体卡片的点击跳转事件,text_notice必填本字段
JumpList []JumpListCont `json:"jump_list"` //跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
}
//发送简化消息
type SentSmallMessage struct {
MessageMain
TemplateCard TemplateCardMsgContSmall `json:"template_card"` //模板卡片消息 参数
}
//简化消息主题
type TemplateCardMsgContSmall struct {
CardType string `json:"card_type"` //模板卡片类型 text_notice:文本卡片;news_notice:图文卡片;button_interaction:按钮卡片,multiple_interaction:多项选择,vote_interaction:投票
Source SourceCont `json:"source"` //卡片来源样式信息,不需要来源样式可不填写
// MainTitle MainTitleCont `json:"main_title"` //一级标题
TaskId string `json:"task_id"` //任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成,最长128字节,填了action_menu字段的话本字段必填
QuoteArea QuoteAreaCont `json:"quote_area"` //引用文献样式
HorizontalContentList []HorizontalContentListCont `json:"horizontal_content_list"` //二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
CardAction CardActionCont `json:"card_action"` //整体卡片的点击跳转事件,text_notice必填本字段
JumpList []JumpListCont `json:"jump_list"` //跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
}
/*
更新文本信息
*/
type UpdateMessage struct {
UpdatePublic
TemplateCard UpdateTemplateCardMsgCont `json:"template_card"` //模板卡片消息 参数
}
//更新文本信息模板
type UpdateTemplateCardMsgCont struct {
UpdateTemplateCardPublic
UpdateTextImgButton
subTitleText
EmphasisContent EmphasisContentInfo `json:"emphasis_content"` //关键数据样式
JumpList []JumpListCont `json:"jump_list"` //跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
}
//发送文本信息
type TemplateCardMsgCont struct {
TemplateCardCont
ActionMenu ActionMenuCont `json:"action_menu"` //卡片右上角更多操作按钮
EmphasisContent EmphasisContentInfo `json:"emphasis_content"` //关键数据样式
subTitleText //二级普通文本,建议不超过160个字,(支持id转译)
JumpList []JumpListCont `json:"jump_list"` //跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
}
/*
发送图文信息
*/
type SentImagesMessage struct {
MessageMain
TemplateCard TemplateCardImgCont `json:"template_card"` //模板卡片消息 参数
}
//发送图文主体
type TemplateCardImgCont struct {
TemplateCardCont
action_menu ActionMenuCont `json:"action_menu"` //卡片右上角更多操作按钮
ImageTextArea ImageTextAreaCont `json:"image_text_area"` //左图右文样式,news_notice类型的卡片,card_image和image_text_area两者必填一个字段,不可都不填
CardImage CardImageCont `json:"card_image"` //图片样式,news_notice类型的卡片,card_image和image_text_area两者必填一个字段,不可都不填
VerticalContentList []VerticalContentListCont `json:"vertical_content_list"` //卡片二级垂直内容,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过4
JumpList JumpListCont `json:"jump_list"` //跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
}
/*
更新图文信息
*/
type UpdateMessageImg struct {
UpdatePublic
TemplateCard UpdateTemplateCardMsgContImg `json:"template_card"` //模板卡片消息 参数
}
//更新图文信息模板
type UpdateTemplateCardMsgContImg struct {
UpdateTemplateCardPublic
UpdateTextImgButton
ImageTextArea ImageTextAreaCont `json:"image_text_area"`
CardImage CardImageCont `json:"card_image"`
VerticalContentList []VerticalContentListCont `json:"vertical_content_list"`
JumpList []JumpListCont `json:"jump_list"` //跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
}
/*
发送按钮信息
*/
type SentButtonMessage struct {
MessageMain
TemplateCard TemplateCardButCont `json:"template_card"` //模板卡片消息 参数
}
//发送按钮主体
type TemplateCardButCont struct {
TemplateCardCont
action_menu ActionMenuCont `json:"action_menu"` //卡片右上角更多操作按钮
subTitleText
ButtonSelection ButtonSelectionCont `json:"button_selection"` //按钮型卡片的下拉框样式
ButtonList []ButtonListCont `json:"button_list"` //按钮列表,列表长度不超过6
}
/*
发送多项选择信息
*/
type SentMultipleMessage struct {
MessageMain
TemplateCard TemplateCardMultiple `json:"template_card"` //模板卡片消息 参数
}
//发送多项选择主体
type TemplateCardMultiple struct {
TemplatePublic
action_menu ActionMenuCont `json:"action_menu"` //卡片右上角更多操作按钮
SelectList []SelectListCont `json:"select_list"` //下拉式的选择器列表,multiple_interaction类型的卡片该字段不可为空,一个消息最多支持 3 个选择器
SubmitButton SubmitButtonCont `json:"submit_button"` //提交按钮样式
}
/*
更多选项文信息
*/
type UpdateMessageMult struct {
UpdatePublic
TemplateCard UpdateTemplateCardMsgContMult `json:"template_card"` //模板卡片消息 参数
}
//更多选项文信息模板
type UpdateTemplateCardMsgContMult struct {
UpdateTemplateCardPublic
SelectList []SelectListCont `json:"select_list"` //下拉式的选择器列表,multiple_interaction类型的卡片该字段不可为空,一个消息最多支持 3 个选择器
SubmitButton SubmitButtonCont `json:"submit_button"` //提交按钮样式
ReplaceTextInfo
}
/*
发送投票选择信息
*/
type SentVoteMessage struct {
MessageMain
TemplateCard TemplateCardVote `json:"template_card"` //模板卡片消息 参数
}
//发送投票选择主体
type TemplateCardVote struct {
TemplatePublic
CheckBox CheckBoxCont `json:"checkbox"` //
SubmitButton SubmitButtonCont `json:"submit_button"` //提交按钮样式
}
/*
更新投票项文信息
*/
type UpdateMessageVote struct {
UpdatePublic
TemplateCard UpdateTemplateCardMsgContVote `json:"template_card"` //模板卡片消息 参数
}
//更新投票项文信息模板
type UpdateTemplateCardMsgContVote struct {
UpdateTemplateCardPublic
CheckBox CheckBoxCont `json:"checkbox"` //
SubmitButton SubmitButtonCont `json:"submit_button"` //提交按钮样式
}
//文本参数主体
type msgTextCont struct {
}

253
api/workwechat/entrypublic.go

@ -0,0 +1,253 @@
package workwechat
//通用部分
type descInfo struct {
Desc string `json:"desc"`
}
type idInfo struct {
Id string `json:"id"`
}
type textInfo struct {
Text string `json:"text"`
}
type keyInfo struct {
Key string `json:"key"`
}
type titleInfo struct {
Title string `json:"title"`
}
type typeInfo struct {
Type int `json:"type"`
}
type styleInfo struct {
Style int `json:"style"`
}
type urlInfo struct {
Url string `json:"url"`
}
type subTitleText struct {
SubTitleText string `json:"sub_title_text"`
}
type keynameInfo struct {
Keyname string `json:"keyname"`
}
type valueInfo struct {
Value string `json:"value"`
}
type mediaIdInfo struct {
MediaId string `json:"media_id"`
}
type useridInfo struct {
UserId string `json:"userid"`
}
type appidInfo struct {
AppId string `json:"appid"`
}
type pagepathInfo struct {
PagePath string `json:"pagepath"`
}
type questionkeyInfo struct {
QuestionKey string `json:"question_key"`
}
type selectedidInfo struct {
SelectedId string `json:"selected_id"`
}
type isCheckedInfo struct {
IsChecked bool `json:"is_checked"`
}
type ReplaceTextInfo struct {
ReplaceText bool `json:"replace_text"`
}
//模版主体
type MessageMain struct {
ToUser string `json:"touser"` //消息接收人 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送
ToParty string `json:"toparty"` //部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
ToTag string `json:"totag"` //标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
MsgType string `json:"msgtype"` //消息类型 template_card(模板卡片消息)
AgentId int `json:"agentid"` //企业应用的id,整型。企业内部开发,可在应用的设置页面查看;第三方服务商,可通过接口 获取企业授权信息 获取该参数值
EnableIdTrans int `json:"enable_id_trans"` //表示是否开启id转译,0表示否,1表示是,默认0
EnableDuplicateCheck int `json:"enable_duplicate_check"` //表示是否开启重复消息检查,0表示否,1表示是,默认0
DuplicateCheckInterval int `json:"aduplicate_check_intervalgentid"` //表示是否重复消息检查的时间间隔,默认1800s,最大不超过4小时
}
//通用模版数据
type TemplatePublic struct {
CardType string `json:"card_type"` //模板卡片类型 text_notice:文本卡片;news_notice:图文卡片;button_interaction:按钮卡片,multiple_interaction:多项选择,vote_interaction:投票
Source SourceCont `json:"source"` //卡片来源样式信息,不需要来源样式可不填写
MainTitle MainTitleCont `json:"main_title"` //一级标题
TaskId string `json:"task_id"` //任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成,最长128字节,填了action_menu字段的话本字段必填
}
//模板卡片消息 参数(文本、图文、按钮通用部分)
type TemplateCardCont struct {
TemplatePublic
QuoteArea QuoteAreaCont `json:"quote_area"` //引用文献样式
HorizontalContentList []HorizontalContentListCont `json:"horizontal_content_list"` //二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
CardAction CardActionCont `json:"card_action"` //整体卡片的点击跳转事件,text_notice必填本字段
}
//卡片来源样式信息,不需要来源样式可不填写
type SourceCont struct {
IconUrl string `json:"icon_url"` //来源图片的url,来源图片的尺寸建议为72*72
descInfo //来源图片的描述,建议不超过20个字,(支持id转译)
DescColor int `json:"desc_color"` //来源文字的颜色,目前支持:0(默认) 灰色,1 黑色,2 红色,3 绿色
}
//卡片右上角更多操作按钮
type ActionMenuCont struct {
descInfo //更多操作界面的描述
ActionList []ActionListCont `json:"action_list"` //操作列表,列表长度取值范围为 [1, 3]
}
//操作列表,列表长度取值范围为 [1, 3]
type ActionListCont struct {
textInfo //操作的描述文案
keyInfo //操作key值,用户点击后,会产生回调事件将本参数作为EventKey返回,回调事件会带上该key值,最长支持1024字节,不可重复
}
//一级标题
type MainTitleCont struct {
titleInfo //一级标题,建议不超过36个字,文本通知型卡片本字段非必填,但不可本字段和sub_title_text都不填,(支持id转译)
descInfo //标题辅助信息,建议不超过44个字,(支持id转译)
}
//引用文献样式
type QuoteAreaCont struct {
typeInfo //引用文献样式区域点击事件,0或不填代表没有点击事件,1 代表跳转url,2 代表跳转小程序
urlInfo //点击跳转的url,quote_area.type是1时必填
titleInfo //引用文献样式的标题
QuoteText string `json:"quote_text"` //引用文献样式的引用文案
}
//整体卡片的点击跳转事件,text_notice必填本字段
type CardActionCont struct {
typeInfo //跳转事件类型,1 代表跳转url,2 代表打开小程序。text_notice卡片模版中该字段取值范围为[1,2]
urlInfo //跳转事件的url,card_action.type是1时必填
appidInfo //跳转事件的小程序的appid,必须是与当前应用关联的小程序,card_action.type是2时必填
pagepathInfo //跳转事件的小程序的pagepath,card_action.type是2时选填
}
//二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
type HorizontalContentListCont struct {
typeInfo //链接类型,0或不填代表不是链接,1 代表跳转url,2 代表下载附件,3 代表点击跳转成员详情
keynameInfo //二级标题,建议不超过5个字
valueInfo //二级文本,如果horizontal_content_list.type是2,该字段代表文件名称(要包含文件类型),建议不超过30个字,(支持id转译)
urlInfo //链接跳转的url,horizontal_content_list.type是1时必填
mediaIdInfo //附件的media_id,horizontal_content_list.type是2时必填
useridInfo //成员详情的userid,horizontal_content_list.type是3时必填
}
//跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
type JumpListCont struct {
typeInfo
titleInfo
urlInfo
appidInfo
pagepathInfo
}
//左图右文样式,news_notice类型的卡片,card_image和image_text_area两者必填一个字段,不可都不填
type ImageTextAreaCont struct {
typeInfo //左图右文样式区域点击事件,0或不填代表没有点击事件,1 代表跳转url,2 代表跳转小程序
urlInfo //点击跳转的url,image_text_area.type是1时必填
titleInfo //左图右文样式的标题
descInfo //左图右文样式的描述
ImageUrl string `json:"image_url"` //左图右文样式的图片url
}
//图片样式,news_notice类型的卡片,card_image和image_text_area两者必填一个字段,不可都不填
type CardImageCont struct {
urlInfo //图片的url
AspectRatio float64 `json:"aspect_ratio"` //图片的宽高比,宽高比要小于2.25,大于1.3,不填该参数默认1.3
}
//卡片二级垂直内容,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过4
type VerticalContentListCont struct {
titleInfo //卡片二级标题,建议不超过38个字
descInfo //二级普通文本,建议不超过160个字
}
//按钮型卡片的下拉框样式
type ButtonSelectionCont struct {
questionkeyInfo //下拉式的选择器的key,用户提交选项后,会产生回调事件,回调事件会带上该key值表示该题,最长支持1024字节
titleInfo //下拉式的选择器左边的标题
OptionList OptionListCont `json:"option_list"` //选项列表,下拉选项不超过 10 个,最少1个
selectedidInfo //默认选定的id,不填或错填默认第一个
}
//选项列表,下拉选项不超过 10 个,最少1个
type OptionListCont struct {
idInfo //下拉式的选择器选项的id,用户提交后,会产生回调事件,回调事件会带上该id值表示该选项,最长支持128字节,不可重复
textInfo //下拉式的选择器选项的文案,建议不超过16个字
isCheckedInfo
}
//按钮列表,列表长度不超过6
type ButtonListCont struct {
typeInfo //按钮点击事件类型,0 或不填代表回调点击事件,1 代表跳转url
textInfo //按钮文案,建议不超过10个字
styleInfo //按钮样式,目前可填1~4,不填或错填默认1
keyInfo //按钮key值,用户点击后,会产生回调事件将本参数作为EventKey返回,回调事件会带上该key值,最长支持1024字节,不可重复,button_list.type是0时必填
urlInfo //跳转事件的url,button_list.type是1时必填
}
//下拉式的选择器列表,multiple_interaction类型的卡片该字段不可为空,一个消息最多支持 3 个选择器
type SelectListCont struct {
questionkeyInfo //下拉式的选择器题目的key,用户提交选项后,会产生回调事件,回调事件会带上该key值表示该题,最长支持1024字节,不可重复
textInfo //下拉式的选择器上面的title
selectedidInfo //默认选定的id,不填或错填默认第一个
OptionList OptionListCont `json:"option_list"` //选项列表,下拉选项不超过 10 个,最少1个
}
//提交按钮样式
type SubmitButtonCont struct {
textInfo //按钮文案,建议不超过10个字,不填默认为提交
keyInfo //提交按钮的key,会产生回调事件将本参数作为EventKey返回,最长支持1024字节
}
//
type CheckBoxCont struct {
questionkeyInfo
OptionList OptionListCont `json:"option_list"` //选项列表,下拉选项不超过 10 个,最少1个
Mode int `json:"mode"` //选择题模式,单选:0,多选:1,不填默认0
}
//关键数据样式
type EmphasisContentInfo struct {
titleInfo
descInfo
}
//更新模板通用
type UpdatePublic struct {
UserIds []string `json:"userids"` //企业的成员ID列表(最多支持1000个)
PartyIds []int `json:"partyids"` //企业的部门ID列表(最多支持100个)
AgentId int `json:"agentid"` //应用的agentid
ResponseCode string `json:"response_code"` //更新卡片所需要消费的code,可通过发消息接口和回调接口返回值获取,一个code只能调用一次该接口,且只能在72小时内调用
EnableIdTrans int `json:"enable_id_trans"` //表示是否开启id转译,0表示否,1表示是,默认0,id转译说明
}
//更新模板template_card模块通用
type UpdateTemplateCardPublic struct {
CardType string `json:"card_type"` //模板卡片类型 text_notice:文本卡片;news_notice:图文卡片;button_interaction:按钮卡片,multiple_interaction:多项选择,vote_interaction:投票
Source SourceCont `json:"source"` //卡片来源样式信息,不需要来源样式可不填写
MainTitle MainTitleCont `json:"main_title"` //一级标题
}
//文本,图文,按钮通用部门
type UpdateTextImgButton struct {
ActionMenu ActionMenuCont `json:"action_menu"` //卡片右上角更多操作按钮
QuoteArea QuoteAreaCont `json:"quote_area"` //引用文献样式
HorizontalContentList []HorizontalContentListCont `json:"horizontal_content_list"` //二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
CardAction CardActionCont `json:"card_action"` //整体卡片的点击跳转事件,text_notice必填本字段
}

279
api/workwechat/message.go

@ -0,0 +1,279 @@
package workwechat
import (
"encoding/json"
"fmt"
"key_performance_indicators/middleware/wechatapp/wechatstatice"
"key_performance_indicators/models/modelshr"
"key_performance_indicators/models/modelskpi"
"key_performance_indicators/overall"
"key_performance_indicators/overall/publicmethod"
"strings"
"time"
)
// 发送文本通知消息
func (s *SentMessage) SendMessage() (callBackByte []byte, err error) {
sendUrl, token, err := wechatstatice.GetSendMsgTokenUrl("kpi", "send")
if err != nil {
return
}
fmt.Printf("%v---------sendUrl, token----------->%v\n", sendUrl, token)
sendDate, _ := json.Marshal(s)
callBackByte = publicmethod.CurlPostJosn(sendUrl, sendDate)
return
}
// 发送迷你信息设定
func (sendMsg *SentSmallMessage) InitMes() *SentSmallMessage {
sendMsg.MsgType = "template_card"
sendMsg.AgentId = 1000036
sendMsg.EnableIdTrans = 0
sendMsg.EnableDuplicateCheck = 0
sendMsg.DuplicateCheckInterval = 1800
// var templateCard TemplateCardMsgContMini
sendMsg.TemplateCard.CardType = "text_notice"
//头部左标题部分
sendMsg.TemplateCard.Source.IconUrl = "https://docu.hxgk.group/images/2022_01/3f7a1120a559e9bee3991b85eb34d103.png"
sendMsg.TemplateCard.Source.DescColor = 1
//引用文献样式
sendMsg.TemplateCard.QuoteArea.Type = 0
//整体卡片的点击跳转事件,text_notice必填本字段
sendMsg.TemplateCard.CardAction.Type = 1
// sendMsg.TemplateCard = templateCard
return sendMsg
}
// 发送迷你信息设定
func (sendMsg *SentMiniMessage) InitMes() *SentMiniMessage {
sendMsg.MsgType = "template_card"
sendMsg.AgentId = 1000036
sendMsg.EnableIdTrans = 0
sendMsg.EnableDuplicateCheck = 0
sendMsg.DuplicateCheckInterval = 1800
// var templateCard TemplateCardMsgContMini
sendMsg.TemplateCard.CardType = "text_notice"
//头部左标题部分
sendMsg.TemplateCard.Source.IconUrl = "https://docu.hxgk.group/images/2022_01/3f7a1120a559e9bee3991b85eb34d103.png"
sendMsg.TemplateCard.Source.DescColor = 1
//引用文献样式
sendMsg.TemplateCard.QuoteArea.Type = 0
//整体卡片的点击跳转事件,text_notice必填本字段
sendMsg.TemplateCard.CardAction.Type = 1
// sendMsg.TemplateCard = templateCard
return sendMsg
}
// 发送迷你文本通知消息
func (s *SentMiniMessage) SendMessage() (callBackByte []byte, err error) {
sendUrl, token, err := wechatstatice.GetSendMsgTokenUrl("kpi", "send")
if err != nil {
return
}
fmt.Printf("%v---------sendUrl, token----------->%v\n", sendUrl, token)
sendDate, _ := json.Marshal(s)
callBackByte = publicmethod.CurlPostJosn(sendUrl, sendDate)
return
}
// 发送迷你文本通知消息
func (s *SentSmallMessage) SendMessage() (callBackByte []byte, err error) {
sendUrl, token, err := wechatstatice.GetSendMsgTokenUrl("kpi", "send")
if err != nil {
return
}
fmt.Printf("%v---------sendUrl, token----------->%v\n", sendUrl, token)
sendDate, _ := json.Marshal(s)
callBackByte = publicmethod.CurlPostJosn(sendUrl, sendDate)
return
}
// 更新文本通知消息
func (s *UpdateMessage) UpdateMessage() (callBackByte []byte, err error) {
sendUrl, token, err := wechatstatice.GetSendMsgTokenUrl("kpi", "update")
if err != nil {
return
}
fmt.Printf("%v---------sendUrl, token----------->%v\n", sendUrl, token)
sendDate, _ := json.Marshal(s)
callBackByte = publicmethod.CurlPostJosn(sendUrl, sendDate)
return
}
// 更新文本通知(map类型)
func UpdateMessageMap(mapAry map[string]interface{}) (callBackByte []byte, err error) {
sendUrl, token, err := wechatstatice.GetSendMsgTokenUrl("kpi", "update")
if err != nil {
return
}
fmt.Printf("%v---------sendUrl, token----------->%v\n", sendUrl, token)
sendDate, _ := json.Marshal(mapAry)
callBackByte = publicmethod.CurlPostJosn(sendUrl, sendDate)
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-24 08:22:22
@ 功能: 写入企业微信模版信息发送回调
@ 参数
#wechatCallBack 文本发送回调
#sendMsg 发送文本信息
#typeClass 类型1文本通知型2图文展示型3按钮交互型4投票选择型5多项选择型
#ordeeId 审批记录Id
#enforcer 接收人
@ 返回值
#err
@ 方法原型
#func WriteUpdateWechatTempmsg(wechatCallBack []byte, sendMsg SentMiniMessage, typeClass int, ordeeId int64, enforcer []string) (err error)
*/
func WriteUpdateWechatTempmsg(wechatCallBack []byte, sendMsg SentMiniMessage, typeClass int, ordeeId int64, enforcer []string) (err error) {
var weChatCallBack publicmethod.WechatCallBack
err = json.Unmarshal(wechatCallBack, &weChatCallBack)
if err != nil {
return
}
if weChatCallBack.Errcode != 0 {
return
}
sendMsgJson, err := json.Marshal(sendMsg)
if err != nil {
return
}
var insetCont modelskpi.UpdateWechatTempmsg
insetCont.Type = typeClass //类型(1:文本通知型;2:图文展示型;3:按钮交互型;4:投票选择型;5:多项选择型)"`
insetCont.Sendmsgcont = string(sendMsgJson) //发送文件信息"`
insetCont.Msgid = weChatCallBack.MsgId //消息id,用于撤回应用消息"`
insetCont.ResponseCode = weChatCallBack.ResponseCode //仅消息类型为“按钮交互型”,“投票选择型”和“多项选择型”的模板卡片消息返回,应用可使用response_code调用更新模版卡片消息接口,72小时内有效,且只能使用一次"`
insetCont.Orderkey = ordeeId //流程id"`
insetCont.Enforcer = strings.Join(enforcer, ",") //执行人"`
insetCont.State = 2 //状态(1:已执行更新;2:未执行更新)"`
insetCont.TaskId = sendMsg.TemplateCard.TaskId //任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成,最长128字节,填了action_menu字段的话本字段必填"`
insetCont.Time = time.Now().Unix() //写入时间"`
err = insetCont.AddCont()
return
}
/*
*
@ 作者: 秦东
@ 时间: 2023-04-24 13:29:27
@ 功能: 更新卡片
@ 参数
#typeClass 类型1文本通知型2图文展示型3按钮交互型4投票选择型5多项选择型'
#attribute 1未操作2同意3驳回
#orderkey 流程识别符
#enforcer 执行人
@ 返回值
#UpDateCont 更新信息
#err 信息提示
@ 方法原型
#func UpdateWechatMsgCont(typeClass int, orderkey, enforcer string) (UpDateCont []byte, err error)
*/
func UpdateWechatMsgCont(typeClass, attribute int, orderkey int64, enforcer string) (UpDateCont []byte, err error) {
if typeClass == 0 {
typeClass = 1
}
if orderkey == 0 || enforcer == "" {
return
}
var updateWechatCont []modelskpi.UpdateWechatTempmsg
err = overall.CONSTANT_DB_KPI.Where("`sate` = 2 AND `type` = ? AND `orderkey` = ? AND FIND_IN_SET(?,`enforcer`)", typeClass, orderkey, enforcer).Find(&updateWechatCont).Error
if err != nil || len(updateWechatCont) < 1 {
return
}
for _, uv := range updateWechatCont {
sendUpdateMsg := publicmethod.MapOut[string]()
var weChatMsgCont SentMiniMessage
json.Unmarshal([]byte(uv.Sendmsgcont), &weChatMsgCont)
templateCardCont := publicmethod.MapOut[string]()
templateCardCont["card_type"] = weChatMsgCont.TemplateCard.CardType
templateCardCont["source"] = weChatMsgCont.TemplateCard.Source
templateCardCont["main_title"] = weChatMsgCont.TemplateCard.MainTitle
templateCardCont["task_id"] = weChatMsgCont.TemplateCard.TaskId
templateCardCont["action_menu"] = weChatMsgCont.TemplateCard.ActionMenu
templateCardCont["quote_area"] = weChatMsgCont.TemplateCard.QuoteArea
templateCardCont["horizontal_content_list"] = weChatMsgCont.TemplateCard.HorizontalContentList
templateCardCont["card_action"] = weChatMsgCont.TemplateCard.CardAction
var userCont modelshr.PersonArchives
userCont.GetCont(map[string]interface{}{"`key`": enforcer}, "`name`")
attributeTitle := "同意申请"
switch attribute {
case 2:
attributeTitle = "同意申请"
case 3:
attributeTitle = "驳回申请"
default:
attributeTitle = "操作申请"
}
titleStr := fmt.Sprintf("%v已%v,查看详情", userCont.Name, attributeTitle)
for i, v := range weChatMsgCont.TemplateCard.JumpList {
if v.Type == 1 {
weChatMsgCont.TemplateCard.JumpList[i].Title = titleStr
}
}
templateCardCont["jump_list"] = weChatMsgCont.TemplateCard.JumpList
receiveMsgMan := strings.Split(uv.Enforcer, ",")
if len(receiveMsgMan) < 1 {
return
}
var weCahtOpenId []string
for _, v := range receiveMsgMan {
var userContWechat modelshr.PersonArchives
userContWechat.GetCont(map[string]interface{}{"`key`": v}, "`wechat`", "`work_wechat`")
if userContWechat.Wechat != "" {
if !publicmethod.IsInTrue[string](userContWechat.Wechat, weCahtOpenId) {
weCahtOpenId = append(weCahtOpenId, userContWechat.Wechat)
}
}
if userContWechat.WorkWechat != "" {
if !publicmethod.IsInTrue[string](userContWechat.WorkWechat, weCahtOpenId) {
weCahtOpenId = append(weCahtOpenId, userContWechat.WorkWechat)
}
}
}
if len(weCahtOpenId) < 1 {
return
}
sendUpdateMsg["userids"] = weCahtOpenId
sendUpdateMsg["agentid"] = weChatMsgCont.AgentId
sendUpdateMsg["response_code"] = uv.ResponseCode
sendUpdateMsg["enable_id_trans"] = 1
sendUpdateMsg["template_card"] = templateCardCont
UpDateCont, err = UpdateMessageMap(sendUpdateMsg)
if err != nil {
return
}
var editUpdateWechatCont modelskpi.UpdateWechatTempmsg
editCont := publicmethod.MapOut[string]()
editCont["`sate`"] = 1
editCont["`time`"] = time.Now().Unix()
err = editUpdateWechatCont.EiteCont(map[string]interface{}{"`id`": uv.Id}, editCont)
}
return
}

36
apirouter/apishiyan/maptostruct.go

@ -13,8 +13,38 @@ func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
var methodBinding = shiyan.AppApiEntry.MapToStructApi
{
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("maptostructshiyan", methodBinding.MapToStructShiyan) //map转struct
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("maptostructshiyan", methodBinding.MapToStructShiyan) //map转struct
apiRouter.POST("simulationcallback", methodBinding.SimulationCallBack) //模拟回调
apiRouter.POST("setuphrsystem", methodBinding.SetUpHrSystem) //设置HR系统对接账号和密码
apiRouter.POST("cang_chu_three", methodBinding.CangChuThree) //实验仓储数据读取
apiRouter.GET("cang_chu_three", methodBinding.CangChuThree) //实验仓储数据读取
apiRouter.GET("evalproctime", methodBinding.EvalProcTime) //审批流规制发生时间
apiRouter.POST("evalproctime", methodBinding.EvalProcTime) //审批流规制发生时间
apiRouter.POST("correcting_depart_man", methodBinding.CorrectingDepartAndMan) //验证指标关联部门与指标关联提报人数据
apiRouter.POST("verif_depart_sontarget", methodBinding.VerifDepartSonTarget) //验证部门子栏目关联对照
apiRouter.POST("verif_depart_detasil", methodBinding.VerifDepartDetasil) //验证部门指标细则关系对照
apiRouter.POST("new_verif_depart_detasil", methodBinding.XiaoZhengBumenBylaws) //验证部门指标细则关系对照
apiRouter.POST("xiao_zheng_fangan", methodBinding.XiaoZhengFangAn) //验证部门方案指标细则关系对照
apiRouter.POST("xzbkhbm", methodBinding.XiangzhengBeikaoBumen) //验证部门指标细则关系对照
//验证工作流
apiRouter.POST("test_verify_workflow", methodBinding.TestAndVerifyWorkflow) //验证工作流函数
//校正老流程
apiRouter.POST("check_old_workflow", methodBinding.CheckOldWorkflow) //校正老流程
//实验企业微信相关
apiRouter.POST("send_message", methodBinding.SendMessage) //发送文本信息
apiRouter.POST("update_textmessage", methodBinding.UpdateTextMsg) //更新文本信息
apiRouter.POST("send_message_mini", methodBinding.SendMessageMini) //发送文本信息迷你消息
apiRouter.POST("update_mini_card", methodBinding.UpdateMiniCard) //更新文本信息迷你消息
apiRouter.POST("get_hash_get", methodBinding.GetHashGet) //实验读取哈希
}
}

9
apirouter/empower/apirouter.go

@ -12,9 +12,10 @@ func (e *EmpowerApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("empower")
var methodBinding = empower.AppApiEntry.EmpowerApi
{
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("givemetoken", methodBinding.GainToken) //获取令牌
apiRouter.POST("encryption", methodBinding.Encryption) //加密验证
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("givemetoken", methodBinding.GainToken) //获取令牌
apiRouter.POST("encryption", methodBinding.Encryption) //加密验证
apiRouter.POST("write_token", methodBinding.WriteToken) //写入令牌
}
}

31
apirouter/entry.go

@ -3,27 +3,38 @@ package apirouter
import (
"key_performance_indicators/apirouter/apishiyan"
"key_performance_indicators/apirouter/empower"
"key_performance_indicators/apirouter/v1/approvalsystem"
"key_performance_indicators/apirouter/v1/bookimg"
"key_performance_indicators/apirouter/v1/departmentseting"
"key_performance_indicators/apirouter/v1/empowerrouter"
honorsRoute "key_performance_indicators/apirouter/v1/honorsRoute"
"key_performance_indicators/apirouter/v1/newsclassrouter"
"key_performance_indicators/apirouter/v1/postseting"
"key_performance_indicators/apirouter/v1/statisticsrouter"
"key_performance_indicators/apirouter/v1/systempower"
"key_performance_indicators/apirouter/verifyLogin"
// "key_performance_indicators/v1"
"key_performance_indicators/apirouter/wechaturl"
"key_performance_indicators/apirouter/workflowchart"
"key_performance_indicators/apirouter/workflowrouter"
)
// 路由结构
type RouterGroup struct {
EmpowerRouter empower.EmpowerApiRouter
VerifyLogin verifyLogin.ApiRouter
ShiyanApi apishiyan.ApiRouter
HonorsSouteRouter honorsRoute.ApiRouter
PostRouter postseting.ApiRouter
DepartmentRouter departmentseting.ApiRouter
BookImg bookimg.ApiRouter
SystemPowerRouter systempower.ApiRouter
Empowerouter empowerrouter.ApiRouter
EmpowerRouter empower.EmpowerApiRouter
VerifyLogin verifyLogin.ApiRouter
ShiyanApi apishiyan.ApiRouter
HonorsSouteRouter honorsRoute.ApiRouter
PostRouter postseting.ApiRouter
DepartmentRouter departmentseting.ApiRouter
BookImg bookimg.ApiRouter
SystemPowerRouter systempower.ApiRouter
Empowerouter empowerrouter.ApiRouter
WechatRouter wechaturl.ApiRouter
WorkFlowRouter workflowchart.ApiRouter
ExamineSystemApp approvalsystem.ApiRouter
MyWorkFlowRouter workflowrouter.ApiRouter
StatisticsApiRouter statisticsrouter.ApiRouter
NewsClassApiRouter newsclassrouter.ApiRouter
}
var RouterGroupEntry = new(RouterGroup)

20
apirouter/v1/approvalsystem/approval_route.go

@ -0,0 +1,20 @@
package approvalsystem
import (
"key_performance_indicators/api/version1"
"github.com/gin-gonic/gin"
)
// 岗位考核审批路由
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("examine")
var apiFunc = version1.AppApiEntry.SystemAppExamine
{
apiRouter.GET("", apiFunc.Index) //入口
apiRouter.POST("", apiFunc.Index) //入口
apiRouter.POST("postnatureappflow", apiFunc.PostNatureAppFlow) //岗位定性审批
}
}

4
apirouter/v1/approvalsystem/type.go

@ -0,0 +1,4 @@
package approvalsystem
//系统审批路由
type ApiRouter struct{}

46
apirouter/v1/departmentseting/pc.go

@ -15,12 +15,19 @@ func (a *ApiRouter) RouterGroupPc(router *gin.RouterGroup) {
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("new_depart_tar_list", methodBinding.NewDepartmentTargetList) //部门指标列表(新版)
apiRouter.POST("departmenttargetlist", methodBinding.DepartmentTargetList) //部门指标列表
apiRouter.POST("shiyan", methodBinding.Shiyan) //实验
apiRouter.POST("getdepartabouttarget", methodBinding.GetDepartAboutTarget) //获取部门定性考核部门关联列表
apiRouter.POST("gettargetreport", methodBinding.GetTargetReport) //获取部门指标相关执行人
apiRouter.POST("new_del_target", methodBinding.TargetChangeState) //指标改变状态(启用、禁用、软删除、硬删除)
apiRouter.POST("deltarget", methodBinding.DelTarget) //删除指标
apiRouter.POST("get_target_details_list", methodBinding.GetTargetDetailsList) //获取指定指标下的细则列表
apiRouter.POST("get_target_column_list", methodBinding.GetTargetColumnList) //获取指定指标下的栏目列表
apiRouter.POST("deltarget", methodBinding.DelTarget) //删除指标
apiRouter.POST("new_add_depart_details", methodBinding.NewAddDepartDetails) //新版添加部门指标细则
apiRouter.POST("addsuntargetdetailed", methodBinding.AddSunTargetDetailed) //添加定性考核子栏目及细则
apiRouter.POST("getdepartmenttragetcontlist", methodBinding.GetDepartmentTragetContList) //获取定性考核指标列表内容
@ -32,19 +39,50 @@ func (a *ApiRouter) RouterGroupPc(router *gin.RouterGroup) {
apiRouter.POST("getsontargetcont", methodBinding.GetSonTargetCont) //获取子栏目基础信息
apiRouter.POST("delsontarget", methodBinding.DelSonTarget) //删除子栏目
apiRouter.POST("table_add_detailses", methodBinding.TableAddDetailses) //根据栏目添加细则
apiRouter.POST("edit_table_depart_man", methodBinding.EditTableContAndDepartOfMan) //修改栏目名称及关联岗位和提报人
apiRouter.POST("getonedetailedtarget", methodBinding.GetOneDetailedTarget) //获取单一指标细则内容
apiRouter.POST("edit_one_detailed_target", methodBinding.EditOneDetailedTarget) //编辑单一指标细则内容
apiRouter.POST("del_one_detailed_target", methodBinding.DelOneDetailedTarget) //删除单一指标细则
apiRouter.POST("add_department_target", methodBinding.AddDepartmentTarget) //添加部门指标
apiRouter.POST("get_one_terget_info", methodBinding.GetOneTergetInfo) //获取单一指标详细内容
apiRouter.POST("edit_one_target", methodBinding.EditOneTarget) //编辑单一部门指标
apiRouter.POST("edit_details_state", methodBinding.EditDetailsState) //编辑指标细则状态
apiRouter.POST("edit_details_cont", methodBinding.EditDetailsCont) //编辑单一指标细则内容(新版)
apiRouter.POST("add_department_target", methodBinding.AddDepartmentTarget) //添加部门指标
apiRouter.POST("get_one_terget_info", methodBinding.GetOneTergetInfo) //获取单一指标详细内容
apiRouter.POST("edit_one_target", methodBinding.EditOneTarget) //编辑单一部门指标
apiRouter.POST("new_add_depar_target", methodBinding.NewAddDepartmentTarget) //添加部门指标(新版)
apiRouter.POST("new_edit_one_target", methodBinding.NewEditOneTarget) //编辑单一部门指标(新版)
apiRouter.POST("new_dep_tar_post", methodBinding.NewDeparmentTargetAboutPost) //指标关联岗位(新版)
apiRouter.POST("deparment_target_about_post", methodBinding.DeparmentTargetAboutPost) //指标关联岗位
apiRouter.POST("depar_son_target_about_post", methodBinding.DeparSonTargetAboutPost) //子栏目关联部门岗位
apiRouter.POST("depar_detaile_about_post", methodBinding.DeparDetaileAboutPost) //指标细则关联部门岗位
apiRouter.POST("get_target_relevant_post_Report", methodBinding.GetTargetRelevantPostOfReport) //获取部门指标关联的岗位及提报人
//部门指标与部门关系举证
apiRouter.POST("department_rules_matrix", methodBinding.DepartmentRulesMatrix) //定性指标细则与部门矩阵
//部门方案相关
apiRouter.POST("department_programme", methodBinding.DepartmentProgramme) //部门考核方案列表
apiRouter.POST("edit_depart_progra_state", methodBinding.EditDepartPrograState) //部门考核方案状态
apiRouter.POST("create_scheme_for_deparment", methodBinding.CreateSchemeForDeparment) //添加部门考核方案
apiRouter.POST("look_scheme_for_deparment", methodBinding.LookSchemeForDeparment) //查看部门考核方案详情
apiRouter.POST("look_scheme_bylaws", methodBinding.LookSchemeBylaws) //获取部门考核指标关联得细则
apiRouter.POST("get_runman_scheme", methodBinding.GetRunManScheme) //查看执行人
apiRouter.POST("edit_scheme_target_cont", methodBinding.EditSchemeTargetCont) //编辑方案指标
apiRouter.POST("del_scheme_target_cont", methodBinding.DelSchemeTargetCont) //删除方案指标
apiRouter.POST("ge_copy_scheme_cont", methodBinding.GetCopySchemeCont) //获取复制方案详情
apiRouter.POST("ge_add_scheme_cont", methodBinding.GetAddSchemeCont) //获取新增方案内容方案详情
//数据提报相关
apiRouter.POST("get_quantitative_tasks", methodBinding.GetQuantitativeTasks) //获取定量考核任务列表
apiRouter.POST("get_quality_tasks", methodBinding.GetQualityTasks) //获取定性考核任务列表
apiRouter.POST("get_qualbylaws_tasks", methodBinding.GetQualityBylawsTasks) //相关提报人定性考核细则列表
apiRouter.POST("submit_quality_assess", methodBinding.SubmitQualityAssess) //提交定性考核
apiRouter.POST("submit_quantify_target", methodBinding.SubmitQuantifyTarget) //提交定量考核
}
}

14
apirouter/v1/departmentseting/web.go

@ -15,5 +15,19 @@ func (a *ApiRouter) RouterGroupWeb(router *gin.RouterGroup) {
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("target_list_for_department", methodBinding.TargetListForDepartment) //指标列表
apiRouter.POST("get_qualbylaws_tasks", methodBinding.GetQualityBylawsTasks) //相关提报人定性考核细则列表(web使用)
apiRouter.POST("base_post_table_have_target", methodBinding.BasePostTableHaveTarget) //根据栏目获取获取相关指标(web使用)
apiRouter.POST("bdtts", methodBinding.BasisDepartTargetTimeStatistics) //根据部门、指标、年份统计每月的目标值、实际值、达成率
apiRouter.POST("bdttsyoy", methodBinding.BasisDepartTargetTimeStatisticsYOY) //历史同比根据部门、定量指标、年份统计每月的实际值
apiRouter.POST("totalscore_org_from_timesearch", methodBinding.TotalScoreOFOrgComesFromTimeSearch) //通过时间获取组织总分
apiRouter.POST("get_hinge_target", methodBinding.GetHingeTarget) //获取关键指标
apiRouter.POST("get_everyone_org_month_result", methodBinding.GetEveryOneOrgToMonthResult) //获取单一行政组织指定年度各月份成绩
apiRouter.POST("get_everyone_org_months_result", methodBinding.GetEveryOneOrgToMonthsResult) //获取单一行政组织多年度各月份成绩
apiRouter.POST("bdttsattryoy", methodBinding.BasisDepartAttrTargetTimeStatistics) //历史同比根据部门、定性指标、年份统计每月的实际值
}
}

18
apirouter/v1/newsclassrouter/apirouter.go

@ -0,0 +1,18 @@
package newsclassrouter
import (
"key_performance_indicators/api/version1"
"github.com/gin-gonic/gin"
)
// 新闻类接口路由
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("news")
var newsClassRouter = version1.AppApiEntry.NewsClassApi
{
apiRouter.GET("", newsClassRouter.Index) //入口
apiRouter.POST("", newsClassRouter.Index) //入口
}
}

4
apirouter/v1/newsclassrouter/type.go

@ -0,0 +1,4 @@
package newsclassrouter
//新闻类路由设定
type ApiRouter struct{}

54
apirouter/v1/postseting/pc.go

@ -19,6 +19,26 @@ func (a *ApiRouter) RouterGroupPc(router *gin.RouterGroup) {
apiRouter.POST("submit_post_scheme", methodBinding.SubmitPostScheme) //提交岗位考核方案
apiRouter.POST("get_post_scheme", methodBinding.GetPostScheme) //获取岗位方案内容列表
apiRouter.POST("get_copy_sheme_infor", methodBinding.GetCopyShemeInfor) //获取复制岗位考核方案
apiRouter.POST("have_post_target", methodBinding.HavePostTarget) //获取岗位指标(添加方案时使用)
apiRouter.POST("set_evaluation_objectives", methodBinding.SetEvaluationObjectives) //提交岗位定量目标设定
apiRouter.POST("post_config_list", methodBinding.PostConfigList) //岗位定量考核目标列表
apiRouter.POST("post_config_list_news", methodBinding.PostConfigListNews) //岗位定量考核目标列表(新版)
apiRouter.POST("eite_quantitative_config", methodBinding.EiteQuantitativeConfig) //修改考核目标设置
apiRouter.POST("del_quantitative_config", methodBinding.DelQuantitativeConfig) //删除考核目标设置
apiRouter.POST("lookposttiveconfig", methodBinding.LookPosttiveConfig) // 查看定量考核目标设定
apiRouter.POST("new_del_quantitative_config", methodBinding.NewDelQuantitativeConfig) //删除考核目标设置(新版)
apiRouter.POST("post_people_list", methodBinding.PeopleConfigList) //个人定量考核目标列表
apiRouter.POST("set_eval_object_man", methodBinding.SetEvaluationObjectivMan) //人员定量目标设定
apiRouter.POST("lookpeopleconfig", methodBinding.LookPeopleConfig) // 查看人员定量考核目标设定
apiRouter.POST("eite_quant_man_config", methodBinding.EiteQuantitativeManConfig) //修改人员考核目标设置
apiRouter.POST("new_del_quantman_config", methodBinding.NewDelQuantitativeManConfig) //删除人员考核目标设置(新版)
/*
岗位定性指标
*/
@ -31,12 +51,18 @@ func (a *ApiRouter) RouterGroupPc(router *gin.RouterGroup) {
apiRouter.POST("add_post_target_cont", methodBinding.AddPostTargetCont) //根据指标添加岗位细则
apiRouter.POST("edit_scheme_state_of_del", methodBinding.EditSchemeStateOfDel) //编辑方案版本状态或删除
apiRouter.POST("posttargetsunlist", methodBinding.PostTargetSunList) //根据指标获取岗位定性指标细则列表
apiRouter.POST("getnew_target_depart_postman", methodBinding.GetNewTargetAboutDepartToPostMan) //获取岗位指标关联部门相关岗位及提报人(新版)
/*
岗位定性指标子栏目
*/
apiRouter.POST("get_sun_target_info", methodBinding.GetSunTargetInfo) //获取岗位子栏目详情
apiRouter.POST("edit_son_target_cont", methodBinding.EditSonTargetCont) //编辑岗位子栏目内容
apiRouter.POST("del_son_target_cont", methodBinding.DelSonTargetCont) //删除子栏目
apiRouter.POST("get_sun_target_info", methodBinding.GetSunTargetInfo) //获取岗位子栏目详情
apiRouter.POST("edit_son_target_cont", methodBinding.EditSonTargetCont) //编辑岗位子栏目内容
apiRouter.POST("del_son_target_cont", methodBinding.DelSonTargetCont) //删除子栏目
apiRouter.POST("table_base_post_target", methodBinding.TableBasePostTarget) //根据指标获取岗位指标栏目
apiRouter.POST("get_new_table_departMan", methodBinding.GetNewTableDepartToPostMan) //获取岗位栏目关联部门相关岗位及提报人(新版)
apiRouter.POST("edit_newson_target_cont", methodBinding.EditSonTargetContNew) //编辑岗位子栏目内容(新版)
/*
定性指标细则
*/
@ -45,5 +71,27 @@ func (a *ApiRouter) RouterGroupPc(router *gin.RouterGroup) {
apiRouter.POST("editdeatilscont", methodBinding.EditDeatilsCont) //编辑定性指标细则内容
apiRouter.POST("getdetailscont", methodBinding.GetDetailsCont) //获取指标细则内容
apiRouter.POST("getdetailslist", methodBinding.GetDetailsList) //根据指标获取细则列表
apiRouter.POST("adddetailslist", methodBinding.AddDetailsList) //根据指标添加细则列表
apiRouter.POST("edit_post_detailscont", methodBinding.EditPostDetailsCont) //编辑岗位指标细则(新版)
apiRouter.POST("addtabledetailslist", methodBinding.AddTableDetailsList) //根据栏目添加细则列表
/*
针对岗位指标特殊要求API
*/
apiRouter.POST("search_orgpost_list", methodBinding.SearchOrgPostList) //搜索岗位列表
apiRouter.POST("get_orgary", methodBinding.GetOrgAry) //获取行政组织级联数组
apiRouter.POST("new_add_posttarget", methodBinding.NewAddPostTarget) //添加岗位指标(新)
apiRouter.POST("addposttargetcont", methodBinding.NewAddPostTargetCont) //添加岗位指标(新改版)
apiRouter.POST("neweditposttarget", methodBinding.NewEditPostTarget) //编辑岗位指标(新版)
apiRouter.POST("get_organdpost_ary", methodBinding.GetOrgAndPostAry) //获取行政组织级联数组和岗位
/*
岗位指标
*/
apiRouter.POST("get_posttarget_list", methodBinding.GetPostTargetList) //获取岗位指标列表
apiRouter.POST("set_posttarget_state", methodBinding.SetPostTargetState) //设置岗位指标状态
}
}

25
apirouter/v1/postseting/web.go

@ -15,13 +15,22 @@ func (a *ApiRouter) RouterGroupWeb(router *gin.RouterGroup) {
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("getposttarget", methodBinding.GetPostTarget) //获取指定人要考核的项目列表
apiRouter.POST("getpostnature", methodBinding.GetPostNature) //定性指标列表
apiRouter.POST("getpostration", methodBinding.GetPostRation) //获取定量指标列表
apiRouter.POST("get_post_deimenso_info", methodBinding.GetPostDeimensoInfo) //获取岗位定性考核指标细则列表
apiRouter.POST("get_nature_post_dimerons", methodBinding.GetNaturePostDimerons) //获取被考核人定性指标细则详细内容
apiRouter.POST("send_us_nature_evaluation", methodBinding.SendUsNatureEvaluation) //提交个人岗位定性考核数据
apiRouter.POST("get_ration_target_cont", methodBinding.GetRationTargetCont) //获取定量考核详细内容
apiRouter.POST("submit_ration_post_cont", methodBinding.SubmitRationPostCont) //提交定量考核数据
apiRouter.POST("getposttarget", methodBinding.GetPostTarget) //获取指定人要考核的项目列表
apiRouter.POST("getpostnature", methodBinding.GetPostNature) //定性指标列表
apiRouter.POST("get_post_nature_son_target", methodBinding.GetPostNatureSonTarget) //定性子栏目列表
apiRouter.POST("getpostration", methodBinding.GetPostRation) //获取定量指标列表
apiRouter.POST("get_post_deimenso_info", methodBinding.GetPostDeimensoInfo) //获取岗位定性考核指标细则列表
apiRouter.POST("get_nature_post_dimerons", methodBinding.GetNaturePostDimerons) //获取被考核人定性指标细则详细内容
apiRouter.POST("send_us_nature_evaluation", methodBinding.SendUsNatureEvaluation) //提交个人岗位定性考核数据
apiRouter.POST("get_ration_target_cont", methodBinding.GetRationTargetCont) //获取定量考核详细内容
apiRouter.POST("submit_ration_post_cont", methodBinding.SubmitRationPostCont) //提交定量考核数据
apiRouter.POST("post_rectification_measures", methodBinding.PostRectificationMeasures) //提交整改措施
apiRouter.POST("getflowmap", methodBinding.GetFlowMap) //获取流程图
apiRouter.POST("get_quantification_cont", methodBinding.GetQuantificationCont) //获取定量指标相关内容
apiRouter.POST("getpostflowlog", methodBinding.GetPostFlowLog) //岗位审批记录
apiRouter.POST("lookflowmap", methodBinding.LookFlowMap) //获取审批流详情
apiRouter.POST("lookflowmapcorra", methodBinding.LookFlowMapCorra) //获取审批流详情-->整改措施专用(岗位)
}
}

44
apirouter/v1/statisticsrouter/pc.go

@ -0,0 +1,44 @@
package statisticsrouter
import (
"key_performance_indicators/api/version1"
"github.com/gin-gonic/gin"
)
/*
*
@ 作者: 秦东
@ 时间: 2023-07-27 10:17:05
@ 功能: 统计路由
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("strtistics")
var statisRouter = version1.AppApiEntry.StatisticsApi
{
apiRouter.GET("", statisRouter.Index) //入口
apiRouter.POST("", statisRouter.Index) //入口
apiRouter.POST("orgtranscript", statisRouter.OrgTranscript) //行政组织成绩单
apiRouter.POST("summarydetailslianglog", statisRouter.SummaryDetailsLiangLog) //汇总详情定量历史记录
apiRouter.POST("summarydetails", statisRouter.SummaryDetails) //方案得分明细
apiRouter.POST("summaryplanrecord", statisRouter.SummaryPlanRecord) //汇总方案定量指标详情历史记录(新版)
apiRouter.POST("newsummarydetails", statisRouter.NewSummaryDetails) //方案得分明细(新版)
apiRouter.POST("neworgtranscript", statisRouter.OrgTranscriptNew) //行政组织成绩单(新版)
apiRouter.POST("org_target_annual_statistics", statisRouter.OrgTargetAnnualStatistics) //行政组织年度成绩单
}
}

14
apirouter/v1/statisticsrouter/type.go

@ -0,0 +1,14 @@
package statisticsrouter
/**
@ 作者: 秦东
@ 时间: 2023-07-27 10:16:28
@ 功能: 数据统计路由
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
type ApiRouter struct{}

33
apirouter/v1/systempower/pc.go

@ -12,13 +12,40 @@ func (a *ApiRouter) RouterGroupPc(router *gin.RouterGroup) {
var methodBinding = version1.AppApiEntry.JurisdictionpcApi
{
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("edit_power", methodBinding.EditPower) //编辑权限
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("edit_power", methodBinding.EditPower) //编辑权限
apiRouter.POST("edit_power_new", methodBinding.EditPowerNew) //编辑权限
apiRouter.POST("edit_role_power_new", methodBinding.EditRolePowerNew) //编辑角色权限
//系统
apiRouter.POST("add_system", methodBinding.AddSystem) //添加应用系统
apiRouter.POST("system_list", methodBinding.SystemList) //系统列表
apiRouter.POST("edit_system", methodBinding.EditSystem) //编辑应用系统信息
apiRouter.POST("edit_state_of_del", methodBinding.EditStateOfDel) //更改状态或删除
//相关系统菜单
apiRouter.POST("system_about_menu", methodBinding.SystemAboutMenu) //系统菜单行政组织岗位
apiRouter.POST("system_about_role_menu", methodBinding.SystemRoleAboutMenu) //系统菜单角色
apiRouter.POST("system_about_power_menu", methodBinding.SystemAboutPowerMenu) //系统权限菜单(岗位)
apiRouter.POST("system_about_power_menurole", methodBinding.SystemAboutPowerMenuRole) //系统权限菜单(角色)
//角色
apiRouter.POST("add_system_role", methodBinding.AddSystemRole) //系统角色添加
apiRouter.POST("edit_system_role", methodBinding.EditSystemRole) //系统角色编辑
apiRouter.POST("system_role_list", methodBinding.SystemRoleList) //系统角色列表
apiRouter.POST("edit_system_role_state", methodBinding.EditSystemRoleState) //系统角色状态
apiRouter.POST("edit_system_role_statebatch", methodBinding.EditSystemRoleStateBatch) //批量编辑系统角色状态
apiRouter.POST("role_about_people_list", methodBinding.RoleAboutPeopleList) //角色相关人员
apiRouter.POST("batch_del_roleman", methodBinding.BatchDeletToRoleAboutMan) //批量删除角色关联人员
apiRouter.POST("add_role_user", methodBinding.AddRoleUser) //添加角色关联人员
//工作流使用APi列表
apiRouter.POST("system_role_list_flow", methodBinding.SystemRoleListFlow) //系统角色列表(工作流专版)
apiRouter.POST("search_people", methodBinding.SearchPeople) //搜索人员
apiRouter.POST("get_position_unify", methodBinding.GetPositionUnify) //获取统一岗位
apiRouter.POST("search_position_unify", methodBinding.SearchPositionUnify) //搜索统一岗位
//授权
apiRouter.POST("grant_post_system_powers", methodBinding.GrantPostSystemPowers) //给指定岗位授权
apiRouter.POST("grant_role_system_powers", methodBinding.GrantRoleSystemPowers) //给指角色位授权
}
}

23
apirouter/verifyLogin/route.go

@ -12,10 +12,23 @@ func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("base")
var methodBinding = base.AppApiEntry.LoginVerify
{
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("captcha", methodBinding.Captcha) //获取验证码
apiRouter.POST("login", methodBinding.ScanCodeLogin) //登录
apiRouter.POST("signout", methodBinding.SignOut) //退出登录
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.POST("captcha", methodBinding.Captcha) //获取验证码
apiRouter.POST("login", methodBinding.ScanCodeLogin) //登录
apiRouter.POST("signout", methodBinding.SignOut) //退出登录
apiRouter.POST("verify_empower", methodBinding.VerifyEmpower) //验证授权是否还有效
apiRouter.POST("login_not_verify", methodBinding.ScanCodeLoginNotVerify) //登录(无验证码)
apiRouter.POST("verify_empower_istrue", methodBinding.VerifyEmpowerIsTrue) //验证授权是否过期
apiRouter.POST("get_work_wechat_jsapi_config", methodBinding.GetWorkWechatJsApiConfig) //获取企业微信jsapi_ticket
apiRouter.GET("authuser", methodBinding.AuthenticationUser) //获取身份认证
apiRouter.GET("callbackauthuser", methodBinding.CallBackAuthUser) //企业微信身份回调认证
apiRouter.POST("laissezpasser", methodBinding.LaissezPasser) //免登录
apiRouter.GET("scan_qrcode_callback", methodBinding.ScanQrCodeCallBackAuthUser) //扫码登录
}
}

5
apirouter/wechaturl/entry.go

@ -0,0 +1,5 @@
package wechaturl
//企业微信回调
type ApiRouter struct{}

20
apirouter/wechaturl/wechatrouter.go

@ -0,0 +1,20 @@
package wechaturl
import (
"key_performance_indicators/middleware/wechatapp"
"github.com/gin-gonic/gin"
)
// 企业微信回调路由
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("wechatcallback")
var methodBinding = wechatapp.WechatAppApi.WechatCallBackApi
{
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.GET("callback_message_api", methodBinding.CallbackMessageApi) //回调入口
apiRouter.POST("callback_message_api", methodBinding.CallbackMessageApi) //回调入口
}
}

12
apirouter/workflowchart/entry.go

@ -0,0 +1,12 @@
package workflowchart
/**
@ 作者: 秦东
@ 时间: 2022-09-30 09:49:37
@ 功能: 工作流路由
@ 参数
#
@ 返回值
#
*/
type ApiRouter struct{}

24
apirouter/workflowchart/flowes.go

@ -0,0 +1,24 @@
package workflowchart
import (
"key_performance_indicators/api/version1"
"github.com/gin-gonic/gin"
)
// 工作流
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("workflow")
var workFlow = version1.AppApiEntry.WorkFlowChat
{
apiRouter.GET("", workFlow.Index) //入口
apiRouter.POST("", workFlow.Index) //入口
apiRouter.POST("review_workflow", workFlow.ReviewWorkFlow) //生成审批流程流
apiRouter.POST("get_approval_record", workFlow.GetApprovalRecord) //流程记录
apiRouter.POST("look_work_flowcont", workFlow.LookWorkFlowCont) //查看流程记录详情
apiRouter.POST("examine_and_approve", workFlow.ExamineAndApprove) //执行审批
}
}

14
apirouter/workflowrouter/entry.go

@ -0,0 +1,14 @@
package workflowrouter
/**
@ 作者: 秦东
@ 时间: 2023-01-18 09:33:49
@ 功能: 工作流路由
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
type ApiRouter struct{}

38
apirouter/workflowrouter/flowrouter.go

@ -0,0 +1,38 @@
package workflowrouter
import (
"github.com/gin-gonic/gin"
"key_performance_indicators/api/workflow"
)
// 工作流
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("workflowapi")
var workFlow = workflow.AppApiEntry.WorkFlowApi
{
apiRouter.GET("", workFlow.Index) //入口
apiRouter.POST("", workFlow.Index) //入口
//实验用接口
apiRouter.POST("shiyan_data", workFlow.ShiyanData) //入口
apiRouter.POST("judge_optional_node", workFlow.JudgeOptionalNode) //判断是否显示(指定审批节点自选)选项及可选节点
apiRouter.POST("get_all_parent_node", workFlow.GetAllParentNode) //获取所有父级审批节点
apiRouter.POST("judging_condition", workFlow.JudgingCondition) //判断条件
apiRouter.POST("get_data_base_table", workFlow.GetDataBaseTable) //获取数据表列表
apiRouter.POST("get_data_base_tablecont", workFlow.GetDataBaseTableCont) //获取数据表结构
apiRouter.POST("get_work_flow_list", workFlow.GetWorkFlowList) //获取工作流列表
apiRouter.POST("publish_work_flow", workFlow.PublishWorkFlow) //发布工作流
apiRouter.POST("edit_work_flow_state", workFlow.EditWorkFlowState) //编辑工作流主体状态
apiRouter.POST("look_work_flow", workFlow.LookWorkFlowCont) //查看工作流
apiRouter.POST("init_work_flow", workFlow.InitializeWorkFlow) //初始化流程
apiRouter.POST("get_workflow_version_list", workFlow.GetWorkFlowVersionList) //获取流程版本列表
apiRouter.POST("edit_workflow_cont", workFlow.EditWorkFlowCont) //编辑流程主体
apiRouter.POST("start_using_version", workFlow.StartUsingVersion) //启用流程版本
apiRouter.POST("get_work_flow_fullview", workFlow.GetWorkFlowFullView) //获取顺序工作流
}
}

17
config/configApp/server.go

@ -6,6 +6,9 @@ type Server struct {
Logsetup logsetup `mapstructure:"logconfig" json:"logconfig" yaml:"logconfig"`
Captcha captcha `mapstructure:"captcha" json:"captcha" yaml:"captcha"`
RedisPrefixStr redisPrefixStr `mapstructure:"redisprefix" json:"redisprefix" yaml:"redisprefix"`
WechatCompany wechatCompany `mapstructure:"wechatcompany" json:"wechatcompany" yaml:"wechatcompany"` //企业ID
WechatSchool wechatConfig `mapstructure:"wechatschool" json:"wechatschool" yaml:"wechatschool"` //知行学院
WechatKpi wechatConfig `mapstructure:"wechatkpi" json:"wechatkpi" yaml:"wechatkpi"` //绩效考核
}
//服务配置详情
@ -16,6 +19,8 @@ type appsetup struct {
AppKey string `mapstructure:"appkey" json:"appkey" yaml:"appkey"`
DefaultPassword string `mapstructure:"password" json:"password" yaml:"password"`
PreFix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"`
WebUrl string `mapstructure:"weburl" json:"weburl" yaml:"weburl"`
PcbUrl string `mapstructure:"pcurl" json:"pcurl" yaml:"pcurl"`
}
//日志配置
@ -34,3 +39,15 @@ type redisPrefixStr struct {
PreFix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // redis键前缀
Alias string `mapstructure:"alias" json:"alias" yaml:"alias"` // redis键前缀
}
//企业微信基础配置
type wechatCompany struct {
CompanyId string `mapstructure:"companyid" json:"companyid" yaml:"companyid"` // 企业ID
}
type wechatConfig struct {
Agentid string `mapstructure:"agentid" json:"agentid" yaml:"agentid"` // Agentid
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` // Secret
Token string `mapstructure:"token" json:"token" yaml:"token"` // Token
Encodingaeskey string `mapstructure:"encodingaeskey" json:"encodingaeskey" yaml:"encodingaeskey"` // EncodingAESKey
}

10
config/configDatabase/database.go

@ -2,6 +2,7 @@ package configDatabase
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
@ -9,7 +10,8 @@ import (
)
type MysqlSetUp struct {
MasterMysql MasterMysqlSetUp `mapstructure:"master" json:"master" yaml:"master"` //主数据库
MasterMysql MasterMysqlSetUp `mapstructure:"master" json:"master" yaml:"master"` //主数据库
AppPlatformDatabase MasterMysqlSetUp `mapstructure:"appPlatformDatabase" json:"appPlatformDatabase" yaml:"appPlatformDatabase"` //应用平台
//其他数据库依次添加
WechatMysql MasterMysqlSetUp `mapstructure:"wechat" json:"wechat" yaml:"wechat"` //微信数据库
HrMysql MasterMysqlSetUp `mapstructure:"hrdatabase" json:"hrdatabase" yaml:"hrdatabase"` //HR数据库
@ -44,7 +46,7 @@ type MasterMysqlSetUp struct {
func (m *MasterMysqlSetUp) SqlDsn() (dsnStr string) {
dsnStr = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v", m.UserName, m.PassWord, m.UrlPath, m.Port, m.Name, m.Charset)
if m.ParseTime == true {
if m.ParseTime {
dsnStr = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=%v&loc=%v", m.UserName, m.PassWord, m.UrlPath, m.Port, m.Name, m.Charset, m.ParseTime, m.Loc)
}
return
@ -59,7 +61,7 @@ func (m *MasterMysqlSetUp) OpenSql() *gorm.DB {
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if m.GormLog == true {
if m.GormLog {
if opDb, err := gorm.Open(mysql.New(sqlConfig), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
}); err != nil {
@ -68,6 +70,7 @@ func (m *MasterMysqlSetUp) OpenSql() *gorm.DB {
sqlDb, _ := opDb.DB()
sqlDb.SetMaxIdleConns(m.MaxIdleConns)
sqlDb.SetMaxOpenConns(m.MaxOpenConns)
sqlDb.SetConnMaxLifetime(5 * time.Minute)
return opDb
}
} else {
@ -77,6 +80,7 @@ func (m *MasterMysqlSetUp) OpenSql() *gorm.DB {
sqlDb, _ := opDb.DB()
sqlDb.SetMaxIdleConns(m.MaxIdleConns)
sqlDb.SetMaxOpenConns(m.MaxOpenConns)
sqlDb.SetConnMaxLifetime(5 * time.Minute)
return opDb
}
}

47
config/configDatabase/database.yaml

@ -30,12 +30,19 @@ wechat:
hrdatabase:
url_path: '127.0.0.1' #数据库地址
port: 3306 #数据库端口
charset: 'utf8mb4' #数据库编码方式
parseTime: 'True' #是否自动转换时间
loc: 'Local' #时区
name: 'hr_new' #数据库名称
username: 'root' #数据库用户民
password: 'root' #数据库密码
# url_path: '172.20.5.33' #数据库地址
# port: 4000 #数据库端口
# name: 'hr_new' #数据库名称
# username: 'root' #数据库用户民
# password: '9z_Bu28r1*DZ3K6@+a' #数据库密码
charset: 'utf8mb4' #数据库编码方式
parseTime: 'True' #是否自动转换时间
loc: 'Local' #时区
max_idle_conns: 100 #最大空闲数量
max_open_conns: 1500 #最大打开数量
gorm_log: true #是否开启gorm日志
@ -151,14 +158,18 @@ healthReportDate:
#绩效考核数据库
kpiDate:
url_path: '127.0.0.1' #数据库地址
port: 3306 #数据库端口
# url_path: '127.0.0.1' #数据库地址
# port: 3306 #数据库端口
url_path: '172.20.5.33' #数据库地址
port: 4000 #数据库端口
charset: 'utf8mb4' #数据库编码方式
parseTime: 'True' #是否自动转换时间
loc: 'Local' #时区
name: 'perform' #数据库名称
# name: 'performing' #数据库名称
username: 'root' #数据库用户民
password: 'root' #数据库密码
# password: 'root' #数据库密码
password: '9z_Bu28r1*DZ3K6@+a' #数据库密码
max_idle_conns: 100 #最大空闲数量
max_open_conns: 1500 #最大打开数量
gorm_log: true #是否开启gorm日志
@ -208,12 +219,34 @@ systemPermission:
#仓库系统
storage:
url_path: '172.20.2.87' #数据库地址
port: 3306 #数据库端口
name: 'depository' #数据库名称
username: 'depository' #数据库用户民
password: 'NhE47edekBHxhjYk' #数据库密码
# url_path: '127.0.0.1' #数据库地址
# port: 3306 #数据库端口
# name: 'depository' #数据库名称
# username: 'root' #数据库用户民
# password: 'root' #数据库密码
charset: 'utf8mb4' #数据库编码方式
parseTime: 'True' #是否自动转换时间
loc: 'Local' #时区
max_idle_conns: 100 #最大空闲数量
max_open_conns: 1500 #最大打开数量
gorm_log: true #是否开启gorm日志
#应用平台数据库
appPlatformDatabase:
url_path: '127.0.0.1' #数据库地址
port: 3306 #数据库端口
charset: 'utf8mb4' #数据库编码方式
parseTime: 'True' #是否自动转换时间
loc: 'Local' #时区
name: 'depository' #数据库名称
name: 'app_platform' #数据库名称
username: 'root' #数据库用户民
password: 'root' #数据库密码
max_idle_conns: 100 #最大空闲数量

1
go.mod

@ -36,6 +36,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/shopspring/decimal v1.3.1 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect

2
go.sum

@ -490,6 +490,8 @@ github.com/shirou/gopsutil v3.20.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMT
github.com/shirou/gopsutil/v3 v3.22.5/go.mod h1:so9G9VzeHt/hsd0YwqprnjHnfARAUktauykSbr+y2gA=
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=

13
identification/interceptor/identity.go

@ -16,6 +16,7 @@ func AuthenticateUser() gin.HandlerFunc {
userKey := c.Request.Header.Get("user-key")
userToken := c.Request.Header.Get("user-token")
userAgent := c.Request.Header.Get("User-Agent")
userAgent = overall.CONSTANT_CONFIG.Appsetup.AppKey
// fmt.Printf("userKey---------->%v----------userToken---------->%v--------userAgent---------->%v\n", userKey, userToken, userAgent)
if userKey == "" || userToken == "" || userAgent == "" {
response.FailWithDetailed(gin.H{"reload": false, "code": 300}, "未登录或非法访问", c)
@ -27,7 +28,7 @@ func AuthenticateUser() gin.HandlerFunc {
redisClient := grocerystore.RunRedis(overall.CONSTANT_REDIS5)
userRedisToken, isTrue := redisClient.HashGetAll(redisFileKey)
if isTrue == false {
response.FailWithDetailed(gin.H{"reload": false, "code": 301}, "未登录或非法访问", c)
response.FailWithDetailed(gin.H{"reload": false, "code": 301}, redisFileKey, c)
c.Abort()
return
}
@ -111,6 +112,15 @@ func AuthenticateUser() gin.HandlerFunc {
// fmt.Printf("myContRedisJson------------>%v\n", string(myContRedisJson))
redisClient.HashMsetAdd(redisMyContKey, myContRedis)
//获取授权信息
// powerCont, powerErr := publicmethod.GetPostOfUsEmpowerCont(myCont.AdminOrg, myCont.Position, "kpi")
// c.Set(overall.MyContJwtPower, powerCont)
// fmt.Printf("redisMyContKey------Login----->%v----->%v\n", powerErr, powerCont)
//获取权限
var powerCont EmpowerCont
powerCont.RoleName, powerCont.PointId, powerCont.Operation, powerCont.Level = publicmethod.GetNewAccredit("kpi", myCont.Role, myCont.Key, myCont.AdminOrg, myCont.Position)
c.Set(overall.MyContJwtPower, powerCont)
c.Next()
}
}
@ -131,6 +141,7 @@ func VerifyUrl() gin.HandlerFunc {
act := c.Request.Method
menuIdAry, menuUrl, err := publicmethod.GetPostPower(context.AdminOrg, context.Position, "kpi")
//此功能暂时不开启
// if err != nil || len(menuUrl) < 1 || len(menuIdAry) < 1 {
// response.FailWithDetailed(gin.H{"reload": false, "code": 402}, "对不起!你没有访问此功能的权限!", c)

8
identification/interceptor/type.go

@ -6,3 +6,11 @@ type ValidatorToken struct {
UserKey string `json:"userkey"` //用户名
PassWord string `json:"password"` //密码
}
//权限相关
type EmpowerCont struct {
RoleName string `json:"roleName"`
PointId string `json:"pointid"`
Operation string `json:"operation"`
Level int `json:"level"`
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save