MVC controller父类demo

发布于:2025-04-08 ⋅ 阅读:(15) ⋅ 点赞:(0)

BaseController

import cn.gson.financial.kernel.model.vo.UserVo;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public abstract class BaseController {

    protected UserVo currentUser;

    protected Integer accountSetsId;

    protected HttpSession session;

    @ModelAttribute
    public void common(HttpServletRequest request, HttpSession session) {
        this.currentUser = (UserVo) request.getSession().getAttribute("user");
        if (this.currentUser != null) {
            this.accountSetsId = this.currentUser.getAccountSetsId();
        }
        this.session = session;
    }
}

BaseCrudController

package cn.gson.financial.base;

import cn.gson.financial.kernel.controller.JsonResult;
import cn.gson.financial.kernel.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Map;

@Slf4j
public abstract class BaseCrudController<T extends IService, E> extends BaseController {

    @Autowired
    protected T service;

    private Class<E> entityClass;

    @ModelAttribute
    public void common(HttpServletRequest request, HttpSession session) {
        super.common(request, session);
        this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    /**
     * 列表数据
     *
     * @return
     */
    @GetMapping
    public JsonResult list(@RequestParam Map<String, String> params) {
        return this.getPageList(params, this.service);
    }

    /**
     * 根据 Id 获取元素
     *
     * @param id
     * @return
     */
    @GetMapping("/{id:\\d+}")
    public JsonResult load(@PathVariable Long id) {
        QueryWrapper qw = Wrappers.query();
        qw.eq("id", id);
        this.setQwAccountSetsId(qw);
        return JsonResult.successful(service.getOne(qw));
    }

    /**
     * 删除元素
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id:\\d+}")
    public JsonResult delete(@PathVariable Long id) {
        try {
            QueryWrapper qw = Wrappers.query();
            qw.eq("id", id);
            this.setQwAccountSetsId(qw);
            service.remove(qw);
            return JsonResult.successful();
        } catch (ServiceException se) {
            log.error("删除失败!", se);
            return JsonResult.failure(se.getMessage());
        } catch (Exception e) {
            log.error("删除失败!", e);
            return JsonResult.failure("删除失败!");
        }
    }

    /**
     * 创建元素
     *
     * @param entity
     * @return
     */
    @PostMapping
    public JsonResult save(@RequestBody E entity) {
        try {
            this.setEntityAccountSetsId(entity);
            service.save(entity);
            return JsonResult.successful();
        } catch (Exception e) {
            log.error("创建失败!", e);
            return JsonResult.failure(e.getMessage());
        }
    }

    /**
     * 更新元素
     *
     * @return
     */
    @PutMapping
    public JsonResult update(@RequestBody E entity) {
        this.setEntityAccountSetsId(entity);

        try {
            QueryWrapper qw = Wrappers.query();
            Field field = this.entityClass.getDeclaredField("id");
            field.setAccessible(true);
            qw.eq("id", field.get(entity));
            this.setQwAccountSetsId(qw);
            service.update(entity, qw);
            return JsonResult.successful();
        } catch (Exception e) {
            log.error("更新失败!", e);
            return JsonResult.failure(e.getMessage());
        }
    }

    /**
     * 限制数据的安全
     *
     * @param qw
     */
    protected void setQwAccountSetsId(QueryWrapper qw) {
        try {
            entityClass.getDeclaredField("accountSetsId");
            qw.eq("account_sets_id", currentUser.getAccountSetsId());
        } catch (Exception ex) {
            // 没有这个字段就不做处理了
        }
    }

    /**
     * 设置数据归属
     *
     * @param entity
     */
    protected void setEntityAccountSetsId(E entity) {
        try {
            Field field = entityClass.getDeclaredField("accountSetsId");
            field.setAccessible(true);
            field.set(entity, currentUser.getAccountSetsId());
        } catch (Exception ex) {
            // 没有这个字段就不做处理了
        }
    }

    protected final JsonResult getPageList(Map<String, String> params, IService s) {
        QueryWrapper qw = new QueryWrapper<>();
        this.setQwAccountSetsId(qw);
        JsonResult jsonResult;
        if (params.containsKey("page")) {
            Page<Map<String, String>> pageable = new Page<>(Integer.parseInt(params.get("page")), Integer.parseInt(params.getOrDefault("size", "20")));
            params.remove("page");
            params.remove("size");
            qw.allEq(params);
            jsonResult = JsonResult.successful(s.page(pageable, qw));
        } else {
            qw.allEq(params);
            jsonResult = JsonResult.successful(s.list(qw));
        }
        return jsonResult;
    }
}

SubjectController

package cn.gson.financial.controller;

import cn.gson.financial.base.BaseCrudController;
import cn.gson.financial.common.SubjectExcelUtils;
import cn.gson.financial.kernel.controller.JsonResult;
import cn.gson.financial.kernel.exception.ServiceException;
import cn.gson.financial.kernel.model.entity.Subject;
import cn.gson.financial.kernel.model.entity.VoucherDetails;
import cn.gson.financial.kernel.model.vo.SubjectVo;
import cn.gson.financial.kernel.service.SubjectService;
import cn.gson.financial.kernel.service.VoucherDetailsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/subject")
public class SubjectController extends BaseCrudController<SubjectService, Subject> {

    @Autowired
    private VoucherDetailsService voucherDetailsService;

    @Autowired
    private SubjectExcelUtils excelUtils;

    @Override
    public JsonResult list(@RequestParam Map<String, String> params) {
        QueryWrapper qw = new QueryWrapper<>();
        this.setQwAccountSetsId(qw);
        qw.allEq(params);
        return JsonResult.successful(service.listVo(qw));
    }

    /**
     * 凭证下拉数据
     *
     * @return
     */
    @RequestMapping("voucher/select")
    public JsonResult voucherSelect(@RequestParam(defaultValue = "0") boolean showAll) {
        QueryWrapper qw = Wrappers.query();
        this.setQwAccountSetsId(qw);
        List data = service.selectData(qw, showAll);
        return JsonResult.successful(data);
    }

    @RequestMapping("loadByCode")
    public JsonResult loadByCode(String[] code, Integer checkYear, Integer checkMonth, String name) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, checkYear);
        cal.set(Calendar.MONTH, checkMonth - 1);

        QueryWrapper qw = Wrappers.query();
        this.setQwAccountSetsId(qw);

        qw.and(wrapper -> {
            QueryWrapper qwe = (QueryWrapper) wrapper;
            for (String s : code) {
                qwe.or(true).likeRight("code", s);
            }
            if ("结转损益".equals(name)) {
                qwe.or(true).eq("type", "损益");
            }
        });

        List<Subject> subjects = service.list(qw);
        List<SubjectVo> vos = subjects.stream().distinct().collect(ArrayList::new, (list, source) -> {
            SubjectVo vo = new SubjectVo();
            BeanUtils.copyProperties(source, vo);
            list.add(vo);
        }, List::addAll);

        Map<String, SubjectVo> collect1 = vos.stream().distinct().collect(Collectors.toMap(SubjectVo::getCode, subjectVo -> subjectVo));

        for (String s : code) {
            SubjectVo sbj = collect1.get(s);
            if (sbj.getLevel() != 1) {
                this.recursiveParent(vos, sbj.getParentId());
            }
        }

        Map<Integer, SubjectVo> collect = vos.stream().distinct().collect(Collectors.toMap(SubjectVo::getId, subject -> subject));

        vos.forEach(subject -> {
            if (subject.getLevel() != 1) {
                SubjectVo parent = collect.get(subject.getParentId());
                parent.getChildren().add(subject);
            }
        });


        if (vos.size() > code.length) {
            List<SubjectVo> collect2 = vos.stream().filter(subjectVo -> subjectVo.getChildren().isEmpty()).collect(Collectors.toList());
            for (Subject subjectVo : collect2) {
                if (subjectVo.getLevel() != 1) {
                    this.recursiveChildren(collect, subjectVo, subjectVo.getParentId());
                }
            }
            vos = collect2;
        }

        List<SubjectVo> collect2 = vos.stream().sorted(Comparator.comparing(Subject::getCode)).distinct().collect(Collectors.toList());

        Set<String> codeSet = collect2.stream().collect(Collectors.mapping(subjectVo -> subjectVo.getCode(), Collectors.toSet()));

        Map<String, VoucherDetails> aggregateAmount = voucherDetailsService.getAggregateAmount(this.accountSetsId, codeSet, cal.getTime());

        Map<String, Object> data = new HashMap<>(2);
        data.put("subject", collect2);
        data.put("amount", aggregateAmount);

        return JsonResult.successful(data);
    }

    private void recursiveParent(List<SubjectVo> subjects, Integer parentId) {
        QueryWrapper qw = Wrappers.query();
        this.setQwAccountSetsId(qw);
        qw.eq("id", parentId);
        Subject parent = this.service.getOne(qw);
        SubjectVo vo = new SubjectVo();
        BeanUtils.copyProperties(parent, vo);
        subjects.add(vo);
        if (parent.getLevel() != 1) {
            this.recursiveParent(subjects, parent.getParentId());
        }
    }

    private void recursiveChildren(Map<Integer, SubjectVo> subjectMap, Subject subject, Integer parentId) {
        Subject parent = subjectMap.get(parentId);
        if (parent != null) {
            subject.setName(parent.getName() + "-" + subject.getName());
            if (parent.getLevel() != 1) {
                recursiveChildren(subjectMap, subject, parent.getParentId());
            }
        }
    }

    /**
     * 使用状态检查
     *
     * @param id
     * @return
     */
    @GetMapping("checkUse/{id}")
    public JsonResult checkUse(@PathVariable Integer id) {
        Boolean used = service.checkUse(id);
        return JsonResult.successful(used);
    }

    /**
     * 科目余额
     *
     * @param subjectId
     * @return
     */
    @GetMapping("balance")
    public JsonResult balance(Integer subjectId, Integer categoryId, Integer categoryDetailsId) {
        Double balance = service.balance(this.accountSetsId, subjectId, categoryId, categoryDetailsId);
        return JsonResult.successful(balance);
    }

    /**
     * 导入
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/import")
    public JsonResult importVoucher(@RequestParam("file") MultipartFile multipartFile) {
        try {
            List<SubjectVo> voucherList = excelUtils.readExcel(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), this.currentUser);
            this.service.importVoucher(voucherList, this.currentUser.getAccountSets());
            return JsonResult.successful();
        } catch (ServiceException e) {
            return JsonResult.failure(e.getMessage());
        } catch (Exception e) {
            log.error("导入失败", e);
            throw new ServiceException("导入失败~", e);
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到