zhou zhou
7 天以前 34d36a15f339d331d668d4063cfdff50cffa5800
rsf-server/src/main/java/com/vincent/rsf/server/manager/controller/LocController.java
@@ -1,35 +1,43 @@
package com.vincent.rsf.server.manager.controller;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vincent.rsf.framework.common.Cools;
import com.vincent.rsf.framework.common.R;
import com.vincent.rsf.framework.exception.CoolException;
import com.vincent.rsf.server.common.utils.ExcelUtil;
import com.vincent.rsf.server.common.annotation.OperationLog;
import com.vincent.rsf.server.common.domain.BaseParam;
import com.vincent.rsf.server.common.domain.KeyValVo;
import com.vincent.rsf.server.common.domain.PageParam;
import com.vincent.rsf.server.common.service.AsyncListExportTaskService;
import com.vincent.rsf.server.common.service.ListExportHandler;
import com.vincent.rsf.server.common.service.ListExportService;
import com.vincent.rsf.server.common.utils.ExcelUtil;
import com.vincent.rsf.server.common.utils.FileServerUtil;
import com.vincent.rsf.server.common.utils.OptimisticLockUtils;
import com.vincent.rsf.server.manager.controller.params.LocMastInitParam;
import com.vincent.rsf.server.manager.controller.params.LocModifyParams;
import com.vincent.rsf.server.manager.entity.Loc;
import com.vincent.rsf.server.manager.enums.CommonStatus;
import com.vincent.rsf.server.manager.enums.LocStsType;
import com.vincent.rsf.server.manager.service.LocService;
import com.vincent.rsf.server.manager.utils.buildPageRowsUtils;
import com.vincent.rsf.server.system.controller.BaseController;
import com.vincent.rsf.server.system.entity.ExportTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
@@ -37,52 +45,134 @@
@Api(tags = "库位信息")
@RestController
public class LocController extends BaseController {
    private static final String EXPORT_RESOURCE_KEY = "loc";
    private static final String EXPORT_DEFAULT_REPORT_TITLE = "库位报表";
    @Autowired
    private LocService locService;
    @Autowired
    private ListExportService listExportService;
    @Autowired
    private AsyncListExportTaskService asyncListExportTaskService;
    private final ListExportHandler<Loc, BaseParam> locExportHandler = new ListExportHandler<>() {
        @Override
        public List<Loc> listByIds(List<Long> ids) {
            return locService.listByIds(ids);
        }
        @Override
        public List<Loc> listByFilter(Map<String, Object> sanitizedMap, BaseParam baseParam) {
            PageParam<Loc, BaseParam> pageParam = new PageParam<>(baseParam, Loc.class);
            return locService.list(pageParam.buildWrapper(true, getLocSortedFields()));
        }
        @Override
        public void fillExportFields(List<Loc> records) {
            buildPageRowsUtils.rowsMap(records);
        }
        @Override
        public Map<String, Object> toExportRow(Loc record, List<ExcelUtil.ExportColumn> columns) {
            return buildLocExportRow(record, columns);
        }
        @Override
        public String defaultReportTitle() {
            return EXPORT_DEFAULT_REPORT_TITLE;
        }
    };
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @PostMapping("/loc/page")
    public R page(@RequestBody Map<String, Object> map) {
        BaseParam baseParam = buildParam(map, BaseParam.class);
        PageParam<Loc, BaseParam> pageParam = new PageParam<>(baseParam, Loc.class);
        List<String> list = new ArrayList<>();
        list.add("row");
        list.add("col");
        list.add("lev");
        return R.ok().add(locService.page(pageParam, pageParam.buildWrapper(true,list)));
        PageParam<Loc, BaseParam> page = locService.page(pageParam, pageParam.buildWrapper(true, getLocSortedFields()));
        return R.ok().add(buildPageRowsUtils.rowsMap(page));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @PostMapping("/loc/list")
    public R list(@RequestBody Map<String, Object> map) {
        return R.ok().add(locService.list());
        return R.ok().add(buildPageRowsUtils.rowsMap(locService.list()));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @ApiOperation(("获取库位使用率"))
    @PostMapping("/loc/pie/list")
    public R locPie() {
        return R.ok().add(buildPageRowsUtils.rowsMap(locService.getLocPies()));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @PostMapping("/loc/areaNoUse/list")
    public R areaNoUselist(@RequestBody Map<String, Object> map) {
        String locCode = map.get("locCode").toString();
        Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, locCode),false);
        Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, locCode)
                .last("LIMIT 1"));
        List<Loc> list = locService.list(new LambdaQueryWrapper<Loc>()
                .eq(Loc::getAreaId, loc.getAreaId())
                .eq(Loc::getChannel,loc.getChannel())
//                .eq(!Objects.isNull(loc.getChannel()), Loc::getChannel,loc.getChannel())//
                .eq(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
        );
        List<String> list1 = list.stream().map(obj -> obj.getCode()).collect(Collectors.toList());
        return R.ok(list1);
    }
    /** 同库区空闲库位分页,支持按库位号前缀过滤;用于下拉滚动分页或输入前缀实时加载 */
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @PostMapping("/loc/areaNoUse/page")
    public R areaNoUsePage(@RequestBody Map<String, Object> map) {
        String locCode = (String) map.get("locCode");
        int current = map.get("current") != null ? Integer.parseInt(String.valueOf(map.get("current"))) : 1;
        int pageSize = map.get("pageSize") != null ? Integer.parseInt(String.valueOf(map.get("pageSize"))) : 50;
        if (Cools.isEmpty(locCode)) {
            Page<String> emptyPage = new Page<>(current, pageSize);
            emptyPage.setRecords(Collections.emptyList());
            emptyPage.setTotal(0L);
            return R.ok().add(buildPageRowsUtils.rowsMap(emptyPage));
        }
        Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, locCode).last("LIMIT 1"));
        if (loc == null) {
            Page<String> emptyPage = new Page<>(current, pageSize);
            emptyPage.setRecords(Collections.emptyList());
            emptyPage.setTotal(0L);
            return R.ok().add(buildPageRowsUtils.rowsMap(emptyPage));
        }
        String q = map.get("q") != null ? String.valueOf(map.get("q")).trim() : null;
        if (StringUtils.isBlank(q) && map.get("condition") != null) {
            q = String.valueOf(map.get("condition")).trim();
        }
        LambdaQueryWrapper<Loc> wrapper = new LambdaQueryWrapper<Loc>()
                .select(Loc::getCode)
                .eq(Loc::getAreaId, loc.getAreaId())
                .eq(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                .orderByAsc(Loc::getCode);
        if (StringUtils.isNotBlank(q)) {
            wrapper.likeRight(Loc::getCode, q);
        }
        Page<Loc> page = new Page<>(current, pageSize);
        Page<Loc> result = locService.page(page, wrapper);
        List<String> records = result.getRecords().stream().map(Loc::getCode).collect(Collectors.toList());
        Page<String> pageOut = new Page<>(current, pageSize);
        pageOut.setRecords(records);
        pageOut.setTotal(result.getTotal());
        return R.ok().add(buildPageRowsUtils.rowsMap(pageOut));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @PostMapping({"/loc/many/{ids}", "/locs/many/{ids}"})
    public R many(@PathVariable Long[] ids) {
        return R.ok().add(locService.listByIds(Arrays.asList(ids)));
        return R.ok().add(buildPageRowsUtils.rowsMap(locService.listByIds(Arrays.asList(ids))));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @GetMapping("/loc/{id}")
    public R get(@PathVariable("id") Long id) {
        return R.ok().add(locService.getById(id));
        return R.ok().add(buildPageRowsUtils.rowsMap(locService.getById(id)));
    }
    @PreAuthorize("hasAuthority('manager:loc:save')")
@@ -110,7 +200,7 @@
        if (!locService.saveType(loc)) {
            throw new CoolException("库位类型关联关系保存失败!!");
        }
        return R.ok("Save Success").add(loc);
        return R.ok("Save Success").add(buildPageRowsUtils.rowsMap(loc));
    }
    @PreAuthorize("hasAuthority('manager:loc:update')")
@@ -118,19 +208,27 @@
    @PostMapping("/loc/update")
    @Transactional(rollbackFor = Exception.class)
    public R update(@RequestBody Loc loc) {
        OptimisticLockUtils.requireVersion("库位", loc.getVersion());
        loc.setUpdateBy(getLoginUserId());
        String join = StringUtils.join(loc.getTypeIds(), ",");
        loc.setType(join);
        if (Objects.isNull(loc.getTypeIds())) {
            throw new CoolException("库位类型不能为空!!");
        if (!Objects.isNull(loc.getTypeIds())) {
            loc.setType(join);
        }
        if (Objects.isNull(loc.getTypeIds()) && !Objects.isNull(loc.getType())) {
            loc.setTypeIds(Arrays.asList(Long.valueOf(loc.getType())));
        }
        if (loc.getStatus().equals(CommonStatus.COMMONSTATUS_NO.val)) {
            loc.setUseStatus(LocStsType.LOC_STS_TYPE_X.type);
        }
        if (!locService.updateById(loc)) {
            return R.error("Update Fail");
        }
        if (!locService.updateLoc(loc)) {
            throw new CoolException("库位类型关联关系修改失败!@!");
        }
        return R.ok("Update Success").add(loc);
        return R.ok("Update Success").add(buildPageRowsUtils.rowsMap(loc));
    }
    @PreAuthorize("hasAuthority('manager:loc:remove')")
@@ -140,7 +238,7 @@
        if (!locService.removeByIds(Arrays.asList(ids))) {
            return R.error("Delete Fail");
        }
        return R.ok("Delete Success").add(ids);
        return R.ok("Delete Success").add(buildPageRowsUtils.rowsMap(ids));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
@@ -154,20 +252,70 @@
        locService.page(new Page<>(1, 30), wrapper).getRecords().forEach(
                item -> vos.add(new KeyValVo(item.getId(), item.getCode()))
        );
        return R.ok().add(vos);
        return R.ok().add(buildPageRowsUtils.rowsMap(vos));
    }
    @PreAuthorize("hasAuthority('manager:loc:list')")
    @PreAuthorize("hasAuthority('manager:loc:export')")
    @ApiOperation("库位导出")
    @PostMapping("/loc/export")
    public void export(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        List<Loc> locs = new ArrayList<>();
        if (Objects.isNull(map.get("ids"))) {
            locs = locService.list();
        } else {
            locs = locService.list(new LambdaQueryWrapper<Loc>().eq(Loc::getStatus, 1));
        listExportService.export(
                map,
                exportMap -> buildParam(exportMap, BaseParam.class),
                locExportHandler,
                response
        );
    }
    @PreAuthorize("hasAuthority('manager:loc:export')")
    @PostMapping("/loc/export/async")
    public R createAsyncExportTask(@RequestBody Map<String, Object> map) {
        ExportTask task = asyncListExportTaskService.createTask(
                EXPORT_RESOURCE_KEY,
                EXPORT_DEFAULT_REPORT_TITLE,
                map,
                getTenantId(),
                getLoginUserId()
        );
        asyncListExportTaskService.executeAsync(
                task.getId(),
                EXPORT_RESOURCE_KEY,
                new HashMap<>(map),
                exportMap -> buildParam(exportMap, BaseParam.class),
                locExportHandler
        );
        return R.ok("导出任务已创建").add(buildPageRowsUtils.rowsMap(task));
    }
    @PreAuthorize("hasAuthority('manager:loc:export')")
    @GetMapping("/loc/export/task/{taskId}")
    public R getExportTask(@PathVariable("taskId") Long taskId) {
        ExportTask task = asyncListExportTaskService.getTask(
                taskId,
                EXPORT_RESOURCE_KEY,
                getTenantId(),
                getLoginUserId()
        );
        if (task == null) {
            return R.error("导出任务不存在");
        }
        ExcelUtil.build(ExcelUtil.create(locs, Loc.class), response);
        return R.ok().add(buildPageRowsUtils.rowsMap(task));
    }
    @PreAuthorize("hasAuthority('manager:loc:export')")
    @GetMapping("/loc/export/task/{taskId}/download")
    public void downloadExportTask(
            @PathVariable("taskId") Long taskId,
            HttpServletResponse response,
            HttpServletRequest request
    ) {
        File file = asyncListExportTaskService.getDownloadFile(
                taskId,
                EXPORT_RESOURCE_KEY,
                getTenantId(),
                getLoginUserId()
        );
        FileServerUtil.preview(file, true, file.getName(), null, null, response, request);
    }
    @PreAuthorize("hasAuthority('manager:loc:update')")
@@ -203,9 +351,6 @@
        if (Objects.isNull(param.getTypeIds()) && param.getTypeIds().isEmpty()) {
            return R.error("库位类型不能为空!!");
        }
        if (Objects.isNull(param.getWarehouseId())) {
            return R.error("仓库ID不能为空!!");
        }
        if (Objects.isNull(param.getAreaId())) {
            return R.error("库区ID不能为空!!");
        }
@@ -234,4 +379,49 @@
        return locService.initLocs(param, getLoginUserId());
    }
    private List<String> getLocSortedFields() {
        return Arrays.asList("row", "col", "lev");
    }
    private Map<String, Object> buildLocExportRow(Loc record, List<ExcelUtil.ExportColumn> columns) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(record);
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("warehouseName", record.getWarehouseId$());
        row.put("areaName", record.getAreaId$());
        row.put("typeIdsText", record.getTypeIds$());
        row.put("useStatus", normalizeExportText(record.getUseStatus$()));
        row.put("flagLogicText", toYesNoText(record.getFlagLogic()));
        row.put("flagLabelMangeText", toYesNoText(record.getFlagLabelMange()));
        row.put("status", record.getStatus$());
        row.put("updateTimeText", record.getUpdateTime$());
        for (ExcelUtil.ExportColumn column : columns) {
            if (row.containsKey(column.getSource())) {
                continue;
            }
            if (beanWrapper.isReadableProperty(column.getSource())) {
                row.put(column.getSource(), beanWrapper.getPropertyValue(column.getSource()));
            }
        }
        return row;
    }
    private String toYesNoText(Object value) {
        if (value == null) {
            return "";
        }
        if (Objects.equals(value, 1) || Objects.equals(value, (short) 1) || Objects.equals(value, true)) {
            return "是";
        }
        if (Objects.equals(value, 0) || Objects.equals(value, (short) 0) || Objects.equals(value, false)) {
            return "否";
        }
        return String.valueOf(value);
    }
    private String normalizeExportText(String value) {
        return value == null ? "" : value.trim();
    }
}