Files
mp-java/src/main/java/com/gxwebsoft/credit/controller/CreditHistoricalLegalPersonController.java
gxwebsoft 409a078e2d feat(batch-import): 批量导入功能支持企业名称回填
- 在 BatchImportSupport 中新增 refreshCompanyIdByCompanyName 方法用于按企业名称匹配并回填 companyId 和 companyName
- 在 CreditAdministrativeLicenseController、CreditBranchController、CreditHistoricalLegalPersonController、CreditNearbyCompanyController 和 CreditSuspectedRelationshipController 中添加公司名称回填逻辑
- 修改实体类中 companyName 字段的 TableField 注解从 exist=false 改为 company_name
- 更新各个 Mapper XML 文件中的查询 SQL,使用 COALESCE 函数确保当关联企业名称为空时使用本地存储的公司名称
- 在批量导入过程中增加固定公司名称的获取和设置逻辑
2026-02-25 12:59:50 +08:00

377 lines
16 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.gxwebsoft.credit.controller;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.credit.entity.CreditCompany;
import com.gxwebsoft.credit.entity.CreditHistoricalLegalPerson;
import com.gxwebsoft.credit.param.CreditHistoricalLegalPersonImportParam;
import com.gxwebsoft.credit.param.CreditHistoricalLegalPersonParam;
import com.gxwebsoft.credit.service.CreditCompanyService;
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
import com.gxwebsoft.credit.service.CreditHistoricalLegalPersonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 历史法定代表人控制器
*
* @author 科技小王子
* @since 2026-01-07 13:52:14
*/
@Tag(name = "历史法定代表人管理")
@RestController
@RequestMapping("/api/credit/credit-historical-legal-person")
public class CreditHistoricalLegalPersonController extends BaseController {
@Resource
private CreditHistoricalLegalPersonService creditHistoricalLegalPersonService;
@Resource
private BatchImportSupport batchImportSupport;
@Resource
private CreditCompanyService creditCompanyService;
@Resource
private CreditCompanyRecordCountService creditCompanyRecordCountService;
@Operation(summary = "分页查询历史法定代表人")
@GetMapping("/page")
public ApiResult<PageResult<CreditHistoricalLegalPerson>> page(CreditHistoricalLegalPersonParam param) {
// 使用关联查询
return success(creditHistoricalLegalPersonService.pageRel(param));
}
@Operation(summary = "查询全部历史法定代表人")
@GetMapping()
public ApiResult<List<CreditHistoricalLegalPerson>> list(CreditHistoricalLegalPersonParam param) {
// 使用关联查询
return success(creditHistoricalLegalPersonService.listRel(param));
}
@Operation(summary = "根据id查询历史法定代表人")
@GetMapping("/{id}")
public ApiResult<CreditHistoricalLegalPerson> get(@PathVariable("id") Integer id) {
// 使用关联查询
return success(creditHistoricalLegalPersonService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:save')")
@OperationLog
@Operation(summary = "添加历史法定代表人")
@PostMapping()
public ApiResult<?> save(@RequestBody CreditHistoricalLegalPerson creditHistoricalLegalPerson) {
// 记录当前登录用户id
// User loginUser = getLoginUser();
// if (loginUser != null) {
// creditHistoricalLegalPerson.setUserId(loginUser.getUserId());
// }
if (creditHistoricalLegalPersonService.save(creditHistoricalLegalPerson)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:update')")
@OperationLog
@Operation(summary = "修改历史法定代表人")
@PutMapping()
public ApiResult<?> update(@RequestBody CreditHistoricalLegalPerson creditHistoricalLegalPerson) {
if (creditHistoricalLegalPersonService.updateById(creditHistoricalLegalPerson)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:remove')")
@OperationLog
@Operation(summary = "删除历史法定代表人")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (batchImportSupport.hardRemoveById(CreditHistoricalLegalPerson.class, id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:save')")
@OperationLog
@Operation(summary = "批量添加历史法定代表人")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<CreditHistoricalLegalPerson> list) {
if (creditHistoricalLegalPersonService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:update')")
@OperationLog
@Operation(summary = "批量修改历史法定代表人")
@PutMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody BatchParam<CreditHistoricalLegalPerson> batchParam) {
if (batchParam.update(creditHistoricalLegalPersonService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:remove')")
@OperationLog
@Operation(summary = "批量删除历史法定代表人")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (batchImportSupport.hardRemoveByIds(CreditHistoricalLegalPerson.class, ids)) {
return success("删除成功");
}
return fail("删除失败");
}
/**
* 根据企业名称匹配企业并更新 companyId匹配 CreditCompany.name / CreditCompany.matchName
*
* <p>默认仅更新 companyId=0 的记录;如需覆盖更新,传 onlyNull=false。</p>
*/
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:update')")
@OperationLog
@Operation(summary = "根据企业名称匹配并更新companyId")
@PostMapping("/company-id/refresh")
public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
@RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
@RequestParam(value = "limit", required = false) Integer limit
) {
User loginUser = getLoginUser();
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
creditHistoricalLegalPersonService,
creditCompanyService,
currentTenantId,
onlyNull,
limit,
CreditHistoricalLegalPerson::getId,
CreditHistoricalLegalPerson::setId,
CreditHistoricalLegalPerson::getName,
CreditHistoricalLegalPerson::getCompanyId,
CreditHistoricalLegalPerson::setCompanyId,
CreditHistoricalLegalPerson::setCompanyName,
CreditHistoricalLegalPerson::getHasData,
CreditHistoricalLegalPerson::setHasData,
CreditHistoricalLegalPerson::getTenantId,
CreditHistoricalLegalPerson::new
);
if (!stats.anyDataRead) {
return success("无可更新数据", stats.toMap());
}
return success("更新完成,更新" + stats.updated + "", stats.toMap());
}
/**
* 批量导入历史法定代表人
*/
@PreAuthorize("hasAuthority('credit:creditHistoricalLegalPerson:save')")
@Operation(summary = "批量导入历史法定代表人")
@PostMapping("/import")
public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
@RequestParam(value = "companyId", required = false) Integer companyId) {
List<String> errorMessages = new ArrayList<>();
int successCount = 0;
Set<Integer> touchedCompanyIds = new HashSet<>();
try {
ExcelImportSupport.ImportResult<CreditHistoricalLegalPersonImportParam> importResult = ExcelImportSupport.readAnySheet(
file, CreditHistoricalLegalPersonImportParam.class, this::isEmptyImportRow);
List<CreditHistoricalLegalPersonImportParam> list = importResult.getData();
int usedTitleRows = importResult.getTitleRows();
int usedHeadRows = importResult.getHeadRows();
int usedSheetIndex = importResult.getSheetIndex();
if (CollectionUtils.isEmpty(list)) {
return fail("未读取到数据,请确认模板表头与示例格式一致", null);
}
User loginUser = getLoginUser();
Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "名称");
String fixedCompanyName = null;
if (companyId != null && companyId > 0) {
CreditCompany fixedCompany = creditCompanyService.getById(companyId);
fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
}
final int chunkSize = 500;
final int mpBatchSize = 500;
List<CreditHistoricalLegalPerson> chunkItems = new ArrayList<>(chunkSize);
List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);
for (int i = 0; i < list.size(); i++) {
CreditHistoricalLegalPersonImportParam param = list.get(i);
try {
CreditHistoricalLegalPerson item = convertImportParamToEntity(param);
if (!ImportHelper.isBlank(item.getName())) {
String link = urlByName.get(item.getName().trim());
if (link != null && !link.isEmpty()) {
item.setUrl(link);
}
}
if (item.getCompanyId() == null && companyId != null) {
item.setCompanyId(companyId);
if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
item.setCompanyName(fixedCompanyName);
}
}
if (item.getUserId() == null && currentUserId != null) {
item.setUserId(currentUserId);
}
if (item.getTenantId() == null && currentTenantId != null) {
item.setTenantId(currentTenantId);
}
if (item.getStatus() == null) {
item.setStatus(0);
}
if (item.getRecommend() == null) {
item.setRecommend(0);
}
if (item.getDeleted() == null) {
item.setDeleted(0);
}
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
if (ImportHelper.isBlank(item.getName())) {
errorMessages.add("" + excelRowNumber + "行:名称不能为空");
continue;
}
if (item.getCompanyId() != null && item.getCompanyId() > 0) {
touchedCompanyIds.add(item.getCompanyId());
}
chunkItems.add(item);
chunkRowNumbers.add(excelRowNumber);
if (chunkItems.size() >= chunkSize) {
successCount += batchImportSupport.persistInsertOnlyChunk(
creditHistoricalLegalPersonService,
chunkItems,
chunkRowNumbers,
mpBatchSize,
CreditHistoricalLegalPerson::getName,
"",
errorMessages
);
chunkItems.clear();
chunkRowNumbers.clear();
}
} catch (Exception e) {
int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
errorMessages.add("" + excelRowNumber + "行:" + e.getMessage());
e.printStackTrace();
}
}
if (!chunkItems.isEmpty()) {
successCount += batchImportSupport.persistInsertOnlyChunk(
creditHistoricalLegalPersonService,
chunkItems,
chunkRowNumbers,
mpBatchSize,
CreditHistoricalLegalPerson::getName,
"",
errorMessages
);
}
creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.HISTORICAL_LEGAL_PERSON, touchedCompanyIds);
if (errorMessages.isEmpty()) {
return success("成功导入" + successCount + "条数据", null);
} else {
return success("导入完成,成功" + successCount + "条,失败" + errorMessages.size() + "", errorMessages);
}
} catch (Exception e) {
e.printStackTrace();
return fail("导入失败:" + e.getMessage(), null);
}
}
/**
* 下载历史法定代表人导入模板
*/
@Operation(summary = "下载历史法定代表人导入模板")
@GetMapping("/import/template")
public void downloadTemplate(HttpServletResponse response) throws IOException {
List<CreditHistoricalLegalPersonImportParam> templateList = new ArrayList<>();
CreditHistoricalLegalPersonImportParam example = new CreditHistoricalLegalPersonImportParam();
example.setName("张三");
example.setRegisterDate("2020-01-01");
example.setPublicDate("2023-06-01");
example.setComments("备注信息");
templateList.add(example);
Workbook workbook = ExcelImportSupport.buildTemplate("历史法定代表人导入模板", "历史法定代表人", CreditHistoricalLegalPersonImportParam.class, templateList);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=credit_historical_legal_person_import_template.xlsx");
workbook.write(response.getOutputStream());
workbook.close();
}
private boolean isEmptyImportRow(CreditHistoricalLegalPersonImportParam param) {
if (param == null) {
return true;
}
if (isImportHeaderRow(param)) {
return true;
}
return ImportHelper.isBlank(param.getName())
&& ImportHelper.isBlank(param.getRegisterDate())
&& ImportHelper.isBlank(param.getPublicDate());
}
private boolean isImportHeaderRow(CreditHistoricalLegalPersonImportParam param) {
return isHeaderValue(param.getName(), "名称")
|| isHeaderValue(param.getRegisterDate(), "任职日期")
|| isHeaderValue(param.getPublicDate(), "卸任日期");
}
private static boolean isHeaderValue(String value, String headerText) {
if (value == null) {
return false;
}
return headerText.equals(value.trim());
}
private CreditHistoricalLegalPerson convertImportParamToEntity(CreditHistoricalLegalPersonImportParam param) {
CreditHistoricalLegalPerson entity = new CreditHistoricalLegalPerson();
entity.setName(param.getName());
entity.setRegisterDate(param.getRegisterDate());
entity.setPublicDate(param.getPublicDate());
entity.setComments(param.getComments());
return entity;
}
}