This commit is contained in:
Paidax
2025-08-13 16:00:10 +08:00
parent cc8216eff7
commit 8fcfafbd5a
64 changed files with 3309 additions and 327 deletions
@@ -0,0 +1,13 @@
package io.v.nutz.base.event.user;
/**
* @version 1.0
* @Author zzr
* @nameUserChangeEventListener
* @Date 2025/8/13 14:18
* @注释
*/
public interface UserChangeEventListener {
void receive(UserChangeMsg message);
}
@@ -0,0 +1,70 @@
package io.v.nutz.base.event.user;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @version 1.0
* @Author zzr
* @nameUserChangeMsg
* @Date 2025/8/13 11:51
* @注释
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserChangeMsg {
/**
* 变更资源,用户Id
*/
private List<String> userIds;
/**
* 操作类型
*/
private Integer operationType;
/**
* 变更前的单位Id,当operationType值为1时,该字段有效
*/
private String sourceUnitId;
/**
* 变更后的单位Id,当operationType值为1时,该字段有效
*/
private String targetUnitId;
/**
* 单位变动
*/
public final static int UNIT_CHANGE_OPERATION = 1;
/**
* 退休
*/
public final static int RETIRE_OPERATION = 2;
/**
* 入会
*/
public final static int RESTORE_OPERATION = 3;
public UserChangeMsg(List<String> userIds, Integer operationType) {
super();
this.userIds = userIds;
this.operationType = operationType;
}
public UserChangeMsg(List<String> userIds, Integer operationType, String sourceUnitId) {
super();
this.userIds = userIds;
this.operationType = operationType;
this.sourceUnitId = sourceUnitId;
}
}
@@ -0,0 +1,22 @@
package io.v.nutz.base.event.user;
import org.nutz.mvc.Mvcs;
/**
* @version 1.0
* @Author zzr
* @nameUserChangePublisher
* @Date 2025/8/13 14:23
* @注释
*/
public class UserChangePublisher {
// 发送消息给所有订阅者
public static void broadcast(UserChangeMsg msg) {
String[] names = Mvcs.getIoc().getNamesByType(UserChangeEventListener.class);
for (String listener : names) {
UserChangeEventListener listenerBean = Mvcs.getIoc().get(UserChangeEventListener.class, listener);
listenerBean.receive(msg);
}
}
}
@@ -107,6 +107,63 @@ public class MsgApi {
}
}
/**
* @param channels 推送渠道 (INNER:站内消息; SMS:短信; Mail:邮件; WeChat:微信; DingTalk:钉钉;同时推送多个渠道用英文逗号分隔 )
* @param loginNameList 工号集合
* @param mtype 消息类型; 0: 图文 1: 文字 2: 外链
* @param title 标题
* @param content 内容
* @param imageUrl 图片URL
* @author zhf
* @description
*/
public void sendMsg(List<String> channels, List<String> loginNameList, Integer mtype, String title, String content, String imageUrl,String link) {
try {
if (!Globals.MyConfig.getBoolean("SendMsg")) {
log.info("发送失败,消息暂未开启!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return;
}
if (Globals.isEnv(Env.dev)) {
log.info("开发模式不允许发送短信!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return;
}
if (StrUtil.isBlank(title)||StrUtil.isBlank(content) ||Lang.isEmpty(channels) || Lang.isEmpty(loginNameList)) {
log.info("发送失败,缺少需要参数请检查!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return;
}
if (Lang.isNotEmpty(loginNameList)) {
List<List<String>> splitList = ListUtil.split(loginNameList, 100);
for (List<String> sublist : splitList) {
// 获取token
String msgToken = getMsgToken();
// 封装发送消息的参数
NutMap map = createMessageMap(channels, sublist, mtype, title, content, imageUrl, link);
System.out.println(map);
// 发送请求
JSONObject jsonObject = sendRequest(msgToken, map);
// 判断发送结果
int status = jsonObject.getInteger("code");
if (status == 200) {
log.info("=================================================================================================发送成功: {}", jsonObject.toJSONString());
} else {
log.error("=================================================================================================发送失败: {}", jsonObject.toJSONString());
throw new RuntimeException("Message sending failed with status code: " + status + ", Message: " + jsonObject.getString("message"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 封装发送消息的参数
* @param channels
@@ -6,6 +6,8 @@ import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.StrUtil;
import cn.wizzer.framework.base.Result;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.event.user.UserChangeMsg;
import io.v.nutz.base.event.user.UserChangePublisher;
import io.v.nutz.base.page.Pagination;
import io.v.nutz.base.utils.PageUtil;
import io.v.nutz.base.utils.Roles;
@@ -30,6 +32,7 @@ import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
@@ -38,10 +41,7 @@ import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Trans;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/**
@@ -342,9 +342,37 @@ public class SysUnionMangeCon {
try {
//再删除工会负责人的权限
sysUnionService.clear("sys_user_role", Cnd.where("unionid", "=", unionid).and("roleid", "=", Roles.UNION_MANGER));
for (String id : Json.fromJsonAsList(String.class, userids)) {
sysUnionService.clear("sys_user_role", Cnd.where("unionid", "is", null).and("roleid", "=", Roles.UNION_MANGER));
List<String> strings = Json.fromJsonAsList(String.class, userids).stream().distinct().collect(Collectors.toList());
for (String id : strings) {
sysUnionService.insert("sys_user_role", Chain.make("roleid", Roles.UNION_MANGER).add("userid", id).add("unionid", unionid));
}
// 删除这个人在其他分工会的角色 096072
sysUserService.dao().clear(Sys_user_role.class, Cnd.where("userId", "in", strings)
.and("unionId", "!=", unionid));
// 找出分工会里面所有的工会干部,看这些人的工会与对应的分工会管理员是不是一致的,不一致的删除
List<Sys_user_role> userRoleList = sysUserService.dao().query(Sys_user_role.class, Cnd.where("roleId", "=", Roles.UNION_MANGER));
// 去查询user中的unionid
Set<String> userIds = userRoleList.stream().map(Sys_user_role::getUserId).collect(Collectors.toSet());
Sql sql = Sqls.create("SELECT u.id,u.unionid from `user` u WHERE u.id in (@userIds)").setParam("userIds", userIds);
sql.setCallback(Sqls.callback.maps());
sysUserService.dao().execute(sql);
List<NutMap> userList = (List<NutMap>) sql.getResult();
// 转map,找差异
Map<String, String> userMap = userList.stream().collect(Collectors.toMap(v -> v.getString("id"), v -> v.getString("unionid")));
List<Sys_user_role> diffUnionRoleList = userRoleList.stream().filter(v -> userMap.containsKey(v.getUserId())
&& !v.getUnionid().equals(userMap.get(v.getUserId()))).collect(Collectors.toList());
// 删除这些人的角色
if (org.nutz.lang.Lang.isNotEmpty(diffUnionRoleList)) {
sysUserService.dao().clear(Sys_user_role.class, Cnd.where("userId", "in", diffUnionRoleList.stream().map(Sys_user_role::getUserId).collect(Collectors.toList())));
}
// 发送广播订阅
UserChangePublisher.broadcast(new UserChangeMsg(List.of("1"), UserChangeMsg.UNIT_CHANGE_OPERATION));
sysUserService.clearCache();
sysRoleService.clearCache();
return Result.success();
@@ -6,7 +6,7 @@ import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.web.commons.controller.userpartupdate.models.UserPartUp;
import io.v.nutz.web.commons.controller.userpartupdate.service.UserPatUpService;
import io.v.nutz.web.commons.controller.userpartupdate.service.UserPartUpService;
import io.v.nutz.zhgh.activity.models.ActivityUserCnd;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.service.BaseService;
@@ -16,7 +16,6 @@ import io.v.nutz.base.utils.ViTool;
import io.v.nutz.web.commons.utils.ShiroUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
@@ -53,7 +52,7 @@ public class UserPartUpdateController {
private BaseService baseService;
@Inject
private UserPatUpService userPartUpService;
private UserPartUpService userPartUpService;
/**
@@ -5,14 +5,25 @@ import io.v.nutz.web.commons.controller.userpartupdate.models.UserPartUp;
import java.util.List;
public interface UserPatUpService extends ViService<UserPartUp> {
public interface UserPartUpService extends ViService<UserPartUp> {
/**
* 大量数据插入
*/
void largeDataInsert(List<UserPartUp> list);
/**
* 更新在职状态和人员类型
*/
void renewUserState();
/**
* 修改不在源数据中的人员为普通角色同时修改在职状态和人员类型
*/
void deleteNotInSourceUser(Boolean isAuto);
/**
* 更新工会小组
*/
void renewUnionGroup();
}
@@ -4,13 +4,13 @@ import cn.hutool.core.collection.CollectionUtil;
import io.v.nutz.base.service.impl.ViServiceImpl;
import io.v.nutz.base.utils.DateUtil;
import io.v.nutz.base.utils.Roles;
import io.v.nutz.sys.models.Sys_unit;
import io.v.nutz.sys.models.Sys_user;
import io.v.nutz.sys.models.Sys_user_role;
import io.v.nutz.web.commons.controller.userpartupdate.models.UserPartUp;
import io.v.nutz.web.commons.controller.userpartupdate.service.UserPatUpService;
import io.v.nutz.web.commons.controller.userpartupdate.service.UserPartUpService;
import io.v.nutz.sys.models.Sys_dict;
import io.v.nutz.sys.services.SysDictService;
import io.v.nutz.zhgh.data.model.UserSource;
import lombok.extern.slf4j.Slf4j;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
@@ -36,7 +36,7 @@ import java.util.stream.Collectors;
@IocBean(args = {"refer:dao"})
@Slf4j
public class UserPartUpServiceImpl extends ViServiceImpl<UserPartUp> implements UserPatUpService {
public class UserPartUpServiceImpl extends ViServiceImpl<UserPartUp> implements UserPartUpService {
public UserPartUpServiceImpl(Dao dao) {
super(dao);
}
@@ -204,4 +204,23 @@ public class UserPartUpServiceImpl extends ViServiceImpl<UserPartUp> implements
}
}
/**
* 更新工会小组
*/
@Override
@Aop(TransAop.READ_COMMITTED)
public void renewUnionGroup() {
// 直接全部清空所有人的工会小组
dao().update(Sys_user.class, Chain.make("threeUnitId", ""), Cnd.where("threeUnitId", "!=", ""));
// 在单位表里面查出有工会小组的单位
Sql sql = Sqls.create("""
UPDATE sys_user
SET threeUnitId = CONCAT(unitid, 'SJDW')
WHERE
unitid IN (SELECT parentId FROM sys_unit WHERE unionGroupId IS NOT NULL AND unionGroupId <> '' GROUP BY parentId)
""");
dao().execute(sql);
}
}
@@ -0,0 +1,22 @@
package io.v.nutz.zhgh.activity.listener;
import io.v.nutz.base.event.user.UserChangeEventListener;
import io.v.nutz.base.event.user.UserChangeMsg;
import org.nutz.ioc.loader.annotation.IocBean;
/**
* @version 1.0
* @Author zzr
* @nameActivityCommonListener
* @Date 2025/8/13 14:41
* @注释 活动的广播监听
*/
@IocBean
public class ActivityUserChangeListener implements UserChangeEventListener {
@Override
public void receive(UserChangeMsg message) {
System.out.println("=======================================================接收到消息=======================================================");
System.out.println(message);
}
}
@@ -53,7 +53,7 @@ public interface SourceData {
put("XBM", new String[]{"sex"});// 性别码
put("MZMC", new String[]{"nation"});// 民族码
put("SJ", new String[]{"mobile"}); // 手机号
// put("SFZJH", new String[]{"idcard"}); // 身份证件号
put("SFZJH", new String[]{"idcard"}); // 身份证件号
put("ZZMMM", new String[]{"political"}); // 政治面貌码
put("DQZTM", new String[]{"userState", "personalStatus"}); // 在职状态码
put("RYFLMC", new String[]{"personType"}); // 人员类型码
@@ -23,7 +23,7 @@ import io.v.nutz.sys.models.Sys_user;
import io.v.nutz.sys.services.SysRoleService;
import io.v.nutz.sys.services.SysUserService;
import io.v.nutz.web.commons.controller.userpartupdate.models.UserPartUp;
import io.v.nutz.web.commons.controller.userpartupdate.service.UserPatUpService;
import io.v.nutz.web.commons.controller.userpartupdate.service.UserPartUpService;
import io.v.nutz.zhgh.staffmanage.member.constant.MemberChangeOrigin;
import io.v.nutz.zhgh.staffmanage.member.constant.MemberChangeType;
import io.v.nutz.zhgh.staffmanage.member.service.MemberCommonService;
@@ -51,8 +51,6 @@ import org.springframework.beans.BeanUtils;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/**
@@ -86,7 +84,7 @@ public class SourceUserServiceImpl extends ViServiceImpl<UserSource> implements
@Inject
private HistoryUserService historyUserService;
@Inject
private UserPatUpService userPatUpService;
private UserPartUpService userPatUpService;
@Inject
private SysRoleService sysRoleService;
@Inject
@@ -313,6 +311,10 @@ public class SourceUserServiceImpl extends ViServiceImpl<UserSource> implements
dao().clear(SourceChangeMiddleTable.class, Cnd.where("loginname", "in", loginNameList).and("isOperate", "=", false));
manyAddOrRenewUtil.asyncExecuteFastInsert(middleTables, 200);
}
// 修改三级单位
userPatUpService.renewUnionGroup();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
@@ -687,60 +689,57 @@ public class SourceUserServiceImpl extends ViServiceImpl<UserSource> implements
}
// 类级别定义共享线程池(推荐使用ThreadPoolExecutor便于后续调优)
private static final ExecutorService ASYNC_UPDATE_EXECUTOR = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors() * 2,
Runtime.getRuntime().availableProcessors() * 4,
60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000),
new ThreadPoolExecutor.CallerRunsPolicy()
);
/**
* 数据大批量更新
*
* @param needDoUpdateList 需要更新的数据
* @param isPart 是否部分更新
* @param filterColumnDao 部分更新传递(部分更新存在过滤字段)
* @param isPart 是否部分更新
* @param filterColumnDao 部分更新传递(部分更新存在过滤字段)
*/
private void massUpdatesAsync(List<Sys_user> needDoUpdateList, Boolean isPart, AtomicReference<Dao> filterColumnDao) {
// 创建一个CPU核心数的2倍的线程池
int numberOfThreads = Runtime.getRuntime().availableProcessors() * 2;
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
ExecutorCompletionService<Void> ecs = new ExecutorCompletionService<>(executorService);
public void massUpdatesAsync(List<Sys_user> needDoUpdateList, Boolean isPart, AtomicReference<Dao> filterColumnDao) {
int batchSize = 200;
// 共享锁
Lock lock = new ReentrantLock();
try {
for (int i = 0; i < needDoUpdateList.size(); i += batchSize) {
final int end = Math.min(i + batchSize, needDoUpdateList.size());
List<Sys_user> batch = needDoUpdateList.subList(i, end);
ecs.submit(() -> {
Dao daoToUse = isPart ? filterColumnDao.get() : dao();
lock.lock();
try {
daoToUse.updateIgnoreNull(batch);
} finally {
lock.unlock();
}
return null;
});
}
for (int i = 0; i < needDoUpdateList.size(); i += batchSize) {
try {
Future<Void> future = ecs.take();
future.get();
} catch (InterruptedException | ExecutionException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Error during batch update", e);
}
}
} catch (Exception e) {
log.error("Error in massUpdatesAsync", e);
throw new RuntimeException("Error in massUpdatesAsync", e);
} finally {
executorService.shutdown();
try {
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// 参数校验
if (needDoUpdateList == null || needDoUpdateList.isEmpty()) {
CompletableFuture.completedFuture(null);
return;
}
final int batchSize = 200;
final int totalBatches = (needDoUpdateList.size() + batchSize - 1) / batchSize;
// 存储所有batch的future
List<CompletableFuture<Void>> batchFutures = new ArrayList<>(totalBatches);
for (int i = 0; i < needDoUpdateList.size(); i += batchSize) {
final int end = Math.min(i + batchSize, needDoUpdateList.size());
List<Sys_user> batch = needDoUpdateList.subList(i, end);
CompletableFuture<Void> batchFuture = CompletableFuture.runAsync(() -> {
Dao daoToUse = isPart ? filterColumnDao.get() : dao();
try {
// 假设updateIgnoreNull内部已处理线程安全
daoToUse.updateIgnoreNull(batch);
} catch (Exception e) {
log.error("Batch update failed", e);
throw new CompletionException(e);
}
}, ASYNC_UPDATE_EXECUTOR);
batchFutures.add(batchFuture);
}
// 合并所有future
CompletableFuture.allOf(batchFutures.toArray(new CompletableFuture[0]));
}
}
@@ -110,10 +110,10 @@ public class MemberInquireIntegrateController {
}
if (StrUtil.isNotBlank(isUnit)) {
cnd.and("u.unitid", isUnit.equals("true") ? "is not" : "is", null);
cnd.and("u.unitid", "true".equals(isUnit) ? "is not" : "is", null);
}
if (StrUtil.isNotBlank(isUnion)) {
cnd.and("u.unionid", isUnion.equals("true") ? "is not" : "is", null);
cnd.and("u.unionid", "true".equals(isUnion) ? "is not" : "is", null);
}
if (StrUtil.isNotBlank(pageForm.getSearchKeyword())) {
cnd.and(new SqlExpressionGroup().andLike(pageForm.getSearchName(), pageForm.getSearchKeyword()));
@@ -123,7 +123,7 @@ public class MemberInquireIntegrateController {
cnd.and(new SqlExpressionGroup().andLike(memberSearchName, memberSearchKeyWord));
}
List<Integer> status = new ArrayList<>();
// List<Integer> status = new ArrayList<>();
// status.add(MemberStatus.NORMAL.getCode());
// status.add(MemberStatus.TURN_IN.getCode());
// status.add(MemberStatus.RESTORE.getCode());
@@ -194,7 +194,7 @@ public class MemberApplyRecord {
@Column
@Comment("变更类型")
@ColDefine(type = ColType.VARCHAR, width = 20)
@ColDefine(type = ColType.VARCHAR, width = 50)
private String changeType;
@Column
@@ -305,7 +305,7 @@ public class SourceChangeManageServiceImpl extends BaseServiceImpl<SourceChangeM
NutMap afterUnionMap = (NutMap) afterUnionSql.getResult();
// 如果这两个单位归属的是不同的分工会,发送消息提醒两个分工会
if (!beforeUnionMap.getString("id").equals(afterUnionMap.getString("id"))) {
if (StrUtil.isAllNotBlank(beforeUnionMap.getString("id"), afterUnionMap.getString("id")) && !beforeUnionMap.getString("id").equals(afterUnionMap.getString("id"))) {
// 找到变更前的分工会会员管理员,发送消息提醒
Sql beforeUnionAdminSql = Sqls.create("""
SELECT
@@ -357,6 +357,11 @@ public class SourceChangeManageServiceImpl extends BaseServiceImpl<SourceChangeM
msgApi.sendMsg(List.of("DingTalk"), map.getString("loginname"), 1, "工会关系转入通知", afterContent, "", "");
}
}
// 发送消息给个人,告知异动到了新工会
String content = "亲爱的%s老师,欢迎您加入%s".formatted(middleTable.getUsername(), afterUnionMap.getString("unionname"));
msgApi.sendMsg(List.of("DingTalk"), middleTable.getLoginname(), 1, "", content, "", "");
}
}
@@ -82,6 +82,8 @@ public class TheRapyRecuperationAuditServiceImpl extends ViServiceImpl<Audit> im
Sql sql = Sqls.create("""
SELECT
lxs.travelAgencyName,
travel.travelAgencyName AS baseTravelAgencyName,
base.baseName,
enroll.*,
line.lineName,
if(enroll.takePartInUnionId!=enroll.selfUnionId,true,false) isTransferIn,
@@ -91,6 +93,8 @@ public class TheRapyRecuperationAuditServiceImpl extends ViServiceImpl<Audit> im
LEFT JOIN the_rapy_recuperation_line_union_select lineu ON lineu.id = enroll.takePartInLineId
LEFT JOIN the_rapy_recuperation_line line ON line.id = lineu.lineId
LEFT JOIN the_rapy_recuperation_travel_agency lxs ON lxs.id = line.travelAgencyId
LEFT JOIN the_rapy_recuperation_base_management base ON base.id = enroll.takePartInBaseManagementId
LEFT JOIN the_rapy_recuperation_travel_agency travel ON travel.id = base.travelAgencyId
where enroll.id=@id
""").setParam("id", id);
@@ -1,93 +0,0 @@
package io.v.nutz.zhgh.welfare.controller;
import cn.hutool.core.util.StrUtil;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.query.PageForm;
import io.v.nutz.base.service.SimpleService;
import io.v.nutz.zhgh.welfare.model.WelfareProjectSubject;
import io.v.nutz.zhgh.welfare.model.WelfareProjectSubjectOption;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ClassName WelfareEvaluateStatisticsController
* @Description 评价统计
* @Author zhf
* @Date 2024/5/7 20:02
*/
@IocBean
@Ok("json:full")
@At("/platform/welfare/evaluate/statistics")
public class WelfareEvaluateStatisticsController {
@Inject
private SimpleService simpleService;
@Inject
private Dao dao;
@At("")
@Ok("beetl:/platform/welfare/evaluateStatistics.html")
@RequiresPermissions("welfare.evaluate.statistics")
public void index() {
}
@At
@ViReturn
@RequiresPermissions("welfare.evaluate.statistics")
public Object pageData(PageForm pageForm, String projectId, String unionId, String unitId, String personType, String userState, Integer evaluateScore, String optionId) {
Sql sql = Sqls.create("""
SELECT
we.evaluateText,
we.evaluateScore,
we.userName,
we.loginName,
u.unionname,
u.unitname,
u.userState,
u.personType
FROM
`welfare_evaluate` we
LEFT JOIN `user` u ON u.id = we.userId
$condition
""");
Cnd cnd = Cnd.NEW();
if (StrUtil.isNotBlank(pageForm.getSearchName()) && StrUtil.isNotBlank(pageForm.getSearchKeyword())) {
cnd.and(Cnd.likeEX(pageForm.getSearchName(), pageForm.getSearchKeyword()));
}
if (StrUtil.isNotBlank(pageForm.getPageOrderName()) && StrUtil.isNotBlank(pageForm.getPageOrderBy())) {
cnd.orderBy(pageForm.getPageOrderName(), pageForm.getPageOrderBy().equals("ascending") ? "asc" : "desc");
} else {
cnd.desc("we.evaluateScore");
}
cnd.and("we.projectId", "=", projectId);
cnd.andEX("u.unionid", "=", unionId);
cnd.andEX("u.unitid", "=", unitId);
cnd.andEX("u.personType", "=", personType);
cnd.andEX("u.userState", "=", userState);
cnd.andEX("we.evaluateScore", "=", evaluateScore);
cnd.andEX("optionId", "=", optionId);
sql.setCondition(cnd);
return simpleService.listPageMap(pageForm.getPageNumber(), pageForm.getPageSize(), sql);
}
@At
@ViReturn
@RequiresPermissions("welfare.evaluate.statistics")
public Object welfareOptions(String projectId) {
List<WelfareProjectSubject> subjects = dao.query(WelfareProjectSubject.class, Cnd.where("projectId", "=", projectId));
List<String> subjectIds = subjects.stream().map(v -> v.getId()).collect(Collectors.toList());
return dao.query(WelfareProjectSubjectOption.class, Cnd.where("subjectId", "in", subjectIds).asc("optionSort"));
}
}
@@ -74,19 +74,21 @@ public class WelfareMineController {
GROUP_CONCAT( DISTINCT wuso.optionName, IF(wus.selectSpecs is not null, (CONCAT('—规格:', wus.selectSpecs)), ''), '', wus.selectNum, '份)' ) AS gist_list,
wus.receiveAddress,
wcn.courierNumber,
wl.userId
wl.userId,
wea.id AS evaId
FROM
welfare_project wp
LEFT JOIN welfare_project_user_selection wus ON wp.id = wus.welfareId AND wus.selectUserId = @selectUserId
LEFT JOIN welfare_courier_number wcn ON wp.id = wcn.welfareId AND wcn.selectUserId = @selectUserId
LEFT JOIN welfare_list wl ON wp.id = wl.projectId AND wl.userId = @selectUserId
LEFT JOIN welfare_project_subject_option wuso ON wus.selectOptionId = wuso.id
LEFT JOIN welfare_evaluate_activity wea ON wea.welfareId = wp.id
$condition
""");
sql.setParam("selectUserId", ShiroUtil.getUserId());
Cnd cnd = Cnd.NEW();
cnd.and("wp.isDisabled", "=", 0);
// cnd.andEX("YEAR(wp.choiceTimeStart)", "=", year);
cnd.andEX("YEAR(wp.choiceTimeStart)", "=", year);
cnd.and("wp.id","in",Sqls.create("(select projectId from view_welfare_list where id = @userId)").setParam("userId",ShiroUtil.getUserId()));
cnd.groupBy("wp.id");
cnd.desc("wp.choiceTimeStart");
@@ -321,7 +321,7 @@ public class WelfareProjectMangeController {
sql.setParam("projectId", projectId);
List<NutMap> userList = listService.listMap(sql);
Set<String> loginNameList = userList.stream().map(user -> user.getString("loginname")).collect(Collectors.toSet());
String loginNames = loginNameList.stream().collect(Collectors.joining(","));
String loginNames = String.join(",", loginNameList);
// WelfareProject project = dao.fetch(WelfareProject.class, projectId);
String link = Globals.AppDomain + "/mobile/welfare/list/receive?projectId=%s".formatted(projectId);
@@ -0,0 +1,256 @@
package io.v.nutz.zhgh.welfare.controller.evaluate;
import cn.hutool.core.util.StrUtil;
import cn.wizzer.framework.base.Result;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.page.Pagination;
import io.v.nutz.base.query.PageForm;
import io.v.nutz.base.utils.MsgApi;
import io.v.nutz.web.commons.base.Globals;
import io.v.nutz.zhgh.welfare.model.WelfareProject;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateActivity;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateOption;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateSubject;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateUserAnswerRecord;
import io.v.nutz.zhgh.welfare.service.WelfareEvaluateActivityService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateActivityController
* @Date 2025/8/11 14:38
* @注释 福利评价活动
*/
@IocBean
@Ok("json:full")
@At("/platform/welfare/evaluate/activity")
public class WelfareEvaluateActivityController {
@Inject
private Dao dao;
@Inject
private MsgApi msgApi;
@Inject
private WelfareEvaluateActivityService welfareEvaluateActivityService;
@At("")
@RequiresPermissions("welfare.evaluate.activity")
@Ok("beetl:/platform/welfare/evaluate/activity/index.html")
public void index() {
}
@At
@RequiresPermissions("welfare.evaluate.activity")
public Result pageData(@Valid PageForm pageForm,
@Param(value = "year", required = false) Integer year,
@Param(value = "title", required = false) String title,
@Param(value = "welfareId", required = false) String welfareId) {
Sql sql = Sqls.create("""
SELECT
eva.*,
wp.`name` AS welfareName
FROM
welfare_evaluate_activity eva
LEFT JOIN welfare_project wp ON wp.id = eva.welfareId
$condition
""");
Cnd cnd = Cnd.NEW();
cnd.andEX("YEAR(eva.startTime)", "=", year);
cnd.and(Cnd.likeEX("eva.title",title));
cnd.andEX("eva.welfareId", "=", welfareId);
cnd.desc("eva.startTime");
sql.setCondition(cnd);
Pagination pagination = welfareEvaluateActivityService.listPageMap(pageForm.getPageNumber(), pageForm.getPageSize(), sql);
return Result.success(pagination);
}
@At
@RequiresPermissions("welfare.evaluate.activity")
public Result save(WelfareEvaluateActivity activity){
dao.insertOrUpdate(activity);
return Result.success();
}
@At
@Aop(TransAop.READ_COMMITTED)
@RequiresPermissions("welfare.evaluate.activity")
public Result delete(String id) {
dao.clear(WelfareEvaluateActivity.class, Cnd.where("id", "=", id));
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class, Cnd.where("activityId", "=", id));
List<String> subjectIds = subjects.stream().map(WelfareEvaluateSubject::getId).toList();
dao.clear(WelfareEvaluateSubject.class, Cnd.where("activityId", "=", id));
if (Lang.isNotEmpty(subjectIds)) {
dao.clear(WelfareEvaluateOption.class, Cnd.where("subjectId", "in", subjectIds));
}
dao.clear(WelfareEvaluateUserAnswerRecord.class, Cnd.where("activityId", "=", id));
return Result.success();
}
/**
* 获取评价活动
* @param id
* @return
*/
@At
@ViReturn
@RequiresPermissions("welfare.evaluate.activity")
public Result findOne(@Valid String id) {
WelfareEvaluateActivity activity = dao.fetch(WelfareEvaluateActivity.class, id);
return Result.success(activity);
}
@At
@ViReturn
@RequiresPermissions("welfare.evaluate.activity")
public Result listSubjects(@Valid String activityId){
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class, Cnd.where("activityId", "=", activityId).asc("sortNum"));
dao.fetchLinks(subjects, "options",Cnd.NEW().asc("sortNum"));
return Result.success(subjects);
}
@At
@ViReturn
@Aop(TransAop.READ_COMMITTED)
@RequiresPermissions("welfare.evaluate.activity")
public Result saveSubjects(@Param("activityId") @Valid String activityId, @Param("subjects") WelfareEvaluateSubject[] evaSubjects){
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class, Cnd.where("activityId", "=", activityId));
List<String> subjectIds = subjects.stream().map(WelfareEvaluateSubject::getId).toList();
//新题目
List<String> newSubjectIds = Arrays.stream(evaSubjects).map(WelfareEvaluateSubject::getId).toList();
//过滤出需要删除的题目
List<String> deleteSubjectIds = subjectIds.stream().filter(id -> !newSubjectIds.contains(id)).toList();
dao.clear(WelfareEvaluateSubject.class, Cnd.where("id", "in", deleteSubjectIds));
for (int i = 0; i < evaSubjects.length; i++) {
WelfareEvaluateSubject evaSubject = evaSubjects[i];
evaSubject.setSortNum(i + 1);
evaSubject.setActivityId(activityId);
//更新或添加题目
dao.insertOrUpdate(evaSubject);
//更新或添加选项
List<WelfareEvaluateOption> newOptions = evaSubject.getOptions();
List<String> optionIds = newOptions.stream().map(WelfareEvaluateOption::getId).toList();
List<WelfareEvaluateOption> oldOptions = dao.query(WelfareEvaluateOption.class, Cnd.where("subjectId", "=", evaSubject.getId()));
List<String> oldOptionIds = oldOptions.stream().map(WelfareEvaluateOption::getId).toList();
List<String> deleteOptionIds = oldOptionIds.stream().filter(id -> !optionIds.contains(id)).toList();
dao.clear(WelfareEvaluateOption.class, Cnd.where("id", "in", deleteOptionIds));
if ("radio".equals(evaSubject.getType()) || "checkbox".equals(evaSubject.getType())) {
for (int i1 = 0; i1 < newOptions.size(); i1++) {
newOptions.get(i1).setSortNum(i1 + 1);
newOptions.get(i1).setSubjectId(evaSubject.getId());
}
dao.insertOrUpdate(newOptions);
List<String> correctOptionIds = newOptions.stream().filter(WelfareEvaluateOption::getIsCorrect).map(WelfareEvaluateOption::getId).toList();
evaSubject.setCorrectAnswer(correctOptionIds);
} else {
dao.clear(WelfareEvaluateOption.class, Cnd.where("subjectId", "=", evaSubject.getId()));
}
dao.update(evaSubject);
}
return Result.success();
}
/**
* 查询福利项目
* @param id 如果有Id表明是编辑
* @return
*/
@At
@RequiresPermissions("welfare.evaluate.activity")
public Result queryProject(String id) {
List<WelfareEvaluateActivity> activities = dao.query(WelfareEvaluateActivity.class, Cnd.NEW());
List<String> stringList = activities.stream().map(WelfareEvaluateActivity::getWelfareId).toList();
// 查询福利项目
Sql sql = Sqls.create("SELECT id,`name` FROM welfare_project $condition");
Cnd cnd = Cnd.NEW();
if (Lang.isNotEmpty(stringList)) {
if (StrUtil.isNotBlank(id)) {
WelfareEvaluateActivity activity = activities.stream().filter(item -> item.getId().equals(id)).findFirst().orElse(null);
if (activity != null) {
List<String> result = stringList.stream().filter(item -> !item.equals(activity.getWelfareId())).toList();
cnd.andEX("id", "not in", result);
}
} else {
cnd.andEX("id", "not in", stringList);
}
}
cnd.desc("opAt");
sql.setCondition(cnd);
sql.setCallback(Sqls.callback.maps());
dao.execute(sql);
List<NutMap> reslutList = (List<NutMap>) sql.getResult();
return Result.success(reslutList);
}
@At
@RequiresPermissions("welfare.list.mange")
public Result sendMsgToNotWelfareUsers(String activityId, String title, String sendMsgValue) {
try {
WelfareEvaluateActivity activity = dao.fetch(WelfareEvaluateActivity.class, activityId);
String welfareId = activity.getWelfareId();
Sql sql = Sqls.create("""
SELECT
u.loginname
FROM
welfare_project_user_selection ws
LEFT JOIN welfare_list wl ON wl.projectId = @welfareId
AND wl.userId = ws.selectUserId
LEFT JOIN sys_user u ON u.id = wl.userId
WHERE
ws.welfareId = @welfareId
AND ws.selectUserId NOT IN (SELECT userId FROM welfare_evaluate_user_answer_record WHERE welfareId = @welfareId)
""").setParam("welfareId", welfareId);
sql.setCallback(Sqls.callback.strList());
dao.execute(sql);
List<String> loginNames = sql.getList(String.class);
System.out.println(loginNames);
String link = Globals.AppDomain + "/platform/h5/welfare/evaluate?activityId=%s".formatted(activityId);
// msgApi.sendMsg(List.of("DingTalk"), loginNames, 2, title, sendMsgValue, "", link);
return Result.success();
} catch (Exception e) {
e.printStackTrace();
return Result.error();
}
}
}
@@ -0,0 +1,273 @@
package io.v.nutz.zhgh.welfare.controller.evaluate;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.wizzer.framework.base.Result;
import io.v.nutz.base.annontation.ViReturn;
import io.v.nutz.base.page.Pagination;
import io.v.nutz.base.query.PageForm;
import io.v.nutz.base.service.SimpleService;
import io.v.nutz.base.utils.CommonDownloadUtil;
import io.v.nutz.zhgh.qsv.models.QsvOption;
import io.v.nutz.zhgh.qsv.models.QsvSubject;
import io.v.nutz.zhgh.welfare.model.WelfareProjectSubject;
import io.v.nutz.zhgh.welfare.model.WelfareProjectSubjectOption;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateActivity;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateOption;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateSubject;
import io.v.nutz.zhgh.welfare.service.WelfareEvaluateActivityService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @ClassName WelfareEvaluateStatisticsController
* @Description 评价统计
* @Author zhf
* @Date 2024/5/7 20:02
*/
@IocBean
@Ok("json:full")
@At("/platform/welfare/evaluate/statistics")
public class WelfareEvaluateStatisticsController {
@Inject
private Dao dao;
@Inject
private SimpleService simpleService;
@Inject
private WelfareEvaluateActivityService welfareEvaluateActivityService;
@At("")
@Ok("beetl:/platform/welfare/evaluate/statistics/index.html")
@RequiresPermissions("welfare.evaluate.statistics")
public void index() {
}
@At
@ViReturn
@RequiresPermissions("welfare.evaluate.statistics")
public Object pageData(PageForm pageForm, String projectId, String unionId, String unitId, String personType, String userState, String optionId) {
WelfareEvaluateActivity evaluate = dao.fetch(WelfareEvaluateActivity.class, Cnd.where("welfareId", "=", projectId));
if (Lang.isEmpty(evaluate)) {
return Result.error("未找到相应福利");
}
String activityId = evaluate.getId();
Sql sql = Sqls.create("""
SELECT
record.*,
u.mobile,
u.userState,
u.personType,
GROUP_CONCAT( DISTINCT wuso.optionName, IF(wus.selectSpecs is not null, (CONCAT('—规格:', wus.selectSpecs)), ''), '', wus.selectNum, '份)' ) AS gistList
FROM
welfare_evaluate_user_answer_record record
LEFT JOIN welfare_project wp ON wp.id = record.welfareId
LEFT JOIN welfare_project_user_selection wus ON wp.id = wus.welfareId AND wus.selectUserId = record.userId
LEFT JOIN welfare_project_subject_option wuso ON wus.selectOptionId = wuso.id
LEFT JOIN sys_user u ON u.id = record.userId
$condition
""");
Cnd cnd = Cnd.NEW();
if (StrUtil.isAllNotBlank(pageForm.getSearchName(), pageForm.getSearchKeyword())) {
cnd.and(Cnd.likeEX("record." + pageForm.getSearchName(), pageForm.getSearchKeyword()));
}
cnd.and("record.activityId", "=", activityId);
cnd.and("record.isFinish", "=", true);
cnd.and("record.welfareId", "=", projectId);
cnd.andEX("record.unionid", "=", unionId);
cnd.andEX("record.unitid", "=", unitId);
cnd.andEX("record.personType", "=", personType);
cnd.andEX("record.userState", "=", userState);
cnd.andEX("wus.selectOptionId", "=", optionId);
cnd.groupBy("record.userId");
sql.setCondition(cnd);
// Cnd.where("activityId", "=", activityId)
// .and("isFinish", "=", true)
Pagination pagination = welfareEvaluateActivityService.listPageMap(pageForm.getPageNumber(), pageForm.getPageSize(), sql);
List<NutMap> answerRecords = pagination.getList();
// 查询活动题目列表
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class, Cnd.where("activityId", "=", activityId).asc("sortNum"));
// 将题目列表转换为Map
Map<String, WelfareEvaluateSubject> subjectMap = subjects.stream().collect(Collectors.toMap(WelfareEvaluateSubject::getId, v -> v));
// 获取题目ID列表
List<String> subjectIds = subjects.stream().map(WelfareEvaluateSubject::getId).toList();
// 查询题目选项列表
List<WelfareEvaluateOption> options = dao.query(WelfareEvaluateOption.class, Cnd.where("subjectId", "in", subjectIds).asc("sortNum"));
// 构建Excel导出实体
List<ExcelExportEntity> excelExportEntities = welfareEvaluateActivityService.buildExcelExportEntities(subjects);
// 构建答题记录列表
List<NutMap> list = answerRecords.stream().map(record -> {
JSONObject extJson = record.getAs("extJson", JSONObject.class);
if (extJson != null) {
NutMap map = NutMap.NEW()
.addv("id", record.getString("id"))
.addv("loginName", record.getString("loginName"))
.addv("userName", record.getString("userName"))
.addv("unitName", record.getString("unitName"))
.addv("unionName", record.getString("unionName"))
.addv("mobile", record.getString("mobile"))
.addv("gistList", record.getString("gistList"));
extJson.forEach((k, v) -> {
JSONObject jsonVal = (JSONObject) v;
String type = subjectMap.get(k).getType();
if ("text".equals(type)) {
map.addv(k, jsonVal.getStr("text"));
} else if ("radio".equals(type) || "checkbox".equals(type)) {
List<NutMap> optionContents = jsonVal.getBeanList("optionContents", NutMap.class);
String selectOptionTexts = optionContents.stream().map(item -> {
WelfareEvaluateOption eva = options.stream().filter(option -> option.getId().equals(item.getString("optionId"))).findFirst().orElse(new WelfareEvaluateOption());
return eva.getText() + (StrUtil.isNotBlank(item.getString("content")) ? ("" + eva.getContentPrefix() + ":") + item.getString("content") : "");
}).collect(Collectors.joining(";"));
map.addv(k, selectOptionTexts);
}
});
return map;
} else {
return record;
}
}).toList();
pagination.setList(list);
// 构建表格列信息
List<NutMap> tableColumns = excelExportEntities.stream()
.map(v -> NutMap.NEW().addv("prop", v.getKey()).addv("label", v.getName()))
.toList();
return NutMap.NEW()
.addv("tableColumns", tableColumns)
.addv("tableData", pagination);
}
@At
@ViReturn
@RequiresPermissions("welfare.evaluate.statistics")
public Object welfareOptions(String projectId) {
List<WelfareProjectSubject> subjects = dao.query(WelfareProjectSubject.class, Cnd.where("projectId", "=", projectId));
List<String> subjectIds = subjects.stream().map(WelfareProjectSubject::getId).collect(Collectors.toList());
return dao.query(WelfareProjectSubjectOption.class, Cnd.where("subjectId", "in", subjectIds).asc("optionSort"));
}
@At
@RequiresPermissions("welfare.evaluate.statistics")
public Result dataReport(String welfareId){
WelfareEvaluateActivity activity = dao.fetch(WelfareEvaluateActivity.class, Cnd.where("welfareId", "=", welfareId));
List<NutMap> list = welfareEvaluateActivityService.dataReport(activity.getId());
return Result.success().addData(list);
}
@At
@Ok("void")
@RequiresPermissions("welfare.evaluate.statistics")
public void exportReportXlsx(String welfareId, HttpServletResponse response) {
WelfareEvaluateActivity activity = dao.fetch(WelfareEvaluateActivity.class, Cnd.where("welfareId", "=", welfareId));
welfareEvaluateActivityService.exportReportXlsx(activity.getId(), response);
}
@At
@Ok("void")
@RequiresPermissions("welfare.evaluate.statistics")
public void exportXlsx(PageForm pageForm, String projectId, String unionId, String unitId,
String personType, String userState, String optionId,
HttpServletResponse response) {
try {
WelfareEvaluateActivity evaluate = dao.fetch(WelfareEvaluateActivity.class, Cnd.where("welfareId", "=", projectId));
if (Lang.isEmpty(evaluate)) {
throw new RuntimeException("未找到相应福利");
}
String activityId = evaluate.getId();
Sql sql = Sqls.create("""
SELECT
record.*,
u.mobile,
u.userState,
u.personType,
GROUP_CONCAT( DISTINCT wuso.optionName, IF(wus.selectSpecs is not null, (CONCAT('—规格:', wus.selectSpecs)), ''), '', wus.selectNum, '份)' ) AS gistList
FROM
welfare_evaluate_user_answer_record record
LEFT JOIN welfare_project wp ON wp.id = record.welfareId
LEFT JOIN welfare_project_user_selection wus ON wp.id = wus.welfareId AND wus.selectUserId = record.userId
LEFT JOIN welfare_project_subject_option wuso ON wus.selectOptionId = wuso.id
LEFT JOIN sys_user u ON u.id = record.userId
$condition
""");
Cnd cnd = Cnd.NEW();
if (StrUtil.isAllNotBlank(pageForm.getSearchName(), pageForm.getSearchKeyword())) {
cnd.and(Cnd.likeEX("record." + pageForm.getSearchName(), pageForm.getSearchKeyword()));
}
cnd.and("record.activityId", "=", activityId);
cnd.and("record.isFinish", "=", true);
cnd.and("record.welfareId", "=", projectId);
cnd.andEX("record.unionid", "=", unionId);
cnd.andEX("record.unitid", "=", unitId);
cnd.andEX("record.personType", "=", personType);
cnd.andEX("record.userState", "=", userState);
cnd.andEX("wus.selectOptionId", "=", optionId);
cnd.groupBy("record.userId");
sql.setCondition(cnd);
// Cnd.where("activityId", "=", activityId)
// .and("isFinish", "=", true)
List<NutMap> answerRecords = welfareEvaluateActivityService.listMap(sql);
// 查询活动题目列表
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class, Cnd.where("activityId", "=", activityId).asc("sortNum"));
// 将题目列表转换为Map
Map<String, WelfareEvaluateSubject> subjectMap = subjects.stream().collect(Collectors.toMap(WelfareEvaluateSubject::getId, v -> v));
// 获取题目ID列表
List<String> subjectIds = subjects.stream().map(WelfareEvaluateSubject::getId).toList();
// 查询题目选项列表
List<WelfareEvaluateOption> options = dao.query(WelfareEvaluateOption.class, Cnd.where("subjectId", "in", subjectIds).asc("sortNum"));
// 构建Excel导出实体
List<ExcelExportEntity> excelExportEntities = welfareEvaluateActivityService.buildExcelExportEntities(subjects);
List<NutMap> list = welfareEvaluateActivityService.buildAnswerRecords(answerRecords, subjectMap, options);
// 导出Excel并下载
ExportParams exportParams = new ExportParams();
exportParams.setType(ExcelType.XSSF);
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, excelExportEntities, list);
CommonDownloadUtil.download(evaluate.getTitle() + "记录" + ".xlsx", workbook, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,135 @@
package io.v.nutz.zhgh.welfare.h5controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.wizzer.framework.base.Result;
import io.v.nutz.web.commons.utils.ShiroUtil;
import io.v.nutz.zhgh.activity.models.ActivityUserScope;
import io.v.nutz.zhgh.qsv.models.QsvActivity;
import io.v.nutz.zhgh.qsv.models.QsvSubject;
import io.v.nutz.zhgh.qsv.models.QsvUserAnswerRecord;
import io.v.nutz.zhgh.qsv.param.QsvAnswerParam;
import io.v.nutz.zhgh.welfare.model.WelfareUserSelection;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateActivity;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateSubject;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateUserAnswerRecord;
import io.v.nutz.zhgh.welfare.param.WelfareEvaluateAnswerParam;
import io.v.nutz.zhgh.welfare.service.WelfareEvaluateActivityService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @version 1.0
* @Author zzr
* @nameH5WelfareEvaluateController
* @Date 2025/8/12 8:55
* @注释
*/
@IocBean
@Ok("json:full")
@At("/platform/h5/welfare/evaluate")
public class H5WelfareEvaluateController {
@Inject
private Dao dao;
@Inject
private WelfareEvaluateActivityService welfareEvaluateActivityService;
@At("")
@RequiresPermissions("welfare.mine")
@Ok("beetl:/mobile/welfare/evaluate/index.html")
public void index() {
}
@At
@RequiresPermissions("welfare.mine")
public Result subjects(String activityId) {
WelfareEvaluateActivity activity = dao.fetch(WelfareEvaluateActivity.class, activityId);
if (activity == null) {
return Result.error("调查不存在");
}
int count = dao.count(WelfareUserSelection.class, Cnd.where("welfareId", "=", activity.getWelfareId()).and("selectUserId", "=", ShiroUtil.getUserId()));
if (count != 1) {
return Result.error("您无需参加此次投票,感谢您的关注!");
}
String answerRecordId = null;
WelfareEvaluateUserAnswerRecord answerRecord = dao.fetch(WelfareEvaluateUserAnswerRecord.class, Cnd.where("activityId", "=", activityId)
.and("userId", "=", ShiroUtil.getUserId()));
if (answerRecord == null) {
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class,
Cnd.where("activityId", "=", activityId).asc("sortNum"));
welfareEvaluateActivityService.insertRecord(activityId, subjects.stream().map(WelfareEvaluateSubject::getId).toList());
}
WelfareEvaluateUserAnswerRecord answerRecord2 = dao.fetch(WelfareEvaluateUserAnswerRecord.class,
Cnd.where("activityId", "=", activityId)
.and("userId", "=", ShiroUtil.getUserId()));
answerRecordId = answerRecord2.getId();
List<WelfareEvaluateSubject> subjects = dao.query(WelfareEvaluateSubject.class,
Cnd.where("id", "in", answerRecord2.getSubjectIds()).asc("sortNum"));
dao.fetchLinks(subjects, "options", Cnd.NEW().asc("sortNum"));
for (WelfareEvaluateSubject subject : subjects) {
if (subject.getUserSelectOptionIds() == null) {
subject.setUserSelectOptionIds(new ArrayList<>());
}
}
NutMap result = NutMap.NEW().addv("subjects", subjects).addv("answerRecordId", answerRecordId).addv("activity", activity);
return Result.success(result);
}
@At
@RequiresPermissions("welfare.mine")
public Result answerRecord(@Valid String answerRecordId) {
WelfareEvaluateUserAnswerRecord record = dao.fetch(WelfareEvaluateUserAnswerRecord.class, answerRecordId);
return Result.success(record);
}
@At
@RequiresPermissions("welfare.mine")
public Result submitAnswer(@Valid @Param("answer") WelfareEvaluateAnswerParam qsvAnswerParam) {
WelfareEvaluateActivity activity = dao.fetch(WelfareEvaluateActivity.class, qsvAnswerParam.getActivityId());
WelfareEvaluateUserAnswerRecord answerRecord = dao.fetch(WelfareEvaluateUserAnswerRecord.class, qsvAnswerParam.getAnswerRecordId());
JSONObject extJson = answerRecord.getExtJson();
for (WelfareEvaluateAnswerParam.Subject subject : qsvAnswerParam.getSubjects()) {
JSONObject entries = extJson.get(subject.getId(), JSONObject.class);
if (ObjectUtil.isNotEmpty(entries)) {
entries.set("optionIds", subject.getUserSelectOptionIds());
entries.set("optionContents", subject.getUserSelectOptionContent());
entries.set("text", subject.getUserFillContent());
}
extJson.set(subject.getId(), entries);
}
answerRecord.setWelfareId(activity.getWelfareId());
answerRecord.setAttemptDate(new Date());
answerRecord.setSubmitTime(new Date());
answerRecord.setIsFinish(true);
dao.update(answerRecord);
return Result.success("提交成功");
}
}
@@ -0,0 +1,79 @@
package io.v.nutz.zhgh.welfare.model.eavluate;
import io.v.nutz.base.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.dao.entity.annotation.*;
import org.nutz.dao.interceptor.annotation.PrevInsert;
import java.util.Date;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateActivity
* @Date 2025/8/11 14:18
* @注释 福利评价
*/
@Data
@Table
@EqualsAndHashCode(callSuper = true)
public class WelfareEvaluateActivity extends BaseModel {
@Name
@Comment("ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
@PrevInsert(uu32 = true)
private String id;
@Column
@Comment("福利Id")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String welfareId;
@Column
@Comment("所属模块(quiz, survey, vote)")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String category;
@Column
@Comment("标题")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String title;
@Column
@Comment("描述")
@ColDefine(type = ColType.TEXT)
private String description;
@Column
@Comment("尾行内容")
@ColDefine(type = ColType.TEXT)
private String lastContent;
@Column
@Comment("活动开始时间")
@ColDefine(type = ColType.DATETIME)
private Date startTime;
@Column
@Comment("活动结束时间")
@ColDefine(type = ColType.DATETIME)
private Date endTime;
@Column
@Comment("模式:定时定题模式(scheduled)或常规模式(regular")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String mode;
@Column
@Comment("是否可重复答题")
@ColDefine(type = ColType.BOOLEAN)
@Default("0")
private Boolean repeatable;
@Column
@Comment("最大答题次数(0表示不限制)")
@ColDefine(type = ColType.INT, width = 1)
private Integer maxAttempts;
}
@@ -0,0 +1,64 @@
package io.v.nutz.zhgh.welfare.model.eavluate;
import io.v.nutz.base.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.dao.entity.annotation.*;
import org.nutz.dao.interceptor.annotation.PrevInsert;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateOption
* @Date 2025/8/11 14:27
* @注释 福利评价选项表
*/
@Data
@Table
@EqualsAndHashCode(callSuper = true)
public class WelfareEvaluateOption extends BaseModel {
@Name
@Comment("ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
@PrevInsert(uu32 = true)
private String id;
@Column
@Comment("题目表")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String subjectId;
@Column
@Comment("选项内容")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String text;
@Column
@Default("0")
@Comment("是否为正确答案(仅答题模块使用)")
@ColDefine(type = ColType.BOOLEAN)
private Boolean isCorrect;
@Column
@Default("0")
@Comment("是否开启内容填写")
@ColDefine(type = ColType.BOOLEAN)
private Boolean isOpenContent;
@Column
@Comment("内容前缀")
@ColDefine(type = ColType.VARCHAR, width = 100)
private String contentPrefix;
@Column
@Comment("详情")
@ColDefine(customType = "longtext")
private String description;
@Column
@Comment("排序")
@ColDefine(type = ColType.INT)
private Integer sortNum;
}
@@ -0,0 +1,86 @@
package io.v.nutz.zhgh.welfare.model.eavluate;
import io.v.nutz.base.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.dao.entity.annotation.*;
import org.nutz.dao.interceptor.annotation.PrevInsert;
import java.util.Date;
import java.util.List;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateSubject
* @Date 2025/8/11 14:27
* @注释 福利评价题目表
*/
@Data
@Table
@EqualsAndHashCode(callSuper = true)
public class WelfareEvaluateSubject extends BaseModel {
@Name
@Comment("ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
@PrevInsert(uu32 = true)
private String id;
@Column
@Comment("活动ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String activityId;
@Column
@Comment("题目标题")
@ColDefine(type = ColType.VARCHAR, width = 255)
private String title;
@Column
@Comment("题目类型(single, multi, judge, fill")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String type;
@Column
@Comment("正确答案")
@ColDefine(type = ColType.MYSQL_JSON)
private List<String> correctAnswer;
@Column
@Comment("题目分数(仅答题模块使用)")
@ColDefine(type = ColType.INT, width = 1)
private Integer score;
@Column
@Comment("显示时间")
@ColDefine(type = ColType.DATE)
private Date displayDate;
@Column
@Comment("多选,最多选几个")
@ColDefine(type = ColType.INT, width = 1)
private Integer maxMulti;
@Column
@Comment("排序")
@ColDefine(type = ColType.INT, width = 1)
private Integer sortNum;
/**
* 选项
*/
@Many(target = WelfareEvaluateOption.class, field = "subjectId")
private List<WelfareEvaluateOption> options;
/**
* 用户选择的选项(选择题)
*/
private List<String> userSelectOptionIds;
/**
* 用户填写的内容(填空题)
*/
private String userFillContent;
}
@@ -0,0 +1,134 @@
package io.v.nutz.zhgh.welfare.model.eavluate;
import cn.hutool.json.JSONObject;
import cn.wizzer.framework.base.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nutz.dao.entity.annotation.*;
import org.nutz.dao.interceptor.annotation.PrevInsert;
import java.util.Date;
import java.util.List;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateUserAnswerRecord
* @Date 2025/8/12 9:19
* @注释
*/
@Data
@Table
@EqualsAndHashCode(callSuper = true)
public class WelfareEvaluateUserAnswerRecord extends BaseModel {
@Name
@Comment("ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
@PrevInsert(uu32 = true)
private String id;
@Column
@Comment("用户ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String userId;
@Column
@Comment("工号")
@ColDefine(type = ColType.VARCHAR, width = 200)
private String loginName;
@Column
@Comment("姓名")
@ColDefine(type = ColType.VARCHAR, width = 200)
private String userName;
@Column
@Comment("分工会")
@ColDefine(type = ColType.VARCHAR, width = 50)
private String unionName;
@Column
@Comment("分工会ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String unionId;
@Column
@Comment("单位")
@ColDefine(type = ColType.VARCHAR, width = 200)
private String unitName;
@Column
@Comment("单位ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String unitId;
@Column
@Comment("活动ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String activityId;
@Column
@Comment("福利Id")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String welfareId;
@Column
@Comment("扩展字段")
@ColDefine(type = ColType.MYSQL_JSON)
private JSONObject extJson;
@Column
@Comment("题目ID")
@ColDefine(type = ColType.MYSQL_JSON)
private List<String> subjectIds;
@Column
@Comment("答题得分(仅答题模块使用)")
@ColDefine(type = ColType.FLOAT)
private Float totalScore;
@Column
@Comment("随机次数(仅答题模块使用随机抽取模式)")
@ColDefine(type = ColType.INT, width = 1)
private Integer randomNumber;
@Column
@Comment("答题次数(仅答题模块使用)")
@ColDefine(type = ColType.INT, width = 1)
private Integer attemptNumber;
@Column
@Comment("答题日期(用于统计某一天的答题次数)")
@ColDefine(type = ColType.DATE)
private Date attemptDate;
@Column
@Comment("是否为最新得分(仅答题模块使用)")
@ColDefine(type = ColType.BOOLEAN)
@Default("0")
private Boolean isLatestScore;
@Column
@Comment("是否为最高得分(仅答题模块使用)")
@ColDefine(type = ColType.BOOLEAN)
@Default("0")
private Boolean isHighestScore;
@Column
@Comment("是否完成")
@ColDefine(type = ColType.BOOLEAN)
@Default("0")
private Boolean isFinish;
@Column
@Comment("提交时间")
@ColDefine(type = ColType.DATETIME)
private Date submitTime;
@Column
@Comment("答题用时")
@ColDefine(type = ColType.INT)
private Integer answerTime;
}
@@ -0,0 +1,27 @@
package io.v.nutz.zhgh.welfare.param;
import lombok.Data;
import org.nutz.lang.util.NutMap;
import java.util.List;
@Data
public class WelfareEvaluateAnswerParam {
private String activityId;
private String answerRecordId;
private List<Subject> subjects;
private Integer answerTime;
@Data
public static class Subject{
private String id;
private List<String> userSelectOptionIds;
private List<NutMap> userSelectOptionContent;
private String userFillContent;
}
}
@@ -0,0 +1,61 @@
package io.v.nutz.zhgh.welfare.service;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import io.v.nutz.base.service.BaseService;
import io.v.nutz.zhgh.qsv.models.QsvOption;
import io.v.nutz.zhgh.qsv.models.QsvSubject;
import io.v.nutz.zhgh.qsv.models.QsvUserAnswerRecord;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateActivity;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateOption;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateSubject;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateUserAnswerRecord;
import org.nutz.lang.util.NutMap;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateActivityService
* @Date 2025/8/11 15:14
* @注释
*/
public interface WelfareEvaluateActivityService extends BaseService<WelfareEvaluateActivity> {
WelfareEvaluateUserAnswerRecord insertRecord(String activityId, List<String> subjectIds);
/**
* 数据报告
* @param activityId
* @return
*/
List<NutMap> dataReport(String activityId);
/**
* 构建导出实体
* @param subjects
* @return
*/
List<ExcelExportEntity> buildExcelExportEntities(List<WelfareEvaluateSubject> subjects);
/**
* 构建用户答案记录
* @param answerRecords
* @param subjectMap
* @param options
* @return
*/
List<NutMap> buildAnswerRecords(List<NutMap> answerRecords,
Map<String, WelfareEvaluateSubject> subjectMap,
List<WelfareEvaluateOption> options);
/**
* 导出数据报告
* @param activityId
* @param response
*/
void exportReportXlsx(String activityId, HttpServletResponse response);
}
@@ -0,0 +1,275 @@
package io.v.nutz.zhgh.welfare.service.impl;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import io.v.nutz.base.service.impl.BaseServiceImpl;
import io.v.nutz.base.utils.CommonDownloadUtil;
import io.v.nutz.sys.models.User;
import io.v.nutz.web.commons.utils.ShiroUtil;
import io.v.nutz.zhgh.qsv.models.QsvOption;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateActivity;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateOption;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateSubject;
import io.v.nutz.zhgh.welfare.model.eavluate.WelfareEvaluateUserAnswerRecord;
import io.v.nutz.zhgh.welfare.service.WelfareEvaluateActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @version 1.0
* @Author zzr
* @nameWelfareEvaluateActivityServiceImpl
* @Date 2025/8/11 15:14
* @注释
*/
@Slf4j
@IocBean(args = {"refer:dao"})
public class WelfareEvaluateActivityServiceImpl extends BaseServiceImpl<WelfareEvaluateActivity> implements WelfareEvaluateActivityService {
public WelfareEvaluateActivityServiceImpl(Dao dao) {
super(dao);
}
@Override
public WelfareEvaluateUserAnswerRecord insertRecord(String activityId, List<String> subjectIds) {
WelfareEvaluateUserAnswerRecord record = new WelfareEvaluateUserAnswerRecord();
record.setActivityId(activityId);
record.setUserId(ShiroUtil.getUserId());
record.setSubjectIds(subjectIds);
JSONObject extJson = new JSONObject();
for (String subjectId : subjectIds) {
extJson.set(subjectId, Dict.create()
.set("optionIds", new ArrayList<>())
.set("text", null)
.set("isCorrect", null)
);
}
record.setExtJson(extJson);
User user = dao().fetch(User.class, Cnd.where("id", "=", ShiroUtil.getUserId()));
record.setLoginName(user.getLoginname());
record.setUserName(user.getUsername());
record.setUnitId(user.getUnitid());
record.setUnitName(user.getUnitname());
record.setUnionId(user.getUnionid());
record.setUnionName(user.getUnionname());
dao().insert(record);
return record;
}
@Override
public List<NutMap> dataReport(String activityId) {
// 检查活动ID是否为空
if (activityId == null || activityId.isEmpty()) {
throw new IllegalArgumentException("活动ID不能为空");
}
try {
// 查询用户答题记录
List<WelfareEvaluateUserAnswerRecord> answerRecords = dao().query(WelfareEvaluateUserAnswerRecord.class, Cnd.where("activityId", "=", activityId)
.and("isFinish", "=", true));
// 将答题记录的扩展JSON转换为JSONObject列表
List<JSONObject> answerExtList = answerRecords.stream().map(WelfareEvaluateUserAnswerRecord::getExtJson).toList();
// 查询活动题目列表
List<NutMap> subjects = querySubjects(activityId);
// 获取题目ID列表
List<String> subjectIds = subjects.stream().map(v -> v.getString("id")).toList();
// 查询题目选项列表
List<WelfareEvaluateOption> options = dao().query(WelfareEvaluateOption.class, Cnd.where("subjectId", "in", subjectIds).asc("sortNum"));
// 按题目ID分组选项
Map<String, List<WelfareEvaluateOption>> optionsGroup = options.stream().collect(Collectors.groupingBy(WelfareEvaluateOption::getSubjectId));
// 处理每个题目
for (NutMap subject : subjects) {
// 获取当前题目的选项列表
List<NutMap> subjectOptions = Lang.collection2list(optionsGroup.get(subject.getString("id")), NutMap.class);
// 获取题目类型
String subjectType = subject.getString("type");
// 处理文本类型题目
if ("text".equals(subjectType)) {
List<String> texts = answerExtList.stream()
.filter(ext -> ObjectUtil.isNotNull(ext.get(subject.getString("id"), JSONObject.class)))
.map(ext -> ext.get(subject.getString("id"), JSONObject.class).getStr("text"))
.toList();
subject.put("texts", texts);
}
// 处理单选类型题目 处理多选类型题目
else if ("radio".equals(subjectType) || "checkbox".equals(subjectType)) {
long selectTotal = answerExtList.stream()
.filter(ext -> ext.containsKey(subject.getString("id")))
.count();
subjectOptions.forEach(subjectOption -> {
long selectCount = answerExtList.stream()
.filter(ext ->
{
JSONObject jsonObject = ext.get(subject.getString("id"), JSONObject.class);
return jsonObject != null
&& jsonObject.getJSONArray("optionIds") != null
&& jsonObject.getJSONArray("optionIds").contains(subjectOption.getString("id"));
})
.count();
long round = Math.round((double) selectCount / selectTotal * 100);
subjectOption.put("selectPercent", round + "%");
subjectOption.put("selectCount", selectCount);
});
subjectOptions.sort((o1, o2) -> {
int count1 = o1.getInt("selectCount");
int count2 = o2.getInt("selectCount");
if (count1 == count2) {
return Integer.compare(o1.getInt("sortNum"), o2.getInt("sortNum"));
}
return Integer.compare(count2, count1);
});
subject.put("selectTotal", selectTotal);
}
// 添加选项到题目中
subject.addv("options", subjectOptions);
}
return subjects;
} catch (Exception e) {
log.error("报告生成失败", e);
throw new RuntimeException("报告生成失败", e);
}
}
@Override
public List<ExcelExportEntity> buildExcelExportEntities(List<WelfareEvaluateSubject> subjects) {
List<ExcelExportEntity> excelExportEntities = new ArrayList<>();
excelExportEntities.add(new ExcelExportEntity("工号", "loginName", 20));
excelExportEntities.add(new ExcelExportEntity("姓名", "userName", 20));
excelExportEntities.add(new ExcelExportEntity("单位", "unitName", 20));
excelExportEntities.add(new ExcelExportEntity("分工会", "unionName", 20));
excelExportEntities.add(new ExcelExportEntity("联系方式", "mobile", 20));
excelExportEntities.add(new ExcelExportEntity("所选福利", "gistList", 20));
for (WelfareEvaluateSubject subject : subjects) {
excelExportEntities.add(new ExcelExportEntity(subject.getTitle(), subject.getId(), 20));
}
return excelExportEntities;
}
@Override
public List<NutMap> buildAnswerRecords(List<NutMap> answerRecords,
Map<String, WelfareEvaluateSubject> subjectMap,
List<WelfareEvaluateOption> options) {
return answerRecords.stream().map(record -> {
NutMap map = NutMap.NEW()
.addv("loginName", record.getString("loginName"))
.addv("userName", record.getString("userName"))
.addv("unitName", record.getString("unitName"))
.addv("unionName", record.getString("unionName"))
.addv("mobile", record.getString("mobile"))
.addv("gistList", record.getString("gistList"));
JSONObject extJson = record.getAs("extJson", JSONObject.class);
if (extJson == null) {
extJson = new JSONObject();
}
extJson.forEach((k, v) -> {
// JSONObject jsonVal = (JSONObject) v;
//
// String type = subjectMap.get(k).getType();
// if ("text".equals(type)) {
// map.addv(k, jsonVal.getStr("text"));
// } else if ("radio".equals(type) || "checkbox".equals(type)) {
// JSONArray optionIds = jsonVal.getJSONArray("optionIds");
// String selectOptionTexts = options.stream().filter(option -> optionIds.contains(option.getId()))
// .map(WelfareEvaluateOption::getText).collect(Collectors.joining(";"));
// map.addv(k, selectOptionTexts);
// }
JSONObject jsonVal = (JSONObject) v;
String type = subjectMap.get(k).getType();
if ("text".equals(type)) {
map.addv(k, jsonVal.getStr("text"));
} else if ("radio".equals(type) || "checkbox".equals(type)) {
List<NutMap> optionContents = jsonVal.getBeanList("optionContents", NutMap.class);
String selectOptionTexts = optionContents.stream().map(item -> {
WelfareEvaluateOption eva = options.stream().filter(option -> option.getId().equals(item.getString("optionId"))).findFirst().orElse(new WelfareEvaluateOption());
return eva.getText() + (StrUtil.isNotBlank(item.getString("content")) ? ("" + eva.getContentPrefix() + ":") + item.getString("content") : "");
}).collect(Collectors.joining(";"));
map.addv(k, selectOptionTexts);
}
});
return map;
}).collect(Collectors.toList());
}
@Override
public void exportReportXlsx(String activityId, HttpServletResponse response) {
List<NutMap> report = dataReport(activityId);
List<ExcelExportEntity> exportEntities = new ArrayList<>();
exportEntities.add(new ExcelExportEntity("选项名称", "text", 20));
exportEntities.add(new ExcelExportEntity("选择人数", "selectCount", 20));
exportEntities.add(new ExcelExportEntity("选择比例", "selectPercent", 20));
Map<String, List<NutMap>> listMap = report.stream().collect(Collectors.groupingBy(v -> v.getString("id")));
Workbook workbook = new XSSFWorkbook();
listMap.forEach((k, v) -> {
NutMap nutMap = v.get(0);
ExcelExportService service = new ExcelExportService();
ExportParams exportParams = new ExportParams();
exportParams.setTitle(nutMap.getString("title"));
exportParams.setSheetName(nutMap.getString("title"));
exportParams.setType(ExcelType.XSSF);
service.createSheetForMap(workbook, exportParams, exportEntities, nutMap.getList("options", NutMap.class));
});
CommonDownloadUtil.download("满意度分析.xlsx", workbook, response);
}
private List<NutMap> querySubjects(String activityId) {
Sql sql = Sqls.create("""
SELECT
id,
title,
type,
sortNum
FROM
welfare_evaluate_subject
WHERE
activityId = @activityId
ORDER BY
sortNum ASC
""");
sql.setParam("activityId", activityId);
sql.setCallback(Sqls.callback.maps());
dao().execute(sql);
return (List<NutMap>) sql.getResult();
}
}