合同登记上传附件0.1

This commit is contained in:
李靖 2024-05-30 10:53:24 +08:00
parent e9f23a4847
commit 799d538d55
2 changed files with 346 additions and 0 deletions

View File

@ -0,0 +1,53 @@
package shkd.fi.em.plugin;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.IOperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.mvc.list.ListView;
import kd.sdk.plugin.Plugin;
import java.util.List;
import java.util.stream.Collectors;
/**
* 标准单据列表插件
*/
public class ContractBillExtList extends AbstractListPlugin implements Plugin {
public void afterDoOperation(AfterDoOperationEventArgs e) {
super.afterDoOperation(e);
String key = e.getOperateKey();
IOperationResult result = e.getOperationResult();
IDataModel dataModel = this.getModel();
ListView listView = (ListView)this.getView();
ListSelectedRowCollection selectedRowCollection = listView.getSelectedRows();
List<Object> pks = (List)selectedRowCollection.stream().map(ListSelectedRow::getPrimaryKeyValue).collect(Collectors.toList());
switch (key) {
case "popup":
if (result.isSuccess()) {
if (pks.size() != 1) {
this.getView().showTipNotification("请选择一行数据进行归档附件上传操作。");
return;
}
FormShowParameter parameter = new FormShowParameter();
Object pkValue = pks.get(0);
parameter.setCustomParam("pkid", pkValue);
parameter.setFormId("shkd_er_contractbill_pop");
parameter.getOpenStyle().setShowType(ShowType.Modal);
this.getView().showForm(parameter);
}
break;
}
}
public void beforeDoOperation(BeforeDoOperationEventArgs args) {
}
}

View File

@ -0,0 +1,293 @@
package shkd.fi.em.plugin;
import com.alibaba.excel.util.StringUtils;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.*;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.Label;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeClosedEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.attachment.AttachmentFieldServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.CollectionUtils;
import kd.bos.util.FileNameUtils;
import kd.sdk.plugin.Plugin;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* 员工借款单借款单表单插件
*/
public class ContractBillPopFormPlugin extends AbstractFormPlugin implements Plugin {
private static final Log log = LogFactory.getLog(ContractBillPopFormPlugin.class);
public static final String ATTACH_KEY = "shkd_attachmentpanelap"; // 动态表单的附件面板标识 - 根据情况修改
@Override
public void afterDoOperation(AfterDoOperationEventArgs args) {
if (this.hasAttachmentUploading()) {
this.getView().showTipNotification("附件上传中,请稍后再试。");
return;
}
String operateKey = args.getOperateKey();
if ("upload".equals(operateKey)) {
List<DynamicObject> timeOutAttList = AttachmentFieldServiceHelper.getTimeOutAttList(this.getView().getPageId());
if (!CollectionUtils.isEmpty(timeOutAttList)) {
// ResManager.LoadKDString("临时附件已超时,请重新上传以下文件:\r\n", "UploadAtt2BillsFormPlugin_2")
StringBuilder timeoutMessage = new StringBuilder("临时附件已超时,请重新上传文件");
for (DynamicObject attDynamicObj : timeOutAttList) {
timeoutMessage.append(attDynamicObj.getLocaleString("name").getLocaleValue()).append("\r\n");
}
this.getView().showConfirm(timeoutMessage.toString(), MessageBoxOptions.OK);
return;
}
this.doUpload();
} else if ("clean".equals(operateKey)) {
AttachmentPanel attachmentPanel = getControl(ATTACH_KEY);
List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
if (attachmentData.size() > 0) {
// ResManager.LoadKDString("是否清空当前附件面板?", "UploadAtt2BillsFormPlugin_3"),
// MessageBoxOptions.YesNo, new ConfirmCallBackListener("clean_callback", this)
this.getView().showConfirm("是否清空当前附件面板?",
MessageBoxOptions.YesNo, new ConfirmCallBackListener("clean_callback", this));
} else {
// ResManager.LoadKDString("附件面板已清空!", "UploadAtt2BillsFormPlugin_4")
this.getView().showTipNotification("附件面板已清空!");
}
}
}
private boolean hasAttachmentUploading() {
IPageCache cache = this.getView().getService(IPageCache.class);
String uploadingAttJson = cache.get("UploadingAtt" + this.getView().getPageId());
return StringUtils.isNotBlank(uploadingAttJson);
}
private void doUpload() {
String entityNumber = "er_contractbill";//当前单据实体编码
String attKey = "zc88_attachmentpanelap"; // 单据面板标识 attachmentpanel
AttachmentPanel attachmentPanel = getControl(ATTACH_KEY);
List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
if (attachmentData.size() == 0) {
// ResManager.LoadKDString("请先上传文件。", "UploadAtt2BillsFormPlugin_8")
this.getView().showTipNotification("请先上传文件。");
return;
}
FormShowParameter showParameter = this.getView().getFormShowParameter();
Object pkidobj = showParameter.getCustomParam("pkid");
if (pkidobj == null) {
// todo: 表单直接预览
this.getView().showTipNotification("pkid is blank !");
return;
}
boolean hasAttachmentDataUploadedErr = false, hasFormDataErr = false;
ORM orm = ORM.create();
List<Object> formDataErr = new ArrayList<Object>();
List<DynamicObject> attBillRelList = new ArrayList<>();
List<Map<String, Object>> attachmentDataUploaded = new ArrayList<>();
for (Map<String, Object> attachment : attachmentData) {
String path = this.uploadFileServer(attachment);
if (StringUtils.isBlank(path)) {
hasAttachmentDataUploadedErr = true;
continue;
}
Map<String, Object> map = new HashMap<>(attachment);
map.put("url", path);
attachmentDataUploaded.add(map);
attBillRelList.clear();
try {
DynamicObjectCollection tempRel =
this.genAttachmentRel(entityNumber, String.valueOf(pkidobj), attKey, attachmentDataUploaded, orm);
attBillRelList.addAll(tempRel);
} catch (Exception e) {
hasFormDataErr = true;
log.error(e.getMessage());
formDataErr.add(pkidobj);
}
if (formDataErr.isEmpty()) {
// 删除面板附件及临时文件
attachmentPanel.remove(attachment);
} else {
log.error(String.format("附件[%s]%s条单据绑定附件数据失败\r\n%s", attachment, 1, 1));
formDataErr.clear();
}
attachmentDataUploaded.clear();
SaveServiceHelper.save(attBillRelList.toArray(new DynamicObject[0]));
}
if (!hasAttachmentDataUploadedErr && !hasFormDataErr) {
// ResManager.LoadKDString("上传成功!", "UploadAtt2BillsFormPlugin_5")
// MessageBoxLink
this.getView().showConfirm("上传成功!", MessageBoxOptions.OK,
new ConfirmCallBackListener("upload_success", this));
// this.getView().showSuccessNotification("上传成功!");
} else if (hasAttachmentDataUploadedErr && !hasFormDataErr) {
// ResManager.LoadKDString("以下附件上传失败,请重新上传文件!", "UploadAtt2BillsFormPlugin_6")
this.getView().showTipNotification("以下附件上传失败,请重新上传文件!");
} else {
// ResManager.LoadKDString("附件上传出现未知异常,请联系管理员查询日志分析!", "UploadAtt2BillsFormPlugin_7")
this.getView().showErrorNotification("附件上传出现未知异常,请联系管理员查询日志分析!");
}
}
/**
* 保存临时文件到文件服务器进行持久化
* @see AttachmentServiceHelper#saveTempToFileService
* @param attDataItem 已上传的附件临时文件Map信息
* @return 上传文件服务器返回url
*/
private String uploadFileServer(Map<String, Object> attDataItem) {
try{
FileService fs = FileServiceFactory.getAttachmentFileService();
RequestContext requestContext = RequestContext.get();
TempFileCache fileCache = CacheFactory.getCommonCacheFactory().getTempFileCache();
String filename = (String) attDataItem.get("name");
String tempUrl = (String) attDataItem.get("url");
String uuid = UUID.randomUUID().toString().replace("-", "");
String filepath = FileNameUtils.getAttachmentFileName( // 此处 attachmentpanel 用于文件路径的唯一标识
requestContext.getTenantId(), requestContext.getAccountId(), "attachmentpanel", uuid + "/" + filename);
InputStream inputStream = fileCache.getInputStream(tempUrl);
FileItem item = new FileItem(filename, filepath, inputStream);
String[] splits = filename.trim().split("\\.");
String fileType = splits[splits.length - 1];
long compressPicSize = 0L;
int fileSize = inputStream.available() / 1024;
if ("jpg,jpeg,png,gif,bmp,tiff,tga,ico,dib,rle,emf,jpe,jfif,pcx,dcx,pic,tif,wmf".contains(fileType.toLowerCase())) {
compressPicSize = AttachmentServiceHelper.getCompressPicSize();
}
if (compressPicSize != 0L && fileSize > compressPicSize) {
return fs.compressPicUpload(item, compressPicSize);
} else {
return fs.upload(item);
}
} catch (Exception e){
log.error("uploadFileServer err: " + e.getMessage());
return null;
}
}
/**
* 绑定附件到单据的附件面板
* @see AttachmentServiceHelper#upload
* @param entityNumber 实体编码
* @param billPkId 单据主键
* @param attList 附件信息
* @param orm orm实例
* @return 附件面板实体数据用于入库记录
*/
private DynamicObjectCollection genAttachmentRel(String entityNumber, String billPkId, String attachKey, List<Map<String, Object>> attList, ORM orm){
DynamicObjectType entityType = (DynamicObjectType)orm.getDataEntityType("bos_attachment");
DynamicObjectCollection dynColl = new DynamicObjectCollection(entityType, null);
if (attList == null || attList.size() == 0) {
return dynColl;
}
long[] ids = orm.genLongIds(entityType, attList.size());
Date today = new Date();
for(int i = 0; i < attList.size(); i++) {
Map<String, Object> attach = attList.get(i);
DynamicObject dynamicObject = new DynamicObject(entityType);
dynamicObject.set("id", ids[i]);
dynamicObject.set("FNUMBER", attach.get("uid"));
dynamicObject.set("FBillType", entityNumber);
dynamicObject.set("FInterID", billPkId);
Object lastModified = attach.get("lastModified");
if (lastModified instanceof Date) {
dynamicObject.set("FModifyTime", lastModified);
} else if (lastModified instanceof Long) {
dynamicObject.set("FModifyTime", new Date((Long)lastModified));
} else {
dynamicObject.set("FModifyTime", today);
}
dynamicObject.set("fcreatetime", attach.getOrDefault("uploadTime", today));
String name = (String)attach.get("name");
dynamicObject.set("FaliasFileName", name);
dynamicObject.set("FAttachmentName", name);
String extName = name != null ? name.substring(name.lastIndexOf(46) + 1) : "";
dynamicObject.set("FExtName", extName);
long compressPicSize = AttachmentServiceHelper.getCompressPicSize();
if ("jpg,jpeg,png,gif,bmp,tiff,tga,ico,dib,rle,emf,jpe,jfif,pcx,dcx,pic,tif,wmf".contains(extName.toLowerCase()) && compressPicSize != 0L && Long.parseLong(attach.get("size").toString()) > compressPicSize * 1024L) {
dynamicObject.set("FATTACHMENTSIZE", compressPicSize * 1024L);
} else {
dynamicObject.set("FATTACHMENTSIZE", attach.get("size"));
}
dynamicObject.set("FFileId", attach.get("url"));
dynamicObject.set("FCREATEMEN", RequestContext.get().getCurrUserId());
dynamicObject.set("fattachmentpanel", attachKey);
dynamicObject.set("filesource", attach.get("filesource"));
if (attach.containsKey("description")) {
dynamicObject.set("fdescription", attach.get("description"));
}
dynColl.add(dynamicObject);
}
return dynColl;
}
@Override
public void beforeClosed(BeforeClosedEvent e) {
super.beforeClosed(e);
AttachmentPanel attachmentPanel = getControl(ATTACH_KEY);
List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
if (attachmentData.size() > 0) {
e.setCancel(true);
// ResManager.LoadKDString("是否放弃已上传的附件?", "UploadAtt2BillsFormPlugin_0")
this.getView().showConfirm("是否放弃已上传的附件?",
MessageBoxOptions.YesNo, new ConfirmCallBackListener("cancel_callback", this));
}
}
@Override
public void confirmCallBack(MessageBoxClosedEvent evt) {
switch(evt.getCallBackId()){
case "cancel_callback":
if (MessageBoxResult.Yes.equals(evt.getResult())) {
this.cleanAllAttach();
this.getView().close();
}
break;
case "clean_callback":
if (MessageBoxResult.Yes.equals(evt.getResult())) {
this.cleanAllAttach();
}
break;
case "upload_success":
if (MessageBoxResult.Cancel.equals(evt.getResult())) {
this.getView().close();
}
break;
}
}
private void cleanAllAttach() {
AttachmentPanel attachmentPanel = getControl(ATTACH_KEY);
List<Map<String, Object>> attachmentData = attachmentPanel.getAttachmentData();
for (Map<String, Object> data : attachmentData) {
attachmentPanel.remove(data);
}
}
}