Compare commits
15 Commits
a22a573c0d
...
36015f26d9
| Author | SHA1 | Date | |
|---|---|---|---|
| 36015f26d9 | |||
| 6733f5f641 | |||
| 23a6b717d7 | |||
| f2bfb001f2 | |||
|
|
2ffb3b4ebe | ||
|
|
21ffca5ded | ||
|
|
4571208ad9 | ||
|
|
5b3c59b632 | ||
|
|
890f7ea666 | ||
|
|
2e034eb6f2 | ||
|
|
8032f4c39c | ||
| e3b6915fbe | |||
| 530a0f13e7 | |||
|
|
3bfaec8cbc | ||
|
|
1b280af9e2 |
@@ -148,3 +148,60 @@ WHERE id IN (
|
||||
'1860000000000000041',
|
||||
'1860000000000000051'
|
||||
);
|
||||
|
||||
-- ======================================================
|
||||
-- 新增菜单:原材料检验项目
|
||||
-- ======================================================
|
||||
INSERT INTO sys_permission(id, parent_id, name, url, component, component_name, menu_type, perms, perms_type, sort_no, is_route, is_leaf, hidden, status, del_flag, keep_alive, internal_or_external, create_by, create_time)
|
||||
VALUES ('1860000000000000061', '1860000000000000001', '原材料检验项目', '/mes/rawmaterialinspectitem', 'mes/material/MesRawMaterialInspectItemList', 'MesRawMaterialInspectItemList', 1, NULL, '1', 6, 1, 1, 0, '1', 0, 1, 0, 'admin', NOW())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
parent_id=VALUES(parent_id), name=VALUES(name), url=VALUES(url), component=VALUES(component), component_name=VALUES(component_name),
|
||||
menu_type=VALUES(menu_type), perms=VALUES(perms), perms_type=VALUES(perms_type), sort_no=VALUES(sort_no),
|
||||
is_route=VALUES(is_route), is_leaf=VALUES(is_leaf), hidden=VALUES(hidden), status=VALUES(status), del_flag=VALUES(del_flag),
|
||||
keep_alive=VALUES(keep_alive), internal_or_external=VALUES(internal_or_external);
|
||||
INSERT INTO sys_permission(id,parent_id,name,menu_type,perms,perms_type,status,del_flag,create_by,create_time) VALUES
|
||||
('1860000000000000062','1860000000000000061','新增',2,'mes:mes_raw_material_inspect_item:add','1','1',0,'admin',NOW()),
|
||||
('1860000000000000063','1860000000000000061','编辑',2,'mes:mes_raw_material_inspect_item:edit','1','1',0,'admin',NOW()),
|
||||
('1860000000000000064','1860000000000000061','删除',2,'mes:mes_raw_material_inspect_item:delete','1','1',0,'admin',NOW()),
|
||||
('1860000000000000065','1860000000000000061','批量删除',2,'mes:mes_raw_material_inspect_item:deleteBatch','1','1',0,'admin',NOW()),
|
||||
('1860000000000000066','1860000000000000061','导出',2,'mes:mes_raw_material_inspect_item:exportXls','1','1',0,'admin',NOW()),
|
||||
('1860000000000000067','1860000000000000061','导入',2,'mes:mes_raw_material_inspect_item:importExcel','1','1',0,'admin',NOW())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
parent_id=VALUES(parent_id), name=VALUES(name), menu_type=VALUES(menu_type), perms=VALUES(perms), perms_type=VALUES(perms_type),
|
||||
status=VALUES(status), del_flag=VALUES(del_flag);
|
||||
|
||||
-- ======================================================
|
||||
-- 新增菜单:原材料检验标准
|
||||
-- ======================================================
|
||||
INSERT INTO sys_permission(id, parent_id, name, url, component, component_name, menu_type, perms, perms_type, sort_no, is_route, is_leaf, hidden, status, del_flag, keep_alive, internal_or_external, create_by, create_time)
|
||||
VALUES ('1860000000000000071', '1860000000000000001', '原材料检验标准', '/mes/rawmaterialinspectstd', 'mes/material/MesRawMaterialInspectStdList', 'MesRawMaterialInspectStdList', 1, NULL, '1', 7, 1, 1, 0, '1', 0, 1, 0, 'admin', NOW())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
parent_id=VALUES(parent_id), name=VALUES(name), url=VALUES(url), component=VALUES(component), component_name=VALUES(component_name),
|
||||
menu_type=VALUES(menu_type), perms=VALUES(perms), perms_type=VALUES(perms_type), sort_no=VALUES(sort_no),
|
||||
is_route=VALUES(is_route), is_leaf=VALUES(is_leaf), hidden=VALUES(hidden), status=VALUES(status), del_flag=VALUES(del_flag),
|
||||
keep_alive=VALUES(keep_alive), internal_or_external=VALUES(internal_or_external);
|
||||
INSERT INTO sys_permission(id,parent_id,name,menu_type,perms,perms_type,status,del_flag,create_by,create_time) VALUES
|
||||
('1860000000000000072','1860000000000000071','新增',2,'mes:mes_raw_material_inspect_std:add','1','1',0,'admin',NOW()),
|
||||
('1860000000000000073','1860000000000000071','编辑',2,'mes:mes_raw_material_inspect_std:edit','1','1',0,'admin',NOW()),
|
||||
('1860000000000000074','1860000000000000071','删除',2,'mes:mes_raw_material_inspect_std:delete','1','1',0,'admin',NOW()),
|
||||
('1860000000000000075','1860000000000000071','批量删除',2,'mes:mes_raw_material_inspect_std:deleteBatch','1','1',0,'admin',NOW()),
|
||||
('1860000000000000076','1860000000000000071','启用停用',2,'mes:mes_raw_material_inspect_std:enable','1','1',0,'admin',NOW()),
|
||||
('1860000000000000077','1860000000000000071','导出',2,'mes:mes_raw_material_inspect_std:exportXls','1','1',0,'admin',NOW()),
|
||||
('1860000000000000078','1860000000000000071','导入',2,'mes:mes_raw_material_inspect_std:importExcel','1','1',0,'admin',NOW())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
parent_id=VALUES(parent_id), name=VALUES(name), menu_type=VALUES(menu_type), perms=VALUES(perms), perms_type=VALUES(perms_type),
|
||||
status=VALUES(status), del_flag=VALUES(del_flag);
|
||||
|
||||
-- 新增菜单授权:admin
|
||||
INSERT INTO sys_role_permission(id, role_id, permission_id, operate_date, operate_ip)
|
||||
SELECT REPLACE(UUID(),'-',''), 'f6817f48af4fb3af11b9e8bf182f618b', p.id, NOW(), '127.0.0.1'
|
||||
FROM sys_permission p
|
||||
WHERE p.id IN (
|
||||
'1860000000000000061','1860000000000000062','1860000000000000063','1860000000000000064','1860000000000000065','1860000000000000066','1860000000000000067',
|
||||
'1860000000000000071','1860000000000000072','1860000000000000073','1860000000000000074','1860000000000000075','1860000000000000076','1860000000000000077','1860000000000000078'
|
||||
) AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys_role_permission rp
|
||||
WHERE rp.role_id = 'f6817f48af4fb3af11b9e8bf182f618b'
|
||||
AND rp.permission_id = p.id
|
||||
);
|
||||
|
||||
37
jeecg-boot/db/mes-xsl-raw-material-summary-menu.sql
Normal file
@@ -0,0 +1,37 @@
|
||||
-- 原材料汇总页面菜单(参考:原材料库存菜单配置)
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
-- 优先复用「原材料库存」的父级菜单;不存在时回退到原固定父级
|
||||
SET @xsl_parent_id = (
|
||||
SELECT parent_id
|
||||
FROM sys_permission
|
||||
WHERE id = '1900000000000000600'
|
||||
LIMIT 1
|
||||
);
|
||||
SET @xsl_parent_id = IFNULL(@xsl_parent_id, '1900000000000000300');
|
||||
|
||||
-- 页面菜单
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000610', @xsl_parent_id, '原材料汇总', '/xslmes/mesXslRawMaterialSummary', 'xslmes/mesXslRawMaterialSummary/MesXslRawMaterialSummaryList', 1, NULL, NULL, 1, NULL, '0', 13.00, 0, 'ant-design:database-outlined', 0, 1, 0, 0, '原材料汇总', 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000610');
|
||||
|
||||
-- 导出按钮权限
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000611', '1900000000000000610', '导出', NULL, NULL, 0, NULL, NULL, 2, 'xslmes:mes_xsl_raw_material_summary:exportXls', '1', 1.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000611');
|
||||
|
||||
-- 默认管理员角色授权
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), 'f6817f48af4fb3af11b9e8bf182f618b', '1900000000000000610', NULL, NOW(), '127.0.0.1'
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `sys_role_permission`
|
||||
WHERE `role_id` = 'f6817f48af4fb3af11b9e8bf182f618b' AND `permission_id` = '1900000000000000610'
|
||||
);
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), 'f6817f48af4fb3af11b9e8bf182f618b', '1900000000000000611', NULL, NOW(), '127.0.0.1'
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `sys_role_permission`
|
||||
WHERE `role_id` = 'f6817f48af4fb3af11b9e8bf182f618b' AND `permission_id` = '1900000000000000611'
|
||||
);
|
||||
|
||||
@@ -670,7 +670,7 @@ public class MesXslDesktopAnonController {
|
||||
if (tpl == null) return Result.error("绑定的打印模板不存在");
|
||||
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
|
||||
JsonNode bizRoot = objectMapper.valueToTree(card);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping, tpl.getTemplateJson());
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
|
||||
Map<String, Object> out = new HashMap<>(8);
|
||||
out.put("cardId", card.getId());
|
||||
@@ -697,7 +697,7 @@ public class MesXslDesktopAnonController {
|
||||
if (tpl == null) return Result.error("绑定的打印模板不存在");
|
||||
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
|
||||
JsonNode bizRoot = objectMapper.valueToTree(entry);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping, tpl.getTemplateJson());
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
|
||||
Map<String, Object> out = new HashMap<>(8);
|
||||
out.put("entryId", entry.getId());
|
||||
|
||||
@@ -228,7 +228,7 @@ public class MesXslRawMaterialCardController extends JeecgController<MesXslRawMa
|
||||
ArrayNode mapping =
|
||||
PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
|
||||
JsonNode bizRoot = objectMapper.valueToTree(card);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping, tpl.getTemplateJson());
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
|
||||
Map<String, Object> out = new HashMap<>(8);
|
||||
out.put("cardId", card.getId());
|
||||
|
||||
@@ -218,7 +218,7 @@ public class MesXslRawMaterialEntryController extends JeecgController<MesXslRawM
|
||||
}
|
||||
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
|
||||
JsonNode bizRoot = objectMapper.valueToTree(entry);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping, tpl.getTemplateJson());
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
|
||||
Map<String, Object> out = new HashMap<>(8);
|
||||
out.put("entryId", entry.getId());
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package org.jeecg.modules.xslmes.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialSummary;
|
||||
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
|
||||
import org.jeecgframework.poi.excel.entity.ExportParams;
|
||||
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
|
||||
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
/**
|
||||
* 原材料汇总
|
||||
*/
|
||||
@Tag(name = "原材料汇总")
|
||||
@RestController
|
||||
@RequestMapping("/xslmes/mesXslRawMaterialSummary")
|
||||
@Slf4j
|
||||
public class MesXslRawMaterialSummaryController {
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Operation(summary = "原材料汇总-分页列表查询")
|
||||
@GetMapping(value = "/list")
|
||||
public Result<IPage<MesXslRawMaterialSummary>> queryPageList(
|
||||
MesXslRawMaterialSummary query,
|
||||
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
|
||||
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
|
||||
List<Object> params = new ArrayList<>();
|
||||
String groupedSql = buildGroupedSql(query, params);
|
||||
String countSql = "SELECT COUNT(1) FROM (" + groupedSql + ") t";
|
||||
Long total = jdbcTemplate.queryForObject(countSql, Long.class, params.toArray());
|
||||
long totalCount = total == null ? 0L : total;
|
||||
|
||||
int offset = Math.max((pageNo - 1) * pageSize, 0);
|
||||
String pageSql = groupedSql + " ORDER BY warehouseName, materialName LIMIT ? OFFSET ?";
|
||||
List<Object> pageParams = new ArrayList<>(params);
|
||||
pageParams.add(pageSize);
|
||||
pageParams.add(offset);
|
||||
List<MesXslRawMaterialSummary> rows = queryRows(pageSql, pageParams);
|
||||
|
||||
Page<MesXslRawMaterialSummary> page = new Page<>(pageNo, pageSize, totalCount);
|
||||
page.setRecords(rows);
|
||||
return Result.OK(page);
|
||||
}
|
||||
|
||||
@RequiresPermissions("xslmes:mes_xsl_raw_material_summary:exportXls")
|
||||
@RequestMapping(value = "/exportXls")
|
||||
public ModelAndView exportXls(HttpServletRequest request, MesXslRawMaterialSummary query) {
|
||||
List<Object> params = new ArrayList<>();
|
||||
String groupedSql = buildGroupedSql(query, params) + " ORDER BY warehouseName, materialName";
|
||||
List<MesXslRawMaterialSummary> exportList = queryRows(groupedSql, params);
|
||||
|
||||
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
|
||||
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
|
||||
mv.addObject(NormalExcelConstants.FILE_NAME, "原材料汇总");
|
||||
mv.addObject(NormalExcelConstants.CLASS, MesXslRawMaterialSummary.class);
|
||||
mv.addObject(
|
||||
NormalExcelConstants.PARAMS,
|
||||
new ExportParams("原材料汇总报表", "导出人:" + (sysUser == null ? "admin" : sysUser.getRealname()), "原材料汇总", ExcelType.XSSF));
|
||||
mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
|
||||
String exportFields = request.getParameter(NormalExcelConstants.EXPORT_FIELDS);
|
||||
if (oConvertUtils.isNotEmpty(exportFields)) {
|
||||
mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields);
|
||||
}
|
||||
return mv;
|
||||
}
|
||||
|
||||
private String buildGroupedSql(MesXslRawMaterialSummary query, List<Object> params) {
|
||||
String warehouseExpr = "COALESCE(NULLIF(TRIM(i.warehouse_name),''), TRIM(w.warehouse_name))";
|
||||
String materialNameExpr = "COALESCE(NULLIF(TRIM(i.material_name),''), TRIM(m.material_name))";
|
||||
String materialCodeExpr = "COALESCE(NULLIF(TRIM(i.material_code),''), TRIM(m.material_code))";
|
||||
StringBuilder sql = new StringBuilder();
|
||||
sql.append("SELECT ")
|
||||
.append(warehouseExpr).append(" AS warehouseName, ")
|
||||
.append(materialNameExpr).append(" AS materialName, ")
|
||||
.append(materialCodeExpr).append(" AS materialCode, ")
|
||||
.append("SUM(COALESCE(i.total_packages,0)) AS totalPackages, ")
|
||||
.append("SUM(COALESCE(i.total_weight,0)) AS totalWeight ")
|
||||
.append("FROM mes_xsl_raw_material_inventory i ")
|
||||
.append("LEFT JOIN mes_xsl_warehouse w ON w.id = i.warehouse_id ")
|
||||
.append("AND (w.del_flag = 0 OR w.del_flag IS NULL) ")
|
||||
.append("LEFT JOIN mes_mixer_material m ON m.id = i.material_id ")
|
||||
.append("AND (m.del_flag = 0 OR m.del_flag IS NULL) ")
|
||||
.append("WHERE (i.del_flag = 0 OR i.del_flag IS NULL) ");
|
||||
|
||||
if (query != null && StringUtils.isNotBlank(query.getWarehouseName())) {
|
||||
sql.append("AND ").append(warehouseExpr).append(" LIKE ? ");
|
||||
params.add("%" + query.getWarehouseName().trim() + "%");
|
||||
}
|
||||
if (query != null && StringUtils.isNotBlank(query.getMaterialName())) {
|
||||
sql.append("AND ").append(materialNameExpr).append(" LIKE ? ");
|
||||
params.add("%" + query.getMaterialName().trim() + "%");
|
||||
}
|
||||
if (query != null && StringUtils.isNotBlank(query.getMaterialCode())) {
|
||||
sql.append("AND ").append(materialCodeExpr).append(" LIKE ? ");
|
||||
params.add("%" + query.getMaterialCode().trim() + "%");
|
||||
}
|
||||
|
||||
sql.append("GROUP BY ")
|
||||
.append(warehouseExpr).append(", ")
|
||||
.append(materialNameExpr).append(", ")
|
||||
.append(materialCodeExpr);
|
||||
return sql.toString();
|
||||
}
|
||||
|
||||
private List<MesXslRawMaterialSummary> queryRows(String sql, List<Object> params) {
|
||||
return jdbcTemplate.query(
|
||||
sql,
|
||||
rs -> {
|
||||
List<MesXslRawMaterialSummary> list = new ArrayList<>();
|
||||
int seq = 1;
|
||||
while (rs.next()) {
|
||||
MesXslRawMaterialSummary row = new MesXslRawMaterialSummary();
|
||||
row.setWarehouseName(trim(rs.getString("warehouseName")));
|
||||
row.setMaterialName(trim(rs.getString("materialName")));
|
||||
row.setMaterialCode(trim(rs.getString("materialCode")));
|
||||
row.setTotalPackages(rs.getBigDecimal("totalPackages"));
|
||||
row.setTotalWeight(rs.getBigDecimal("totalWeight"));
|
||||
row.setId(row.getWarehouseName() + "_" + row.getMaterialCode() + "_" + seq++);
|
||||
list.add(row);
|
||||
}
|
||||
return list;
|
||||
},
|
||||
params.toArray());
|
||||
}
|
||||
|
||||
private String trim(String v) {
|
||||
return v == null ? "" : v.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package org.jeecg.modules.xslmes.entity;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import lombok.Data;
|
||||
import org.jeecgframework.poi.excel.annotation.Excel;
|
||||
|
||||
/**
|
||||
* 原材料汇总(按仓库+物料)
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "原材料汇总")
|
||||
public class MesXslRawMaterialSummary implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键")
|
||||
private String id;
|
||||
|
||||
@Excel(name = "所在仓库", width = 20)
|
||||
@Schema(description = "所在仓库")
|
||||
private String warehouseName;
|
||||
|
||||
@Excel(name = "物料名称", width = 20)
|
||||
@Schema(description = "物料名称")
|
||||
private String materialName;
|
||||
|
||||
@Excel(name = "物料编码", width = 20)
|
||||
@Schema(description = "物料编码")
|
||||
private String materialCode;
|
||||
|
||||
@Excel(name = "总包数", width = 15)
|
||||
@Schema(description = "总包数")
|
||||
private BigDecimal totalPackages;
|
||||
|
||||
@Excel(name = "总重量", width = 15)
|
||||
@Schema(description = "总重量")
|
||||
private BigDecimal totalWeight;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.jeecg.modules.mes.material.constant;
|
||||
|
||||
/**
|
||||
* 原材料检验标准等 MES 物料模块的打印业务编码:与「业务打印绑定」中 biz_code、print_biz_perm_entity.perm_id 一致。
|
||||
*/
|
||||
public final class MesMaterialPrintConstants {
|
||||
|
||||
/** 原材料检验标准列表页菜单(sys_permission.id,见 Flyway V3.9.2_62) */
|
||||
public static final String RAW_MATERIAL_INSPECT_STD_MENU_PERM_ID = "1900000000000000730";
|
||||
|
||||
/** 历史或手工绑定时可能使用的语义型 biz_code(服务端 prepareNativePrint 会作为次选查询) */
|
||||
public static final String RAW_MATERIAL_INSPECT_STD_SEMANTIC_BIZ_CODE = "MES_RAW_MATERIAL_INSPECT_STD";
|
||||
|
||||
private MesMaterialPrintConstants() {}
|
||||
}
|
||||
@@ -3,22 +3,40 @@ package org.jeecg.modules.mes.material.controller;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.shiro.authz.annotation.Logical;
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.aspect.annotation.AutoLog;
|
||||
import org.jeecg.common.system.base.controller.JeecgController;
|
||||
import org.jeecg.common.system.query.QueryGenerator;
|
||||
import org.jeecg.modules.mes.material.constant.MesMaterialPrintConstants;
|
||||
import org.jeecg.modules.mes.material.entity.MesRawMaterialInspectStd;
|
||||
import org.jeecg.modules.mes.material.entity.MesRawMaterialInspectStdLine;
|
||||
import org.jeecg.modules.mes.material.service.IMesRawMaterialInspectStdService;
|
||||
import org.jeecg.modules.mes.material.vo.MesRawMaterialInspectStdPage;
|
||||
import org.jeecg.modules.print.entity.PrintBizPermEntity;
|
||||
import org.jeecg.modules.print.entity.PrintBizTemplateBind;
|
||||
import org.jeecg.modules.print.entity.PrintTemplate;
|
||||
import org.jeecg.modules.print.service.IPrintBizPermEntityService;
|
||||
import org.jeecg.modules.print.service.IPrintBizTemplateBindService;
|
||||
import org.jeecg.modules.print.service.IPrintTemplateService;
|
||||
import org.jeecg.modules.print.support.PrintServerEnvironmentService;
|
||||
import org.jeecg.modules.print.support.PrintServerPdfJobService;
|
||||
import org.jeecg.modules.print.util.PrintBizDataMappingUtil;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -31,6 +49,12 @@ import org.springframework.web.servlet.ModelAndView;
|
||||
public class MesRawMaterialInspectStdController extends JeecgController<MesRawMaterialInspectStd, IMesRawMaterialInspectStdService> {
|
||||
|
||||
@Autowired private IMesRawMaterialInspectStdService mesRawMaterialInspectStdService;
|
||||
@Autowired private PrintServerEnvironmentService printServerEnvironmentService;
|
||||
@Autowired private PrintServerPdfJobService printServerPdfJobService;
|
||||
@Autowired private IPrintBizTemplateBindService printBizTemplateBindService;
|
||||
@Autowired private IPrintBizPermEntityService printBizPermEntityService;
|
||||
@Autowired private IPrintTemplateService printTemplateService;
|
||||
@Autowired private ObjectMapper objectMapper;
|
||||
|
||||
@GetMapping("/list")
|
||||
public Result<IPage<MesRawMaterialInspectStd>> queryPageList(
|
||||
@@ -114,6 +138,136 @@ public class MesRawMaterialInspectStdController extends JeecgController<MesRawMa
|
||||
return Result.OK(flag == 1 ? "已启用" : "已停用");
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询可用打印机(与原材料卡片 {@code MesXslRawMaterialCardController#queryPrinters} 一致)。
|
||||
*/
|
||||
@Operation(summary = "MES-原材料检验标准-查询可用打印机")
|
||||
@GetMapping("/queryPrinters")
|
||||
@RequiresPermissions(
|
||||
value = {"mes:mes_raw_material_inspect_std:edit", "mes:mes_raw_material_inspect_std:exportXls"},
|
||||
logical = Logical.OR)
|
||||
public Result<Map<String, Object>> queryPrinters() {
|
||||
return Result.OK(printServerEnvironmentService.buildPrinterQueryResult());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据业务打印绑定生成模板 JSON + 映射后的 printData,供前端生成 PDF 后调用 printPdf(与原材料卡片 prepareNativePrint 一致)。
|
||||
*/
|
||||
@Operation(summary = "MES-原材料检验标准-准备原生打印数据")
|
||||
@GetMapping("/prepareNativePrint")
|
||||
@RequiresPermissions("mes:mes_raw_material_inspect_std:edit")
|
||||
public Result<Map<String, Object>> prepareNativePrint(@RequestParam(name = "id") String id) {
|
||||
try {
|
||||
MesRawMaterialInspectStd main = mesRawMaterialInspectStdService.getById(id);
|
||||
if (main == null) {
|
||||
return Result.error("未找到原材料检验标准");
|
||||
}
|
||||
PrintBizTemplateBind bind = resolveInspectStdPrintBind();
|
||||
if (bind == null) {
|
||||
return Result.error(
|
||||
"请先在「业务打印绑定」中配置原材料检验标准与打印模板;业务编码需为当前列表菜单的权限 id,或与 print_biz_perm_entity 中该业务实体一致");
|
||||
}
|
||||
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
|
||||
if (tpl == null) {
|
||||
return Result.error("绑定的打印模板不存在");
|
||||
}
|
||||
List<MesRawMaterialInspectStdLine> lines = mesRawMaterialInspectStdService.selectLinesByStdId(id);
|
||||
MesRawMaterialInspectStdPage pageVo = new MesRawMaterialInspectStdPage();
|
||||
BeanUtils.copyProperties(main, pageVo);
|
||||
pageVo.setLineList(lines);
|
||||
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
|
||||
JsonNode bizRoot = objectMapper.valueToTree(pageVo);
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping, tpl.getTemplateJson());
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
|
||||
Map<String, Object> out = new HashMap<>(8);
|
||||
out.put("stdId", main.getId());
|
||||
out.put("templateCode", bind.getTemplateCode());
|
||||
out.put("templateJson", tpl.getTemplateJson());
|
||||
out.put("paperWidthMm", tpl.getPaperWidthMm());
|
||||
out.put("paperHeightMm", tpl.getPaperHeightMm());
|
||||
out.put("paperOrientation", tpl.getPaperOrientation());
|
||||
out.put("printData", objectMapper.convertValue(printData, Map.class));
|
||||
return Result.OK(out);
|
||||
} catch (Exception e) {
|
||||
log.error("原材料检验标准准备打印数据失败 id={}", id, e);
|
||||
return Result.error("准备打印数据失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将前端生成的 PDF Base64 提交到服务器打印机(与原材料卡片 printPdf 一致)。
|
||||
*/
|
||||
@AutoLog(value = "MES-原材料检验标准-PDF后端打印")
|
||||
@Operation(summary = "MES-原材料检验标准-PDF后端打印")
|
||||
@PostMapping("/printPdf")
|
||||
@RequiresPermissions("mes:mes_raw_material_inspect_std:edit")
|
||||
public Result<String> printPdf(@RequestBody Map<String, Object> body) {
|
||||
String sid = String.valueOf(body.getOrDefault("id", "")).trim();
|
||||
String printerName = String.valueOf(body.getOrDefault("printerName", "")).trim();
|
||||
String pdfBase64 = String.valueOf(body.getOrDefault("pdfBase64", "")).trim();
|
||||
String fileName = String.valueOf(body.getOrDefault("fileName", "")).trim();
|
||||
if (StringUtils.isBlank(sid)) {
|
||||
return Result.error("id 不能为空");
|
||||
}
|
||||
MesRawMaterialInspectStd std = mesRawMaterialInspectStdService.getById(sid);
|
||||
if (std == null) {
|
||||
return Result.error("未找到原材料检验标准");
|
||||
}
|
||||
String prefix =
|
||||
StringUtils.isNotBlank(std.getStandardNo()) ? std.getStandardNo() : std.getId();
|
||||
String fn =
|
||||
StringUtils.isNotBlank(fileName) ? fileName : ("原材料检验标准-" + prefix + ".pdf");
|
||||
return printServerPdfJobService.submitPdfBase64(
|
||||
printerName, pdfBase64, fn, "RAW_INSPECT_STD_" + prefix);
|
||||
}
|
||||
|
||||
private PrintBizTemplateBind resolveInspectStdPrintBind() {
|
||||
PrintBizTemplateBind bind =
|
||||
printBizTemplateBindService.getByBizCode(MesMaterialPrintConstants.RAW_MATERIAL_INSPECT_STD_MENU_PERM_ID);
|
||||
if (bind != null) {
|
||||
return bind;
|
||||
}
|
||||
bind =
|
||||
printBizTemplateBindService.getByBizCode(MesMaterialPrintConstants.RAW_MATERIAL_INSPECT_STD_SEMANTIC_BIZ_CODE);
|
||||
if (bind != null) {
|
||||
return bind;
|
||||
}
|
||||
// 不同环境菜单 id 不一致:按 print_biz_perm_entity 中指向本实体的任意 perm_id 解析绑定
|
||||
String entityFqn = MesRawMaterialInspectStd.class.getName();
|
||||
List<PrintBizPermEntity> permRows =
|
||||
printBizPermEntityService.lambdaQuery().eq(PrintBizPermEntity::getEntityClass, entityFqn).list();
|
||||
for (PrintBizPermEntity row : permRows) {
|
||||
if (StringUtils.isBlank(row.getPermId())) {
|
||||
continue;
|
||||
}
|
||||
bind = printBizTemplateBindService.getByBizCode(row.getPermId());
|
||||
if (bind != null) {
|
||||
return bind;
|
||||
}
|
||||
}
|
||||
// 最后兜底:业务名称与绑定页一致(避免 perm 映射表未同步时仍找不到)
|
||||
List<PrintBizTemplateBind> byName =
|
||||
printBizTemplateBindService
|
||||
.lambdaQuery()
|
||||
.eq(PrintBizTemplateBind::getBizName, "原材料检验标准")
|
||||
.orderByDesc(PrintBizTemplateBind::getCreateTime)
|
||||
.last("LIMIT 8")
|
||||
.list();
|
||||
if (byName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (byName.size() == 1) {
|
||||
return byName.get(0);
|
||||
}
|
||||
for (PrintBizTemplateBind b : byName) {
|
||||
PrintBizPermEntity pe = printBizPermEntityService.getByPermId(b.getBizCode());
|
||||
if (pe != null && entityFqn.equals(StringUtils.trimToEmpty(pe.getEntityClass()))) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
return byName.get(0);
|
||||
}
|
||||
|
||||
@RequiresPermissions("mes:mes_raw_material_inspect_std:exportXls")
|
||||
@RequestMapping("/exportXls")
|
||||
public ModelAndView exportXls(HttpServletRequest request, MesRawMaterialInspectStd model) {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package org.jeecg.modules.mes.material.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.experimental.Accessors;
|
||||
@@ -71,4 +73,9 @@ public class MesRawMaterialInspectStd implements Serializable {
|
||||
private Date updateTime;
|
||||
|
||||
private Integer delFlag;
|
||||
|
||||
/** 检验标准明细(子表 mes_raw_material_inspect_std_line,通过 stdId 关联本表 id;不参与主表入库映射) */
|
||||
@TableField(exist = false)
|
||||
@Schema(description = "MES原材料检验标准-检验项明细列表")
|
||||
private List<MesRawMaterialInspectStdLine> lineList;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
package org.jeecg.modules.mes.material.vo;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.jeecg.modules.mes.material.entity.MesRawMaterialInspectStd;
|
||||
import org.jeecg.modules.mes.material.entity.MesRawMaterialInspectStdLine;
|
||||
|
||||
/** 主子保存/编辑页 VO,继承主表实体(含 {@link MesRawMaterialInspectStd#lineList} 明细)。 */
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class MesRawMaterialInspectStdPage extends MesRawMaterialInspectStd {
|
||||
|
||||
private List<MesRawMaterialInspectStdLine> lineList;
|
||||
}
|
||||
public class MesRawMaterialInspectStdPage extends MesRawMaterialInspectStd {}
|
||||
|
||||
@@ -38,6 +38,7 @@ import org.jeecg.modules.print.vo.PrintBizDetailSlotVO;
|
||||
import org.jeecg.modules.print.vo.PrintBizFieldItemVO;
|
||||
import org.jeecg.modules.print.vo.PrintBizTypeVO;
|
||||
import org.jeecg.modules.print.vo.PrintTemplateFieldItemVO;
|
||||
import org.jeecg.modules.print.vo.PrintTemplateStructureVO;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -182,6 +183,23 @@ public class PrintBizTemplateBindController extends JeecgController<PrintBizTemp
|
||||
return Result.OK(fields);
|
||||
}
|
||||
|
||||
@Operation(summary = "解析原生模板占位结构:主表参数 + 按明细表分组(供多标签映射)")
|
||||
@GetMapping("/parseTemplateStructure")
|
||||
@RequiresPermissions("print:bizBind:list")
|
||||
public Result<PrintTemplateStructureVO> parseTemplateStructure(
|
||||
@RequestParam(name = "templateId") String templateId) {
|
||||
if (StringUtils.isBlank(templateId)) {
|
||||
return Result.error("templateId 不能为空");
|
||||
}
|
||||
PrintTemplate tpl = printTemplateService.getById(templateId);
|
||||
if (tpl == null) {
|
||||
return Result.error("模板不存在");
|
||||
}
|
||||
PrintTemplateStructureVO structure =
|
||||
PrintNativeTemplateFieldExtractor.extractStructure(tpl.getTemplateJson());
|
||||
return Result.OK(structure);
|
||||
}
|
||||
|
||||
@Operation(summary = "主实体上的明细槽位(List<明细实体> / 明细数组 / 嵌套对象),用于先选明细再反射明细字段")
|
||||
@GetMapping("/detailSlots")
|
||||
@RequiresPermissions("print:bizBind:list")
|
||||
@@ -258,12 +276,15 @@ public class PrintBizTemplateBindController extends JeecgController<PrintBizTemp
|
||||
return Result.error("未配置该业务的打印绑定");
|
||||
}
|
||||
try {
|
||||
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
|
||||
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
|
||||
JsonNode bizRoot = PrintBizDataMappingUtil.parseBizJson(body.getBizDataJson());
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
|
||||
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
|
||||
String tplJson = tpl != null ? tpl.getTemplateJson() : null;
|
||||
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping, tplJson);
|
||||
if (tpl != null && StringUtils.isNotBlank(tpl.getTemplateJson())) {
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
|
||||
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson(), true);
|
||||
PrintBizDataMappingUtil.fillPreviewDetailPlaceholderRowValues(
|
||||
printData, bizRoot, mapping, tpl.getTemplateJson());
|
||||
}
|
||||
Map<String, Object> res = new HashMap<>(4);
|
||||
res.put("templateCode", bind.getTemplateCode());
|
||||
|
||||
@@ -3,19 +3,35 @@ package org.jeecg.modules.print.util;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jeecg.modules.print.vo.PrintTemplateFieldItemVO;
|
||||
|
||||
/** 按映射规则把业务 JSON 转为模板打印数据(键为模板 bindField) */
|
||||
/**
|
||||
* 按映射规则把业务 JSON 转为模板打印数据(键为模板 bindField)。支持业务数组字段映射到模板明细表(如 List2.Field1)。
|
||||
*
|
||||
* <p>模板 {@code dataBinding.detailTables} 中明细列统一为 {@code tableKey.fieldKey}(如 List1.Field1);无双缀旧映射仍可借助
|
||||
* {@link #resolveSyntheticDetailTemplateField} 参与列表展开。
|
||||
*/
|
||||
public final class PrintBizDataMappingUtil {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final JsonNodeFactory NF = MAPPER.getNodeFactory();
|
||||
|
||||
private PrintBizDataMappingUtil() {}
|
||||
|
||||
public static ObjectNode mapBizToPrintData(JsonNode bizRoot, ArrayNode mappingRules) {
|
||||
return mapBizToPrintData(bizRoot, mappingRules, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param templateJson 原生模板 JSON;非空时可为无双缀明细列绑定补齐 tableKey,生成正确的明细数组结构
|
||||
*/
|
||||
public static ObjectNode mapBizToPrintData(JsonNode bizRoot, ArrayNode mappingRules, String templateJson) {
|
||||
ObjectNode printData = MAPPER.createObjectNode();
|
||||
if (bizRoot == null || mappingRules == null) {
|
||||
return printData;
|
||||
@@ -26,21 +42,109 @@ public final class PrintBizDataMappingUtil {
|
||||
}
|
||||
String templateField = text(rule, "templateField");
|
||||
String bizField = text(rule, "bizField");
|
||||
// 仅要求模板字段名;业务字段为空表示「不参与取数」,仍向 printData 写入空字符串,避免模板占位符缺键
|
||||
if (StringUtils.isBlank(templateField)) {
|
||||
continue;
|
||||
}
|
||||
// 模板明细列多为「tableKey.columnKey」(如 List2.Field1),业务字段为「数组字段.列」(如 lineList.inspectItemId)
|
||||
if (qualifiesForListExpansion(bizRoot, templateField, bizField)) {
|
||||
continue;
|
||||
}
|
||||
// 无双缀占位(Field1)+ 业务侧为明细数组:交由列表展开写入 printData.List1[],避免落在根上导致表格 source 读不到
|
||||
if (shouldDeferShortDetailFieldForListExpansion(bizRoot, templateField, bizField, templateJson)) {
|
||||
continue;
|
||||
}
|
||||
JsonNode val;
|
||||
if (StringUtils.isBlank(bizField)) {
|
||||
val = MAPPER.getNodeFactory().textNode("");
|
||||
val = NF.textNode("");
|
||||
} else {
|
||||
val = resolvePath(bizRoot, bizField);
|
||||
}
|
||||
setPath(printData, templateField, val);
|
||||
}
|
||||
applyListExpandedMappings(bizRoot, mappingRules, printData, templateJson);
|
||||
return printData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 {@code dataBinding.detailTables} 中按声明顺序查找首个包含 {@code fieldKey} 的明细表,返回 {@code tableKey.fieldKey}。
|
||||
*
|
||||
* <p>与同模块抽取器中「明细列统一为 tableKey.fieldKey」一致;仍兼容历史绑定里保存的短键。
|
||||
*/
|
||||
private static String resolveSyntheticDetailTemplateField(String templateJson, String shortFieldKey) {
|
||||
if (StringUtils.isAnyBlank(templateJson, shortFieldKey)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode root = MAPPER.readTree(templateJson);
|
||||
JsonNode db = root.get("dataBinding");
|
||||
if (db == null || !db.isObject()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode tables = db.get("detailTables");
|
||||
if (tables == null || !tables.isArray()) {
|
||||
return null;
|
||||
}
|
||||
for (JsonNode t : tables) {
|
||||
if (t == null || !t.isObject()) {
|
||||
continue;
|
||||
}
|
||||
String tableKey = text(t, "tableKey").trim();
|
||||
if (StringUtils.isBlank(tableKey)) {
|
||||
continue;
|
||||
}
|
||||
JsonNode fields = t.get("fields");
|
||||
if (fields == null || !fields.isArray()) {
|
||||
continue;
|
||||
}
|
||||
for (JsonNode f : fields) {
|
||||
if (f != null && f.isObject() && shortFieldKey.equals(text(f, "key").trim())) {
|
||||
return tableKey + "." + shortFieldKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String resolveEffectiveTemplateFieldForListExpansion(
|
||||
String templateJson, String templateFieldRaw, String bizField, JsonNode bizRoot) {
|
||||
if (StringUtils.isBlank(templateFieldRaw)) {
|
||||
return templateFieldRaw;
|
||||
}
|
||||
String tf = templateFieldRaw.trim();
|
||||
if (splitFirstDotPair(tf) != null) {
|
||||
return tf;
|
||||
}
|
||||
if (StringUtils.isBlank(templateJson) || StringUtils.isBlank(bizField)) {
|
||||
return tf;
|
||||
}
|
||||
HeadTail biz = splitFirstDotPair(bizField.trim());
|
||||
if (biz == null) {
|
||||
return tf;
|
||||
}
|
||||
JsonNode arr = bizRoot != null ? bizRoot.get(biz.head()) : null;
|
||||
if (arr == null || !arr.isArray()) {
|
||||
return tf;
|
||||
}
|
||||
String synthetic = resolveSyntheticDetailTemplateField(templateJson, tf);
|
||||
return StringUtils.isNotBlank(synthetic) ? synthetic : tf;
|
||||
}
|
||||
|
||||
private static boolean shouldDeferShortDetailFieldForListExpansion(
|
||||
JsonNode bizRoot, String templateField, String bizField, String templateJson) {
|
||||
if (StringUtils.isBlank(templateJson) || StringUtils.isAnyBlank(templateField, bizField)) {
|
||||
return false;
|
||||
}
|
||||
if (splitFirstDotPair(templateField) != null) {
|
||||
return false;
|
||||
}
|
||||
String eff =
|
||||
resolveEffectiveTemplateFieldForListExpansion(templateJson, templateField, bizField, bizRoot);
|
||||
return qualifiesForListExpansion(bizRoot, eff, bizField);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按模板中已声明的绑定路径({@code dataBinding.params}、画布/表格等元素的 {@code bindField},与
|
||||
* {@link PrintNativeTemplateFieldExtractor} 一致),向 printData 补齐缺失路径(空字符串)。
|
||||
@@ -48,6 +152,15 @@ public final class PrintBizDataMappingUtil {
|
||||
* <p>避免字段映射未包含某键时 API 缺键,桌面端渲染把「设计稿占位 text」当成数据显示。
|
||||
*/
|
||||
public static ObjectNode fillMissingDataBindingParamKeys(ObjectNode printData, String templateJson) {
|
||||
return fillMissingDataBindingParamKeys(printData, templateJson, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param detailPreviewPlaceholderRow 为 true 时(如绑定预览):明细数据源无行数据时用模板列生成一行 {@code null} 占位,便于 JSON 里看出字段;
|
||||
* 为 false 时(真实打印):保持 {@code []},避免出现空白假行。
|
||||
*/
|
||||
public static ObjectNode fillMissingDataBindingParamKeys(
|
||||
ObjectNode printData, String templateJson, boolean detailPreviewPlaceholderRow) {
|
||||
if (printData == null) {
|
||||
printData = MAPPER.createObjectNode();
|
||||
}
|
||||
@@ -60,18 +173,260 @@ public final class PrintBizDataMappingUtil {
|
||||
if (item == null || StringUtils.isBlank(item.getBindField())) {
|
||||
continue;
|
||||
}
|
||||
// 明细表列占位:必须由「明细数组映射」展开;不可用空串占位,否则会生成 List2 对象为 {Field1:""},
|
||||
// 前端 resolveTableRows 要求 List2 为数组(见原生 TableElement)。
|
||||
String et = StringUtils.defaultString(item.getElementType()).toLowerCase();
|
||||
if ("detailfield".equals(et) || "column".equals(et)) {
|
||||
continue;
|
||||
}
|
||||
String bf = item.getBindField().trim();
|
||||
if (!hasPath(printData, bf)) {
|
||||
setPath(printData, bf, MAPPER.getNodeFactory().textNode(""));
|
||||
setPath(printData, bf, NF.textNode(""));
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 模板解析异常时不阻断打印
|
||||
}
|
||||
try {
|
||||
normalizeNativeDetailTableShapes(printData, templateJson, detailPreviewPlaceholderRow);
|
||||
} catch (Exception ignored) {
|
||||
// 明细形态规整失败不阻断
|
||||
}
|
||||
return printData;
|
||||
}
|
||||
|
||||
/** 判断 printData 上是否存在该点分路径(含嵌套对象) */
|
||||
/**
|
||||
* 按模板 {@code dataBinding.detailTables} 将各明细数据源键规范为<strong>数组</strong>,并去掉首张明细表误落在根上的短列键。
|
||||
*
|
||||
* <p>无业务数据时:真实打印侧保留空数组 {@code []};预览侧可选注入一行列占位(见 {@code detailPreviewPlaceholderRow})。
|
||||
*/
|
||||
private static void normalizeNativeDetailTableShapes(
|
||||
ObjectNode printData, String templateJson, boolean detailPreviewPlaceholderRow) {
|
||||
if (printData == null || StringUtils.isBlank(templateJson)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JsonNode root = MAPPER.readTree(templateJson);
|
||||
JsonNode db = root.get("dataBinding");
|
||||
if (db == null || !db.isObject()) {
|
||||
return;
|
||||
}
|
||||
JsonNode tables = db.get("detailTables");
|
||||
if (tables == null || !tables.isArray()) {
|
||||
return;
|
||||
}
|
||||
boolean firstTable = true;
|
||||
LinkedHashSet<String> firstTableColumnKeys = new LinkedHashSet<>();
|
||||
|
||||
for (JsonNode t : tables) {
|
||||
if (t == null || !t.isObject()) {
|
||||
continue;
|
||||
}
|
||||
String tk = text(t, "tableKey").trim();
|
||||
if (StringUtils.isBlank(tk)) {
|
||||
continue;
|
||||
}
|
||||
JsonNode fields = t.get("fields");
|
||||
LinkedHashSet<String> columnKeys = new LinkedHashSet<>();
|
||||
if (fields != null && fields.isArray()) {
|
||||
for (JsonNode f : fields) {
|
||||
if (f != null && f.isObject()) {
|
||||
String k = text(f, "key").trim();
|
||||
if (StringUtils.isNotBlank(k)) {
|
||||
columnKeys.add(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (firstTable) {
|
||||
firstTableColumnKeys.addAll(columnKeys);
|
||||
firstTable = false;
|
||||
}
|
||||
|
||||
JsonNode cur = printData.get(tk);
|
||||
if (cur == null || cur.isNull()) {
|
||||
printData.set(tk, emptyDetailTableArray(columnKeys, detailPreviewPlaceholderRow));
|
||||
} else if (cur.isObject()) {
|
||||
ObjectNode obj = (ObjectNode) cur;
|
||||
if (obj.isEmpty() || objectLeavesOnlyEmptyPlaceholders(obj)) {
|
||||
printData.set(tk, emptyDetailTableArray(columnKeys, detailPreviewPlaceholderRow));
|
||||
} else {
|
||||
ArrayNode arr = MAPPER.createArrayNode();
|
||||
arr.add(obj.deepCopy());
|
||||
printData.set(tk, arr);
|
||||
}
|
||||
} else if (cur.isArray()) {
|
||||
ArrayNode arr = (ArrayNode) cur;
|
||||
if (arr.size() == 0) {
|
||||
printData.set(tk, emptyDetailTableArray(columnKeys, detailPreviewPlaceholderRow));
|
||||
}
|
||||
} else {
|
||||
printData.set(tk, emptyDetailTableArray(columnKeys, detailPreviewPlaceholderRow));
|
||||
}
|
||||
}
|
||||
|
||||
for (String fk : firstTableColumnKeys) {
|
||||
printData.remove(fk);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 无明细行时的数组形态:预览用模板声明的列键生成一行 {@code null},便于看清字段;真实打印返回 {@code []}。
|
||||
*/
|
||||
private static ArrayNode emptyDetailTableArray(
|
||||
LinkedHashSet<String> columnKeys, boolean detailPreviewPlaceholderRow) {
|
||||
ArrayNode arr = MAPPER.createArrayNode();
|
||||
if (!detailPreviewPlaceholderRow || columnKeys == null || columnKeys.isEmpty()) {
|
||||
return arr;
|
||||
}
|
||||
ObjectNode row = MAPPER.createObjectNode();
|
||||
for (String k : columnKeys) {
|
||||
row.putNull(k);
|
||||
}
|
||||
arr.add(row);
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览专用:占位明细行单元格为 {@code null}/空串时,按映射从业务 JSON 取数写入(明细数组取<strong>第一行</strong>)。
|
||||
*/
|
||||
public static void fillPreviewDetailPlaceholderRowValues(
|
||||
ObjectNode printData, JsonNode bizRoot, ArrayNode mappingRules, String templateJson) {
|
||||
if (printData == null || bizRoot == null || mappingRules == null || StringUtils.isBlank(templateJson)) {
|
||||
return;
|
||||
}
|
||||
LinkedHashSet<String> declaredTables = loadDeclaredDetailTableKeys(templateJson);
|
||||
if (declaredTables.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (JsonNode rule : mappingRules) {
|
||||
if (rule == null || !rule.isObject()) {
|
||||
continue;
|
||||
}
|
||||
String tfRaw = text(rule, "templateField").trim();
|
||||
String bfRaw = text(rule, "bizField").trim();
|
||||
if (StringUtils.isBlank(tfRaw)) {
|
||||
continue;
|
||||
}
|
||||
String tfEff = tfRaw;
|
||||
if (splitFirstDotPair(tfEff) == null) {
|
||||
String syn = resolveSyntheticDetailTemplateField(templateJson, tfEff);
|
||||
if (StringUtils.isNotBlank(syn)) {
|
||||
tfEff = syn;
|
||||
}
|
||||
}
|
||||
HeadTail tpl = splitFirstDotPair(tfEff);
|
||||
if (tpl == null || StringUtils.isAnyBlank(tpl.head(), tpl.tail())) {
|
||||
continue;
|
||||
}
|
||||
if (!declaredTables.contains(tpl.head())) {
|
||||
continue;
|
||||
}
|
||||
JsonNode arrNode = printData.get(tpl.head());
|
||||
if (!(arrNode instanceof ArrayNode arr) || arr.size() != 1) {
|
||||
continue;
|
||||
}
|
||||
JsonNode rowNode = arr.get(0);
|
||||
if (!(rowNode instanceof ObjectNode row)) {
|
||||
continue;
|
||||
}
|
||||
String col = tpl.tail();
|
||||
if (!row.has(col)) {
|
||||
continue;
|
||||
}
|
||||
if (!cellNeedsPreviewFill(row.get(col))) {
|
||||
continue;
|
||||
}
|
||||
JsonNode val = resolveBizFieldPreviewCell(bizRoot, bfRaw);
|
||||
putLeaf(row, col, val);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 预览填充失败不阻断
|
||||
}
|
||||
}
|
||||
|
||||
private static LinkedHashSet<String> loadDeclaredDetailTableKeys(String templateJson) {
|
||||
LinkedHashSet<String> out = new LinkedHashSet<>();
|
||||
try {
|
||||
JsonNode root = MAPPER.readTree(templateJson);
|
||||
JsonNode db = root.get("dataBinding");
|
||||
if (db == null || !db.isObject()) {
|
||||
return out;
|
||||
}
|
||||
JsonNode tables = db.get("detailTables");
|
||||
if (tables == null || !tables.isArray()) {
|
||||
return out;
|
||||
}
|
||||
for (JsonNode t : tables) {
|
||||
if (t != null && t.isObject()) {
|
||||
String tk = text(t, "tableKey").trim();
|
||||
if (StringUtils.isNotBlank(tk)) {
|
||||
out.add(tk);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean cellNeedsPreviewFill(JsonNode cur) {
|
||||
if (cur == null || cur.isNull()) {
|
||||
return true;
|
||||
}
|
||||
return cur.isTextual() && cur.asText("").isEmpty();
|
||||
}
|
||||
|
||||
private static JsonNode resolveBizFieldPreviewCell(JsonNode bizRoot, String bizField) {
|
||||
if (bizRoot == null || StringUtils.isBlank(bizField)) {
|
||||
return mappingValueOrEmptyText(null);
|
||||
}
|
||||
String bf = bizField.trim();
|
||||
HeadTail biz = splitFirstDotPair(bf);
|
||||
if (biz != null) {
|
||||
JsonNode arr = bizRoot.get(biz.head());
|
||||
if (arr != null && arr.isArray() && arr.size() > 0) {
|
||||
JsonNode row = arr.get(0);
|
||||
if (row != null && row.isObject()) {
|
||||
JsonNode v = resolvePath(row, biz.tail());
|
||||
return mappingValueOrEmptyText(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonNode v = resolvePath(bizRoot, bf);
|
||||
return mappingValueOrEmptyText(v);
|
||||
}
|
||||
|
||||
/** 对象仅含空占位(null / 空串),视为无明细行 */
|
||||
private static boolean objectLeavesOnlyEmptyPlaceholders(ObjectNode obj) {
|
||||
if (obj == null || obj.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Iterator<JsonNode> it = obj.elements();
|
||||
while (it.hasNext()) {
|
||||
JsonNode v = it.next();
|
||||
if (v == null || v.isNull()) {
|
||||
continue;
|
||||
}
|
||||
if (v.isTextual() && v.asText("").isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (v.isObject()) {
|
||||
if (!objectLeavesOnlyEmptyPlaceholders((ObjectNode) v)) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean hasPath(ObjectNode root, String path) {
|
||||
if (StringUtils.isBlank(path)) {
|
||||
return false;
|
||||
@@ -173,6 +528,105 @@ public final class PrintBizDataMappingUtil {
|
||||
}
|
||||
}
|
||||
|
||||
/** 第一段为 JSON 对象的键路径;余下段落(可含多级)相对该对象的 field 路径。 */
|
||||
private record HeadTail(String head, String tail) {}
|
||||
|
||||
private static HeadTail splitFirstDotPair(String path) {
|
||||
if (StringUtils.isBlank(path)) {
|
||||
return null;
|
||||
}
|
||||
int dot = path.indexOf('.');
|
||||
if (dot <= 0 || dot >= path.length() - 1) {
|
||||
return null;
|
||||
}
|
||||
String h = path.substring(0, dot).trim();
|
||||
String t = path.substring(dot + 1).trim();
|
||||
if (h.isEmpty() || t.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new HeadTail(h, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务字段首段指向 JSON 数组,且模板字段为「明细表绑定键.列」(如 {@code List2.Field1})时,
|
||||
* 需要将每行业务对象展开为模板 {@code previewData[listKey][i].列},供原生表格 {@code source=listKey}。
|
||||
*/
|
||||
private static boolean qualifiesForListExpansion(JsonNode bizRoot, String templateField, String bizField) {
|
||||
if (bizRoot == null || StringUtils.isBlank(templateField) || StringUtils.isBlank(bizField)) {
|
||||
return false;
|
||||
}
|
||||
HeadTail tpl = splitFirstDotPair(templateField);
|
||||
HeadTail biz = splitFirstDotPair(bizField);
|
||||
if (tpl == null || biz == null) {
|
||||
return false;
|
||||
}
|
||||
JsonNode arr = bizRoot.get(biz.head());
|
||||
return arr != null && arr.isArray();
|
||||
}
|
||||
|
||||
/** 将「业务明细数组 → 模板明细键」的规则写入 {@code printData}。 */
|
||||
private static void applyListExpandedMappings(
|
||||
JsonNode bizRoot, ArrayNode mappingRules, ObjectNode printData, String templateJson) {
|
||||
if (bizRoot == null || mappingRules == null || printData == null) {
|
||||
return;
|
||||
}
|
||||
for (JsonNode rule : mappingRules) {
|
||||
if (rule == null || !rule.isObject()) {
|
||||
continue;
|
||||
}
|
||||
String tfRaw = text(rule, "templateField").trim();
|
||||
String bf = text(rule, "bizField").trim();
|
||||
String tfEff = resolveEffectiveTemplateFieldForListExpansion(templateJson, tfRaw, bf, bizRoot);
|
||||
if (!qualifiesForListExpansion(bizRoot, tfEff, bf)) {
|
||||
continue;
|
||||
}
|
||||
HeadTail tpl = splitFirstDotPair(tfEff);
|
||||
HeadTail biz = splitFirstDotPair(bf);
|
||||
if (tpl == null || biz == null) {
|
||||
continue;
|
||||
}
|
||||
JsonNode srcArrNode = bizRoot.get(biz.head());
|
||||
if (srcArrNode == null || !srcArrNode.isArray()) {
|
||||
continue;
|
||||
}
|
||||
ArrayNode tgtArr = ensureRowObjectArray(printData, tpl.head(), srcArrNode.size());
|
||||
for (int i = 0; i < srcArrNode.size(); i++) {
|
||||
JsonNode srcRow = srcArrNode.get(i);
|
||||
JsonNode val =
|
||||
srcRow != null && srcRow.isObject() ? resolvePath(srcRow, biz.tail()) : null;
|
||||
ObjectNode tgtRow = (ObjectNode) tgtArr.get(i);
|
||||
setPath(tgtRow, tpl.tail(), mappingValueOrEmptyText(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 缺省占位与主映射一致:空则用空字符串。 */
|
||||
private static JsonNode mappingValueOrEmptyText(JsonNode val) {
|
||||
if (val == null || val.isNull()) {
|
||||
return NF.textNode("");
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/** 保证 printData.{tableKey} 为数组,且长度为 rowCount(元素为展开行 Json 对象)。 */
|
||||
private static ArrayNode ensureRowObjectArray(ObjectNode printData, String tableKey, int rowCount) {
|
||||
JsonNode existed = printData.get(tableKey);
|
||||
ArrayNode arr;
|
||||
if (existed instanceof ArrayNode a) {
|
||||
arr = a;
|
||||
} else {
|
||||
if (existed != null) {
|
||||
printData.remove(tableKey);
|
||||
}
|
||||
arr = MAPPER.createArrayNode();
|
||||
printData.set(tableKey, arr);
|
||||
}
|
||||
while (arr.size() < rowCount) {
|
||||
arr.add(MAPPER.createObjectNode());
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
private static String text(JsonNode n, String key) {
|
||||
if (n == null || !n.isObject()) {
|
||||
return "";
|
||||
|
||||
@@ -3,11 +3,16 @@ package org.jeecg.modules.print.util;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jeecg.modules.print.vo.PrintTemplateDetailTableVO;
|
||||
import org.jeecg.modules.print.vo.PrintTemplateFieldItemVO;
|
||||
import org.jeecg.modules.print.vo.PrintTemplateStructureVO;
|
||||
|
||||
/**
|
||||
* 从原生打印模板 JSON 中收集所有 bindField / 表格列 field,供业务字段映射使用。
|
||||
@@ -40,9 +45,206 @@ public final class PrintNativeTemplateFieldExtractor {
|
||||
} catch (Exception ignored) {
|
||||
return list;
|
||||
}
|
||||
dedupeShortDetailFieldsWhenPrefixedExists(list);
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* dataBinding 已产出 {@code List1.Field1} 时,去掉画布扫描残留的同名短键 {@code Field1},避免映射表里重复一行。
|
||||
*/
|
||||
private static void dedupeShortDetailFieldsWhenPrefixedExists(List<PrintTemplateFieldItemVO> list) {
|
||||
HashSet<String> columnSuffixes = new HashSet<>();
|
||||
for (PrintTemplateFieldItemVO vo : list) {
|
||||
String bf = vo.getBindField();
|
||||
if (StringUtils.isBlank(bf)) {
|
||||
continue;
|
||||
}
|
||||
int d = bf.indexOf('.');
|
||||
if (d > 0 && d < bf.length() - 1) {
|
||||
columnSuffixes.add(bf.substring(d + 1).trim());
|
||||
}
|
||||
}
|
||||
list.removeIf(
|
||||
vo -> {
|
||||
String bf = vo.getBindField();
|
||||
if (StringUtils.isBlank(bf) || bf.indexOf('.') >= 0) {
|
||||
return false;
|
||||
}
|
||||
String et = StringUtils.defaultString(vo.getElementType()).toLowerCase();
|
||||
if (!"detailfield".equals(et) && !"column".equals(et)) {
|
||||
return false;
|
||||
}
|
||||
return columnSuffixes.contains(bf.trim());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 {@link #extract(String)} 的扁平结果拆成「主表参数 + 按明细表分组」,供前端多标签映射。
|
||||
*
|
||||
* <p>分组规则:带 {@code tableKey.} 前缀的占位归入对应明细表;无双缀短键按 dataBinding.detailTables 中字段声明归属;
|
||||
* 若模板仅声明单个明细表则将短键归入该表;否则归入 {@code __general__}(其它画布/未归类占位)。
|
||||
*/
|
||||
public static PrintTemplateStructureVO extractStructure(String templateJson) {
|
||||
PrintTemplateStructureVO vo = new PrintTemplateStructureVO();
|
||||
if (StringUtils.isBlank(templateJson)) {
|
||||
return vo;
|
||||
}
|
||||
JsonNode root;
|
||||
try {
|
||||
root = MAPPER.readTree(templateJson);
|
||||
} catch (Exception e) {
|
||||
return vo;
|
||||
}
|
||||
|
||||
List<DetailTableMeta> metaTables = readDetailTableMeta(root);
|
||||
LinkedHashSet<String> metaKeysOrdered = new LinkedHashSet<>();
|
||||
Map<String, String> tableLabels = new LinkedHashMap<>();
|
||||
Map<String, String> shortFieldOwner = new LinkedHashMap<>();
|
||||
for (DetailTableMeta m : metaTables) {
|
||||
if (StringUtils.isNotBlank(m.tableKey)) {
|
||||
metaKeysOrdered.add(m.tableKey.trim());
|
||||
if (StringUtils.isNotBlank(m.label)) {
|
||||
tableLabels.put(m.tableKey.trim(), m.label.trim());
|
||||
}
|
||||
for (String fk : m.fieldKeys) {
|
||||
if (StringUtils.isNotBlank(fk)) {
|
||||
shortFieldOwner.putIfAbsent(fk.trim(), m.tableKey.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<PrintTemplateFieldItemVO> flat = extract(templateJson);
|
||||
List<PrintTemplateFieldItemVO> params = new ArrayList<>();
|
||||
List<PrintTemplateFieldItemVO> nonParams = new ArrayList<>();
|
||||
for (PrintTemplateFieldItemVO f : flat) {
|
||||
if (f == null) {
|
||||
continue;
|
||||
}
|
||||
if ("param".equalsIgnoreCase(StringUtils.defaultString(f.getElementType()))) {
|
||||
params.add(f);
|
||||
} else {
|
||||
nonParams.add(f);
|
||||
}
|
||||
}
|
||||
vo.setParams(params);
|
||||
|
||||
LinkedHashSet<String> dottedPrefixes = new LinkedHashSet<>();
|
||||
for (PrintTemplateFieldItemVO f : nonParams) {
|
||||
String bf = StringUtils.trimToEmpty(f.getBindField());
|
||||
int dot = bf.indexOf('.');
|
||||
if (dot > 0) {
|
||||
String prefix = bf.substring(0, dot).trim();
|
||||
if (StringUtils.isNotBlank(prefix)) {
|
||||
dottedPrefixes.add(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String soleMetaKey = metaKeysOrdered.size() == 1 ? metaKeysOrdered.iterator().next() : null;
|
||||
|
||||
Map<String, List<PrintTemplateFieldItemVO>> groups = new LinkedHashMap<>();
|
||||
for (String k : metaKeysOrdered) {
|
||||
groups.put(k, new ArrayList<>());
|
||||
}
|
||||
for (String p : dottedPrefixes) {
|
||||
groups.computeIfAbsent(p, key -> new ArrayList<>());
|
||||
}
|
||||
|
||||
final String generalKey = "__general__";
|
||||
for (PrintTemplateFieldItemVO f : nonParams) {
|
||||
String bf = StringUtils.trimToEmpty(f.getBindField());
|
||||
String groupKey;
|
||||
int dot = bf.indexOf('.');
|
||||
if (dot > 0) {
|
||||
groupKey = bf.substring(0, dot).trim();
|
||||
} else if (soleMetaKey != null) {
|
||||
groupKey = soleMetaKey;
|
||||
} else if (StringUtils.isNotBlank(bf) && shortFieldOwner.containsKey(bf)) {
|
||||
groupKey = shortFieldOwner.get(bf);
|
||||
} else if (metaKeysOrdered.isEmpty() && dottedPrefixes.size() == 1) {
|
||||
groupKey = dottedPrefixes.iterator().next();
|
||||
} else {
|
||||
groupKey = generalKey;
|
||||
}
|
||||
groups.computeIfAbsent(groupKey, key -> new ArrayList<>());
|
||||
groups.get(groupKey).add(f);
|
||||
}
|
||||
|
||||
List<PrintTemplateDetailTableVO> tables = new ArrayList<>();
|
||||
Set<String> emitted = new LinkedHashSet<>();
|
||||
|
||||
for (DetailTableMeta m : metaTables) {
|
||||
String tk = StringUtils.trimToEmpty(m.tableKey);
|
||||
if (StringUtils.isBlank(tk)) {
|
||||
continue;
|
||||
}
|
||||
emitted.add(tk);
|
||||
List<PrintTemplateFieldItemVO> fields = groups.getOrDefault(tk, List.of());
|
||||
tables.add(new PrintTemplateDetailTableVO(tk, tableLabels.get(tk), new ArrayList<>(fields)));
|
||||
}
|
||||
|
||||
List<String> extras = new ArrayList<>();
|
||||
for (String g : groups.keySet()) {
|
||||
if (!emitted.contains(g) && !groups.get(g).isEmpty()) {
|
||||
extras.add(g);
|
||||
}
|
||||
}
|
||||
extras.sort(String::compareTo);
|
||||
for (String g : extras) {
|
||||
String lbl =
|
||||
generalKey.equals(g) ? "其它(未归类画布/明细占位)" : null;
|
||||
tables.add(new PrintTemplateDetailTableVO(g, lbl, new ArrayList<>(groups.get(g))));
|
||||
}
|
||||
|
||||
vo.setDetailTables(tables);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private static final class DetailTableMeta {
|
||||
String tableKey = "";
|
||||
String label = "";
|
||||
List<String> fieldKeys = new ArrayList<>();
|
||||
}
|
||||
|
||||
private static List<DetailTableMeta> readDetailTableMeta(JsonNode root) {
|
||||
List<DetailTableMeta> out = new ArrayList<>();
|
||||
if (root == null || !root.isObject()) {
|
||||
return out;
|
||||
}
|
||||
JsonNode db = root.get("dataBinding");
|
||||
if (db == null || !db.isObject()) {
|
||||
return out;
|
||||
}
|
||||
JsonNode detailTables = db.get("detailTables");
|
||||
if (detailTables == null || !detailTables.isArray()) {
|
||||
return out;
|
||||
}
|
||||
for (JsonNode t : detailTables) {
|
||||
if (t == null || !t.isObject()) {
|
||||
continue;
|
||||
}
|
||||
DetailTableMeta m = new DetailTableMeta();
|
||||
m.tableKey = text(t, "tableKey").trim();
|
||||
m.label = firstNonBlank(text(t, "label"), text(t, "title")).trim();
|
||||
JsonNode fields = t.get("fields");
|
||||
if (fields != null && fields.isArray()) {
|
||||
for (JsonNode f : fields) {
|
||||
if (f != null && f.isObject()) {
|
||||
String k = text(f, "key").trim();
|
||||
if (StringUtils.isNotBlank(k)) {
|
||||
m.fieldKeys.add(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotBlank(m.tableKey)) {
|
||||
out.add(m);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 解析 schema.dataBinding:params(参数键)、detailTables(明细字段) */
|
||||
private static void collectDataBinding(JsonNode root, Set<String> seen, List<PrintTemplateFieldItemVO> list) {
|
||||
JsonNode db = root.get("dataBinding");
|
||||
@@ -81,11 +283,8 @@ public final class PrintNativeTemplateFieldExtractor {
|
||||
if (StringUtils.isBlank(fk)) {
|
||||
continue;
|
||||
}
|
||||
// 与画布列 bindField 一致时多为短 key;多表明细同字段再加 tableKey 前缀消歧
|
||||
String bindKey = fk;
|
||||
if (seen.contains(bindKey) && StringUtils.isNotBlank(tableKey)) {
|
||||
bindKey = tableKey + "." + fk;
|
||||
}
|
||||
// 统一使用 tableKey.fieldKey,与多表明细、列表展开、预览占位一致(避免首张表仍用短键 Field1)
|
||||
String bindKey = StringUtils.isNotBlank(tableKey) ? tableKey + "." + fk : fk;
|
||||
if (seen.contains(bindKey) || !seen.add(bindKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.jeecg.modules.print.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/** 原生模板中单个明细表(对应 dataBinding.detailTables[].tableKey)及其占位字段 */
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "打印模板明细表分组")
|
||||
public class PrintTemplateDetailTableVO implements Serializable {
|
||||
|
||||
@Schema(description = "明细表绑定键,与画布表格 source、占位前缀一致,如 List1、List2")
|
||||
private String tableKey;
|
||||
|
||||
@Schema(description = "设计器中配置的明细表显示名(可选)")
|
||||
private String label;
|
||||
|
||||
@Schema(description = "该明细表下的模板占位字段(bindField 已与全局解析逻辑一致)")
|
||||
private List<PrintTemplateFieldItemVO> fields = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.jeecg.modules.print.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 原生打印模板占位结构的结构化视图:主表参数 + 按明细表分组,供「业务打印绑定」弹窗标签页展示。
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "打印模板占位结构(参数 + 多明细表)")
|
||||
public class PrintTemplateStructureVO implements Serializable {
|
||||
|
||||
@Schema(description = "主表参数(dataBinding.params)")
|
||||
private List<PrintTemplateFieldItemVO> params = new ArrayList<>();
|
||||
|
||||
@Schema(description = "明细表分组(顺序与模板 dataBinding.detailTables 一致,含画布推断的补充分组)")
|
||||
private List<PrintTemplateDetailTableVO> detailTables = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
-- 原材料检验标准:菜单(与前端 mes/rawmaterialinspectstd/index 一致)+ 打印实体映射 + 可选纳入打印白名单
|
||||
-- 若环境已存在同名菜单(不同 id),不会覆盖;打印绑定时请使用本脚本中的列表页 id 作为 biz_code,或沿用语义码 MES_RAW_MATERIAL_INSPECT_STD(后端支持双查询)
|
||||
|
||||
-- ===================== 1. 菜单权限(父菜单:MES XSL 1900000000000000300)=====================
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000730', '1900000000000000300', '原材料检验标准', '/mes/rawMaterialInspectStd', 'mes/rawmaterialinspectstd/index', 1, NULL, NULL, 1, NULL, '0', 11.30, 0, 'ant-design:safety-outlined', 0, 1, 0, 0, 'MES原材料检验标准', 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000730');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000731', '1900000000000000730', '添加', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:add', '1', 1.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000731');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000732', '1900000000000000730', '编辑', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:edit', '1', 2.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000732');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000733', '1900000000000000730', '删除', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:delete', '1', 3.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000733');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000734', '1900000000000000730', '批量删除', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:deleteBatch', '1', 4.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000734');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000735', '1900000000000000730', '启用停用', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:enable', '1', 5.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000735');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000736', '1900000000000000730', '导出', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:exportXls', '1', 6.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000736');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`)
|
||||
SELECT '1900000000000000737', '1900000000000000730', '导入', NULL, NULL, 0, NULL, NULL, 2, 'mes:mes_raw_material_inspect_std:importExcel', '1', 7.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000737');
|
||||
|
||||
-- ===================== 2. 角色菜单授权(admin)=====================
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000730', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000730');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000731', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000731');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000732', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000732');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000733', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000733');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000734', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000734');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000735', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000735');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000736', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000736');
|
||||
|
||||
INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`)
|
||||
SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000737', NULL, NOW(), '127.0.0.1'
|
||||
FROM `sys_role` r WHERE r.`role_code` = 'admin'
|
||||
AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000737');
|
||||
|
||||
-- ===================== 3. 打印业务:菜单关联实体(含主子 lineList)=====================
|
||||
INSERT INTO `print_biz_perm_entity` (`perm_id`, `entity_class`)
|
||||
SELECT '1900000000000000730', 'org.jeecg.modules.mes.material.entity.MesRawMaterialInspectStd'
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `print_biz_perm_entity` WHERE `perm_id` = '1900000000000000730');
|
||||
|
||||
-- ===================== 4. 纳入「业务打印绑定」可选范围(若表存在且尚未包含)=====================
|
||||
INSERT INTO `print_biz_bind_perm_whitelist` (`perm_id`)
|
||||
SELECT '1900000000000000730'
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `print_biz_bind_perm_whitelist` WHERE `perm_id` = '1900000000000000730');
|
||||
1340
jeecgboot-vue3/pnpm-lock.yaml
generated
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 65 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 20 KiB |
@@ -12,6 +12,9 @@ enum Api {
|
||||
queryById = '/mes/material/rawMaterialInspectStd/queryById',
|
||||
queryLineList = '/mes/material/rawMaterialInspectStd/queryLineListByStdId',
|
||||
setEnable = '/mes/material/rawMaterialInspectStd/setEnable',
|
||||
queryPrinters = '/mes/material/rawMaterialInspectStd/queryPrinters',
|
||||
prepareNativePrint = '/mes/material/rawMaterialInspectStd/prepareNativePrint',
|
||||
printPdf = '/mes/material/rawMaterialInspectStd/printPdf',
|
||||
}
|
||||
|
||||
export const getExportUrl = Api.exportXls;
|
||||
@@ -37,3 +40,15 @@ export const batchDelete = (params, handleSuccess) => {
|
||||
export const saveOrUpdate = (params, isUpdate) => defHttp.post({ url: isUpdate ? Api.edit : Api.save, params });
|
||||
|
||||
export const setEnable = (params) => defHttp.post({ url: Api.setEnable, params });
|
||||
|
||||
export const queryPrinters = () => defHttp.get({ url: Api.queryPrinters });
|
||||
|
||||
export const prepareNativePrint = (id: string) =>
|
||||
defHttp.get({
|
||||
url: Api.prepareNativePrint,
|
||||
params: { id, _t: Date.now() },
|
||||
});
|
||||
|
||||
/** id + 前端生成的 pdfBase64;printerName 空则用默认队列(与原材料卡片一致) */
|
||||
export const printPdf = (data: { id: string; printerName?: string; pdfBase64: string; fileName?: string }) =>
|
||||
defHttp.post({ url: Api.printPdf, data, timeout: 3 * 60 * 1000 });
|
||||
|
||||
@@ -2,32 +2,107 @@
|
||||
<div>
|
||||
<BasicTable @register="registerTable" :rowSelection="rowSelection">
|
||||
<template #tableTitle>
|
||||
<a-button type="primary" v-auth="'mes:mes_raw_material_inspect_std:add'" @click="handleAdd" preIcon="ant-design:plus-outlined"
|
||||
>新增</a-button
|
||||
<a-button type="primary" v-auth="'mes:mes_raw_material_inspect_std:add'" @click="handleAdd" preIcon="ant-design:plus-outlined">
|
||||
新增
|
||||
</a-button>
|
||||
<JDictSelectTag
|
||||
v-model:value="printDotWsUrl"
|
||||
dictCode="xslmes_print_dot_ws"
|
||||
:showChooseOption="false"
|
||||
style="width: 280px; margin-left: 8px"
|
||||
placeholder="选择 PrintDot 地址"
|
||||
@change="onPrintDotWsUrlChange"
|
||||
/>
|
||||
<a-button v-if="!printDotConnected" style="margin-left: 8px" @click="downloadPrintPlugin">下载打印插件</a-button>
|
||||
<a-select
|
||||
v-model:value="selectedPrinterName"
|
||||
:options="printerOptions"
|
||||
style="width: 220px; margin-left: 8px"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:placeholder="printerSelectPlaceholder"
|
||||
/>
|
||||
<a-button style="margin-left: 8px" @click="() => refreshPrinterOptions(true)">刷新打印机</a-button>
|
||||
<a-button
|
||||
type="primary"
|
||||
ghost
|
||||
v-auth="'mes:mes_raw_material_inspect_std:edit'"
|
||||
:loading="printLoading"
|
||||
:disabled="selectedRowKeys.length === 0"
|
||||
@click="handlePrintSelected"
|
||||
>
|
||||
<Icon icon="ant-design:printer-outlined" />
|
||||
打印选中
|
||||
</a-button>
|
||||
</template>
|
||||
<template #action="{ record }">
|
||||
<TableAction
|
||||
:actions="[
|
||||
{ label: '编辑', onClick: handleEdit.bind(null, record), auth: 'mes:mes_raw_material_inspect_std:edit' },
|
||||
]"
|
||||
:actions="getTableAction(record)"
|
||||
:dropDownActions="getDropDownAction(record)"
|
||||
/>
|
||||
</template>
|
||||
</BasicTable>
|
||||
<MesRawMaterialInspectStdModal @register="registerModal" @success="reload" />
|
||||
<MesRawMaterialInspectStdPrintPreviewModal
|
||||
v-model:open="printPreviewOpen"
|
||||
:std-id="printPreviewStdId"
|
||||
:standard-no="printPreviewStandardNo"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { Icon } from '/@/components/Icon';
|
||||
import { BasicTable, TableAction } from '/@/components/Table';
|
||||
import { useModal } from '/@/components/Modal';
|
||||
import { useListPage } from '/@/hooks/system/useListPage';
|
||||
import { initDictOptions } from '/@/utils/dict';
|
||||
import { JDictSelectTag } from '/@/components/Form';
|
||||
import MesRawMaterialInspectStdModal from './modules/MesRawMaterialInspectStdModal.vue';
|
||||
import MesRawMaterialInspectStdPrintPreviewModal from './modules/MesRawMaterialInspectStdPrintPreviewModal.vue';
|
||||
import { columns, searchFormSchema } from './MesRawMaterialInspectStd.data';
|
||||
import { list, deleteOne, setEnable } from './MesRawMaterialInspectStd.api';
|
||||
import { list, deleteOne, setEnable, prepareNativePrint } from './MesRawMaterialInspectStd.api';
|
||||
import { useMessage } from '/@/hooks/web/useMessage';
|
||||
import {
|
||||
PRINT_TEMPLATE_SELECTED_PRINTER_KEY,
|
||||
printNativeSchemaViaPrintDot,
|
||||
} from '/@/views/print/template/utils/printNativeViaPrintDot';
|
||||
import { normalizeImportedNativeSchema } from '/@/views/print/template/native/core/nativeSchemaNormalize';
|
||||
import {
|
||||
fetchPrintDotPrinters,
|
||||
getPrintDotBridgeConfig,
|
||||
setPrintDotBridgeConfig,
|
||||
} from '/@/views/print/template/utils/printDotBridge';
|
||||
|
||||
const { createMessage } = useMessage();
|
||||
const PRINT_DOT_WS_DICT = 'xslmes_print_dot_ws';
|
||||
const printDotWsUrl = ref('');
|
||||
const printDotConnected = ref(false);
|
||||
|
||||
function persistPrintDotConfig() {
|
||||
setPrintDotBridgeConfig(String(printDotWsUrl.value || '').trim(), '');
|
||||
void refreshPrinterOptions(false);
|
||||
}
|
||||
|
||||
function onPrintDotWsUrlChange() {
|
||||
printDotConnected.value = false;
|
||||
persistPrintDotConfig();
|
||||
}
|
||||
|
||||
function downloadPrintPlugin() {
|
||||
const base = import.meta.env.BASE_URL || '/';
|
||||
const normalizedBase = base.endsWith('/') ? base : `${base}/`;
|
||||
const url = `${normalizedBase}print-plugin/XSL-PrintDot.exe`;
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', 'XSL-PrintDot.exe');
|
||||
link.rel = 'noopener';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
|
||||
const [registerModal, { openModal }] = useModal();
|
||||
const { tableContext } = useListPage({
|
||||
tableProps: {
|
||||
@@ -36,10 +111,208 @@
|
||||
columns,
|
||||
canResize: true,
|
||||
formConfig: { labelWidth: 100, schemas: searchFormSchema, autoSubmitOnEnter: true },
|
||||
actionColumn: { width: 200 },
|
||||
actionColumn: { width: 280, fixed: 'right' },
|
||||
},
|
||||
});
|
||||
const [registerTable, { reload }, { rowSelection }] = tableContext;
|
||||
const [registerTable, { reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;
|
||||
|
||||
const printPreviewOpen = ref(false);
|
||||
const printPreviewStdId = ref<string | null>(null);
|
||||
const printPreviewStandardNo = ref<string | undefined>(undefined);
|
||||
|
||||
function handlePrintPreview(record: Recordable) {
|
||||
printPreviewStdId.value = record.id as string;
|
||||
printPreviewStandardNo.value = record.standardNo as string | undefined;
|
||||
printPreviewOpen.value = true;
|
||||
}
|
||||
|
||||
const printerOptions = ref<Array<{ label: string; value: string }>>([]);
|
||||
const selectedPrinterName = ref<string>('__system_default__');
|
||||
const printLoading = ref(false);
|
||||
const PRINT_ROW_LOADING_KEY = 'mesRawMaterialInspectStd-print-row';
|
||||
const PRINT_BATCH_LOADING_KEY = 'mesRawMaterialInspectStd-print-batch';
|
||||
const printerSelectPlaceholder = '选择打印机(PrintDot 桥接)';
|
||||
|
||||
watch(selectedPrinterName, (v) => {
|
||||
if (v) {
|
||||
localStorage.setItem(PRINT_TEMPLATE_SELECTED_PRINTER_KEY, v);
|
||||
}
|
||||
});
|
||||
|
||||
async function refreshPrinterOptions(showMessage = true) {
|
||||
const optionMap = new Map<string, { label: string; value: string }>();
|
||||
optionMap.set('__system_default__', { label: '系统默认打印机', value: '__system_default__' });
|
||||
try {
|
||||
const dotList = await fetchPrintDotPrinters();
|
||||
printDotConnected.value = true;
|
||||
dotList.forEach((p) => {
|
||||
const name = String(p.name || '').trim();
|
||||
if (!name) return;
|
||||
const defMark = p.isDefault ? '(默认)' : '';
|
||||
optionMap.set(name, { label: `${name}${defMark}`, value: name });
|
||||
});
|
||||
printerOptions.value = Array.from(optionMap.values());
|
||||
if (showMessage) {
|
||||
if (dotList.length) {
|
||||
createMessage.success(`已从 PrintDot 桥接识别 ${dotList.length} 台打印机`);
|
||||
} else {
|
||||
createMessage.warning('PrintDot 已连接但未返回打印机列表');
|
||||
}
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
printDotConnected.value = false;
|
||||
printerOptions.value = Array.from(optionMap.values());
|
||||
if (showMessage) {
|
||||
createMessage.warning(`PrintDot:${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function executePrint(record: Recordable, options?: { silentSuccess?: boolean }) {
|
||||
try {
|
||||
const prep = (await prepareNativePrint(record.id as string)) as Record<string, unknown>;
|
||||
const templateJsonRaw = prep.templateJson as string;
|
||||
const printData = prep.printData as Record<string, unknown>;
|
||||
const paperWidthMm = Number((prep as any).paperWidthMm ?? 0);
|
||||
const paperHeightMm = Number((prep as any).paperHeightMm ?? 0);
|
||||
const paperOrientation = String((prep as any).paperOrientation || '').toLowerCase();
|
||||
if (!templateJsonRaw) {
|
||||
throw new Error('模板 JSON 为空');
|
||||
}
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = typeof templateJsonRaw === 'string' ? JSON.parse(templateJsonRaw) : templateJsonRaw;
|
||||
} catch {
|
||||
throw new Error('模板 JSON 格式错误');
|
||||
}
|
||||
const schema = normalizeImportedNativeSchema(raw);
|
||||
if (paperWidthMm > 0 && paperHeightMm > 0) {
|
||||
const orient = paperOrientation === 'landscape' ? 'landscape' : paperOrientation === 'portrait' ? 'portrait' : '';
|
||||
const normalized =
|
||||
orient === 'landscape'
|
||||
? {
|
||||
width: Math.max(paperWidthMm, paperHeightMm),
|
||||
height: Math.min(paperWidthMm, paperHeightMm),
|
||||
}
|
||||
: orient === 'portrait'
|
||||
? {
|
||||
width: Math.min(paperWidthMm, paperHeightMm),
|
||||
height: Math.max(paperWidthMm, paperHeightMm),
|
||||
}
|
||||
: {
|
||||
width: paperWidthMm,
|
||||
height: paperHeightMm,
|
||||
};
|
||||
schema.page.width = normalized.width;
|
||||
schema.page.height = normalized.height;
|
||||
}
|
||||
const no = String(record.standardNo || '').trim();
|
||||
await printNativeSchemaViaPrintDot({
|
||||
schema,
|
||||
data: printData as Record<string, unknown>,
|
||||
jobName: `原材料检验标准-${no || record.id}.pdf`,
|
||||
printerSelection:
|
||||
selectedPrinterName.value ||
|
||||
localStorage.getItem(PRINT_TEMPLATE_SELECTED_PRINTER_KEY) ||
|
||||
'__system_default__',
|
||||
});
|
||||
if (!options?.silentSuccess) {
|
||||
createMessage.success('已通过 PrintDot 提交打印');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
throw new Error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
function handlePrintSelected() {
|
||||
const rows = selectedRows.value || [];
|
||||
if (!rows.length) {
|
||||
createMessage.warning('请至少勾选一条记录后再点击「打印选中」');
|
||||
return;
|
||||
}
|
||||
printLoading.value = true;
|
||||
createMessage.destroy(PRINT_BATCH_LOADING_KEY);
|
||||
createMessage.loading({
|
||||
content: `正在打印 ${rows.length} 条记录,请稍候…`,
|
||||
key: PRINT_BATCH_LOADING_KEY,
|
||||
duration: 0,
|
||||
});
|
||||
(async () => {
|
||||
try {
|
||||
let ok = 0;
|
||||
let firstError = '';
|
||||
for (const row of rows) {
|
||||
try {
|
||||
await executePrint(row, { silentSuccess: true });
|
||||
ok += 1;
|
||||
} catch (e: unknown) {
|
||||
if (!firstError) {
|
||||
firstError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ok === rows.length) {
|
||||
createMessage.success(`已通过 PrintDot 提交 ${ok} 条打印任务`);
|
||||
} else {
|
||||
createMessage.warning(
|
||||
`打印完成:成功 ${ok},失败 ${rows.length - ok}${firstError ? `。首条错误:${firstError}` : ''}`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
createMessage.destroy(PRINT_BATCH_LOADING_KEY);
|
||||
printLoading.value = false;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
async function handlePrintRow(record: Recordable) {
|
||||
printLoading.value = true;
|
||||
createMessage.destroy(PRINT_ROW_LOADING_KEY);
|
||||
createMessage.loading({
|
||||
content: '正在生成 PDF 并提交打印,版面复杂时可能需数十秒,请稍候…',
|
||||
key: PRINT_ROW_LOADING_KEY,
|
||||
duration: 0,
|
||||
});
|
||||
try {
|
||||
await executePrint(record, { silentSuccess: true });
|
||||
createMessage.success('已通过 PrintDot 提交打印');
|
||||
} catch (e: unknown) {
|
||||
createMessage.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
createMessage.destroy(PRINT_ROW_LOADING_KEY);
|
||||
printLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const cfg = getPrintDotBridgeConfig();
|
||||
setPrintDotBridgeConfig(cfg.wsUrl, '');
|
||||
printDotWsUrl.value = cfg.wsUrl || '';
|
||||
|
||||
try {
|
||||
const raw = await initDictOptions(PRINT_DOT_WS_DICT);
|
||||
const items = Array.isArray(raw) ? raw : [];
|
||||
const values = items
|
||||
.map((it: Recordable) => String(it.value ?? it.itemValue ?? '').trim())
|
||||
.filter(Boolean);
|
||||
const valueSet = new Set(values);
|
||||
if (valueSet.size && printDotWsUrl.value && !valueSet.has(String(printDotWsUrl.value).trim())) {
|
||||
printDotWsUrl.value = values[0];
|
||||
setPrintDotBridgeConfig(printDotWsUrl.value, '');
|
||||
} else if (valueSet.size && !printDotWsUrl.value.trim()) {
|
||||
printDotWsUrl.value = values[0];
|
||||
setPrintDotBridgeConfig(printDotWsUrl.value, '');
|
||||
}
|
||||
} catch {
|
||||
/* 字典未配置时沿用 localStorage */
|
||||
}
|
||||
|
||||
const savedPrinter = localStorage.getItem(PRINT_TEMPLATE_SELECTED_PRINTER_KEY);
|
||||
if (savedPrinter) {
|
||||
selectedPrinterName.value = savedPrinter;
|
||||
}
|
||||
await refreshPrinterOptions(false);
|
||||
});
|
||||
|
||||
function handleAdd() {
|
||||
openModal(true, { isUpdate: false, showFooter: true });
|
||||
@@ -63,7 +336,28 @@
|
||||
createMessage.success('已停用');
|
||||
reload();
|
||||
}
|
||||
function getDropDownAction(record) {
|
||||
|
||||
function getTableAction(record: Recordable) {
|
||||
return [
|
||||
{
|
||||
label: '编辑',
|
||||
onClick: handleEdit.bind(null, record),
|
||||
auth: 'mes:mes_raw_material_inspect_std:edit',
|
||||
},
|
||||
{
|
||||
label: '打印预览',
|
||||
onClick: handlePrintPreview.bind(null, record),
|
||||
auth: 'mes:mes_raw_material_inspect_std:edit',
|
||||
},
|
||||
{
|
||||
label: '打印',
|
||||
onClick: handlePrintRow.bind(null, record),
|
||||
auth: 'mes:mes_raw_material_inspect_std:edit',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function getDropDownAction(record: Recordable) {
|
||||
const actions: any[] = [
|
||||
{ label: '详情', onClick: handleDetail.bind(null, record) },
|
||||
{
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
<template>
|
||||
<a-modal
|
||||
v-model:open="innerOpen"
|
||||
:title="modalTitle"
|
||||
width="960px"
|
||||
:footer="null"
|
||||
destroy-on-close
|
||||
wrap-class-name="mes-raw-material-inspect-std-print-preview-modal"
|
||||
@cancel="onClose"
|
||||
>
|
||||
<a-spin :spinning="loading">
|
||||
<div v-if="errorText" class="preview-error">{{ errorText }}</div>
|
||||
<div v-else class="preview-body">
|
||||
<iframe
|
||||
v-if="previewHtml"
|
||||
class="preview-iframe"
|
||||
title="原材料检验标准打印预览"
|
||||
:srcdoc="previewHtml"
|
||||
/>
|
||||
<a-empty v-else-if="!loading" description="暂无预览内容" />
|
||||
</div>
|
||||
</a-spin>
|
||||
<div class="preview-footer">
|
||||
<a-space>
|
||||
<a-button @click="innerOpen = false">关闭</a-button>
|
||||
<a-button type="primary" :disabled="!previewHtml || !!errorText" @click="handleBrowserPrint">
|
||||
<Icon icon="ant-design:printer-outlined" />
|
||||
浏览器打印
|
||||
</a-button>
|
||||
</a-space>
|
||||
</div>
|
||||
</a-modal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Icon } from '/@/components/Icon';
|
||||
import { useMessage } from '/@/hooks/web/useMessage';
|
||||
import { prepareNativePrint } from '../MesRawMaterialInspectStd.api';
|
||||
import { renderNativePrintHtml } from '/@/views/print/template/native/core/printRenderer';
|
||||
import { normalizeImportedNativeSchema } from '/@/views/print/template/native/core/nativeSchemaNormalize';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
/** 检验标准主键 */
|
||||
stdId: string | null;
|
||||
/** 展示在标题(如标准编号) */
|
||||
standardNo?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:open', v: boolean): void;
|
||||
}>();
|
||||
|
||||
const { createMessage } = useMessage();
|
||||
|
||||
const innerOpen = computed({
|
||||
get: () => props.open,
|
||||
set: (v: boolean) => emit('update:open', v),
|
||||
});
|
||||
|
||||
const modalTitle = computed(() => {
|
||||
const b = String(props.standardNo || '').trim();
|
||||
return b ? `原材料检验标准打印预览(标准编号:${b})` : '原材料检验标准打印预览';
|
||||
});
|
||||
|
||||
const loading = ref(false);
|
||||
const errorText = ref('');
|
||||
const previewHtml = ref('');
|
||||
|
||||
async function loadPreview(id: string) {
|
||||
loading.value = true;
|
||||
errorText.value = '';
|
||||
previewHtml.value = '';
|
||||
try {
|
||||
const prep = (await prepareNativePrint(id)) as Record<string, unknown>;
|
||||
const templateJsonRaw = prep.templateJson as string;
|
||||
const printData = prep.printData as Record<string, unknown>;
|
||||
if (!templateJsonRaw) {
|
||||
throw new Error('模板 JSON 为空,请检查「业务打印绑定」是否已配置');
|
||||
}
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = typeof templateJsonRaw === 'string' ? JSON.parse(templateJsonRaw) : templateJsonRaw;
|
||||
} catch {
|
||||
throw new Error('模板 JSON 格式错误');
|
||||
}
|
||||
const schema = normalizeImportedNativeSchema(raw);
|
||||
previewHtml.value = await renderNativePrintHtml(schema, printData as Record<string, unknown>);
|
||||
} catch (e: unknown) {
|
||||
errorText.value = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleBrowserPrint() {
|
||||
const html = previewHtml.value;
|
||||
if (!html?.trim()) {
|
||||
createMessage.warning('预览未就绪,请稍后再试');
|
||||
return;
|
||||
}
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.setAttribute(
|
||||
'style',
|
||||
'position:fixed;left:0;top:0;width:0;height:0;border:0;opacity:0;pointer-events:none;',
|
||||
);
|
||||
document.body.appendChild(iframe);
|
||||
const doc = iframe.contentDocument;
|
||||
if (!doc) {
|
||||
document.body.removeChild(iframe);
|
||||
createMessage.error('无法创建打印文档');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
doc.open();
|
||||
doc.write(html);
|
||||
doc.close();
|
||||
} catch {
|
||||
document.body.removeChild(iframe);
|
||||
createMessage.error('写入打印内容失败');
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanup = () => {
|
||||
try {
|
||||
if (iframe.parentNode) {
|
||||
document.body.removeChild(iframe);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const runPrint = () => {
|
||||
try {
|
||||
const w = iframe.contentWindow;
|
||||
if (!w) {
|
||||
createMessage.error('无法唤起打印窗口');
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
w.focus();
|
||||
w.print();
|
||||
w.addEventListener('afterprint', cleanup, { once: true });
|
||||
window.setTimeout(cleanup, 120000);
|
||||
} catch {
|
||||
createMessage.error('无法唤起打印,请检查浏览器弹窗/打印权限');
|
||||
cleanup();
|
||||
}
|
||||
};
|
||||
|
||||
window.setTimeout(runPrint, 100);
|
||||
}
|
||||
|
||||
function onClose() {
|
||||
errorText.value = '';
|
||||
previewHtml.value = '';
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.open, props.stdId] as const,
|
||||
([isOpen, id]) => {
|
||||
if (isOpen && id) {
|
||||
void loadPreview(id);
|
||||
}
|
||||
if (!isOpen) {
|
||||
onClose();
|
||||
}
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.preview-error {
|
||||
color: #cf1322;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.preview-body {
|
||||
min-height: 420px;
|
||||
max-height: 72vh;
|
||||
overflow: auto;
|
||||
border: 1px solid #f0f0f0;
|
||||
border-radius: 4px;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
.preview-iframe {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: 400px;
|
||||
border: 0;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.preview-footer {
|
||||
margin-top: 16px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
text-align: right;
|
||||
}
|
||||
</style>
|
||||
@@ -9,6 +9,7 @@ enum Api {
|
||||
bizTypesForBinding = '/print/bizTemplateBind/bizTypesForBinding',
|
||||
permWhitelist = '/print/bizTemplateBind/permWhitelist',
|
||||
parseTemplateFields = '/print/bizTemplateBind/parseTemplateFields',
|
||||
parseTemplateStructure = '/print/bizTemplateBind/parseTemplateStructure',
|
||||
previewMappedData = '/print/bizTemplateBind/previewMappedData',
|
||||
detailSlots = '/print/bizTemplateBind/detailSlots',
|
||||
bizFieldsForDetailSlot = '/print/bizTemplateBind/bizFieldsForDetailSlot',
|
||||
@@ -36,6 +37,16 @@ export const parseTemplateFields = (templateId: string) =>
|
||||
params: { templateId, _t: Date.now() },
|
||||
});
|
||||
|
||||
/** 主表参数 + 按模板明细表分组(多标签映射) */
|
||||
export const parseTemplateStructure = (templateId: string) =>
|
||||
defHttp.get<{
|
||||
params: { bindField: string; elementType?: string; titleHint?: string }[];
|
||||
detailTables: { tableKey: string; label?: string; fields: { bindField: string; elementType?: string; titleHint?: string }[] }[];
|
||||
}>({
|
||||
url: Api.parseTemplateStructure,
|
||||
params: { templateId, _t: Date.now() },
|
||||
});
|
||||
|
||||
/** 预览映射后的打印数据 */
|
||||
export const previewMappedData = (data: { bizCode: string; bizDataJson: Record<string, unknown> }) =>
|
||||
defHttp.post({ url: Api.previewMappedData, data });
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
show-icon
|
||||
class="bind-alert"
|
||||
message="配置说明"
|
||||
description="按卡片顺序操作:先选业务与模板 → 若模板含明细占位,在「明细数据来源」中选择主实体上的集合/嵌套对象 → 点击「解析模板占位字段」→ 在下方「主表参数」「明细与表格」中分别为每个占位选择业务字段;业务字段下拉第一项为「空占位符」,表示不参与业务 JSON 取值(等同输出空)。主表参数一般映射主实体字段;明细占位可选带「明细前缀」的路径(如 lines.qty)。支持 lines.qty(首行)或 lines.0.qty。"
|
||||
description="按卡片顺序操作:先选业务与模板 → 点击「解析模板占位字段」→ 主表参数映射主实体字段 → 若模板含多个明细表,在「明细与表格」标签页中逐表选择与模板明细键对应的业务明细集合,再映射列字段。业务字段下拉第一项为「空占位符」,表示不参与业务 JSON。明细列占位多为「模板明细键.列」(如 List2.Field1),业务侧选「明细属性.列」(如 lineList.qty),打印时会按数组展开。"
|
||||
/>
|
||||
|
||||
<a-card title="基础信息" size="small" :bordered="true" class="bind-card">
|
||||
@@ -89,30 +89,6 @@
|
||||
</a-form>
|
||||
</a-card>
|
||||
|
||||
<a-card size="small" :bordered="true" class="bind-card">
|
||||
<template #title>
|
||||
<span class="bind-card-head">明细数据来源</span>
|
||||
<span class="bind-card-head-extra">(可选)</span>
|
||||
</template>
|
||||
<template #extra>
|
||||
<span class="bind-card-sub">有明细/表格占位时需配置</span>
|
||||
</template>
|
||||
<p class="bind-card-desc">
|
||||
选择主实体类上的明细集合属性(如 List<明细实体>)或嵌套对象;系统将明细类字段并入下方「明细与表格」中的业务字段下拉。
|
||||
</p>
|
||||
<a-select
|
||||
v-model:value="selectedDetailProperty"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
placeholder="无需明细请留空"
|
||||
:options="detailSlotSelectOptions"
|
||||
:loading="detailFieldsLoading"
|
||||
style="width: 100%"
|
||||
@change="onDetailSlotChange"
|
||||
/>
|
||||
</a-card>
|
||||
|
||||
<a-card size="small" :bordered="true" class="bind-card bind-card--mapping">
|
||||
<template #title>
|
||||
<span class="bind-card-head">字段映射</span>
|
||||
@@ -125,7 +101,7 @@
|
||||
<a-button
|
||||
size="small"
|
||||
@click="autoMatchFields"
|
||||
:disabled="(!bizFields.length && !detailBizFields.length) || !tplFields.length"
|
||||
:disabled="(!bizFields.length && !hasAnyDetailBizFields()) || !tplFields.length"
|
||||
>
|
||||
同名自动匹配
|
||||
</a-button>
|
||||
@@ -170,35 +146,59 @@
|
||||
<div class="bind-map-section bind-map-section--detail">
|
||||
<div class="bind-section-bar">
|
||||
<span class="bind-section-title">② 明细与表格列</span>
|
||||
<span class="bind-section-hint">对应明细字段、表格列等;可选主表字段或上方明细来源生成的前缀字段</span>
|
||||
<span class="bind-section-hint">
|
||||
按模板明细表(tableKey)分页配置:每个标签页先选业务明细集合,再映射列;多表明细互不影响
|
||||
</span>
|
||||
</div>
|
||||
<a-table
|
||||
v-if="mappingRowsDetail.length"
|
||||
size="small"
|
||||
row-key="templateField"
|
||||
:pagination="false"
|
||||
:columns="mapTableColumnsDetail"
|
||||
:data-source="mappingRowsDetail"
|
||||
bordered
|
||||
class="bind-map-table"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'tplKind'">
|
||||
{{ templateFieldKindLabel(record.elementType) }}
|
||||
</template>
|
||||
<template v-if="column.key === 'bizField'">
|
||||
<template v-if="detailTablesStructure.length">
|
||||
<a-tabs v-model:activeKey="detailTabKey" type="card" size="small" class="bind-detail-tabs">
|
||||
<a-tab-pane v-for="dt in detailTablesStructure" :key="dt.tableKey" :tab="detailTabTitle(dt)">
|
||||
<p class="bind-card-desc">
|
||||
模板明细键 <code>{{ dt.tableKey }}</code>
|
||||
对应画布表格等组件的数据源;请选择主实体上要绑定到该明细表的业务集合(或嵌套对象)。
|
||||
</p>
|
||||
<a-select
|
||||
v-model:value="record.bizField"
|
||||
:options="bizFieldOptions"
|
||||
v-model:value="detailSlotByTable[dt.tableKey]"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
style="width: 100%"
|
||||
placeholder="选择业务字段"
|
||||
placeholder="选择业务明细属性(如 lineList)"
|
||||
:options="detailSlotSelectOptions"
|
||||
:loading="!!detailFieldsLoadingMap[dt.tableKey]"
|
||||
style="width: 100%; margin-bottom: 12px"
|
||||
@change="(v) => onDetailSlotChangeForTable(dt.tableKey, v as string | undefined)"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
<a-table
|
||||
v-if="mappingRowsForDetailTable(dt).length"
|
||||
size="small"
|
||||
row-key="templateField"
|
||||
:pagination="false"
|
||||
:columns="mapTableColumnsDetail"
|
||||
:data-source="mappingRowsForDetailTable(dt)"
|
||||
bordered
|
||||
class="bind-map-table"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'tplKind'">
|
||||
{{ templateFieldKindLabel(record.elementType) }}
|
||||
</template>
|
||||
<template v-if="column.key === 'bizField'">
|
||||
<a-select
|
||||
v-model:value="record.bizField"
|
||||
:options="bizFieldOptionsForTable(dt.tableKey)"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
style="width: 100%"
|
||||
placeholder="选择业务字段"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
<a-empty v-else class="bind-empty" description="该模板明细表下暂无占位字段(可在设计器中维护 dataBinding.detailTables)" />
|
||||
</a-tab-pane>
|
||||
</a-tabs>
|
||||
</template>
|
||||
<a-empty v-else class="bind-empty" description="本模板未解析到明细/表格列占位" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -269,7 +269,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref, unref } from 'vue';
|
||||
import { computed, reactive, ref, unref } from 'vue';
|
||||
import { BasicTable, TableAction, useTable } from '/@/components/Table';
|
||||
import { BasicModal, useModal } from '/@/components/Modal';
|
||||
import { BasicTree, TreeItem } from '/@/components/Tree';
|
||||
@@ -313,6 +313,12 @@
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface TemplateDetailTableItem {
|
||||
tableKey: string;
|
||||
label?: string;
|
||||
fields: TplFieldItem[];
|
||||
}
|
||||
|
||||
const bizTypesRef = ref<BizTypeItem[]>([]);
|
||||
const tplListRef = ref<{ id: string; templateCode: string; templateName: string }[]>([]);
|
||||
/** 弹窗内:业务列表 + 模板下拉并行加载中(不再阻塞 openModal,避免点按钮好几秒才出框) */
|
||||
@@ -335,9 +341,12 @@
|
||||
const bizFields = ref<BizTypeItem['fields']>([]);
|
||||
const mappingRows = ref<MappingRow[]>([]);
|
||||
const detailSlots = ref<DetailSlotItem[]>([]);
|
||||
const selectedDetailProperty = ref<string | undefined>(undefined);
|
||||
const detailBizFields = ref<BizTypeItem['fields']>([]);
|
||||
const detailFieldsLoading = ref(false);
|
||||
const detailTablesStructure = ref<TemplateDetailTableItem[]>([]);
|
||||
const detailTabKey = ref('');
|
||||
/** 每个模板明细表键对应选中的业务明细属性名 */
|
||||
const detailSlotByTable = reactive<Record<string, string | undefined>>({});
|
||||
const detailBizFieldsMap = reactive<Record<string, BizTypeItem['fields']>>({});
|
||||
const detailFieldsLoadingMap = reactive<Record<string, boolean>>({});
|
||||
|
||||
const isEditMode = ref(false);
|
||||
const modalTitle = computed(() => (unref(isEditMode) ? '编辑业务打印绑定' : '新增业务打印绑定'));
|
||||
@@ -372,19 +381,125 @@
|
||||
return [...head, ...rest];
|
||||
});
|
||||
|
||||
/** 主表 + 明细前缀字段(用于明细/表格占位) */
|
||||
const bizFieldOptions = computed(() => {
|
||||
/** 某一模板明细表标签页:主表字段 + 该表选中的业务明细前缀字段 */
|
||||
function bizFieldOptionsForTable(tableKey: string) {
|
||||
const head = [{ label: '— 空占位符(不参与业务 JSON)—', value: EMPTY_BIZ_FIELD_SENTINEL }];
|
||||
const main = unref(bizFields).map((f) => ({
|
||||
label: f.label ? `${f.label}(${f.fieldKey})` : f.fieldKey,
|
||||
value: f.fieldKey,
|
||||
}));
|
||||
const detail = unref(detailBizFields).map((f) => ({
|
||||
const detail = (detailBizFieldsMap[tableKey] || []).map((f) => ({
|
||||
label: f.label ? `${f.label}(${f.fieldKey})` : f.fieldKey,
|
||||
value: f.fieldKey,
|
||||
}));
|
||||
return [...head, ...main, ...detail];
|
||||
});
|
||||
}
|
||||
|
||||
function hasAnyDetailBizFields(): boolean {
|
||||
for (const k in detailBizFieldsMap) {
|
||||
if ((detailBizFieldsMap[k] || []).length) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function detailTabTitle(dt: TemplateDetailTableItem) {
|
||||
const hint = dt.label || '';
|
||||
return hint ? `${hint}(${dt.tableKey})` : dt.tableKey;
|
||||
}
|
||||
|
||||
/** 属于某一模板明细表的映射行(与后端分组一致) */
|
||||
function mappingRowsForDetailTable(dt: TemplateDetailTableItem): MappingRow[] {
|
||||
const keys = new Set((dt.fields || []).map((f) => (f.bindField || '').trim()).filter(Boolean));
|
||||
return unref(mappingRows).filter((r) => keys.has((r.templateField || '').trim()));
|
||||
}
|
||||
|
||||
/** 根据已保存映射推断业务明细属性(编辑时用) */
|
||||
function inferDetailSlotForTable(tableKey: string): string | undefined {
|
||||
const dt = unref(detailTablesStructure).find((d) => d.tableKey === tableKey);
|
||||
if (!dt?.fields?.length) {
|
||||
return undefined;
|
||||
}
|
||||
const keySet = new Set(dt.fields.map((f) => (f.bindField || '').trim()).filter(Boolean));
|
||||
const counts = new Map<string, number>();
|
||||
for (const r of unref(mappingRows)) {
|
||||
if (!keySet.has((r.templateField || '').trim())) {
|
||||
continue;
|
||||
}
|
||||
const bf = r.bizField;
|
||||
if (!bf || bf === EMPTY_BIZ_FIELD_SENTINEL) {
|
||||
continue;
|
||||
}
|
||||
const s = String(bf);
|
||||
const dot = s.indexOf('.');
|
||||
if (dot <= 0) {
|
||||
continue;
|
||||
}
|
||||
const head = s.slice(0, dot);
|
||||
counts.set(head, (counts.get(head) || 0) + 1);
|
||||
}
|
||||
let best: string | undefined;
|
||||
let bestN = 0;
|
||||
counts.forEach((n, h) => {
|
||||
if (n > bestN) {
|
||||
bestN = n;
|
||||
best = h;
|
||||
}
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
async function loadBizFieldsForTableSlot(tableKey: string, propertyName: string | undefined) {
|
||||
if (!propertyName || !form.value.bizCode) {
|
||||
detailBizFieldsMap[tableKey] = [];
|
||||
return;
|
||||
}
|
||||
const slot = unref(detailSlots).find((s) => s.propertyName === propertyName);
|
||||
const kind = slot?.slotKind || 'LIST';
|
||||
detailFieldsLoadingMap[tableKey] = true;
|
||||
try {
|
||||
const list = await Api.bizFieldsForDetailSlot({
|
||||
bizCode: form.value.bizCode,
|
||||
detailProperty: propertyName,
|
||||
slotKind: kind,
|
||||
});
|
||||
detailBizFieldsMap[tableKey] = (list || []) as BizTypeItem['fields'];
|
||||
} catch {
|
||||
detailBizFieldsMap[tableKey] = [];
|
||||
} finally {
|
||||
detailFieldsLoadingMap[tableKey] = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onDetailSlotChangeForTable(tableKey: string, propertyName: string | undefined) {
|
||||
detailSlotByTable[tableKey] = propertyName;
|
||||
await loadBizFieldsForTableSlot(tableKey, propertyName);
|
||||
}
|
||||
|
||||
async function restoreDetailSlotsFromMapping() {
|
||||
for (const dt of unref(detailTablesStructure)) {
|
||||
const tk = dt.tableKey;
|
||||
const existing = detailSlotByTable[tk];
|
||||
if (existing) {
|
||||
await loadBizFieldsForTableSlot(tk, existing);
|
||||
continue;
|
||||
}
|
||||
const inferred = inferDetailSlotForTable(tk);
|
||||
if (inferred && unref(detailSlots).some((s) => s.propertyName === inferred)) {
|
||||
detailSlotByTable[tk] = inferred;
|
||||
await loadBizFieldsForTableSlot(tk, inferred);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resetDetailTableUiState() {
|
||||
detailTablesStructure.value = [];
|
||||
detailTabKey.value = '';
|
||||
Object.keys(detailSlotByTable).forEach((k) => delete detailSlotByTable[k]);
|
||||
Object.keys(detailBizFieldsMap).forEach((k) => delete detailBizFieldsMap[k]);
|
||||
Object.keys(detailFieldsLoadingMap).forEach((k) => delete detailFieldsLoadingMap[k]);
|
||||
}
|
||||
|
||||
/** 已保存的空字符串映射为下拉哨兵,便于展示「空占位符」项 */
|
||||
function normalizeBizFieldForUi(raw?: string) {
|
||||
@@ -407,11 +522,6 @@
|
||||
unref(mappingRows).filter((r) => (r.elementType || '') === 'param'),
|
||||
);
|
||||
|
||||
/** 非参数占位(明细字段、表格列、其它画布元素) */
|
||||
const mappingRowsDetail = computed(() =>
|
||||
unref(mappingRows).filter((r) => (r.elementType || '') !== 'param'),
|
||||
);
|
||||
|
||||
function templateFieldKindLabel(t?: string) {
|
||||
const m: Record<string, string> = {
|
||||
param: '主表·参数',
|
||||
@@ -545,8 +655,6 @@
|
||||
|
||||
async function refreshDetailSlots(code: string | undefined) {
|
||||
detailSlots.value = [];
|
||||
selectedDetailProperty.value = undefined;
|
||||
detailBizFields.value = [];
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
@@ -557,37 +665,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function onDetailSlotChange(propertyName: string | undefined) {
|
||||
selectedDetailProperty.value = propertyName;
|
||||
if (!propertyName || !form.value.bizCode) {
|
||||
detailBizFields.value = [];
|
||||
return;
|
||||
}
|
||||
const slot = unref(detailSlots).find((s) => s.propertyName === propertyName);
|
||||
const kind = slot?.slotKind || 'LIST';
|
||||
detailFieldsLoading.value = true;
|
||||
try {
|
||||
const list = await Api.bizFieldsForDetailSlot({
|
||||
bizCode: form.value.bizCode,
|
||||
detailProperty: propertyName,
|
||||
slotKind: kind,
|
||||
});
|
||||
detailBizFields.value = (list || []) as BizTypeItem['fields'];
|
||||
} catch {
|
||||
detailBizFields.value = [];
|
||||
} finally {
|
||||
detailFieldsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onBizCodeChange(code: string) {
|
||||
const hit = unref(bizTypesRef).find((b) => b.bizCode === code);
|
||||
bizFields.value = hit?.fields ?? [];
|
||||
form.value.bizName = hit?.bizName;
|
||||
Object.keys(detailSlotByTable).forEach((k) => delete detailSlotByTable[k]);
|
||||
Object.keys(detailBizFieldsMap).forEach((k) => delete detailBizFieldsMap[k]);
|
||||
await refreshDetailSlots(code);
|
||||
if (form.value.templateId && unref(detailTablesStructure).length) {
|
||||
await restoreDetailSlotsFromMapping();
|
||||
}
|
||||
}
|
||||
|
||||
async function onTemplateChange() {
|
||||
resetDetailTableUiState();
|
||||
tplFields.value = [];
|
||||
mappingRows.value = [];
|
||||
await reloadTemplateFields();
|
||||
@@ -598,13 +689,20 @@
|
||||
if (!tid) {
|
||||
tplFields.value = [];
|
||||
mappingRows.value = [];
|
||||
detailTablesStructure.value = [];
|
||||
detailTabKey.value = '';
|
||||
return;
|
||||
}
|
||||
parseLoading.value = true;
|
||||
try {
|
||||
const list = (await Api.parseTemplateFields(tid)) as TplFieldItem[];
|
||||
tplFields.value = list || [];
|
||||
const structure = await Api.parseTemplateStructure(tid);
|
||||
detailTablesStructure.value = structure?.detailTables ?? [];
|
||||
const params = structure?.params ?? [];
|
||||
const flatDetail = (structure?.detailTables ?? []).flatMap((d) => d.fields ?? []);
|
||||
tplFields.value = [...params, ...flatDetail];
|
||||
detailTabKey.value = detailTablesStructure.value[0]?.tableKey ?? '';
|
||||
rebuildMappingRows();
|
||||
await restoreDetailSlotsFromMapping();
|
||||
} finally {
|
||||
parseLoading.value = false;
|
||||
}
|
||||
@@ -648,7 +746,10 @@
|
||||
const savedMappingRef = ref<{ templateField: string; bizField?: string }[]>([]);
|
||||
|
||||
function autoMatchFields() {
|
||||
const merged = [...unref(bizFields), ...unref(detailBizFields)];
|
||||
const merged = [...unref(bizFields)];
|
||||
for (const k in detailBizFieldsMap) {
|
||||
merged.push(...(detailBizFieldsMap[k] || []));
|
||||
}
|
||||
const set = new Map(merged.map((f) => [f.fieldKey, f.fieldKey]));
|
||||
for (const row of unref(mappingRows)) {
|
||||
if (set.has(row.templateField)) {
|
||||
@@ -676,8 +777,7 @@
|
||||
bizFields.value = [];
|
||||
mappingRows.value = [];
|
||||
detailSlots.value = [];
|
||||
selectedDetailProperty.value = undefined;
|
||||
detailBizFields.value = [];
|
||||
resetDetailTableUiState();
|
||||
previewBizJson.value = '';
|
||||
previewResult.value = '';
|
||||
openModal(true);
|
||||
@@ -709,8 +809,7 @@
|
||||
mappingRows.value = [];
|
||||
bizFields.value = [];
|
||||
detailSlots.value = [];
|
||||
selectedDetailProperty.value = undefined;
|
||||
detailBizFields.value = [];
|
||||
resetDetailTableUiState();
|
||||
openModal(true);
|
||||
modalDataLoading.value = true;
|
||||
try {
|
||||
@@ -853,6 +952,14 @@
|
||||
border-top: 1px dashed #f0f0f0;
|
||||
}
|
||||
|
||||
.bind-detail-tabs {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.bind-detail-tabs :deep(.ant-tabs-nav) {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.bind-section-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defHttp } from '/@/utils/http/axios';
|
||||
|
||||
enum Api {
|
||||
list = '/xslmes/mesXslRawMaterialSummary/list',
|
||||
exportXls = '/xslmes/mesXslRawMaterialSummary/exportXls',
|
||||
}
|
||||
|
||||
export const getExportUrl = Api.exportXls;
|
||||
|
||||
export const list = (params) => defHttp.get({ url: Api.list, params });
|
||||
@@ -0,0 +1,23 @@
|
||||
import { BasicColumn, FormSchema } from '/@/components/Table';
|
||||
|
||||
export const columns: BasicColumn[] = [
|
||||
{ title: '所在仓库', align: 'center', dataIndex: 'warehouseName', width: 180 },
|
||||
{ title: '物料名称', align: 'center', dataIndex: 'materialName', width: 180, ellipsis: true },
|
||||
{ title: '物料编码', align: 'center', dataIndex: 'materialCode', width: 180 },
|
||||
{ title: '总包数', align: 'center', dataIndex: 'totalPackages', width: 140 },
|
||||
{ title: '总重量', align: 'center', dataIndex: 'totalWeight', width: 140 },
|
||||
];
|
||||
|
||||
export const searchFormSchema: FormSchema[] = [
|
||||
{ label: '所在仓库', field: 'warehouseName', component: 'JInput', colProps: { span: 6 } },
|
||||
{ label: '物料名称', field: 'materialName', component: 'JInput', colProps: { span: 6 } },
|
||||
{ label: '物料编码', field: 'materialCode', component: 'JInput', colProps: { span: 6 } },
|
||||
];
|
||||
|
||||
export const superQuerySchema = {
|
||||
warehouseName: { title: '所在仓库', order: 0, view: 'text' },
|
||||
materialName: { title: '物料名称', order: 1, view: 'text' },
|
||||
materialCode: { title: '物料编码', order: 2, view: 'text' },
|
||||
totalPackages: { title: '总包数', order: 3, view: 'number' },
|
||||
totalWeight: { title: '总重量', order: 4, view: 'number' },
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
<template>
|
||||
<div>
|
||||
<BasicTable @register="registerTable">
|
||||
<template #tableTitle>
|
||||
<a-button type="primary" v-auth="'xslmes:mes_xsl_raw_material_summary:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls">
|
||||
导出
|
||||
</a-button>
|
||||
<super-query :config="superQueryConfig" @search="handleSuperQuery" />
|
||||
</template>
|
||||
</BasicTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" name="xslmes-mesXslRawMaterialSummary" setup>
|
||||
import { reactive } from 'vue';
|
||||
import { BasicTable } from '/@/components/Table';
|
||||
import { useListPage } from '/@/hooks/system/useListPage';
|
||||
import { columns, searchFormSchema, superQuerySchema } from './MesXslRawMaterialSummary.data';
|
||||
import { list, getExportUrl } from './MesXslRawMaterialSummary.api';
|
||||
|
||||
const queryParam = reactive<any>({});
|
||||
|
||||
const { tableContext, onExportXls } = useListPage({
|
||||
tableProps: {
|
||||
title: '原材料汇总',
|
||||
api: list,
|
||||
columns,
|
||||
canResize: true,
|
||||
formConfig: {
|
||||
schemas: searchFormSchema,
|
||||
autoSubmitOnEnter: true,
|
||||
showAdvancedButton: true,
|
||||
},
|
||||
beforeFetch: (params) => {
|
||||
return Object.assign(params, queryParam);
|
||||
},
|
||||
},
|
||||
exportConfig: {
|
||||
name: '原材料汇总',
|
||||
url: getExportUrl,
|
||||
params: queryParam,
|
||||
},
|
||||
});
|
||||
|
||||
const [registerTable, { reload }] = tableContext;
|
||||
const superQueryConfig = reactive(superQuerySchema);
|
||||
|
||||
function handleSuperQuery(params) {
|
||||
Object.keys(params).forEach((k) => {
|
||||
queryParam[k] = params[k];
|
||||
});
|
||||
reload();
|
||||
}
|
||||
</script>
|
||||
BIN
yy-admin-master/YY.Admin-Release-win-x64-publish.zip
Normal file
@@ -10,6 +10,7 @@ using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Linq.Dynamic.Core;
|
||||
using System.Reflection;
|
||||
@@ -19,7 +20,9 @@ using Yitter.IdGenerator;
|
||||
using YY.Admin.Core;
|
||||
using YY.Admin.Core.Extension;
|
||||
using YY.Admin.Core.Option;
|
||||
using YY.Admin.Core.SeedData;
|
||||
using YY.Admin.Core.Session;
|
||||
using YY.Admin.Core.Util;
|
||||
using DbType = SqlSugar.DbType;
|
||||
|
||||
namespace YY.Admin.Core.SqlSugar
|
||||
@@ -160,6 +163,12 @@ namespace YY.Admin.Core.SqlSugar
|
||||
config.ConnectionString = CryptogramUtil.Decrypt(config.ConnectionString);
|
||||
}
|
||||
|
||||
// SQLite 相对路径默认依赖进程工作目录;快捷方式/从不同目录启动会在别处生成空库,表现为发布后菜单全空
|
||||
if (config.DbType == DbType.Sqlite && !string.IsNullOrWhiteSpace(config.ConnectionString))
|
||||
{
|
||||
config.ConnectionString = ResolveSqliteConnectionToAbsolutePath(config.ConnectionString);
|
||||
}
|
||||
|
||||
var configureExternalServices = new ConfigureExternalServices
|
||||
{
|
||||
EntityNameService = (type, entity) => // 处理表
|
||||
@@ -250,6 +259,96 @@ namespace YY.Admin.Core.SqlSugar
|
||||
//if (config.DbSettings.EnableInitView) InitView(dbProvider);
|
||||
// 初始化种子数据
|
||||
if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
|
||||
// 关闭全量种子时首启可能无菜单数据;补一份基准菜单,避免打包版本左侧空白
|
||||
EnsureBaselineSysMenuSeed(db, config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 SQLite 连接串中的相对 DataSource 解析为基于应用程序基目录的绝对路径。
|
||||
/// </summary>
|
||||
private static string ResolveSqliteConnectionToAbsolutePath(string connectionString)
|
||||
{
|
||||
try
|
||||
{
|
||||
var builder = new SqliteConnectionStringBuilder(connectionString);
|
||||
var ds = builder.DataSource;
|
||||
if (string.IsNullOrWhiteSpace(ds))
|
||||
{
|
||||
return connectionString;
|
||||
}
|
||||
|
||||
if (Path.IsPathFullyQualified(ds))
|
||||
{
|
||||
return connectionString;
|
||||
}
|
||||
|
||||
// Program Files 等安装目录对普通用户只读;SQLite 库放到 LocalApplicationData
|
||||
var dataDir = AppWritablePaths.EnsureDirectoryExists(AppWritablePaths.DataDirectory);
|
||||
var fileName = Path.GetFileName(ds.TrimStart('.', '/', '\\'));
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
{
|
||||
fileName = "Admin.NET.db";
|
||||
}
|
||||
|
||||
builder.DataSource = Path.Combine(dataDir, fileName);
|
||||
return builder.ConnectionString;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return connectionString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 未启用 EnableInitSeed 且 sys_menu 为空时,写入 SysMenu 种子,避免发布后界面无功能菜单。
|
||||
/// </summary>
|
||||
private static void EnsureBaselineSysMenuSeed(SqlSugarScope db, DbConnectionConfig config)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (config.SeedSettings.EnableInitSeed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(config.ConfigId.ToString(), SqlSugarConst.MainConfigId, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.DbType != DbType.Sqlite)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var dbProvider = db.GetConnectionScope(config.ConfigId);
|
||||
var menuEntityInfo = dbProvider.EntityMaintenance.GetEntityInfo(typeof(SysMenu));
|
||||
if (!dbProvider.DbMaintenance.IsAnyTable(menuEntityInfo.DbTableName, false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var cnt = dbProvider.Queryable<SysMenu>().ClearFilter().Count();
|
||||
if (cnt > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var seedType = typeof(SysMenuSeedData);
|
||||
var seedData = GetSeedData(seedType)?.ToList();
|
||||
if (seedData == null || seedData.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
AdjustSeedDataIds(seedData, config);
|
||||
var progress = 0;
|
||||
InsertOrUpdateSeedData(dbProvider, seedType, typeof(SysMenu), seedData, config, ref progress, 1);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 启动阶段不因兜底种子失败而阻断
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
38
yy-admin-master/YY.Admin.Core/Util/AppWritablePaths.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System.IO;
|
||||
|
||||
namespace YY.Admin.Core.Util;
|
||||
|
||||
/// <summary>
|
||||
/// 当前用户可写应用数据目录(避免安装在 Program Files 时无写权限)。
|
||||
/// </summary>
|
||||
public static class AppWritablePaths
|
||||
{
|
||||
private static readonly string Root = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"YY.Admin");
|
||||
|
||||
/// <summary>应用私有根目录:%LocalAppData%\YY.Admin</summary>
|
||||
public static string LocalApplicationRoot => Root;
|
||||
|
||||
/// <summary>SQLite 等业务数据库目录。</summary>
|
||||
public static string DataDirectory => Path.Combine(Root, "Data");
|
||||
|
||||
/// <summary>用户覆盖的配置、Jeecg 同步状态等。</summary>
|
||||
public static string ConfigurationDirectory => Path.Combine(Root, "Configuration");
|
||||
|
||||
/// <summary>按账号划分的本地设置(对应 CommonConst.AppSettingsFilePath 前缀)。</summary>
|
||||
public static string AccountSettingsRootDirectory => Path.Combine(Root, "AppSettings");
|
||||
|
||||
/// <summary>
|
||||
/// 创建目录(若不存在)并返回路径。
|
||||
/// </summary>
|
||||
public static string EnsureDirectoryExists(string directoryPath)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(directoryPath))
|
||||
{
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
|
||||
return directoryPath;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using System.Net.Http;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using YY.Admin.Core.Util;
|
||||
|
||||
namespace YY.Admin.Services.Service.Jeecg;
|
||||
|
||||
@@ -226,7 +227,8 @@ public class JeecgLoginLogReportService : IJeecgLoginLogReportService, IClientLo
|
||||
|
||||
private static string GetQueuePath()
|
||||
{
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppSettings", "offline-scada-log-queue.jsonl");
|
||||
var dir = AppWritablePaths.EnsureDirectoryExists(AppWritablePaths.AccountSettingsRootDirectory);
|
||||
return Path.Combine(dir, "offline-scada-log-queue.jsonl");
|
||||
}
|
||||
|
||||
private static void EnsureQueueDir(string path)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using YY.Admin.Core.Util;
|
||||
|
||||
namespace YY.Admin.Services.Service.Jeecg
|
||||
{
|
||||
/// <summary>
|
||||
/// 读写本地 Jeecg 同步状态文件(与 appsettings 同目录下的 Configuration)
|
||||
/// 读写本地 Jeecg 同步状态文件(用户可写目录,避免 Program Files 无写权限)。
|
||||
/// </summary>
|
||||
public class JeecgSyncStateStore
|
||||
{
|
||||
@@ -12,7 +13,7 @@ namespace YY.Admin.Services.Service.Jeecg
|
||||
|
||||
public JeecgSyncStateStore()
|
||||
{
|
||||
var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration");
|
||||
var dir = AppWritablePaths.EnsureDirectoryExists(AppWritablePaths.ConfigurationDirectory);
|
||||
_filePath = Path.Combine(dir, "jeecg-sync-state.json");
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ using Mapster;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using NewLife;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using YY.Admin.Core;
|
||||
using YY.Admin.EventBus;
|
||||
using YY.Admin.Filter;
|
||||
@@ -14,6 +16,7 @@ using YY.Admin.Services.Service.Print;
|
||||
using YY.Admin.Setup;
|
||||
using YY.Admin.ViewModels;
|
||||
using YY.Admin.Views;
|
||||
using YY.Admin.Core.Util;
|
||||
namespace YY.Admin
|
||||
{
|
||||
/// <summary>
|
||||
@@ -24,32 +27,116 @@ namespace YY.Admin
|
||||
private IConfiguration? _configuration;
|
||||
private ILoggerService? _logger;
|
||||
private readonly SyncModule _syncModule = new();
|
||||
|
||||
public App()
|
||||
{
|
||||
DispatcherUnhandledException += OnDispatcherUnhandledException;
|
||||
AppDomain.CurrentDomain.UnhandledException += OnUnhandledDomainException;
|
||||
}
|
||||
|
||||
private static void TryWriteCrashLog(string headline, Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
var dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YY.Admin", "logs");
|
||||
Directory.CreateDirectory(dir);
|
||||
var file = Path.Combine(dir, $"crash-{DateTime.Now:yyyyMMdd-HHmmss}.txt");
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine(headline);
|
||||
sb.AppendLine(ex.ToString());
|
||||
File.WriteAllText(file, sb.ToString(), Encoding.UTF8);
|
||||
MessageBox.Show($"程序异常已写入日志:\n{file}\n\n{ex.Message}", "智能制造MES工控", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
catch
|
||||
{
|
||||
MessageBox.Show($"{headline}\n{ex}", "智能制造MES工控", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
TryWriteCrashLog("UI 线程未处理异常", e.Exception);
|
||||
e.Handled = true;
|
||||
Shutdown(1);
|
||||
}
|
||||
|
||||
private void OnUnhandledDomainException(object? sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
if (e.ExceptionObject is Exception ex)
|
||||
{
|
||||
TryWriteCrashLog("域未处理异常", ex);
|
||||
}
|
||||
|
||||
if (e.IsTerminating)
|
||||
{
|
||||
Environment.Exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
protected override Window CreateShell()
|
||||
{
|
||||
return Container.Resolve<LoginWindow>();
|
||||
}
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
|
||||
// 构建配置
|
||||
_configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(baseDirectory)
|
||||
.AddJsonFile("Configuration/appsettings.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
// 全局配置
|
||||
TypeAdapterConfig.GlobalSettings.Default
|
||||
.IgnoreNullValues(true)
|
||||
.NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);
|
||||
try
|
||||
{
|
||||
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
|
||||
var cfgPath = Path.Combine(baseDirectory, "Configuration", "appsettings.json");
|
||||
if (!File.Exists(cfgPath))
|
||||
{
|
||||
var msg = $"未找到配置文件(请确认与 YY.Admin.exe 同目录存在 Configuration\\appsettings.json):\n{cfgPath}";
|
||||
TryWriteStartupFailure(msg);
|
||||
Shutdown(1);
|
||||
return;
|
||||
}
|
||||
|
||||
// FluentValidation 全局规则级别配置
|
||||
ValidatorOptions.Global.DefaultRuleLevelCascadeMode = CascadeMode.Stop;
|
||||
var userCfgPath = Path.Combine(
|
||||
AppWritablePaths.EnsureDirectoryExists(AppWritablePaths.ConfigurationDirectory),
|
||||
"appsettings.json");
|
||||
|
||||
// Mapster 全局配置
|
||||
#if DEBUG
|
||||
//TypeAdapterConfig.GlobalSettings.RequireExplicitMapping = true;
|
||||
#endif
|
||||
// 构建配置:安装目录默认 + 用户目录覆盖(JeecgIntegration 等可由服务器设置写入)
|
||||
_configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(baseDirectory)
|
||||
.AddJsonFile(Path.Combine("Configuration", "appsettings.json"), optional: false, reloadOnChange: true)
|
||||
.AddJsonFile(userCfgPath, optional: true, reloadOnChange: true)
|
||||
.Build();
|
||||
// 全局配置
|
||||
TypeAdapterConfig.GlobalSettings.Default
|
||||
.IgnoreNullValues(true)
|
||||
.NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);
|
||||
|
||||
base.OnStartup(e);
|
||||
// FluentValidation 全局规则级别配置
|
||||
ValidatorOptions.Global.DefaultRuleLevelCascadeMode = CascadeMode.Stop;
|
||||
|
||||
// Mapster 全局配置
|
||||
#if DEBUG
|
||||
//TypeAdapterConfig.GlobalSettings.RequireExplicitMapping = true;
|
||||
#endif
|
||||
|
||||
base.OnStartup(e);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TryWriteCrashLog("启动阶段异常(配置/框架初始化失败)", ex);
|
||||
Shutdown(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryWriteStartupFailure(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
var dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YY.Admin", "logs");
|
||||
Directory.CreateDirectory(dir);
|
||||
var file = Path.Combine(dir, $"startup-{DateTime.Now:yyyyMMdd-HHmmss}.txt");
|
||||
File.WriteAllText(file, message, Encoding.UTF8);
|
||||
MessageBox.Show($"{message}\n\n已记录:{file}", "智能制造MES工控", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
catch
|
||||
{
|
||||
MessageBox.Show(message, "智能制造MES工控", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
//注册
|
||||
protected override void RegisterTypes(IContainerRegistry containerRegistry)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.IO;
|
||||
using YY.Admin.Core.Util;
|
||||
|
||||
namespace YY.Admin.Helper
|
||||
{
|
||||
@@ -11,6 +12,37 @@ namespace YY.Admin.Helper
|
||||
{
|
||||
private const string DefaultWebSocketPath = "/websocket/scada-sync";
|
||||
|
||||
/// <summary>
|
||||
/// 安装目录随包发布的默认配置(只读)。
|
||||
/// </summary>
|
||||
public static string GetBundledAppSettingsPath()
|
||||
{
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration", "appsettings.json");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用户覆盖配置(可写),仅覆盖 JeecgIntegration 节点时使用。
|
||||
/// </summary>
|
||||
public static string GetUserAppSettingsPath()
|
||||
{
|
||||
var dir = AppWritablePaths.EnsureDirectoryExists(AppWritablePaths.ConfigurationDirectory);
|
||||
return Path.Combine(dir, "appsettings.json");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 兼容旧调用:优先返回用于读取的实际路径(存在用户覆盖则用用户文件)。
|
||||
/// </summary>
|
||||
public static string GetConfigPath()
|
||||
{
|
||||
var user = GetUserAppSettingsPath();
|
||||
if (File.Exists(user))
|
||||
{
|
||||
return user;
|
||||
}
|
||||
|
||||
return GetBundledAppSettingsPath();
|
||||
}
|
||||
|
||||
public class ServerSettingsModel
|
||||
{
|
||||
public string Ip { get; set; } = "127.0.0.1";
|
||||
@@ -25,22 +57,35 @@ namespace YY.Admin.Helper
|
||||
public bool DisconnectConnection { get; set; } = false;
|
||||
}
|
||||
|
||||
public static string GetConfigPath()
|
||||
private static JObject LoadMergedRoot()
|
||||
{
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration", "appsettings.json");
|
||||
var bundledPath = GetBundledAppSettingsPath();
|
||||
if (!File.Exists(bundledPath))
|
||||
{
|
||||
throw new FileNotFoundException("未找到安装目录默认配置文件 appsettings.json", bundledPath);
|
||||
}
|
||||
|
||||
var root = JObject.Parse(File.ReadAllText(bundledPath));
|
||||
var userPath = GetUserAppSettingsPath();
|
||||
if (!File.Exists(userPath))
|
||||
{
|
||||
return root;
|
||||
}
|
||||
|
||||
var userRoot = JObject.Parse(File.ReadAllText(userPath));
|
||||
var userJeecg = userRoot["JeecgIntegration"] as JObject;
|
||||
if (userJeecg != null)
|
||||
{
|
||||
root["JeecgIntegration"] = userJeecg;
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
public static ServerSettingsModel Load()
|
||||
{
|
||||
var model = new ServerSettingsModel();
|
||||
var path = GetConfigPath();
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return model;
|
||||
}
|
||||
|
||||
var content = File.ReadAllText(path);
|
||||
var root = JObject.Parse(content);
|
||||
var root = LoadMergedRoot();
|
||||
var jeecg = root["JeecgIntegration"] as JObject;
|
||||
if (jeecg == null)
|
||||
{
|
||||
@@ -64,14 +109,7 @@ namespace YY.Admin.Helper
|
||||
|
||||
public static void Save(ServerSettingsModel model)
|
||||
{
|
||||
var path = GetConfigPath();
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
throw new FileNotFoundException("未找到配置文件 appsettings.json", path);
|
||||
}
|
||||
|
||||
var content = File.ReadAllText(path);
|
||||
var root = JObject.Parse(content);
|
||||
var root = LoadMergedRoot();
|
||||
var jeecg = root["JeecgIntegration"] as JObject;
|
||||
if (jeecg == null)
|
||||
{
|
||||
@@ -95,7 +133,9 @@ namespace YY.Admin.Helper
|
||||
jeecg["WebSocketPath"] = webSocketPath;
|
||||
jeecg["DisconnectConnection"] = model.DisconnectConnection;
|
||||
|
||||
File.WriteAllText(path, root.ToString(Formatting.Indented));
|
||||
var userPath = GetUserAppSettingsPath();
|
||||
var outRoot = new JObject { ["JeecgIntegration"] = jeecg };
|
||||
File.WriteAllText(userPath, outRoot.ToString(Formatting.Indented));
|
||||
}
|
||||
|
||||
public static string BuildDefaultWebSocketUrl(string baseScheme, string ip, int port, string basePath, string webSocketPath = DefaultWebSocketPath)
|
||||
@@ -106,6 +146,7 @@ namespace YY.Admin.Helper
|
||||
{
|
||||
safeBasePath = "/" + safeBasePath;
|
||||
}
|
||||
|
||||
var safeWsPath = NormalizeWebSocketPath(webSocketPath);
|
||||
return $"{safeScheme}://{ip}:{port}{safeBasePath}{safeWsPath}";
|
||||
}
|
||||
@@ -117,6 +158,7 @@ namespace YY.Admin.Helper
|
||||
{
|
||||
value = "/" + value;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
23
yy-admin-master/YY.Admin/Helper/WebView2UserDataFolder.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using System.IO;
|
||||
using Microsoft.Web.WebView2.Wpf;
|
||||
using YY.Admin.Core.Util;
|
||||
|
||||
namespace YY.Admin.Helper;
|
||||
|
||||
/// <summary>
|
||||
/// WebView2 默认将用户数据目录放在宿主 exe 旁边;安装在 Program Files 时目录只读会导致初始化失败、预览白屏。
|
||||
/// 统一到当前用户 LocalAppData 下的可写路径。
|
||||
/// </summary>
|
||||
public static class WebView2UserDataFolder
|
||||
{
|
||||
/// <summary>
|
||||
/// 为控件创建 CreationProperties(须在首次 EnsureCoreWebView2Async 之前赋值)。
|
||||
/// </summary>
|
||||
/// <param name="subFolder">子目录名,避免不同场景争用同一 profile。</param>
|
||||
public static CoreWebView2CreationProperties CreateCreationProperties(string subFolder)
|
||||
{
|
||||
var folder = AppWritablePaths.EnsureDirectoryExists(
|
||||
Path.Combine(AppWritablePaths.LocalApplicationRoot, "WebView2", subFolder));
|
||||
return new CoreWebView2CreationProperties { UserDataFolder = folder };
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using System.Text;
|
||||
using System.Windows;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.Wpf;
|
||||
using YY.Admin.Core.Util;
|
||||
|
||||
namespace YY.Admin.Infrastructure.Print;
|
||||
|
||||
@@ -42,7 +43,9 @@ public static class HtmlToPdfRenderer
|
||||
{
|
||||
File.WriteAllText(tempHtml, html, Encoding.UTF8);
|
||||
|
||||
var env = await CoreWebView2Environment.CreateAsync();
|
||||
var userData = AppWritablePaths.EnsureDirectoryExists(
|
||||
Path.Combine(AppWritablePaths.LocalApplicationRoot, "WebView2", "HtmlToPdf"));
|
||||
var env = await CoreWebView2Environment.CreateAsync(browserExecutableFolder: null, userDataFolder: userData);
|
||||
var wv = new WebView2();
|
||||
|
||||
win = new Window
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using Prism.Dialogs;
|
||||
using YY.Admin.ViewModels.Control;
|
||||
using YY.Admin.ViewModels.Dialogs;
|
||||
using YY.Admin.Views;
|
||||
@@ -20,6 +20,15 @@ using YY.Admin.Views.Print;
|
||||
|
||||
namespace YY.Admin
|
||||
{
|
||||
/// <summary>
|
||||
/// Prism DialogService 中 <see cref="KnownDialogParameters.WindowName"/> 使用的宿主窗口注册名。
|
||||
/// </summary>
|
||||
public static class DialogWindowNames
|
||||
{
|
||||
/// <summary>标准边框、可调整大小,且不使用 AllowsTransparency(服务器设置等需改 WindowStyle 的对话框)。</summary>
|
||||
public const string ChromeDialogWindow = "ChromeDialogWindow";
|
||||
}
|
||||
|
||||
public static class NavigationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
@@ -35,8 +44,9 @@ namespace YY.Admin
|
||||
containerRegistry.RegisterDialog<ConfirmDialogView, ConfirmDialogViewModel>("ConfirmDialog");
|
||||
containerRegistry.RegisterDialog<ServerSettingsDialogView, ServerSettingsDialogViewModel>("ServerSettingsDialog");
|
||||
|
||||
// 设置对话框样式
|
||||
// 默认透明无边框宿主;需调整 WindowStyle/AllowsTransparency 的对话框改用命名宿主 ChromeDialogWindow
|
||||
containerRegistry.RegisterDialogWindow<DialogWindow>();
|
||||
containerRegistry.RegisterDialogWindow<ChromeDialogWindow>(DialogWindowNames.ChromeDialogWindow);
|
||||
|
||||
// 注册导航
|
||||
containerRegistry.RegisterForNavigation<DashboardView>("DashboardView");
|
||||
@@ -103,6 +113,30 @@ namespace YY.Admin
|
||||
}
|
||||
public IDialogResult? Result { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标准窗口边框宿主:从构造起即 AllowsTransparency=false,避免窗口显示后再切换透明属性引发异常。
|
||||
/// </summary>
|
||||
public class ChromeDialogWindow : Window, IDialogWindow
|
||||
{
|
||||
public ChromeDialogWindow()
|
||||
{
|
||||
AllowsTransparency = false;
|
||||
Background = SystemColors.WindowBrush;
|
||||
WindowStyle = WindowStyle.SingleBorderWindow;
|
||||
ResizeMode = ResizeMode.CanResizeWithGrip;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
// 按内容测量客户区高度;勿将 Window.Height 设为与 UserControl 相同数值,
|
||||
// 否则会与标题栏/边框抢高度导致底部按钮被裁切。
|
||||
SizeToContent = SizeToContent.WidthAndHeight;
|
||||
MinWidth = 520;
|
||||
MinHeight = 360;
|
||||
Title = "对话框";
|
||||
}
|
||||
|
||||
public IDialogResult? Result { get; set; }
|
||||
}
|
||||
|
||||
//public class DialogWindow : Window, IDialogWindow
|
||||
//{
|
||||
// public DialogWindow()
|
||||
|
||||
@@ -11,6 +11,7 @@ using YY.Admin.Core.EventBus;
|
||||
using YY.Admin.Core.Helper;
|
||||
using YY.Admin.Core.Model;
|
||||
using YY.Admin.Core.Session;
|
||||
using YY.Admin.Core.Util;
|
||||
using HcSkinType = HandyControl.Data.SkinType;
|
||||
|
||||
namespace YY.Admin.ViewModels
|
||||
@@ -167,7 +168,10 @@ namespace YY.Admin.ViewModels
|
||||
public static string GetFilePath()
|
||||
{
|
||||
string filePathSuffix = string.Format(CommonConst.AppSettingsFilePath, AppSession.CurrentUser!.Account);
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePathSuffix);
|
||||
var fullPath = Path.Combine(AppWritablePaths.LocalApplicationRoot, filePathSuffix);
|
||||
var dir = Path.GetDirectoryName(fullPath);
|
||||
AppWritablePaths.EnsureDirectoryExists(dir!);
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -2,6 +2,8 @@ using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Net.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Prism.Dialogs;
|
||||
using YY.Admin;
|
||||
using YY.Admin.Core.Helper;
|
||||
using YY.Admin.Core.Session;
|
||||
using YY.Admin.FluentValidation;
|
||||
@@ -291,7 +293,11 @@ namespace YY.Admin.ViewModels
|
||||
|
||||
private void OpenServerSettings()
|
||||
{
|
||||
_dialogService.ShowDialog("ServerSettingsDialog", r =>
|
||||
var parameters = new DialogParameters
|
||||
{
|
||||
{ KnownDialogParameters.WindowName, DialogWindowNames.ChromeDialogWindow },
|
||||
};
|
||||
_dialogService.ShowDialog("ServerSettingsDialog", parameters, r =>
|
||||
{
|
||||
if (r.Result == ButtonResult.OK)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Mapster;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Prism.Dialogs;
|
||||
using Newtonsoft.Json;
|
||||
using SqlSugar;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -9,6 +10,7 @@ using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using YY.Admin;
|
||||
using YY.Admin.Core;
|
||||
using YY.Admin.Core.Const;
|
||||
using YY.Admin.Core.Model;
|
||||
@@ -16,12 +18,12 @@ using YY.Admin.Core.Services;
|
||||
using YY.Admin.Core.Session;
|
||||
using YY.Admin.Core.Util;
|
||||
using YY.Admin.Event;
|
||||
using YY.Admin.Helper;
|
||||
using YY.Admin.Module;
|
||||
using YY.Admin.Services.Service.Auth;
|
||||
using YY.Admin.Services.Service.Jeecg;
|
||||
using YY.Admin.Services.Service.Menu;
|
||||
using YY.Admin.ViewModels.Control;
|
||||
using YY.Admin.Helper;
|
||||
|
||||
namespace YY.Admin.ViewModels
|
||||
{
|
||||
@@ -724,7 +726,11 @@ namespace YY.Admin.ViewModels
|
||||
|
||||
private void OpenServerSettings()
|
||||
{
|
||||
_dialogService.ShowDialog("ServerSettingsDialog", r =>
|
||||
var parameters = new DialogParameters
|
||||
{
|
||||
{ KnownDialogParameters.WindowName, DialogWindowNames.ChromeDialogWindow },
|
||||
};
|
||||
_dialogService.ShowDialog("ServerSettingsDialog", parameters, r =>
|
||||
{
|
||||
if (r.Result == ButtonResult.OK)
|
||||
{
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ctls="clr-namespace:YY.Admin.Core.Controls;assembly=YY.Admin.Core"
|
||||
Width="520" Height="420"
|
||||
Loaded="UserControl_Loaded">
|
||||
MinWidth="520">
|
||||
<Border Background="White" BorderBrush="#f0f0f0" BorderThickness="1" CornerRadius="4">
|
||||
<Grid Margin="0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<!-- Auto:按表单实际高度排列,避免固定窗体高度时中间行被压扁裁切 -->
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Windows.Controls;
|
||||
using System.Windows;
|
||||
|
||||
namespace YY.Admin.Views.Dialogs
|
||||
{
|
||||
@@ -12,22 +11,5 @@ namespace YY.Admin.Views.Dialogs
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void UserControl_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var win = Window.GetWindow(this);
|
||||
if (win == null) return;
|
||||
|
||||
// 必须先关闭 AllowsTransparency,再改 WindowStyle(否则会抛出:
|
||||
// 「当 AllowsTransparency 为 true 时,WindowStyle.None 是唯一有效值」)
|
||||
win.AllowsTransparency = false;
|
||||
win.WindowStyle = WindowStyle.SingleBorderWindow;
|
||||
win.ResizeMode = ResizeMode.CanResizeWithGrip;
|
||||
win.SizeToContent = SizeToContent.Manual;
|
||||
win.MinWidth = 520;
|
||||
win.MinHeight = 420;
|
||||
if (win.Width < 520) win.Width = 520;
|
||||
if (win.Height < 420) win.Height = 420;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Text.RegularExpressions;
|
||||
using System.Windows;
|
||||
using YY.Admin.Core.Entity;
|
||||
using YY.Admin.Core.Services;
|
||||
using YY.Admin.Helper;
|
||||
using YY.Admin.Services.Service.Print;
|
||||
|
||||
namespace YY.Admin.Views.Print;
|
||||
@@ -32,6 +33,8 @@ public partial class PrintPreviewWindow : HandyControl.Controls.Window
|
||||
_printDotService = printDotService;
|
||||
_initialPrinterName = selectedPrinterName;
|
||||
|
||||
WebView.CreationProperties = WebView2UserDataFolder.CreateCreationProperties("PrintPreview");
|
||||
|
||||
TbTemplateName.Text = template.TemplateName ?? "(未命名)";
|
||||
TbTemplateCode.Text = $"编码:{template.TemplateCode} " +
|
||||
$"尺寸:{template.PaperWidthMm ?? 210}×{template.PaperHeightMm ?? 297} mm " +
|
||||
|
||||
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using YY.Admin.Core.Services;
|
||||
using YY.Admin.Helper;
|
||||
using YY.Admin.ViewModels.RawMaterialEntry;
|
||||
|
||||
namespace YY.Admin.Views.RawMaterialEntry;
|
||||
@@ -101,6 +102,7 @@ public partial class RawMaterialCardGenerateConfirmWindow : HandyControl.Control
|
||||
Func<RawMaterialCardGeneratePlanRow, string> previewHtmlBuilder)
|
||||
{
|
||||
InitializeComponent();
|
||||
PreviewWebView.CreationProperties = WebView2UserDataFolder.CreateCreationProperties("RawMaterialCardConfirm");
|
||||
_printDotService = printDotService;
|
||||
_previewHtmlBuilder = previewHtmlBuilder;
|
||||
HeaderText = $"共 {planItems.Count} 张,左侧展示即将生成的原材料卡片,右侧展示业务关联打印模板预览。";
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using YY.Admin.Helper;
|
||||
using YY.Admin.ViewModels.RawMaterialEntry;
|
||||
|
||||
namespace YY.Admin.Views.RawMaterialEntry;
|
||||
@@ -14,6 +15,7 @@ public partial class RawMaterialEntryOperationView : UserControl
|
||||
public RawMaterialEntryOperationView()
|
||||
{
|
||||
InitializeComponent();
|
||||
PrintPreviewWebView.CreationProperties = WebView2UserDataFolder.CreateCreationProperties("RawMaterialEntryPreview");
|
||||
Loaded += OnLoaded;
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
Unloaded += (_, _) => DetachVm();
|
||||
|
||||
@@ -59,6 +59,8 @@
|
||||
<ItemGroup>
|
||||
<Reference Include="HandyControl">
|
||||
<HintPath>..\YY.Admin.Core\libs\HandyControl.dll</HintPath>
|
||||
<!-- 单文件宿主下外部 UI 库需外置,否则易出现 pack:// 资源加载失败(启动即退出) -->
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
@@ -106,10 +108,12 @@
|
||||
</None>
|
||||
<None Update="Updates\version.xml">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<!-- 单文件发布时须外置,否则安装目录无物理文件 -->
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- 主程序 BaseDirectory 需含 Configuration/appsettings.json;带 RuntimeIdentifier 时子项目 None 未必进入主输出 -->
|
||||
<!-- 主程序须携带 Configuration/appsettings.json。.NET 单文件发布时 Linked None 的 ExcludeFromSingleFile 可能仍不落盘,故 Publish 后再强制复制一次 -->
|
||||
<ItemGroup>
|
||||
<None Include="..\YY.Admin.Services\Configuration\appsettings.json">
|
||||
<Link>Configuration\appsettings.json</Link>
|
||||
@@ -117,4 +121,13 @@
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="EnsureAppSettingsJsonInPublishDirectory" AfterTargets="Publish">
|
||||
<PropertyGroup>
|
||||
<_AppSettingsSource>$(MSBuildProjectDirectory)\..\YY.Admin.Services\Configuration\appsettings.json</_AppSettingsSource>
|
||||
</PropertyGroup>
|
||||
<Error Condition="!Exists('$(_AppSettingsSource)')" Text="缺少源文件 $(_AppSettingsSource),无法发布 Configuration\appsettings.json。" />
|
||||
<MakeDir Directories="$(PublishDir)Configuration" />
|
||||
<Copy SourceFiles="$(_AppSettingsSource)" DestinationFiles="$(PublishDir)Configuration\appsettings.json" SkipUnchangedFiles="false" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
||||
78
yy-admin-master/installer/YY.Admin.Setup.iss
Normal file
@@ -0,0 +1,78 @@
|
||||
; Inno Setup 6 安装脚本 — 用法见同目录 build-installer.ps1
|
||||
; 需先安装: https://jrsoftware.org/isdl.php
|
||||
|
||||
#define MyAppName "智能制造MES工控"
|
||||
#define MyAppExeName "YY.Admin.exe"
|
||||
#define MyAppVersion "1.1.0"
|
||||
#define MyPublisher "星数连科技科技有限公司"
|
||||
; 相对本 .iss 文件位置(installer\ 下的上一级为 yy-admin-master)
|
||||
#define PublishRoot "..\YY.Admin\bin\Release\net8.0-windows10.0.19041\win-x64\publish"
|
||||
|
||||
[Setup]
|
||||
AppId={{B7E8F4A2-9C1D-4E6F-8A3B-2D5E9C1F4A7B}
|
||||
AppName={#MyAppName}
|
||||
AppVersion={#MyAppVersion}
|
||||
AppPublisher={#MyPublisher}
|
||||
AppPublisherURL=https://www.example.com/
|
||||
DefaultDirName={autopf}\{#MyPublisher}\{#MyAppName}
|
||||
DefaultGroupName={#MyAppName}
|
||||
AllowNoIcons=yes
|
||||
OutputDir=..\_installer_output
|
||||
OutputBaseFilename=YY.Admin_Setup_{#MyAppVersion}_win-x64
|
||||
Compression=lzma2/max
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
PrivilegesRequired=admin
|
||||
ArchitecturesAllowed=x64compatible
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
MinVersion=10.0.17763
|
||||
DisableProgramGroupPage=no
|
||||
DisableDirPage=no
|
||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||
SetupLogging=yes
|
||||
|
||||
; 向导语言:使用 Inno 自带的 Default.isl(英文)。若本机存在 Languages\ChineseSimplified.isl,
|
||||
; 可改为: Name: "chinesesimp"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
|
||||
[Languages]
|
||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "在桌面创建快捷方式"; GroupDescription: "附加图标:"; Flags: unchecked
|
||||
Name: "installwebview2"; Description: "安装 Microsoft Edge WebView2 运行时(内嵌网页需要;若已安装会自动跳过)"; GroupDescription: "运行环境:"; Flags: checkedonce
|
||||
|
||||
[Files]
|
||||
; 发布目录完整拷贝(含 Configuration、Updates 等)
|
||||
Source: "{#PublishRoot}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||
; WebView2 引导安装包(由 build-installer.ps1 下载到 redist;编译时若无文件可加 Flags skipifsourcedoesntexist)
|
||||
Source: "redist\MicrosoftEdgeWebview2Setup.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall skipifsourcedoesntexist
|
||||
|
||||
[Icons]
|
||||
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}"
|
||||
Name: "{group}\卸载 {#MyAppName}"; Filename: "{uninstallexe}"
|
||||
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; WorkingDir: "{app}"; Tasks: desktopicon
|
||||
|
||||
[Run]
|
||||
Filename: "{tmp}\MicrosoftEdgeWebview2Setup.exe"; Parameters: "/silent /install"; StatusMsg: "正在安装 WebView2 运行时..."; Flags: waituntilterminated; Tasks: installwebview2; Check: ShouldInstallWebView2()
|
||||
|
||||
Filename: "{app}\{#MyAppExeName}"; Description: "启动 {#MyAppName}"; Flags: nowait postinstall skipifsilent
|
||||
|
||||
[Code]
|
||||
|
||||
// 安装包是否携带了 WebView2 引导程序(已释放到临时目录)
|
||||
function WebView2BootstrapInTmp: Boolean;
|
||||
begin
|
||||
Result := FileExists(ExpandConstant('{tmp}\MicrosoftEdgeWebview2Setup.exe'));
|
||||
end;
|
||||
|
||||
// Evergreen WebView2 是否存在(注册表中存在版本号则认为已装)
|
||||
function WebView2RuntimeInstalled: Boolean;
|
||||
var
|
||||
Ver: String;
|
||||
begin
|
||||
Result := RegQueryStringValue(HKLM, 'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv', Ver) and (Trim(Ver) <> '');
|
||||
end;
|
||||
|
||||
function ShouldInstallWebView2: Boolean;
|
||||
begin
|
||||
Result := WebView2BootstrapInTmp and (not WebView2RuntimeInstalled);
|
||||
end;
|
||||
7
yy-admin-master/installer/build-installer.bat
Normal file
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
echo Running build-installer.ps1 ...
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0build-installer.ps1"
|
||||
echo.
|
||||
pause
|
||||
89
yy-admin-master/installer/build-installer.ps1
Normal file
@@ -0,0 +1,89 @@
|
||||
# Release publish + WebView2 bootstrap download + Inno Setup ISCC
|
||||
# Requires Inno Setup 6 (ISCC.exe)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$Csproj = Join-Path $Root 'YY.Admin\YY.Admin.csproj'
|
||||
$PublishRel = 'YY.Admin\bin\Release\net8.0-windows10.0.19041\win-x64\publish'
|
||||
$PublishDir = Join-Path $Root $PublishRel
|
||||
$RedistDir = Join-Path $PSScriptRoot 'redist'
|
||||
$WebView2Exe = Join-Path $RedistDir 'MicrosoftEdgeWebview2Setup.exe'
|
||||
$WebView2Url = 'https://go.microsoft.com/fwlink/p/?LinkId=2124703'
|
||||
|
||||
Write-Host '>>> dotnet publish (Release, win-x64)...'
|
||||
dotnet publish $Csproj -c Release `
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||
-p:EnableCompressionInSingleFile=true `
|
||||
--verbosity minimal
|
||||
|
||||
if (-not (Test-Path $PublishDir)) {
|
||||
throw "Publish output not found: $PublishDir"
|
||||
}
|
||||
|
||||
$cfgPublish = Join-Path $PublishDir 'Configuration\appsettings.json'
|
||||
if (-not (Test-Path $cfgPublish)) {
|
||||
throw "Missing Configuration\appsettings.json under publish (ExcludeFromSingleFile required). Path: $cfgPublish"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $RedistDir | Out-Null
|
||||
if (-not (Test-Path $WebView2Exe)) {
|
||||
Write-Host '>>> Downloading WebView2 Evergreen bootstrapper...'
|
||||
Invoke-WebRequest -Uri $WebView2Url -OutFile $WebView2Exe -UseBasicParsing
|
||||
}
|
||||
|
||||
function Find-InnoCompiler {
|
||||
if ($env:ISCC -and (Test-Path -LiteralPath $env:ISCC)) {
|
||||
return $env:ISCC
|
||||
}
|
||||
if ($env:INNO_SETUP_DIR) {
|
||||
$p = Join-Path $env:INNO_SETUP_DIR.TrimEnd('\') 'ISCC.exe'
|
||||
if (Test-Path -LiteralPath $p) {
|
||||
return $p
|
||||
}
|
||||
}
|
||||
$cmd = Get-Command 'iscc.exe' -ErrorAction SilentlyContinue
|
||||
if ($cmd -and $cmd.Source -and (Test-Path -LiteralPath $cmd.Source)) {
|
||||
return $cmd.Source
|
||||
}
|
||||
$candidates = @(
|
||||
'D:\Inno Setup 6\ISCC.exe'
|
||||
"${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe"
|
||||
"${env:ProgramFiles}\Inno Setup 6\ISCC.exe"
|
||||
"${env:LocalAppData}\Programs\Inno Setup 6\ISCC.exe"
|
||||
)
|
||||
foreach ($c in $candidates) {
|
||||
if ($c -and (Test-Path -LiteralPath $c)) {
|
||||
return $c
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
$iscc = Find-InnoCompiler
|
||||
|
||||
if (-not $iscc) {
|
||||
throw @'
|
||||
ISCC.exe not found.
|
||||
|
||||
1) Install Inno Setup 6: https://jrsoftware.org/isdl.php
|
||||
2) Or set env ISCC to full path of ISCC.exe, e.g.:
|
||||
set ISCC=C:\Program Files (x86)\Inno Setup 6\ISCC.exe
|
||||
3) Or set INNO_SETUP_DIR to the Inno Setup 6 folder.
|
||||
|
||||
Then run this script again.
|
||||
'@
|
||||
}
|
||||
|
||||
Write-Host ">>> Using ISCC: $iscc"
|
||||
|
||||
$iss = Join-Path $PSScriptRoot 'YY.Admin.Setup.iss'
|
||||
Write-Host '>>> Compiling installer (working dir: installer)...'
|
||||
Push-Location $PSScriptRoot
|
||||
try {
|
||||
& $iscc "`"$iss`""
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$outDir = Join-Path $Root '_installer_output'
|
||||
Write-Host ">>> Done. Output folder: $outDir"
|
||||
2
yy-admin-master/installer/redist/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# WebView2 Evergreen 引导程序由 build-installer.ps1 自动下载,不必提交仓库
|
||||
MicrosoftEdgeWebview2Setup.exe
|
||||