LAPTOP-KB9HII50\70708 2 år sedan
förälder
incheckning
72fab009ba
100 ändrade filer med 11719 tillägg och 0 borttagningar
  1. 123 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/controller/AddressDictEndPoint.java
  2. 133 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/controller/AddressEndPoint.java
  3. 35 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/dao/AddressDictRepository.java
  4. 22 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/dao/AddressRepository.java
  5. 58 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/service/AddressDictService.java
  6. 128 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/service/AddressService.java
  7. 45 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/address/service/PoUtil.java
  8. 118 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiCategoryEndPoint.java
  9. 326 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiEndPoint.java
  10. 108 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiErrorCodeEndPoint.java
  11. 98 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiParameterEndPoint.java
  12. 99 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiResponseEndPoint.java
  13. 523 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppEndPoint.java
  14. 143 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppFeatureEndPoint.java
  15. 49 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppVersionEndPoint.java
  16. 79 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/UserAppEndPoint.java
  17. 11 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiCategoryDao.java
  18. 24 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiDao.java
  19. 14 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiErrorCodeDao.java
  20. 17 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiParameterDao.java
  21. 16 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiResponseDao.java
  22. 19 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppDao.java
  23. 16 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppFeatureDao.java
  24. 11 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppVersionRepository.java
  25. 17 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppsRelationDao.java
  26. 11 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/OauthClientDetailsDao.java
  27. 11 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/ReportCategoryAppRelationDao.java
  28. 33 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/UserAppDao.java
  29. 26 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiCategoryService.java
  30. 18 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiErrorCodeService.java
  31. 47 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiParameterService.java
  32. 47 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiResponseService.java
  33. 249 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiService.java
  34. 106 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppFeatureService.java
  35. 287 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppService.java
  36. 28 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppVersionService.java
  37. 24 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppsRelationService.java
  38. 14 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/OauthClientDetailsService.java
  39. 44 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/UserAppService.java
  40. 26 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/config/TenantConfiguration.java
  41. 845 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/controller/ConventionalDictEndPoint.java
  42. 165 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/controller/SystemDictEndPoint.java
  43. 206 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/controller/SystemDictEntryEndPoint.java
  44. 59 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/dao/SystemDictEntryRepository.java
  45. 27 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/dao/SystemDictRepository.java
  46. 158 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/service/SystemDictEntryService.java
  47. 77 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/service/SystemDictService.java
  48. 175 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/controller/FileResourceEndPoint.java
  49. 101 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/service/FileResource.java
  50. 106 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/service/FileResourceManager.java
  51. 19 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/service/XFileResourceRepository.java
  52. 272 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgDeptEndPoint.java
  53. 79 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgDeptImportEndPoint.java
  54. 645 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgEndPoint.java
  55. 232 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgHealthCategoryEndPoint.java
  56. 328 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgMemberRelationEndPoint.java
  57. 143 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgSaasEndPoint.java
  58. 17 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/LdapEntriesRepository.java
  59. 23 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgDeptDetailRepository.java
  60. 37 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgDeptRepository.java
  61. 30 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgHealthCategoryDao.java
  62. 61 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgMemberRelationRepository.java
  63. 46 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgSaasRepository.java
  64. 79 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrganizationRepository.java
  65. 56 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgDeptDetailService.java
  66. 109 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgDeptImportService.java
  67. 287 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgDeptService.java
  68. 169 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgHealthCategoryService.java
  69. 208 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgMemberRelationService.java
  70. 91 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgSaasService.java
  71. 427 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgService.java
  72. 110 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/AuthenticationEndPoint.java
  73. 168 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/CardEndPoint.java
  74. 112 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/FamiliesEndPoint.java
  75. 119 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/MembersEndPoint.java
  76. 234 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/PatientArchiveEndPoint.java
  77. 344 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/PatientCardsEndPoint.java
  78. 538 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/PatientEndPoint.java
  79. 13 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XAbstractPhysicalCardRepository.java
  80. 20 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XAbstractVirtualCardRepository.java
  81. 20 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XArchiveApplyDao.java
  82. 57 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XArchiveRelationDao.java
  83. 13 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XAuthenticationRepository.java
  84. 25 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XDemographicInfoRepository.java
  85. 13 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XFamiliesRepository.java
  86. 7 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XJsonArchiveDao.java
  87. 19 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XMedicalCardsDao.java
  88. 23 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XMembersRepository.java
  89. 22 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XUserCardsDao.java
  90. 49 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/feign/ConventionalDictClient.java
  91. 28 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/feign/PatientArchiveClient.java
  92. 158 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/ArchiveApplyService.java
  93. 174 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/ArchiveRelationService.java
  94. 19 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/AuthenticationService.java
  95. 184 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/CardManager.java
  96. 515 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/DemographicService.java
  97. 94 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/FamiliesService.java
  98. 48 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/MedicalCardsService.java
  99. 113 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/MembersService.java
  100. 0 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/UserCardsService.java

+ 123 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/controller/AddressDictEndPoint.java

@ -0,0 +1,123 @@
package com.yihu.jw.basic.address.controller;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.entity.ehr.address.AddressDict;
import com.yihu.jw.basic.address.service.AddressDictService;
import com.yihu.jw.restmodel.ehr.geography.MGeographyDict;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 *
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "Geography-Dict", description = "行政区划地址", tags = {"基础信息-行政区划地址"})
public class AddressDictEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AddressDictService geographyDictService;
    /**
     * 根据地址等级查询地址信息
     * @param level
     * @return
     */
    @RequestMapping(value = ServiceApi.Geography.AddressDictByLevel, method = RequestMethod.GET)
    @ApiOperation(value = "根据等级查询行政区划地址")
    public Collection<MGeographyDict> getAddressByLevel(
            @ApiParam(name = "level", value = "等级", defaultValue = "")
            @PathVariable(value = "level") Integer level) {
        List<AddressDict> addressDictList = geographyDictService.getLevelToAddr(level);
        return convertToModels(addressDictList,new ArrayList<>(addressDictList.size()), MGeographyDict.class,"");
    }
    @RequestMapping(value = ServiceApi.Geography.AddressDictByPid, method = RequestMethod.GET)
    @ApiOperation(value = "根据上级编号查询行政区划地址")
    public Collection<MGeographyDict> getAddressDictByPid(
        @ApiParam(name = "pid", value = "上级id", defaultValue = "")
        @PathVariable(value = "pid") Integer pid) {
        List<AddressDict> addressDictList = geographyDictService.getPidToAddr(pid);
        return convertToModels(addressDictList, new ArrayList<>(addressDictList.size()), MGeographyDict.class,"");
    }
    @RequestMapping(value = ServiceApi.Geography.AddressDict, method = RequestMethod.GET)
    @ApiOperation(value = "根据id查询行政区划地址")
    public MGeographyDict getAddressDictById(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @PathVariable(value = "id") String id) {
        AddressDict geographyDict =  geographyDictService.findById(id);
        return convertToModel(geographyDict, MGeographyDict.class);
    }
    @RequestMapping(value = ServiceApi.Geography.AddressDictList, method = RequestMethod.POST)
    @ApiOperation(value = "获取多条行政区划地址")
    public List<MGeographyDict> getAddressDictByIdList(
            @ApiParam(name = "idList", value = "idList", defaultValue = "")
            @RequestParam(value = "idList") List<String> idList) {
        List<MGeographyDict> list=new ArrayList<>();
        for(int i=0;i<idList.size();i++) {
            AddressDict geographyDict = geographyDictService.findById(idList.get(i));
            list.add(convertToModel(geographyDict, MGeographyDict.class));
        }
        return list;
    }
    @RequestMapping(value = ServiceApi.Geography.AddressDictAll, method = RequestMethod.POST)
    @ApiOperation(value = "获取全部行政区划地址")
    public List<AddressDict> getAllAddressDict(){
       return geographyDictService.getAllAddressDict();
    }
    @RequestMapping(value = ServiceApi.Geography.AddressDictByFields, method = RequestMethod.GET)
    @ApiOperation(value = "根据地址中文名 查询地址编号")
    Collection<MGeographyDict> getAddressDict(
            @ApiParam(name = "fields", value = "fields", defaultValue = "")
            @RequestParam(value = "fields") String[] fields ,
            @ApiParam(name = "values", value = "values", defaultValue = "")
            @RequestParam(value = "values") String[] values){
        List<AddressDict> geographyDictList = geographyDictService.findByFields(fields,values);
        return convertToModels(geographyDictList,new ArrayList<>(geographyDictList.size()), MGeographyDict.class,"");
    }
    @RequestMapping(value = ServiceApi.Geography.GetAddressNameByCode, method = RequestMethod.GET)
    @ApiOperation(value = "根据地址中文名 查询地址编号")
    ObjEnvelop getAddressNameByCode(
            @ApiParam(name = "name", value = "name", defaultValue = "")
            @RequestParam(value = "name") String name){
        AddressDict geographyDict = geographyDictService.findByName(name);
        if(geographyDict != null){
            ObjEnvelop objectResult = new ObjEnvelop();
            objectResult.setObj(geographyDict);
            objectResult.setStatus(200);
            return objectResult;
        }
        return null;
    }
    /**
     * 根据地址等级查询地址信息
     * @param name
     * @return
     */
    @RequestMapping(value = "/OrgSaasAreaByname", method = RequestMethod.GET)
    @ApiOperation(value = "根据名称查询行政区划地址")
    public Collection<MGeographyDict> getOrgSaasAreaByname(
            @ApiParam(name = "name", value = "名称", defaultValue = "")
            @RequestParam(value = "name") String name) {
        List<AddressDict> addressDictList = geographyDictService.getAddrDictByname(name);
        return convertToModels(addressDictList,new ArrayList<>(addressDictList.size()), MGeographyDict.class,"");
    }
}

+ 133 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/controller/AddressEndPoint.java

@ -0,0 +1,133 @@
package com.yihu.jw.basic.address.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.address.service.AddressService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.entity.ehr.address.Address;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.geography.MGeography;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.id.BizObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * @author zlf
 * @version 1.0
 * @created 2015.08.10 17:57
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AddressEndPoint", description = "获取常用地址,根据选择地址判断数据库中是否存在,否则保存为新地址", tags = {"基础信息-地址信息管理"})
public class AddressEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AddressService addressService;
    @RequestMapping(value = ServiceApi.Geography.Address, method = RequestMethod.GET)
    @ApiOperation(value = "根据地址编号查询地址")
    public MGeography getAddressById(
            @ApiParam(name = "id", value = "地址编号", defaultValue = "")
            @PathVariable(value = "id") String id) {
        Address address =  addressService.getAddressById(id);
        return convertToModel(address, MGeography.class);
    }
    @RequestMapping(value = ServiceApi.Geography.AddressCanonical, method = RequestMethod.GET)
    @ApiOperation(value = "根据地址编号获取地址中文字符串全拼")
    public String getCanonicalAddress(
            @ApiParam(name = "id", value = "地址代码", defaultValue = "")
            @PathVariable(value = "id") String id) {
        Address address = addressService.getAddressById(id);
        String addressStr = "";
        if(address != null){
            addressStr = addressService.getCanonicalAddress(address);
        }
        return addressStr;
    }
    /**
     * 地址检查并保存
     * @return
     */
    @RequestMapping(value = ServiceApi.Geography.Geographies, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "地址检查,如果地址在数据库中不存在,这新增这条记录,否则返回地址id")
    public String saveAddress(
            @ApiParam(name = "json_data", value = "地址json字符串")
            @RequestBody String jsonData) throws Exception{
//        ObjectMapper objectMapper = new ObjectMapper();
//        Geography geography = objectMapper.readValue(jsonData, Geography.class);
        Address geography = toEntity(jsonData,Address.class);
        if (geography.getCountry() == null) {
            geography.setCountry("中国");
        }
        List<Address> geographies = addressService.isGeographyExist(geography);
        if(geographies==null || geographies.size()==0){
            geography.setId(getObjectId(BizObject.Geography));
            String addressId = addressService.saveAddress(geography);
            return addressId;
        }else {
            return geographies.get(0).getId();
        }
    }
    /**
     * 根据省市县查询地址
     * @param province
     * @param city
     * @param district
     * @return
     */
    @RequestMapping(value = ServiceApi.Geography.Geographies , method = RequestMethod.GET)
    @ApiOperation(value = "根据省市县查询地址并返回地址编号列表")
    public List<String> search(
            @ApiParam(name = "province", value = "省", defaultValue = "")
            @RequestParam(value = "province",required = true) String province,
            @ApiParam(name = "city", value = "市", defaultValue = "")
            @RequestParam(value = "city",required = false) String city,
            @ApiParam(name = "district", value = "县", defaultValue = "")
            @RequestParam(value = "district",required = false) String district) {
        List<String> idList =  addressService.searchList(province,city,district);
        return idList;
    }
    /**
     * 删除地址
     * @param id
     * @return
     */
    @RequestMapping(value = ServiceApi.Geography.GeographiesDelete , method = RequestMethod.DELETE)
    @ApiOperation(value = "根据地址编号删除地址")
    public boolean delete(
            @ApiParam(name = "id" , value = "地址代码" ,defaultValue = "")
            @PathVariable (value = "id") String id) {
        Address address = addressService.getAddressById(id);
        if(address == null){
            throw new ApiException("获取地址失败",ErrorCode.NOT_FOUND.value());
        }
        addressService.deleteAddress(address);
        return true;
    }
    @RequestMapping(value = ServiceApi.Geography.GeographiesNull , method = RequestMethod.GET)
    @ApiOperation(value = "判断是否是个空地址")
    public boolean isNullAddress(
            @ApiParam(name = "json_data", value = "地址json字符串")
            @RequestParam( value = "json_data") String jsonData) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        Address geography = objectMapper.readValue(jsonData,Address.class);
        return addressService.isNullAddress(geography);
    }
}

+ 35 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/dao/AddressDictRepository.java

@ -0,0 +1,35 @@
package com.yihu.jw.basic.address.dao;
import com.yihu.jw.entity.ehr.address.AddressDict;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface AddressDictRepository extends JpaRepository<AddressDict, Integer> {
    @Query("select dict from AddressDict dict where dict.id = :id")
    AddressDict getAddressDictById(@Param("id") String id);
    @Query("select dict from AddressDict dict where dict.level = :level")
    List<AddressDict> getAddrDictByLevel(@Param("level") Integer level);
    @Query("select dict from AddressDict dict where dict.pid = :pid")
    List<AddressDict> getAddrDictByPid(@Param("pid") Integer pid);
    @Query("select dict from AddressDict dict where dict.name = :name")
    List<AddressDict> findByName(@Param("name") String pid);
    @Query("select dict from AddressDict dict where 1=1")
    List<AddressDict> getAll();
    @Query("select dict from AddressDict dict where dict.name like %:name% and dict.level > 0")
    List<AddressDict> getAddrDictByname(@Param("name") String name);
}

+ 22 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/dao/AddressRepository.java

@ -0,0 +1,22 @@
package com.yihu.jw.basic.address.dao;
import com.yihu.jw.entity.ehr.address.Address;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface AddressRepository extends JpaRepository<Address, String> {
    @Query("select geography from Address geography where geography.country = :country")
    List<Address> findAddressListByCountry(@Param("country") String country);
    @Query("select geography.id from Address geography where geography.district in(:district)")
    List<String> findIdByDistrict(@Param("district") List<String> district);
}

+ 58 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/service/AddressDictService.java

@ -0,0 +1,58 @@
package com.yihu.jw.basic.address.service;
import com.yihu.jw.entity.ehr.address.AddressDict;
import com.yihu.jw.basic.address.dao.AddressDictRepository;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 地址管理。对于相同地址,仅保存一份。
 * @author zqb
 * @version 1.0
 * @created 30-六月-2015 19:17:43
 */
@Transactional
@Service
public class AddressDictService extends BaseJpaService<AddressDict,AddressDictRepository> {
    @Autowired
    private AddressDictRepository geographyDictRepository;
	public List<AddressDict> getLevelToAddr(Integer level){
        List<AddressDict> addressDictList = geographyDictRepository.getAddrDictByLevel(level);
        return addressDictList;
	}
	public List<AddressDict> getPidToAddr(Integer pid){
        List<AddressDict> addressDictList = geographyDictRepository.getAddrDictByPid(pid);
        return addressDictList;
	}
    public AddressDict findById(String id) {
        return geographyDictRepository.getOne(Integer.valueOf(id));
    }
    public AddressDict findByName(String name) {
        List<AddressDict> DictList =geographyDictRepository.findByName(name);
        AddressDict geographyDict=new AddressDict();
        if (null != DictList & DictList.size() > 0) {
             geographyDict=DictList.get(0);
        }
        return geographyDict;
    }
    public List<AddressDict> getAllAddressDict() {
        return geographyDictRepository.getAll();
    }
    public List<AddressDict> getAddrDictByname(String name){
        List<AddressDict> addressDictList = geographyDictRepository.getAddrDictByname(name);
        return addressDictList;
    }
}

+ 128 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/service/AddressService.java

@ -0,0 +1,128 @@
package com.yihu.jw.basic.address.service;
import com.yihu.jw.basic.address.dao.AddressRepository;
import com.yihu.jw.entity.ehr.address.Address;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
/**
 * 地址管理。对于相同地址,仅保存一份。
 * @author zqb
 * @version 1.0
 * @created 30-六月-2015 19:17:43
 */
@Transactional
@Service
public class AddressService extends BaseJpaService<Address,AddressRepository>{
    @PersistenceContext
    protected EntityManager entityManager;
    @Autowired
    private AddressRepository geographyRepository;
    /**
	 * 地址检查并保存
     * 返回新地址id
	 * @param geography
	 */
    public String saveAddress(Address geography) {
        return geographyRepository.save(geography).getId();
    }
    public boolean isNullAddress(Address geography) {
        return
                StringUtils.isEmpty(geography.getProvince())
                && StringUtils.isEmpty(geography.getCity())
                && StringUtils.isEmpty(geography.getDistrict())
                && StringUtils.isEmpty(geography.getTown())
                && StringUtils.isEmpty(geography.getCountry())
                && StringUtils.isEmpty(geography.getStreet());
    }
    public Address getAddressById(String Id) {
        return geographyRepository.getOne(Id);
    }
    public String getCanonicalAddress(Address address) {
        String addressStr = "";
        String province = address.getProvince();
        String city = address.getCity();
        String district = address.getDistrict();
        String town = address.getTown();
        String street = address.getStreet();
        String extra = address.getExtra();
        if (!StringUtils.isEmpty(province)){
            addressStr += province;
            if (!"".equals(city)) {
                if (!province.equals(city)){
                    addressStr += city;
                }
            }
        }
        if (!StringUtils.isEmpty(district)){
            addressStr += district;
        }
        if (!StringUtils.isEmpty(town)){
            addressStr += town;
        }
        if (!StringUtils.isEmpty(street)){
            addressStr += street;
        }
        if (!StringUtils.isEmpty(extra)){
            addressStr += extra;
        }
        return addressStr;
    }
    public List<String> searchList(String province, String city, String district) {
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        String hql =
                "SELECT " +
                "addresses.id " +
                "FROM " +
                "addresses " +
                "WHERE 1=1 ";
        if (!StringUtils.isEmpty(province)) {
            hql += " AND addresses.province = '"+province+"'";
        }
        if (!StringUtils.isEmpty(city)) {
            hql += " AND addresses.city = '"+city+"'";
        }
        if (!StringUtils.isEmpty(district)) {
            hql += " AND addresses.district = '"+district+"'";
        }
        Query query = session.createSQLQuery(hql);
        List<String> idList = query.list();
        return idList;
    }
    public void deleteAddress(Address address) {
        geographyRepository.delete(address);
    }
    public List<Address> isGeographyExist(Address geography) throws Exception {
        String hql = PoUtil.getHql(geography,"id","postalCode");
        Session session = currentSession();
        Query query = session.createQuery(hql);
        List<Address> list = query.list();
        return list;
    }
    public List<String> getIdByDistrict(List<String> district) {
        return geographyRepository.findIdByDistrict(district);
    }
}

+ 45 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/address/service/PoUtil.java

@ -0,0 +1,45 @@
package com.yihu.jw.basic.address.service;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
 * Created by Administrator on 2016/2/23.
 */
public class PoUtil {
    /**
     * 通过Bean对象获取查询语句
     * @param obj 对象
     * @return Hql
     */
    public static String getHql(Object obj,String... fieldNames) throws Exception {
        List<String> properties = Arrays.asList(fieldNames);
        StringBuffer strBuffer = new StringBuffer(" from "+ obj.getClass().getSimpleName()+" where 1=1");
        Class<? extends Object> objClass = obj.getClass();
        Field fields[] = objClass.getDeclaredFields();
        for (Field field:fields) {
            String fieldValue = getFieldValue(obj, field);
            if(!properties.contains(field.getName())){
                if (fieldValue!=null ) {
                    strBuffer.append(" and "+field.getName()+"='"+fieldValue+"'");
                }else{
                    strBuffer.append(" and ("+field.getName()+" is null)");
                }
            }
        }
        return strBuffer.toString();
    }
    public static String getFieldValue(Object obj, Field field) throws Exception {
        String name = field.getName();
        String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
        Method method = obj.getClass().getMethod(methodName);
        Object methodValue = method.invoke(obj);
        if(methodValue!=null){
            return methodValue.toString();
        }
        return null;
    }
}

+ 118 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiCategoryEndPoint.java

@ -0,0 +1,118 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.basic.apps.service.AppApiCategoryService;
import com.yihu.jw.basic.apps.service.AppApiService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.apps.AppApiCategory;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * EndPoint - Api业务类别
 * Created by progr1mmer on 2018/3/14.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppApiCategory", description = "接口分类管理", tags = {"平台应用-接口分类管理"})
public class AppApiCategoryEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AppApiCategoryService appApiCategoryService;
    @Autowired
    private AppApiService appApiService;
    @RequestMapping(value = ServiceApi.AppApiCategory.Base, method = RequestMethod.POST)
    @ApiOperation("保存记录")
    public Envelop save(
            @ApiParam(name = "appApiCategory", value = "Json串", required = true)
            @RequestParam(value = "appApiCategory") String appApiCategory) throws Exception {
        AppApiCategory appApiCategory1 = toEntity(appApiCategory, AppApiCategory.class);
        AppApiCategory appApiCategory2 = appApiCategoryService.save(appApiCategory1);
        return success(appApiCategory2);
    }
    @RequestMapping(value = ServiceApi.AppApiCategory.Base, method = RequestMethod.DELETE)
    @ApiOperation("删除记录")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id列表xxxx,xxxx,xxxx,...", required = true)
            @RequestParam(value = "ids") String ids){
        String [] idArr = ids.split(",");
        String parent = "";
        for (String id : idArr) {
            if (appApiService.findByCateId(new Integer(id)).size() > 0) {
                parent += id + ",";
            }
        }
        if (StringUtils.isNotEmpty(parent)) {
            return failed("删除失败,请先删除该类别下关联的接口");
        }
        List<String> strIdList = Arrays.asList(idArr);
        List<Integer> intIdList = new ArrayList<>(idArr.length);
        strIdList.forEach(item -> intIdList.add(new Integer(item)));
        appApiCategoryService.delete(intIdList);
        return success(true);
    }
    @RequestMapping(value = ServiceApi.AppApiCategory.Base, method = RequestMethod.PUT)
    @ApiOperation("更新记录")
    public Envelop update(
            @ApiParam(name = "appApiCategory", value = "Json串", required = true)
            @RequestParam(value = "appApiCategory") String appApiCategory) throws Exception {
        AppApiCategory appApiCategory1 = toEntity(appApiCategory, AppApiCategory.class);
        if (appApiCategory1.getId() == null || appApiCategoryService.findByField("id", appApiCategory1.getId()).size() <= 0) {
            return failed("操作对象不存在", ErrorCode.OBJECT_NOT_FOUND.value());
        }
        AppApiCategory appApiCategory2 = appApiCategoryService.save(appApiCategory1);
        return success(appApiCategory2);
    }
    @RequestMapping(value = ServiceApi.AppApiCategory.Base, method = RequestMethod.GET)
    @ApiOperation(value = "获取分页")
    public Envelop list(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        List<AppApiCategory> appApiCategoryList = appApiCategoryService.search(fields, filters, sorts, page, size);
        int count = (int)appApiCategoryService.getCount(filters);
        Envelop envelop = getPageResult(appApiCategoryList, count, page, size);
        return envelop;
    }
    @RequestMapping(value = ServiceApi.AppApiCategory.Check, method = RequestMethod.GET)
    @ApiOperation(value = "检查字段是否重复")
    public Boolean check(
            @ApiParam(name = "field", value = "检查字段")
            @RequestParam(value = "field", required = false) String field,
            @ApiParam(name = "value", value = "检查值")
            @RequestParam(value = "value", required = false) String value) throws Exception {
        if (appApiCategoryService.findByField(field, value).size() <= 0) {
            return false;
        }
        return true;
    }
}

+ 326 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiEndPoint.java

@ -0,0 +1,326 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.entity.ehr.apps.AppApi;
import com.yihu.jw.entity.ehr.apps.AppApiParameter;
import com.yihu.jw.entity.ehr.apps.AppApiResponse;
import com.yihu.jw.basic.apps.service.*;
import com.yihu.jw.entity.ehr.user.RoleApiRelation;
import com.yihu.jw.entity.ehr.user.RoleAppRelation;
import com.yihu.jw.entity.ehr.user.Roles;
import com.yihu.jw.basic.user.service.RoleApiRelationService;
import com.yihu.jw.basic.user.service.RolesService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.apps.AppApiCategory;
import com.yihu.jw.entity.ehr.apps.AppApiErrorCode;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.app.MAppApi;
import com.yihu.jw.restmodel.ehr.app.MAppApiDetail;
import com.yihu.jw.restmodel.ehr.app.MAppApiParameter;
import com.yihu.jw.restmodel.ehr.app.OpenAppApi;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javafx.beans.binding.ObjectExpression;
import org.springframework.aop.aspectj.annotation.LazySingletonAspectInstanceFactoryDecorator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.*;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:13
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppApi", description = "平台应用接口管理", tags = {"平台应用-接口管理"})
public class AppApiEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AppApiService appApiService;
    @Autowired
    private AppApiParameterService appApiParameterService;
    @Autowired
    private AppApiResponseService appApiResponseService;
    @Autowired
    private AppApiCategoryService appApiCategoryService;
    @Autowired
    private AppApiErrorCodeService appApiErrorCodeService;
    @RequestMapping(value = ServiceApi.AppApi.AppApis, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建AppApi")
    public MAppApi createAppApi(
            @ApiParam(name = "appApi", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appApiJson) throws Exception {
        AppApi appApi = toEntity(appApiJson, AppApi.class);
        appApi = appApiService.createAppApi(appApi);
        return convertToModel(appApi, MAppApi.class);
    }
    @RequestMapping(value = ServiceApi.AppApi.AppApis, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApi列表")
    public Collection<MAppApi> getAppApis(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<AppApi> appApiList = appApiService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, appApiService.getCount(filters), page, size);
        return convertToModels(appApiList, new ArrayList<>(appApiList.size()), MAppApi.class, fields);
    }
    @RequestMapping(value = ServiceApi.AppApi.AppApis, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新appApi")
    public MAppApi updateAppApi(
            @ApiParam(name = "appApi", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appJson) throws Exception {
        AppApi appApi = toEntity(appJson, AppApi.class);
        if (appApiService.retrieve(appApi.getId()) == null) {
            throw new ApiException( "应用API不存在",ErrorCode.NOT_FOUND.value());
        }
        appApiService.save(appApi);
        return convertToModel(appApi, MAppApi.class);
    }
    @RequestMapping(value = ServiceApi.AppApi.AppApi, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApi")
    public MAppApi getAppApi(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        AppApi appApi = appApiService.retrieve(id);
        return convertToModel(appApi, MAppApi.class);
    }
    @RequestMapping(value = ServiceApi.AppApi.AppApi, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除AppApi")
    public boolean deleteAppApi(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        appApiService.delete(id);
        return true;
    }
    @RequestMapping(value = ServiceApi.AppApi.AppApisNoPage, method = RequestMethod.GET)
    @ApiOperation(value = "获取过滤App列表")
    public Collection<MAppApi> getAppApiNoPage(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters
    ) throws Exception {
        List<AppApi> appApiList = appApiService.search(filters);
        return convertToModels(appApiList, new ArrayList<>(appApiList.size()), MAppApi.class, "");
    }
    @RequestMapping(value = ServiceApi.AppApi.AppApiSearch, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApi列表")
    Collection<MAppApiDetail> searchApi(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<AppApi> appApiList = appApiService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, appApiService.getCount(filters), page, size);
        Collection<MAppApiDetail> mAppApiDetails = convertToModels(appApiList, new ArrayList<>(appApiList.size()), MAppApiDetail.class, "");
        mAppApiDetails.forEach(appApi -> {
            try {
                List apiParams = appApiParameterService.search("appApiId=" + appApi.getId());
                Collection<MAppApiParameter> mAppApiParameters = convertToModels(apiParams, new ArrayList<>(apiParams.size()), MAppApiParameter.class, "");
                appApi.setParameters(mAppApiParameters);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        return mAppApiDetails;
    }
    //------------------------ 开放平台基本请求部分 -------------------------
    @RequestMapping(value = ServiceApi.AppApi.CheckName, method = RequestMethod.GET)
    @ApiOperation(value = "检查名称")
    public Boolean checkName(
            @ApiParam(name = "name", value = "api名称", required = true)
            @RequestParam(value = "name") String name,
            @ApiParam(name = "appApiId", value = "appApiId")
            @RequestParam(value = "appApiId", required = false) Integer appApiId) throws Exception {
        if (null == appApiId) {
            if (appApiService.findByName(name).size() > 0) {
                return true;
            }
            return false;
        } else {
            AppApi appApi = appApiService.findById(appApiId);
            if (!appApi.getName().equals(name) && appApiService.findByName(name).size() > 0) {
                return true;
            }
            return false;
        }
    }
    @RequestMapping(value = ServiceApi.AppApi.Save, method = RequestMethod.POST)
    @ApiOperation(value = "新增Api")
    public MixEnvelop save(
            @ApiParam(name = "appApi", value = "对象JSON结构体", required = true, allowMultiple = true)
            @RequestParam(value = "appApi") String appApi,
            @ApiParam(name = "apiParam", value = "api请求参数集合")
            @RequestParam(value = "apiParam", required = false) String apiParam,
            @ApiParam(name = "apiResponse", value = "api响应参数集合")
            @RequestParam(value = "apiResponse", required = false) String apiResponse,
            @ApiParam(name = "apiErrorCode", value = "api错误码集合")
            @RequestParam(value = "apiErrorCode", required = false) String apiErrorCode) throws Exception {
        AppApi appApi1 = appApiService.completeSave(appApi, apiParam, apiResponse, apiErrorCode);
        List<AppApiParameter> appApiParameters = appApiParameterService.search("appApiId=" + appApi1.getId());
        List<AppApiResponse> appApiResponses = appApiResponseService.search("appApiId=" + appApi1.getId());
        List<AppApiErrorCode> appApiErrorCodes = appApiErrorCodeService.search("appApiId=" + appApi1.getId());
        List resultLis = new ArrayList();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("param", appApiParameters);
        dataMap.put("response", appApiResponses);
        dataMap.put("errorCode", appApiErrorCodes);
        resultLis.add(dataMap);
        return MixEnvelop.getSuccess("成功",appApi1, resultLis);
    }
    @RequestMapping(value = ServiceApi.AppApi.Delete, method = RequestMethod.POST)
    @ApiOperation(value = "删除Api")
    public Boolean delete(
            @ApiParam(name = "id", value = "ID", required = true)
            @RequestParam(value = "id") Integer id) throws Exception {
        appApiService.completeDelete(id);
        return true;
    }
    @RequestMapping(value = ServiceApi.AppApi.Update, method = RequestMethod.POST)
    @ApiOperation(value = "更新Api")
    public Envelop update(
            @ApiParam(name = "appApi", value = "对象JSON结构体", required = true, allowMultiple = true)
            @RequestParam(value = "appApi") String appApi,
            @ApiParam(name = "apiParam", value = "api请求参数集合")
            @RequestParam(value = "apiParam", required = false) String apiParam,
            @ApiParam(name = "apiResponse", value = "api响应参数集合")
            @RequestParam(value = "apiResponse", required = false) String apiResponse,
            @ApiParam(name = "apiErrorCode", value = "api错误码集合")
            @RequestParam(value = "apiErrorCode", required = false) String apiErrorCode) throws Exception {
        AppApi appApi1 = toEntity(appApi, AppApi.class);
        if (null == appApiService.findById(appApi1.getId()) ) {
            return failed("操作的API不存在", ErrorCode.OBJECT_NOT_FOUND.value());
        }
        AppApi newAppApi = appApiService.completeSave(appApi, apiParam, apiResponse, apiErrorCode);
        List<AppApiParameter> appApiParameters = appApiParameterService.search("appApiId=" + newAppApi.getId());
        List<AppApiResponse> appApiResponses = appApiResponseService.search("appApiId=" + newAppApi.getId());
        List<AppApiErrorCode> appApiErrorCodes = appApiErrorCodeService.search("appApiId=" + appApi1.getId());
        List resultLis = new ArrayList();
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("param", appApiParameters);
        dataMap.put("response", appApiResponses);
        dataMap.put("errorCode", appApiErrorCodes);
        resultLis.add(dataMap);
        return MixEnvelop.getSuccess("成功",appApi1, resultLis);
    }
    @RequestMapping(value = ServiceApi.AppApi.Page, method = RequestMethod.GET)
    @ApiOperation(value = "Api分页")
    public Envelop page(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,规则参见说明文档")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size) throws Exception {
        List<AppApi> appApiList = appApiService.search(fields, filters, sorts, page, size);
        int count = (int)appApiService.getCount(filters);
        PageEnvelop envelop = getPageResult(appApiList, count, page, size);
        List<AppApi> appApiList1 = envelop.getDetailModelList();
        List<AppApi> appApiList2 = new ArrayList<>(appApiList1.size());
        for (AppApi appApi : appApiList1) {
            if (appApi.getCategory() != null) {
                AppApiCategory appApiCategory = appApiCategoryService.getOne(appApi.getCategory());
                if (appApiCategory != null) {
                    appApi.setCategoryName(appApiCategory.getName());
                }
            }
            appApiList2.add(appApi);
        }
        envelop.setDetailModelList(appApiList2);
        return envelop;
    }
    // -------------------------------- 接入授权部分 --------------------------------
    @RequestMapping(value = ServiceApi.AppApi.AuthList, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApi列表")
    public List<AppApi> authApiList(
            @ApiParam(name = "appId", value = "应用ID", required = true)
            @RequestParam(value = "appId") String appId) throws Exception{
        List<AppApi> appApiList = appApiService.authApiList(appId);
        List<AppApi> appApiList2 = new ArrayList<>(appApiList.size());
        for (AppApi appApi : appApiList) {
            if (appApi.getCategory() != null) {
                AppApiCategory appApiCategory = appApiCategoryService.getOne(appApi.getCategory());
                if (appApiCategory != null) {
                    appApi.setCategoryName(appApiCategory.getName());
                }
            }
            appApiList2.add(appApi);
        }
        return appApiList2;
    }
    @RequestMapping(value = ServiceApi.AppApi.AuthApi, method = RequestMethod.POST)
    @ApiOperation(value = "授权AppApi")
    public Boolean authApi(
            @ApiParam(name = "appId", value = "角色appId", required = true)
            @RequestParam(value = "appId") String appId,
            @ApiParam(name = "code", value = "角色编码", required = true)
            @RequestParam(value = "code") String code,
            @ApiParam(name = "apiId", value = "apiId", required = true)
            @RequestParam(value = "apiId") String apiId) throws Exception{
        appApiService.authApi(code, appId, apiId);
        return true;
    }
    @RequestMapping(value = ServiceApi.AppApi.AuthApi, method = RequestMethod.DELETE)
    @ApiOperation(value = "取消AppApi授权")
    public Boolean unAuthApi(
            @ApiParam(name = "appId", value = "角色appId", required = true)
            @RequestParam(value = "appId") String appId,
            @ApiParam(name = "code", value = "角色编码", required = true)
            @RequestParam(value = "code") String code,
            @ApiParam(name = "apiId", value = "apiId", required = true)
            @RequestParam(value = "apiId") String apiId) throws Exception{
        appApiService.unAuthApi(code, appId, apiId);
        return true;
    }
}

+ 108 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiErrorCodeEndPoint.java

@ -0,0 +1,108 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.basic.apps.service.AppApiErrorCodeService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.apps.AppApiErrorCode;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * EndPoint - Api错误码
 * Created by progr1mmer on 2018/3/14.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppApiCategory", description = "接口错误码管理", tags = {"平台应用-接口错误码管理"})
public class AppApiErrorCodeEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AppApiErrorCodeService appApiErrorCodeService;
    @RequestMapping(value = ServiceApi.AppApiErrorCode.Base, method = RequestMethod.POST)
    @ApiOperation("保存记录")
    public Envelop save(
            @ApiParam(name = "appApiErrorCode", value = "Json串", required = true)
            @RequestParam(value = "appApiErrorCode") String appApiErrorCode) throws Exception {
        AppApiErrorCode appApiErrorCode1 = toEntity(appApiErrorCode, AppApiErrorCode.class);
        AppApiErrorCode appApiErrorCode2 = appApiErrorCodeService.save(appApiErrorCode1);
        return success(appApiErrorCode2);
    }
    @RequestMapping(value = ServiceApi.AppApiErrorCode.Base, method = RequestMethod.DELETE)
    @ApiOperation("删除记录")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id列表xxxx,xxxx,xxxx,...", required = true)
            @RequestParam(value = "ids") String ids){
        String [] idArr = ids.split(",");
        List<String> strIdList = Arrays.asList(idArr);
        List<Integer> intIdList = new ArrayList<>(idArr.length);
        strIdList.forEach(item -> intIdList.add(new Integer(item)));
        appApiErrorCodeService.delete(intIdList);
        return success(true);
    }
    @RequestMapping(value = ServiceApi.AppApiErrorCode.Base, method = RequestMethod.PUT)
    @ApiOperation("更新记录")
    public Envelop update(
            @ApiParam(name = "appApiErrorCode", value = "Json串", required = true)
            @RequestParam(value = "appApiErrorCode") String appApiErrorCode) throws Exception {
        AppApiErrorCode appApiErrorCode1 = toEntity(appApiErrorCode, AppApiErrorCode.class);
        if (appApiErrorCode1.getId() == null || appApiErrorCodeService.findByField("id", appApiErrorCode1.getId()).size() <= 0) {
            return failed("操作对象不存在", ErrorCode.OBJECT_NOT_FOUND.value());
        }
        AppApiErrorCode appApiErrorCode2 = appApiErrorCodeService.save(appApiErrorCode1);
        return success(appApiErrorCode2);
    }
    @RequestMapping(value = ServiceApi.AppApiErrorCode.Base, method = RequestMethod.GET)
    @ApiOperation(value = "获取分页")
    public Envelop list(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        List<AppApiErrorCode> appApiCategoryList = appApiErrorCodeService.search(fields, filters, sorts, page, size);
        int count = (int)appApiErrorCodeService.getCount(filters);
        Envelop envelop = getPageResult(appApiCategoryList, count, page, size);
        return envelop;
    }
    @RequestMapping(value = ServiceApi.AppApiErrorCode.CheckCode, method = RequestMethod.GET)
    @ApiOperation(value = "更新时检查Code是否重复")
    public Boolean check(
            @ApiParam(name = "apiId", value = "apiId")
            @RequestParam(value = "apiId", required = false) Integer apiId,
            @ApiParam(name = "newCode", value = "检查值")
            @RequestParam(value = "newCode", required = false) Integer newCode) throws Exception {
        List<AppApiErrorCode> appApiErrorCodeList = appApiErrorCodeService.findByField("apiId", apiId);
        for (AppApiErrorCode appApiErrorCode : appApiErrorCodeList) {
            if (appApiErrorCode.getCode() == newCode) {
                return true;
            }
        }
        return false;
    }
}

+ 98 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiParameterEndPoint.java

@ -0,0 +1,98 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.entity.ehr.apps.AppApiParameter;
import com.yihu.jw.basic.apps.service.AppApiParameterService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.app.MAppApiParameter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:13
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppApiParameter", description = "API应用请求参数", tags = {"平台应用-API应用请求参数"})
public class AppApiParameterEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AppApiParameterService appApiParameterService;
    @RequestMapping(value = ServiceApi.AppApiParameter.AppApiParameters, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建AppApiParameter")
    public MAppApiParameter createAppApiParameter(
            @ApiParam(name = "AppApiParameter", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appApiParameterJson) throws Exception {
        AppApiParameter appApiParameter = toEntity(appApiParameterJson, AppApiParameter.class);
        appApiParameter = appApiParameterService.createAppApiParameter(appApiParameter);
        return convertToModel(appApiParameter, MAppApiParameter.class);
    }
    @RequestMapping(value = ServiceApi.AppApiParameter.AppApiParameters, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApiParameter列表")
    public Collection<MAppApiParameter> getAppApiParameters(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
            List<AppApiParameter> appApiParameterList = appApiParameterService.search(fields, filters, sorts, page, size);
            pagedResponse(request, response, appApiParameterService.getCount(filters), page, size);
            return convertToModels(appApiParameterList, new ArrayList<>(appApiParameterList.size()), MAppApiParameter.class, fields);
    }
    @RequestMapping(value = ServiceApi.AppApiParameter.AppApiParameters, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新AppApiParameter")
    public MAppApiParameter updateAppApiParameter(
            @ApiParam(name = "AppApiParameter", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appJson) throws Exception {
        AppApiParameter appApiParameter = toEntity(appJson, AppApiParameter.class);
        if (appApiParameterService.retrieve(appApiParameter.getId()) == null) {
            throw new ApiException( "应用不存在",ErrorCode.NOT_FOUND.value());
        }
        appApiParameterService.save(appApiParameter);
        return convertToModel(appApiParameter, MAppApiParameter.class);
    }
    @RequestMapping(value = ServiceApi.AppApiParameter.AppApiParameter, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApiParameter")
    public MAppApiParameter getAppApiParameter(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        AppApiParameter appApiParameter = appApiParameterService.retrieve(id);
        return convertToModel(appApiParameter, MAppApiParameter.class);
    }
    @RequestMapping(value = ServiceApi.AppApiParameter.AppApiParameter, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除AppApiParameter")
    public boolean deleteAppApiParameter(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        appApiParameterService.delete(id);
        return true;
    }
}

+ 99 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppApiResponseEndPoint.java

@ -0,0 +1,99 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.basic.apps.service.AppApiResponseService;
import com.yihu.jw.entity.ehr.apps.AppApiResponse;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.app.MAppApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:13
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppApiResponse", description = "平台应用响应参数", tags = {"平台应用-平台应用响应参数"})
public class AppApiResponseEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AppApiResponseService appApiResponseService;
    @RequestMapping(value = ServiceApi.AppApiResponse.AppApiResponses, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建AppApiResponse")
    public MAppApiResponse createAppApiResponse(
            @ApiParam(name = "AppApiResponse", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appApiResponseJson) throws Exception {
        AppApiResponse appApiResponse = toEntity(appApiResponseJson, AppApiResponse.class);
        appApiResponse = appApiResponseService.createAppApiResponse(appApiResponse);
        return convertToModel(appApiResponse, MAppApiResponse.class);
    }
    @RequestMapping(value = ServiceApi.AppApiResponse.AppApiResponses, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApiResponse列表")
    public Collection<MAppApiResponse> getAppApiResponses(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
            List<AppApiResponse> appApiResponseList = appApiResponseService.search(fields, filters, sorts, page, size);
            pagedResponse(request, response, appApiResponseService.getCount(filters), page, size);
            return convertToModels(appApiResponseList, new ArrayList<>(appApiResponseList.size()), MAppApiResponse.class, fields);
    }
    @RequestMapping(value = ServiceApi.AppApiResponse.AppApiResponses, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新AppApiResponse")
    public MAppApiResponse updateAppApiResponse(
            @ApiParam(name = "AppApiResponse", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appJson) throws Exception {
        AppApiResponse appApiResponse = toEntity(appJson, AppApiResponse.class);
        if (appApiResponseService.retrieve(appApiResponse.getId()) == null) {
            throw new ApiException("应用不存在",ErrorCode.NOT_FOUND.value());
        }
        appApiResponseService.save(appApiResponse);
        return convertToModel(appApiResponse, MAppApiResponse.class);
    }
    @RequestMapping(value = ServiceApi.AppApiResponse.AppApiResponse, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppApiResponse")
    public MAppApiResponse getAppApiResponse(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        AppApiResponse appApiResponse = appApiResponseService.retrieve(id);
        return convertToModel(appApiResponse, MAppApiResponse.class);
    }
    @RequestMapping(value = ServiceApi.AppApiResponse.AppApiResponse, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除AppApiResponse")
    public boolean deleteAppApiResponse(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        appApiResponseService.delete(id);
        return true;
    }
}

+ 523 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppEndPoint.java

@ -0,0 +1,523 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.entity.ehr.apps.App;
import com.yihu.jw.entity.ehr.apps.AppsRelation;
import com.yihu.jw.entity.ehr.apps.UserApp;
import com.yihu.jw.basic.apps.service.AppService;
import com.yihu.jw.basic.apps.service.AppsRelationService;
import com.yihu.jw.basic.apps.service.OauthClientDetailsService;
import com.yihu.jw.basic.apps.service.UserAppService;
import com.yihu.jw.basic.dict.service.SystemDictEntryService;
import com.yihu.jw.basic.util.ConstantUtil;
import com.yihu.jw.entity.ehr.user.RoleAppRelation;
import com.yihu.jw.entity.ehr.user.Roles;
import com.yihu.jw.basic.user.service.RoleAppRelationService;
import com.yihu.jw.basic.user.service.RolesService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.entity.ehr.oauth2.OauthClientDetails;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.app.MApp;
import com.yihu.jw.restmodel.ehr.dict.SystemDictEntryAppModel;
import com.yihu.jw.entity.ehr.id.BizObject;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
 * @author linaz
 * @version 1.0
 * @created 2015.8.12 16:53:06
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "Application", description = "EHR应用管理", tags = {"应用管理-EHR应用管理"})
public class AppEndPoint extends EnvelopRestEndpoint {
    @Value("${fast-dfs.public-server}")
    private String fastDfsPublicServers;
    @Autowired
    private AppService appService;
    @Autowired
    private UserAppService userAppService;
    @Autowired
    private RolesService roleAppRelation;
    @Autowired
    private SystemDictEntryService systemDictEntryService;
    @Autowired
    private AppsRelationService appsRelationService;
    @Autowired
    private OauthClientDetailsService oauthClientDetailsService;
    @Autowired
    private RoleAppRelationService roleAppRelationService;
    @RequestMapping(value = ServiceApi.Apps.Apps, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建App")
    public MApp createApp(
            @ApiParam(name = "app", value = "对象JSON结构体", allowMultiple = true, defaultValue = "{\"name\": \"\", \"url\": \"\", \"catalog\": \"\", \"description\": \"\", \"creator\":\"\"},\"icon\": \"\",\"releaseFlag\": \"\"")
            @RequestBody String appJson) throws Exception {
        App app = toEntity(appJson, App.class);
        app.setId(getObjectId(BizObject.App));
        app = appService.createApp(app);
        //为应用追加默认角色组
        Roles roles=null;
        RoleAppRelation relation =null;
        String[][] rolestr= ConstantUtil.roles;
        for (String[] role : rolestr) {
            roles=new Roles();
            roles.setAppId(app.getId());
            roles.setType("1");
            roles.setCode(role[0]);
            roles.setName(role[1]);
            roles= roleAppRelation.save(roles);
            relation = new RoleAppRelation();
            relation.setAppId(app.getId());
            relation.setRoleId(roles.getId());
            roleAppRelationService.save(relation);
        }
        return convertToModel(app, MApp.class);
    }
    @RequestMapping(value = ServiceApi.Apps.Apps, method = RequestMethod.GET)
    @ApiOperation(value = "获取App列表")
    public Collection<MApp> getApps(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,secret,url,createTime,icon,releaseFlag")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sort", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sort", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
            List<App> appList = appService.search(fields, filters, sorts, page, size);
            pagedResponse(request, response, appService.getCount(filters), page, size);
            return convertToModels(appList, new ArrayList<>(appList.size()), MApp.class, fields);
    }
    @RequestMapping(value = ServiceApi.Apps.AppsNoPage, method = RequestMethod.GET)
    @ApiOperation(value = "获取app列表,不分页")
    public Collection<MApp> getAppsNoPage(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件",defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters) throws Exception {
        List<App> appList = appService.search(filters);
        return convertToModels(appList,new ArrayList<MApp>(appList.size()),MApp.class,"");
    }
    @RequestMapping(value = ServiceApi.Apps.Apps, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新App")
    public MApp updateApp(
            @ApiParam(name = "app", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appJson) throws Exception {
        App app = toEntity(appJson, App.class);
        if (appService.retrieve(app.getId()) == null) {
            throw new ApiException("不存在相应appId:" + app.getId());
        }
        OauthClientDetails oauthClientDetails = oauthClientDetailsService.retrieve(app.getId());
        if (null == oauthClientDetails) {
            oauthClientDetails = new OauthClientDetails();
            oauthClientDetails.setClientId(app.getId());
        }
        oauthClientDetails.setResourceIds("*");
        oauthClientDetails.setClientSecret(app.getSecret());
        oauthClientDetails.setScope("read");
        oauthClientDetails.setAuthorizedGrantTypes("authorization_code,refresh_token,password,implicit,verify_code");
        oauthClientDetails.setWebServerRedirectUri(app.getUrl());
        oauthClientDetails.setAuthorities(null);
        oauthClientDetails.setAccessTokenValidity(null);
        oauthClientDetails.setAccessTokenValidity(null);
        oauthClientDetails.setAdditionalInformation(null);
        oauthClientDetails.setAutoApprove("true");
        appService.update(app, oauthClientDetails);
        return convertToModel(app, MApp.class);
    }
    @RequestMapping(value = ServiceApi.Apps.getApp, method = RequestMethod.GET)
    @ApiOperation(value = "获取App")
    public MApp getApp(
            @ApiParam(name = "app_id", value = "id")
            @RequestParam(value = "app_id") String appId) throws Exception {
        App app = appService.retrieve(appId);
        if (app != null && StringUtils.isNotEmpty(app.getIcon())) {
            String iconUrl = fastDfsPublicServers + "/" + app.getIcon().replace(":", "/");
            app.setIcon(iconUrl);
        }
        return convertToModel(app, MApp.class);
    }
    @RequestMapping(value = ServiceApi.Apps.App, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除App")
    public boolean deleteApp(
            @ApiParam(name = "app_id", value = "id")
            @PathVariable(value = "app_id") String app_id) throws Exception {
        if (appService.retrieve(app_id) != null) {
            appService.delete(app_id);
        }
        return true;
    }
    @RequestMapping(value = ServiceApi.Apps.App, method = RequestMethod.GET)
    @ApiOperation(value = "获取App信息")
    public MApp app (
            @ApiParam(name = "app_id", value = "id")
            @PathVariable(value = "app_id") String app_id) throws Exception {
        App app = appService.retrieve(app_id);
        return convertToModel(app, MApp.class);
    }
    @RequestMapping(value = ServiceApi.Apps.AppStatus, method = RequestMethod.PUT)
    @ApiOperation(value = "修改状态")
    public boolean updateStatus(
            @ApiParam(name = "app_id", value = "id")
            @PathVariable(value = "app_id") String appId,
            @ApiParam(name = "app_status", value = "状态")
            @RequestParam(value = "app_status") String appStatus) throws Exception {
        appService.checkStatus(appId, appStatus);
        return true;
    }
    @RequestMapping(value = ServiceApi.Apps.AppExistence, method = RequestMethod.GET)
    @ApiOperation(value = "验证应用是否存在")
    public boolean isAppExistence(
            @ApiParam(name = "app_id", value = "id")
            @PathVariable(value = "app_id") String appId,
            @ApiParam(name = "secret", value = "")
            @RequestParam(value = "secret") String secret) throws Exception {
        return appService.findByIdAndSecret(appId, secret);
    }
    @RequestMapping(value = ServiceApi.Apps.AppNameExistence, method = RequestMethod.GET)
    @ApiOperation(value = "判断应用名称是否已经存在")
    public boolean isAppNameExists(
            @ApiParam(value = "app_name")
            @PathVariable(value = "app_name") String appName) {
        return appService.isAppNameExists(appName);
    }
    @RequestMapping(value = ServiceApi.Apps.FilterList, method = RequestMethod.GET)
    @ApiOperation(value = "获取过滤App列表")
    public Boolean getAppFilter(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters) throws Exception {
        Long count = appService.getCount(filters);
        return count > 0 ? true : false;
    }
    @RequestMapping(value =  ServiceApi.Apps.getApps, method = RequestMethod.GET)
    @ApiOperation(value = "根据条件,获取app列表")
    public Collection<MApp> getApps(
            @ApiParam(name = "userId", value = "userId", required = true)
            @RequestParam(value = "userId") String userId,
            @ApiParam(name = "catalog", value = "catalog", required = true)
            @RequestParam(value = "catalog") String catalog,
            @ApiParam(name = "manageType", value = "APP管理类型,backStage:后台管理,client:客户端。", required = true)
            @RequestParam(value = "manageType", required = false) String manageType) throws Exception {
        List<App> appList = appService.getApps(userId, catalog, manageType);
        return convertToModels(appList,new ArrayList<MApp>(appList.size()),MApp.class,"");
    }
    @RequestMapping(value = ServiceApi.Apps.getAppTypeAndApps, method = RequestMethod.GET)
    @ApiOperation(value = "根据条件,获取APP类型及其所拥有的应用")
    public ListEnvelop getAppTypeAndApps(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam(value = "userId") String userId,
            @ApiParam(name = "manageType", value = "APP管理类型,backStage:后台管理,client:客户端。")
            @RequestParam(value = "manageType", required = false) String manageType) throws Exception {
        ListEnvelop envelop = new ListEnvelop();
        //获取系统字典项(App类型)
        String filters = "dictId=" + 1;
        String fields = "";
        String sort = "+sort";
        int page = 1;
        int size = 999;
        List<SystemDictEntry> systemDictEntryList = systemDictEntryService.search(fields, filters, sort, page, size);
        List<SystemDictEntryAppModel> systemDictEntryModelList = (List<SystemDictEntryAppModel>) convertToModels(systemDictEntryList, new ArrayList<SystemDictEntryAppModel>(systemDictEntryList.size()), SystemDictEntryAppModel.class, null);
        List<SystemDictEntryAppModel> DictEntryModelList=new ArrayList<>();
        if (systemDictEntryList.size() > 0) {
            for (SystemDictEntryAppModel dict : systemDictEntryModelList){
                Collection<App> mAppList = appService.getApps(userId, dict.getCode(), manageType);
                List<MApp> appModelList = (List<MApp>) convertToModels(mAppList, new ArrayList<MApp>(mAppList.size()), MApp.class, null);
                dict.setChildren(appModelList);
                DictEntryModelList.add(dict);
            }
        }
        //应用列表
        envelop.setStatus(200);
        envelop.setDetailModelList(DictEntryModelList);
        return envelop;
    }
    @RequestMapping(value = ServiceApi.Apps.GetUserApp, method = RequestMethod.GET)
    @ApiOperation(value = "基于新的菜单需求,根据用户获取授权内的应用列表信息")
    public ListEnvelop getUserApp(
            @ApiParam(name = "userId", value = "用户APP对象json")
            @RequestParam(value = "userId", required = true) String userId) throws Exception {
        ListEnvelop res  = new ListEnvelop();
        //查询所有生效的应用列表
        String filters = "";
        List<App> appList = appService.search(filters);
        Collection<MApp> mAppList =  convertToModels(appList,new ArrayList<MApp>(appList.size()),MApp.class,"");
        if(mAppList != null && mAppList.size() > 0){
            res.setStatus(200);
        }else {
            res.setStatus(-1);
            res.setMessage("应用信息列表获取失败,请重试!");
            return res;
        }
        //查询所有的授权应用列表
        filters = "userId="+userId;
        List<UserApp> userAppList =  userAppService.search(filters);
        if(userAppList == null && userAppList.size() == 0){
            res.setDetailModelList(new ArrayList<MApp>(mAppList));
            return res;
        }
        //基于授权的应用列表,更新roleType状态
        //循环更新 roleType状态,初始化为0 ,存在授权的情况,赋值为 1
        for(MApp mApp :mAppList){
            mApp.setRoleType("0");
            String appId = mApp.getId();
            for(UserApp userApp: userAppList){
                if((appId).equals(userApp.getAppId())){
                    mApp.setRoleType("1");
                    break;
                }else{
                    continue;
                }
            }
        }
        res.setStatus(200);
        res.setDetailModelList(new ArrayList<MApp>(mAppList));
        return res;
    }
    // -------------------------- 开放平台 ---------------------------------
    @RequestMapping(value =  ServiceApi.Apps.CheckField, method = RequestMethod.POST)
    @ApiOperation(value = "注册时根据条件判断应用ID或者名称是否存在")
    public Boolean isFieldExist(
            @ApiParam(name = "field", value = "字段", required = true)
            @RequestParam(value = "field") String field,
            @ApiParam(name = "value", value = "值", required = true)
            @RequestParam(value = "value") String value) throws Exception{
        List<App> appList = appService.search(field + "=" + value);
        if (appList != null && appList.size() > 0) {
            return true;
        }
        return false;
    }
    @RequestMapping(value =  ServiceApi.Apps.CheckName, method = RequestMethod.POST)
    @ApiOperation(value = "更新的时候判断名字是否存在")
    public Boolean checkName(
            @ApiParam(name = "appId", value = "应用Id", required = true)
            @RequestParam(value = "appId") String appId,
            @ApiParam(name = "newName", value = "值", required = true)
            @RequestParam(value = "newName") String newName) throws Exception{
        App app = appService.findById(appId);
        if (!app.getName().equals(newName) && appService.findByField("name", newName).size() > 0) {
            return true;
        }
        return false;
    }
    @RequestMapping(value =  ServiceApi.Apps.AppAuthClient, method = RequestMethod.POST)
    @ApiOperation(value = "开放平台审核结果处理接口,包含App初始化和应用角色分配")
    public Envelop authClient(
            @ApiParam(name = "appJson", value = "App", required = true)
            @RequestParam(value = "appJson") String appJson,
            @ApiParam(name = "roleId", value = "基础角色ID", required = true)
            @RequestParam(value = "roleId") Long roleId) throws Exception{
        //app 表
        App app = objectMapper.readValue(appJson, App.class);
        app.setCreateTime(new Date());
        app.setAuditor("system");
        app.setAuditTime(new Date());
        app.setCatalog("ApplicationService");
        app.setStatus("Approved");
        app.setSourceType(0);
        app.setCode("DEFAULT");
        app.setManageType("client");
        app.setReleaseFlag(1);
        //oauth 表
        OauthClientDetails oauthClientDetails = new OauthClientDetails();
        oauthClientDetails.setClientId(app.getId());
        oauthClientDetails.setResourceIds("*");
        oauthClientDetails.setClientSecret(app.getSecret());
        oauthClientDetails.setScope("read");
        oauthClientDetails.setAuthorizedGrantTypes("authorization_code,refresh_token,password,implicit,verify_code");
        oauthClientDetails.setWebServerRedirectUri(app.getUrl());
        oauthClientDetails.setAuthorities(null);
        oauthClientDetails.setAccessTokenValidity(null);
        oauthClientDetails.setAccessTokenValidity(null);
        oauthClientDetails.setAdditionalInformation(null);
        oauthClientDetails.setAutoApprove("true");
        //验证基础角色
        Roles basicRole = roleAppRelation.retrieve(roleId);
        if (null == basicRole) {
            return failed("基础角色为空");
        }
        //创建扩展角色
        Roles additionRole = new Roles();
        additionRole.setCode(app.getId());
        additionRole.setName("扩展开发者");
        additionRole.setDescription("开放平台扩展开发者");
        additionRole.setAppId(basicRole.getAppId()); //此处设置角色所属的应用ID
        additionRole.setType("0");
        App newApp = appService.authClient(app, oauthClientDetails, basicRole, additionRole);
        return success(newApp);
    }
    @RequestMapping(value =  ServiceApi.Apps.SimpleUpdate, method = RequestMethod.POST)
    @ApiOperation(value = "开放平台应用简单更新")
    public Envelop simpleUpdate(
            @ApiParam(name = "appId", value = "AppId", required = true)
            @RequestParam(value = "appId") String appId,
            @ApiParam(name = "name", value = "名称", required = true)
            @RequestParam(value = "name") String name,
            @ApiParam(name = "url", value = "回调地址", required = true)
            @RequestParam(value = "url") String url) {
        List<App> appList = appService.findByField("id", appId);
        if (appList.size() <= 0) {
            return failed("操作对象不存在", ErrorCode.OBJECT_NOT_FOUND.value());
        }
        App app1 = appList.get(0);
        app1.setName(name);
        app1.setUrl(url);
        App app2 = appService.save(app1);
        return success(app2);
    }
    /**
     * 医生工作平台--显示应用列表
     * @param userId
     * @return
     * @throws Exception
     * create by zhangdan on 2018/04/19
     */
    @RequestMapping(value =  ServiceApi.Apps.GetAppsRelationByUserIdAndParentAppId, method = RequestMethod.POST)
    @ApiOperation(value = "医生工作平台个人平台应用列表")
    public Envelop getAppsRelationByUserID(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam(value = "userId") String userId)throws Exception {
        if (StringUtils.isEmpty(userId)){
            return failed("请先登录!");
        }
        List<Map<String,Object>> list = appService.getAppByParentIdAndUserId(userId);
        return success(list);
    }
    @RequestMapping(value =  ServiceApi.Apps.GetAppsRelationByUserJson, method = RequestMethod.POST)
    @ApiOperation(value = "支撑平台配置应用之间的关系")
    public Envelop getAppsByUserJson(
            @ApiParam(name = "jsonData", value = "新增应用关系json字符串", required = true)
            @RequestBody String jsonData)throws Exception {
        AppsRelation appsRelation = toEntity(jsonData, AppsRelation.class);
        AppsRelation relation = appsRelationService.save(appsRelation);
        return success(relation);
    }
    @RequestMapping(value = ServiceApi.Apps.getDoctorAppsByType, method = RequestMethod.GET)
    @ApiOperation(value = "根据条件,医生工作站-获取用户所拥有的应用")
    public ListEnvelop getDoctorAppsByType(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam(value = "userId") String userId) throws Exception {
        ListEnvelop envelop = new ListEnvelop();
        //获取系统字典项(医生工作站App类型)
        String filters = "dictId=179";
        String sort = "+sort";
        int page = 1;
        int size = 999;
        List<SystemDictEntry> systemDictEntryList = systemDictEntryService.search(null, filters, sort, page, size);
        List<SystemDictEntryAppModel> systemDictEntryModelList = (List<SystemDictEntryAppModel>) convertToModels(systemDictEntryList, new ArrayList<SystemDictEntryAppModel>(systemDictEntryList.size()), SystemDictEntryAppModel.class, null);
        List<SystemDictEntryAppModel> DictEntryModelList=new ArrayList<>();
        if (systemDictEntryList.size() > 0) {
            for (SystemDictEntryAppModel dict : systemDictEntryModelList){
                Collection<App> mAppList = appService.getDoctorAppsByType(userId, dict.getCode());
                List<MApp> appModelList = (List<MApp>) convertToModels(mAppList, new ArrayList<MApp>(mAppList.size()), MApp.class, null);
                dict.setChildren(appModelList);
                DictEntryModelList.add(dict);
            }
        }
        //应用列表
        envelop.setStatus(200);
        envelop.setDetailModelList(DictEntryModelList);
        return envelop;
    }
    @RequestMapping(value = ServiceApi.Apps.createAppRolesByAppId, method = RequestMethod.POST)
    @ApiOperation(value = "创建默认的App角色组")
    public Envelop createAppRolesByAppId(
            @ApiParam(name = "appId", value = "appId")
            @RequestParam(value = "appId",required = false) String appId,
            @ApiParam(name = "allAppFlag", value = "allAppFlag",defaultValue = "false")
            @RequestParam(value = "allAppFlag") boolean allAppFlag){
        Envelop envelop =new Envelop();
        //为应用追加默认角色组
        String[][] rolestr= ConstantUtil.roles;
        try {
            if(allAppFlag){
                List<App> appList = appService.search("");
                appList.forEach(app -> {
                    Roles roles=null;
                    RoleAppRelation relation =null;
                    for (String[] role : rolestr) {
                        roles=new Roles();
                        roles.setAppId(app.getId());
                        roles.setType("1");
                        roles.setCode(role[0]);
                        roles.setName(role[1]);
                        roles= roleAppRelation.save(roles);
                        relation = new RoleAppRelation();
                        relation.setAppId(app.getId());
                        relation.setRoleId(roles.getId());
                        roleAppRelationService.save(relation);
                    }
                });
            }else {
                Roles roles=null;
                RoleAppRelation relation =null;
                for (String[] role : rolestr) {
                    roles=new Roles();
                    roles.setAppId(appId);
                    roles.setType("1");
                    roles.setCode(role[0]);
                    roles.setName(role[1]);
                    roles= roleAppRelation.save(roles);
                    relation = new RoleAppRelation();
                    relation.setAppId(appId);
                    relation.setRoleId(roles.getId());
                    roleAppRelationService.save(relation);
                }
            }
            envelop.setStatus(200);
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setStatus(-1);
            envelop.setMessage(e.getMessage());
        }
        return  envelop;
    }
}

+ 143 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppFeatureEndPoint.java

@ -0,0 +1,143 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.entity.ehr.apps.AppFeature;
import com.yihu.jw.basic.apps.service.AppFeatureService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.app.MAppFeature;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:13
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppFeature", description = "功能管理", tags = {"平台应用-功能管理"})
public class AppFeatureEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private AppFeatureService appFeatureService;
    @RequestMapping(value = ServiceApi.AppFeature.AppFeature, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppFeature")
    public MAppFeature getAppFeature(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        AppFeature appFeature = appFeatureService.retrieve(id);
        return convertToModel(appFeature, MAppFeature.class);
    }
    @RequestMapping(value = ServiceApi.AppFeature.AppFeatures, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppFeature列表")
    public Collection<MAppFeature> getAppFeatures(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<AppFeature> appFeatureList = appFeatureService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, appFeatureService.getCount(filters), page, size);
        return convertToModels(appFeatureList, new ArrayList<>(appFeatureList.size()), MAppFeature.class, fields);
    }
    @RequestMapping(value = ServiceApi.AppFeature.FilterFeatureList, method = RequestMethod.GET)
    @ApiOperation(value = "获取过滤AppFeature列表")
    public Boolean getAppFeaturesFilter(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters) throws Exception {
        Long count = appFeatureService.getCount(filters);
        return count > 0 ? true : false;
    }
    @RequestMapping(value = ServiceApi.AppFeature.AppFeatures, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建AppFeature")
    public MAppFeature createAppFeature(
            @ApiParam(name = "AppFeature", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String AppFeatureJson) throws Exception {
        AppFeature appFeature = toEntity(AppFeatureJson, AppFeature.class);
        appFeature = appFeatureService.createAppFeature(appFeature);
        // 拼接菜单JSON对象字符串,并保存
        appFeature = appFeatureService.joinMenuItemJsonStr(appFeature);
        appFeatureService.save(appFeature);
        return convertToModel(appFeature, MAppFeature.class);
    }
    @RequestMapping(value = ServiceApi.AppFeature.AppFeatures, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新AppFeature")
    public MAppFeature updateAppFeature(
            @ApiParam(name = "AppFeature", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String appJson) throws Exception {
        AppFeature appFeature = toEntity(appJson, AppFeature.class);
        if (appFeatureService.retrieve(appFeature.getId()) == null) {
            throw new ApiException("应用不存在",ErrorCode.NOT_FOUND.value());
        }
        // 拼接菜单JSON对象字符串
        appFeature = appFeatureService.joinMenuItemJsonStr(appFeature);
        appFeatureService.save(appFeature);
        return convertToModel(appFeature, MAppFeature.class);
    }
    @RequestMapping(value = ServiceApi.AppFeature.AppFeature, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除AppFeature")
    public boolean deleteAppFeature(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") int id) throws Exception {
        appFeatureService.delete(id);
        return true;
    }
    @RequestMapping(value = ServiceApi.AppFeature.FilterFeatureNoPage, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppFeature列表(不分页)")
    public Collection<MAppFeature> getAppFeatureNoPage(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters) throws Exception {
        List<AppFeature> appFeatureList = appFeatureService.search(filters);
        return convertToModels(appFeatureList, new ArrayList<>(appFeatureList.size()), MAppFeature.class, "");
    }
    @RequestMapping(value = ServiceApi.AppFeature.FilterFeatureNoPageSorts, method = RequestMethod.GET)
    @ApiOperation(value = "获取AppFeature排序后的列表(不分页)")
    public Collection<MAppFeature> getAppFeatureNoPageSorts(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        List<AppFeature> appFeatureList = appFeatureService.search(filters, sorts);
        return convertToModels(appFeatureList, new ArrayList<>(appFeatureList.size()), MAppFeature.class, "");
    }
    @RequestMapping(value = ServiceApi.AppFeature.FindAppMenus, method = RequestMethod.GET)
    @ApiOperation(value = "根据权限,获取应用菜单")
    public List<Map<String, Object>> findAppMenus(
            @ApiParam(name = "appId", value = "应用ID", required = true)
            @RequestParam(value = "appId", required = true) String appId,
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam(value = "userId", required = true) String userId) throws Exception {
        return appFeatureService.findAppMenus(appId, userId, 0);
    }
}

+ 49 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/AppVersionEndPoint.java

@ -0,0 +1,49 @@
package com.yihu.jw.basic.apps.controller;
import com.yihu.jw.basic.apps.service.AppVersionService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.apps.AppVersion;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Trick on 2018/3/12.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "AppVersion", description = "上饶APP资源版本", tags = {"上饶APP应用版本管理"})
public class AppVersionEndPoint extends EnvelopRestEndpoint{
    @Autowired
    private AppVersionService appVersionService;
    @RequestMapping(value = ServiceApi.AppVersion.FindAppVersion, method = RequestMethod.GET)
    @ApiOperation(value = "获取App版本")
    public Envelop getAppVersion(
            @ApiParam(name = "code", value = "当前版本ID", defaultValue = "")
            @RequestParam(value = "code")String code,
            @ApiParam(name = "version", value = "要获取的版本", defaultValue = "")
            @RequestParam(value = "version", required = false)String version){
        AppVersion temp = appVersionService.getAppVersionByCode(code);
        if (temp == null) {
            return failed("无效的APP类型失败!");
        }
        /*if (version > 0) {
            //将版本返回前端,前端判断版本是否一致,决定升级与否
            return success(temp);
        } else {
            return failed("版本号有误");
        }*/
        return success(temp);
    }
}

+ 79 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/controller/UserAppEndPoint.java

@ -0,0 +1,79 @@
package com.yihu.jw.basic.apps.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.ehr.apps.UserApp;
import com.yihu.jw.basic.apps.service.UserAppService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.app.MUserApp;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * @author yeshijie
 * @version 1.0
 * @created 2017年2月16日18:04:13
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "UserApp", description = "用户应用关联", tags = {"平台应用-用户应用关联"})
public class UserAppEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private UserAppService userAppService;
    @RequestMapping(value = ServiceApi.UserApp.UserAppList, method = RequestMethod.GET)
    @ApiOperation(value = "根据用户id获取App列表")
    public Collection<MUserApp> getAppApiNoPage(
            @ApiParam(name = "userId", value = "用户id")
            @RequestParam(value = "userId", required = true) String userId) throws Exception {
        String filters = "userId="+userId;
        List<UserApp> userAppList =  userAppService.search(filters);
        return convertToModels(userAppList,new ArrayList<>(userAppList.size()),MUserApp.class, "");
    }
    @RequestMapping(value = ServiceApi.UserApp.UserAppShow, method = RequestMethod.GET)
    @ApiOperation(value = "更新用户权限应用的云门户展示状态")
    public MUserApp updateUserAppShowFlag(
            @ApiParam(name = "id", value = "用户APP关联ID")
            @RequestParam(value = "id", required = true) String id,
            @ApiParam(name = "flag", value = "要更新的展示状态", defaultValue = "1")
            @RequestParam(value = "flag", required = true) String flag) throws Exception {
            List<UserApp> userAppList = userAppService.findByField("id", id);
            UserApp userApp = new UserApp();
            if(userAppList != null){
                userApp = userAppList.get(0);
                userApp.setShowFlag(Integer.parseInt(flag));
                MUserApp mUserApp = convertToModel(userAppService.save(userApp),MUserApp.class);
                return mUserApp;
            }else{
                return null;
        }
    }
    @RequestMapping(value = ServiceApi.UserApp.CreateUserApp, method = RequestMethod.GET)
    @ApiOperation(value = "创建用户与app关联")
    public MUserApp createUserApp(
            @ApiParam(name = "userAppJson", value = "用户APP对象json")
            @RequestParam(value = "userAppJson", required = true) String userAppJson) throws Exception {
            UserApp userApp =objectMapper.readValue(userAppJson, UserApp.class);
            userApp.setShowFlag(1);
            userApp.setOrgId("");
            userApp.setOrgName("");
            MUserApp mUserApp = convertToModel(userAppService.save(userApp),MUserApp.class);
            return mUserApp;
    }
}

+ 11 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiCategoryDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppApiCategory;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Dao - Api业务类别
 * Created by progr1mmer on 2018/3/14.
 */
public interface AppApiCategoryDao extends JpaRepository<AppApiCategory, Integer> {
}

+ 24 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiDao.java

@ -0,0 +1,24 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppApi;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
 * AppApi 操作接口。
 *
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:05:46
 */
public interface AppApiDao extends JpaRepository<AppApi, Integer> {
    List<AppApi> findByCategory(Integer categoryId);
    List<AppApi> findByName(String name);
    void deleteByAppId(String appId);
    List<AppApi> findByAppId(String appId);
}

+ 14 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiErrorCodeDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppApiErrorCode;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Dao - Api错误码
 * Created by progr1mmer on 2018/3/15.
 */
public interface AppApiErrorCodeDao extends JpaRepository<AppApiErrorCode, Integer> {
    void deleteByAppApiId(Integer apiId);
}

+ 17 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiParameterDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppApiParameter;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * AppApiParameter 操作接口。
 *
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:05:41
 */
public interface AppApiParameterDao extends JpaRepository<AppApiParameter, Integer> {
    void deleteByAppApiId(Integer id);
}

+ 16 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppApiResponseDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppApiResponse;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * AppApiResponse 操作接口。
 *
 * @author linz
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface AppApiResponseDao extends JpaRepository<AppApiResponse, Integer> {
    void deleteByAppApiId(Integer id);
}

+ 19 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.App;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
 * App 操作接口。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface AppDao extends JpaRepository<App, String> {
    App findByName(String name);
    List<App> findByIdAndSecret(String appId, String secret);
}

+ 16 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppFeatureDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppFeature;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * AppApiFeature 操作接口。
 *
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:05:13
 */
public interface AppFeatureDao extends JpaRepository<AppFeature, String> {
    void deleteByAppId(String appId);
}

+ 11 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppVersionRepository.java

@ -0,0 +1,11 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppVersion;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Created by Trick on 2018/3/12.
 */
public interface AppVersionRepository extends JpaRepository<AppVersion, String> {
    public AppVersion findBycode(String code);
}

+ 17 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/AppsRelationDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.AppsRelation;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
 * App 操作接口。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface AppsRelationDao extends JpaRepository<AppsRelation, String> {
}

+ 11 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/OauthClientDetailsDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.oauth2.OauthClientDetails;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Created by progr1mmer on 2018/1/23.
 */
public interface OauthClientDetailsDao extends JpaRepository<OauthClientDetails, String> {
}

+ 11 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/ReportCategoryAppRelationDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.report.ReportCategoryAppRelation;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Created by progr1mmer on 2018/4/8.
 */
public interface ReportCategoryAppRelationDao  extends JpaRepository<ReportCategoryAppRelation, Integer> {
    void deleteByAppId(String appId);
}

+ 33 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/dao/UserAppDao.java

@ -0,0 +1,33 @@
package com.yihu.jw.basic.apps.dao;
import com.yihu.jw.entity.ehr.apps.UserApp;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author yeshijie
 * @version 1.0
 * @created 2017年2月16日18:04:13
 */
public interface UserAppDao extends JpaRepository<UserApp, String> {
    @Query("select userApp from UserApp userApp where userApp.appId = :appId and userApp.userId = :userId" )
    UserApp findByAppIdAndUserId(@Param("appId") String appId, @Param("userId") String userId);
    @Modifying
//    @Query("update UserApp userApp set userApp.status = 1 where userApp.userId = :userId")
    void deleteByUserId(@Param("userId") String userId);
    @Modifying
    void deleteByAppId(@Param("appId") String appId);
    @Query("select userApp from UserApp userApp where userApp.appId = :appId " )
    List<UserApp> findByAppId(@Param("appId") String appId);
    @Query("select userApp from UserApp userApp where userApp.userId in (:userIds) " )
    List<UserApp> findByuserId(@Param("userIds") List<String> userIds);
}

+ 26 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiCategoryService.java

@ -0,0 +1,26 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.AppApiCategoryDao;
import com.yihu.jw.entity.ehr.apps.AppApiCategory;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
/**
 * Service - 接口分类
 * Created by progr1mmer on 2018/3/14.
 */
@Service
@Transactional
public class AppApiCategoryService extends BaseJpaService<AppApiCategory, AppApiCategoryDao> {
    @Autowired
    private AppApiCategoryDao appApiCategoryDao;
    public AppApiCategory getOne(Integer id) {
        return appApiCategoryDao.getOne(id);
    }
}

+ 18 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiErrorCodeService.java

@ -0,0 +1,18 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.AppApiErrorCodeDao;
import com.yihu.jw.entity.ehr.apps.AppApiErrorCode;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
/**
 * Service - Api错误码
 * Created by progr1mmer on 2018/3/15.
 */
@Service
@Transactional
public class AppApiErrorCodeService extends BaseJpaService<AppApiErrorCode, AppApiErrorCodeDao> {
}

+ 47 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiParameterService.java

@ -0,0 +1,47 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.AppApiParameterDao;
import com.yihu.jw.entity.ehr.apps.AppApiParameter;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:41
 */
@Service
@Transactional
public class AppApiParameterService extends BaseJpaService<AppApiParameter, AppApiParameterDao> {
    @Autowired
    private AppApiParameterDao appApiParameterRepository;
    public AppApiParameterService() {
    }
    public Page<AppApiParameter> getAppApiParameterList(String sorts, int page, int size){
        AppApiParameterDao repo = (AppApiParameterDao)getJpaRepository();
        Pageable pageable = PageRequest.of(page, size, parseSorts(sorts));
        return repo.findAll(pageable);
    }
    public AppApiParameter createAppApiParameter(AppApiParameter appApiParameter) {
        appApiParameterRepository.save(appApiParameter);
        return appApiParameter;
    }
    public AppApiParameter updateAppApiParameter(AppApiParameter appApiParameter){
        appApiParameterRepository.save(appApiParameter);
        return appApiParameter;
    }
    public void  deleteAppApiParameter(Integer id){
        appApiParameterRepository.deleteById(id);
    }
}

+ 47 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiResponseService.java

@ -0,0 +1,47 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.AppApiResponseDao;
import com.yihu.jw.entity.ehr.apps.AppApiResponse;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:54
 */
@Service
@Transactional
public class AppApiResponseService extends BaseJpaService<AppApiResponse, AppApiResponseDao> {
    @Autowired
    private AppApiResponseDao xAppApiResponseRepository;
    public AppApiResponseService() {
    }
    public Page<AppApiResponse> getAppApiResponseList(String sorts, int page, int size){
        AppApiResponseDao repo = (AppApiResponseDao)getJpaRepository();
        Pageable pageable = PageRequest.of(page, size, parseSorts(sorts));
        return repo.findAll(pageable);
    }
    public AppApiResponse createAppApiResponse(AppApiResponse appApiResponse) {
        xAppApiResponseRepository.save(appApiResponse);
        return appApiResponse;
    }
    public AppApiResponse updateAppApiResponse(AppApiResponse appApiResponse){
        xAppApiResponseRepository.save(appApiResponse);
        return appApiResponse;
    }
    public void  deleteAppApiResponse(Integer id){
        xAppApiResponseRepository.deleteById(id);
    }
}

+ 249 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppApiService.java

@ -0,0 +1,249 @@
package com.yihu.jw.basic.apps.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.apps.dao.AppApiErrorCodeDao;
import com.yihu.jw.basic.apps.dao.AppApiParameterDao;
import com.yihu.jw.basic.apps.dao.AppApiDao;
import com.yihu.jw.basic.apps.dao.AppApiResponseDao;
import com.yihu.jw.entity.ehr.apps.AppApi;
import com.yihu.jw.entity.ehr.apps.AppApiParameter;
import com.yihu.jw.entity.ehr.apps.AppApiResponse;
import com.yihu.jw.basic.user.dao.RoleApiRelationDao;
import com.yihu.jw.basic.user.dao.RoleAppRelationDao;
import com.yihu.jw.basic.user.dao.RolesDao;
import com.yihu.jw.entity.ehr.user.RoleApiRelation;
import com.yihu.jw.entity.ehr.user.RoleAppRelation;
import com.yihu.jw.entity.ehr.user.Roles;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.jw.entity.ehr.apps.AppApiErrorCode;
import com.yihu.jw.exception.ApiException;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:05:04
 */
@Service
@Transactional
public class AppApiService extends BaseJpaService<AppApi, AppApiDao> {
    private static final String ADD = "add";
    private static final String DELETE = "delete";
    private static final String UPDATE = "update";
    private static final String DATA_STATUS = "__status";
    private static final Integer NEW_DATA = 0;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private AppApiDao appApiRepository;
    @Autowired
    private AppApiParameterDao appApiParameterRepository;
    @Autowired
    private AppApiResponseDao appApiResponseRepository;
    @Autowired
    private RoleApiRelationDao xRoleApiRelationRepository;
    @Autowired
    private RoleAppRelationDao xRoleAppRelationRepository;
    @Autowired
    private AppApiErrorCodeDao appApiErrorCodeDao;
    @Autowired
    private RolesDao xRolesRepository;
    ObjectMapper objectMapper = new ObjectMapper();
    public Page<AppApi> getAppApiList(String sorts, int page, int size){
        AppApiDao repo = (AppApiDao)getJpaRepository();
        Pageable pageable = PageRequest.of(page, size, parseSorts(sorts));
        return repo.findAll(pageable);
    }
    public AppApi createAppApi(AppApi appApi) {
        if ("".equals(appApi.getMethodName())){
            appApi.setMethodName(null);
        }
        appApiRepository.save(appApi);
        return appApi;
    }
    public AppApi updateAppApi(AppApi appApi){
        appApiRepository.save(appApi);
        return appApi;
    }
    public void  deleteAppApi(Integer id){
        appApiRepository.deleteById(id);
    }
    public AppApi completeSave(String appApiStr, String apiParamStr, String apiResponseStr, String apiErrorCodeStr) throws IOException {
        AppApi appApi = objectMapper.readValue(appApiStr, AppApi.class);
        AppApi newAppApi = appApiRepository.save(appApi);
        saveParamAndResponseAndErrorCode(newAppApi.getId(), apiParamStr, apiResponseStr, apiErrorCodeStr);
        return newAppApi;
    }
    public void completeDelete(Integer id) {
        appApiParameterRepository.deleteByAppApiId(id);
        appApiResponseRepository.deleteByAppApiId(id);
        xRoleApiRelationRepository.deleteByApiId((long)id);
        appApiErrorCodeDao.deleteByAppApiId(id);
        appApiRepository.deleteById(id);
    }
    public AppApi findById(Integer id) {
        return appApiRepository.getOne(id);
    }
    public List<AppApi> findByCateId(Integer categoryId) {
        return appApiRepository.findByCategory(categoryId);
    }
    public List<AppApi> authApiList(String clientId) {
        String sql =  "SELECT aa.* FROM apps_api aa \n" +
                "\tLEFT JOIN role_api_relation rar ON rar.app_api_id = aa.id \n" +
                "\tWHERE rar.role_id IN (SELECT role_id FROM role_app_relation WHERE app_id ='" + clientId + "') \n" +
                "\tAND LENGTH(aa.micro_service_url) > 0 AND LENGTH(aa.ms_method_name) > 0";
        RowMapper rowMapper = BeanPropertyRowMapper.newInstance(AppApi.class);
        return (List<AppApi>)jdbcTemplate.query(sql, rowMapper);
    }
    public void authApi(String code, String appId, String appApiId) {
        Roles roles =  xRolesRepository.findByCodeAndAppId(code, appId);
        if (null == roles) {
            //创建扩展角色
            roles = new Roles();
            roles.setCode(code);
            roles.setName("扩展开发者");
            roles.setDescription("开放平台扩展开发者");
            roles.setAppId(appId);
            roles.setType("0");
            roles = xRolesRepository.save(roles);
            RoleAppRelation roleAppRelation = new RoleAppRelation();
            roleAppRelation.setAppId(code);
            roleAppRelation.setRoleId(roles.getId());
            xRoleAppRelationRepository.save(roleAppRelation);
        }
        String [] appApiIdArr = appApiId.split(",");
        for (String id : appApiIdArr) {
            if (null == xRoleApiRelationRepository.findRelation(new Long(id), roles.getId())) {
                RoleApiRelation roleApiRelation = new RoleApiRelation();
                roleApiRelation.setRoleId(roles.getId());
                roleApiRelation.setApiId(new Long(id));
                xRoleApiRelationRepository.save(roleApiRelation);
            }
        }
    }
    public void unAuthApi(String code, String appId, String appApiId) {
        Roles roles =  xRolesRepository.findByCodeAndAppId(code, appId);
        if (null == roles) {
            return;
        }
        String [] appApiIdArr = appApiId.split(",");
        for (String id : appApiIdArr) {
            xRoleApiRelationRepository.deleteByApiIdAndRoleId(new Long(id), roles.getId());
        }
    }
    /**
     * 操作apiParam及apiResponse及apiErrorCode
     *
     * @param apiId
     * @param apiParam
     * @param apiResponse
     */
    private void saveParamAndResponseAndErrorCode(Integer apiId, String apiParam, String apiResponse, String apiErrorCode) throws IOException {
        List<Map<String, Object>> list;
        if (!StringUtils.isEmpty(apiParam)) {
            list = objectMapper.readValue(apiParam, List.class);
            for (Map<String, Object> paramMap : list) {
                //删除的是新增的数据直接跳过
                if (DELETE.equals(paramMap.get(DATA_STATUS)) && NEW_DATA.equals(paramMap.get("id") + "")) {
                    continue;
                } else {
                    paramMap.put("appApiId", apiId);
                    String json = objectMapper.writeValueAsString(paramMap);
                    AppApiParameter appApiParameter = objectMapper.readValue(json, AppApiParameter.class);
                    if (ADD.equals(paramMap.get(DATA_STATUS))) {
                        appApiParameterRepository.save(appApiParameter);
                    } else if (UPDATE.equals(paramMap.get(DATA_STATUS))) {
                        AppApiParameter oldAppApiParameter = appApiParameterRepository.getOne(appApiParameter.getId());
                        if (oldAppApiParameter == null) {
                            throw new ApiException("更新的请求参数不存在:" + appApiParameter.getId(),ErrorCode.OBJECT_NOT_FOUND.value());
                        }
                        appApiParameterRepository.save(appApiParameter);
                    } else if (DELETE.equals(paramMap.get(DATA_STATUS))) {
                        appApiParameterRepository.deleteById(appApiParameter.getId());
                    }
                }
            }
        }
        if (!StringUtils.isEmpty(apiResponse)) {
            list = objectMapper.readValue(apiResponse, List.class);
            for (Map<String, Object> paramMap : list) {
                //删除的是新增的数据直接跳过
                if (DELETE.equals(paramMap.get(DATA_STATUS)) && NEW_DATA.equals(paramMap.get("id") + "")) {
                    continue;
                } else {
                    paramMap.put("appApiId", apiId);
                    String json = objectMapper.writeValueAsString(paramMap);
                    AppApiResponse appApiResponse = objectMapper.readValue(json, AppApiResponse.class);
                    if (ADD.equals(paramMap.get(DATA_STATUS))) {
                        appApiResponseRepository.save(appApiResponse);
                    } else if (UPDATE.equals(paramMap.get(DATA_STATUS))) {
                        AppApiResponse oldAppApiResponse = appApiResponseRepository.getOne(appApiResponse.getId());
                        if (oldAppApiResponse == null) {
                            throw new ApiException("更新的返回参数不存在:" + appApiResponse.getId(),ErrorCode.OBJECT_NOT_FOUND.value());
                        }
                        appApiResponseRepository.save(appApiResponse);
                    } else if (DELETE.equals(paramMap.get(DATA_STATUS))) {
                        appApiResponseRepository.delete(appApiResponse);
                    }
                }
            }
        }
        if (!StringUtils.isEmpty(apiErrorCode)) {
            list = objectMapper.readValue(apiErrorCode, List.class);
            for (Map<String, Object> paramMap : list) {
                //删除的是新增的数据直接跳过
                if (DELETE.equals(paramMap.get(DATA_STATUS)) && NEW_DATA.equals(paramMap.get("id") + "")) {
                    continue;
                } else {
                    paramMap.put("appApiId", apiId);
                    String json = objectMapper.writeValueAsString(paramMap);
                    AppApiErrorCode appApiErrorCode = objectMapper.readValue(json, AppApiErrorCode.class);
                    if (ADD.equals(paramMap.get(DATA_STATUS))) {
                        appApiErrorCodeDao.save(appApiErrorCode);
                    } else if (UPDATE.equals(paramMap.get(DATA_STATUS))) {
                        AppApiErrorCode oldAppApiErrorCode = appApiErrorCodeDao.getOne(appApiErrorCode.getId());
                        if (oldAppApiErrorCode == null) {
                            throw new ApiException("更新的错误码说明不存在:" + appApiErrorCode.getId(),ErrorCode.OBJECT_NOT_FOUND.value());
                        }
                        appApiErrorCodeDao.save(appApiErrorCode);
                    } else if (DELETE.equals(paramMap.get(DATA_STATUS))) {
                        appApiErrorCodeDao.delete(appApiErrorCode);
                    }
                }
            }
        }
    }
    public List<AppApi> findByName(String name) {
        return appApiRepository.findByName(name);
    }
}

+ 106 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppFeatureService.java

@ -0,0 +1,106 @@
package com.yihu.jw.basic.apps.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.apps.dao.AppFeatureDao;
import com.yihu.jw.entity.ehr.apps.AppFeature;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author linz
 * @version 1.0
 * @created 2016年7月7日21:04:33
 */
@Service
@Transactional
public class AppFeatureService extends BaseJpaService<AppFeature, AppFeatureDao> {
    @Autowired
    private AppFeatureDao xAppFeatureRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    ObjectMapper objectMapper;
    public Page<AppFeature> getAppFeatureList(String sorts, int page, int size){
        AppFeatureDao repo = (AppFeatureDao)getJpaRepository();
        Pageable pageable = PageRequest.of(page, size, parseSorts(sorts));
        return repo.findAll(pageable);
    }
    public AppFeature createAppFeature(AppFeature appFeature) {
        xAppFeatureRepository.save(appFeature);
        return appFeature;
    }
    public AppFeature updateAppFeature(AppFeature appFeature){
        xAppFeatureRepository.save(appFeature);
        return appFeature;
    }
    public void  deleteAppFeature(String id){
        xAppFeatureRepository.deleteById(id);
    }
    /**
     * 生成菜单JSON对象字符串
     * @return AppFeature
     */
    public AppFeature joinMenuItemJsonStr(AppFeature appFeature) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("id", appFeature.getId());
        contentMap.put("code", appFeature.getCode());
        contentMap.put("level", appFeature.getLevel());
        contentMap.put("text", appFeature.getName());
        contentMap.put("type", appFeature.getType());
        contentMap.put("iconUrl", appFeature.getIconUrl());
        if (appFeature.getLevel() != 1) {
            contentMap.put("pid", appFeature.getParentId());
        }
        if (appFeature.getUrl().startsWith("/")) {
            contentMap.put("url", appFeature.getPrefixUrl() + appFeature.getUrl());
        }
        appFeature.setContent(objectMapper.writeValueAsString(contentMap));
        return appFeature;
    }
    /**
     * 根据权限,获取应用菜单
     *
     * @param appId 应用ID
     * @param userId 用户ID
     * @return 菜单JSON字符串集合
     */
    public List<Map<String, Object>> findAppMenus(String appId, String userId, int parentId) throws IOException {
        List<Map<String, Object>> menuList = new ArrayList<>();
        String sql = " SELECT DISTINCT af.id AS id, af.content AS content FROM apps_feature af " +
                " JOIN role_user ru ON ru.user_id = '" + userId + "' " +
                " JOIN role_feature_relation rfr ON rfr.feature_id = af.id AND rfr.role_id = ru.role_id " +
                " WHERE af.app_id = '" + appId + "' AND af.parent_id = " + parentId + " AND af.type <> 3 " +
                " ORDER BY af.sort ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> item : list) {
            Map<String, Object> conMap = objectMapper.readValue(item.get("content").toString(), Map.class);
            menuList.add(conMap);
            menuList.addAll(findAppMenus(appId, userId, (int) item.get("id")));
        }
        return menuList;
    }
}

+ 287 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppService.java

@ -0,0 +1,287 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.*;
import com.yihu.jw.basic.resource.dao.RsAppResourceDao;
import com.yihu.jw.basic.resource.dao.RsAppResourceMetadataDao;
import com.yihu.jw.entity.ehr.apps.App;
import com.yihu.jw.entity.ehr.apps.AppApi;
import com.yihu.jw.entity.ehr.apps.UserApp;
import com.yihu.jw.basic.user.dao.RoleApiRelationDao;
import com.yihu.jw.basic.user.dao.RoleAppRelationDao;
import com.yihu.jw.basic.user.dao.RoleReportRelationDao;
import com.yihu.jw.basic.user.dao.RolesDao;
import com.yihu.jw.entity.ehr.user.RoleApiRelation;
import com.yihu.jw.entity.ehr.user.RoleAppRelation;
import com.yihu.jw.entity.ehr.user.Roles;
import com.yihu.jw.entity.ehr.oauth2.OauthClientDetails;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
 * @author Sand
 * @version 1.0
 * @created 03-8月-2015 16:53:06
 */
@Service
@Transactional
public class AppService extends BaseJpaService<App, AppDao> {
    private static final int AppIdLength = 10;
    private static final int AppSecretLength = 16;
    @Autowired
    private UserAppDao userAppDao;
    @Autowired
    private AppDao appDao;
    @Autowired
    private OauthClientDetailsDao oauthClientDetailsDao;
    @Autowired
    private RoleAppRelationDao roleAppRelationDao;
    @Autowired
    private RoleApiRelationDao roleApiRelationDao;
    @Autowired
    private RolesDao rolesDao;
    @Autowired
    private AppApiDao appApiDao;
    @Autowired
    private AppApiErrorCodeDao appApiErrorCodeDao;
    @Autowired
    private AppApiParameterDao appApiParameterDao;
    @Autowired
    private AppApiResponseDao appApiResponseDao;
    @Autowired
    private AppFeatureDao appFeatureDao;
    @Autowired
    private ReportCategoryAppRelationDao reportCategoryAppRelationDao;
    @Autowired
    private RsAppResourceDao rsAppResourceDao;
    @Autowired
    private RsAppResourceMetadataDao rsAppResourceMetadataDao;
    @Autowired
    private RoleReportRelationDao roleReportRelationDao;
    @Value("${fast-dfs.public-server}")
    private String fastDfsPublicServers;
    public AppService() {
    }
    public Page<App> getAppList(String sorts, int page, int size){
        AppDao repo = (AppDao)getJpaRepository();
        Pageable pageable = PageRequest.of(page, size, parseSorts(sorts));
        return repo.findAll(pageable);
    }
    public App createApp(App app) {
        app.setId(getRandomString(AppIdLength));
        app.setSecret(getRandomString(AppSecretLength));
        app.setCreateTime(new Date());
        app.setStatus("WaitingForApprove");
        OauthClientDetails oauthClientDetails = new OauthClientDetails();
        oauthClientDetails.setClientId(app.getId());
        oauthClientDetails.setResourceIds("*");
        oauthClientDetails.setClientSecret(app.getSecret());
        oauthClientDetails.setScope("read");
        oauthClientDetails.setAuthorizedGrantTypes("authorization_code,refresh_token,password,implicit,verify_code");
        oauthClientDetails.setWebServerRedirectUri(app.getUrl());
        oauthClientDetails.setAuthorities(null);
        oauthClientDetails.setAccessTokenValidity(null);
        oauthClientDetails.setAccessTokenValidity(null);
        oauthClientDetails.setAdditionalInformation(null);
        oauthClientDetails.setAutoApprove("true");
        oauthClientDetailsDao.save(oauthClientDetails);
        return appDao.save(app);
    }
    /**
     * 检验App与密码是否正确。
     *
     * @param id
     * @param secret
     * @return
     */
    public boolean verifyApp(String id, String secret) {
        App app = appDao.getOne(id);
        return app != null && app.getSecret().equals(secret);
    }
    public boolean isAppNameExists(String name){
        App app = appDao.findByName(name);
        return app != null;
    }
    public void checkStatus(String appId, String status) {
        App app = appDao.getOne(appId);
        //开启:Approved;禁用:Forbidden;
        app.setStatus(status);
        appDao.save(app);
        //是否显示showFlag
        String showFlag="1";
        if(status.equals("Forbidden")){
            showFlag="0";
        }
        List<UserApp> userAppList = findByAppId(appId);
        if(userAppList != null) {
            for (UserApp userApp : userAppList) {
                userApp.setShowFlag(Integer.parseInt(showFlag));
                userAppDao.save(userApp);
            }
        }
    }
    public List<UserApp> findByAppId(String appId){
        return  userAppDao.findByAppId(appId);
    }
    public boolean findByIdAndSecret(String appId, String secret) {
        return appDao.findByIdAndSecret(appId, secret).size()>0;
    }
    /**
     * 机构资源授权获取
     */
    public List<App> getApps(String userId , String catalog, String manageType) {
        String sql =
                "SELECT * FROM (" +
                        "SELECT b.id, b.name as name, b.secret as secret, b.url as url, b.out_url as outUrl, b.creator as creator," +
                        "   b.auditor as auditor, b.create_time as createTime, b.audit_time as auditTime , b.catalog as catalog, b.status as status, " +
                        "   b.description as description, b.org as org, b.code as code," +
                        "   IF(b.icon IS NULL OR b.icon = '','',CONCAT('" + fastDfsPublicServers + "','/',REPLACE(b.icon,':','/'))) AS icon," +
                        "   b.source_type as sourceType, b.release_flag as releaseFlag, b.manage_type AS manageType" +
                        "   FROM apps b " +
                        "LEFT JOIN user_app m on m.app_id=b.id " +
                        "WHERE b.catalog= :catalog AND m.user_id=:userId AND m.show_flag='1' AND b.status='Approved'";
        if (!StringUtils.isEmpty(manageType)) {
            sql += "AND b.manage_type = :manageType";
        }
        sql += ") p ORDER BY p.id";
        SQLQuery query = currentSession().createSQLQuery(sql);
        query.setParameter("userId", userId);
        query.setParameter("catalog", catalog);
        if (!StringUtils.isEmpty(manageType)) {
            query.setParameter("manageType", manageType);
        }
        query.setResultTransformer(Transformers.aliasToBean(App.class));
        return query.list();
    }
    public App findById(String appId) {
        return appDao.getOne(appId);
    }
    public App update(App app, OauthClientDetails oauthClientDetails){
        oauthClientDetailsDao.save(oauthClientDetails);
        return appDao.save(app);
    }
    public void delete(String appId) {
        List<Roles> rolesList = rolesDao.findByAppId(appId);
        rolesList.forEach(item -> {
            roleReportRelationDao.deleteByRoleId(item.getId());
        });
        roleAppRelationDao.deleteByAppId(appId);
        rolesDao.deleteByAppId(appId);
        userAppDao.deleteByAppId(appId);
        List<AppApi> appApiList = appApiDao.findByAppId(appId);
        appApiList.forEach(item -> {
            roleApiRelationDao.deleteByApiId(item.getId());
            appApiErrorCodeDao.deleteByAppApiId(item.getId());
            appApiParameterDao.deleteByAppApiId(item.getId());
            appApiResponseDao.deleteByAppApiId(item.getId());
        });
        appApiDao.deleteByAppId(appId);
        appFeatureDao.deleteByAppId(appId);
        reportCategoryAppRelationDao.deleteByAppId(appId);
        rsAppResourceDao.deleteByAppId(appId);
        rsAppResourceMetadataDao.deleteByAppId(appId);
        if (oauthClientDetailsDao.getOne(appId) != null) {
            oauthClientDetailsDao.deleteById(appId);
        }
        appDao.deleteById(appId);
    }
    public App authClient(App app, OauthClientDetails oauthClientDetails, Roles basicRole, Roles additionRole) {
        App newApp = appDao.save(app);
        oauthClientDetailsDao.save(oauthClientDetails);
        //扩展角色关联
        if (null == rolesDao.findByCodeAndAppId(additionRole.getCode(), additionRole.getAppId())) {
            additionRole = rolesDao.save(additionRole);
        }
        additionRole = rolesDao.findByCodeAndAppId(additionRole.getCode(), additionRole.getAppId());
        RoleAppRelation additionRoleAppRelation = new RoleAppRelation();
        additionRoleAppRelation.setAppId(app.getId());
        additionRoleAppRelation.setRoleId(additionRole.getId());
        if (null == roleAppRelationDao.findRelation(additionRoleAppRelation.getAppId(), additionRoleAppRelation.getRoleId())) {
            roleAppRelationDao.save(additionRoleAppRelation);
        }
        //通过基础开发者角色扩展api关联
        List<RoleApiRelation> roleApiRelationList = roleApiRelationDao.findByRoleId(basicRole.getId());
        for (RoleApiRelation temp : roleApiRelationList) {
            RoleApiRelation roleApiRelation1 = new RoleApiRelation();
            roleApiRelation1.setRoleId(additionRole.getId());
            roleApiRelation1.setApiId(temp.getApiId());
            roleApiRelationDao.save(roleApiRelation1);
        }
        return newApp;
    }
    public List<Map<String,Object>> getAppByParentIdAndUserId(String userId)throws Exception{
        /*String Sql ="SELECT s.*,r.type " +
                    " FROM user_app a " +
                    " LEFT JOIN apps_relation r ON a.app_id = r.app_id " +
                    " LEFT JOIN apps s ON a.app_id = s.id"+
                    " WHERE a.user_id='"+userId+"' AND r.parent_app_id='"+parentAppId+
                    "' AND a.status=0 AND a.show_flag=1 ";*/
        String sql ="SELECT a.* FROM role_user ru LEFT JOIN roles r ON ru.role_id = r.id LEFT JOIN apps a ON r.app_id = a.id WHERE ru.user_id='"+userId+"' and r.name='医生' and a.release_flag=1";
        List<Map<String,Object>> resultList =  jdbcTemplate.queryForList(sql);
        return resultList;
    }
    /**
     * 医生工作站获取 医生授权的应用
     */
    public List<App> getDoctorAppsByType(String userId , String doctorManageType) {
        String sql =
                "SELECT * FROM (" +
                        "SELECT b.id, b.name as name, b.secret as secret, b.url as url, b.out_url as outUrl, b.creator as creator," +
                        "   b.auditor as auditor, b.create_time as createTime, b.audit_time as auditTime , b.catalog as catalog, b.status as status, " +
                        "   b.description as description, b.org as org, b.code as code," +
                        "   IF(b.icon IS NULL OR b.icon = '','',CONCAT('" + fastDfsPublicServers + "','/',REPLACE(b.icon,':','/'))) AS icon," +
                        "   b.source_type as sourceType, b.release_flag as releaseFlag, b.manage_type AS manageType" +
                        "   FROM apps b " +
                        "LEFT JOIN user_app m on m.app_id=b.id " +
                        "WHERE  m.user_id=:userId AND m.show_flag='1' AND b.status='Approved'";
        if (!StringUtils.isEmpty(doctorManageType)) {
            sql += "AND b.doctor_manage_type = :doctorManageType";
        }
        sql += ") p ORDER BY p.id";
        SQLQuery query = currentSession().createSQLQuery(sql);
        query.setParameter("userId", userId);
        if (!StringUtils.isEmpty(doctorManageType)) {
            query.setParameter("doctorManageType", doctorManageType);
        }
        query.setResultTransformer(Transformers.aliasToBean(App.class));
        return query.list();
    }
}

+ 28 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppVersionService.java

@ -0,0 +1,28 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.AppVersionRepository;
import com.yihu.jw.entity.ehr.apps.AppVersion;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Version;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Trick on 2018/3/12.
 */
@Service
@Transactional
public class AppVersionService extends BaseJpaService<AppVersion, AppVersionRepository> {
    @Autowired
    private AppVersionRepository appVersionRepository;
    public AppVersion getAppVersion(String id){
        return appVersionRepository.getOne(id);
    }
    public AppVersion getAppVersionByCode(String code){
        return appVersionRepository.findBycode(code);
    }
}

+ 24 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/AppsRelationService.java

@ -0,0 +1,24 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.*;
import com.yihu.jw.entity.ehr.apps.AppsRelation;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author Sand
 * @version 1.0
 * @created 03-8月-2015 16:53:06
 */
@Service
@Transactional
public class AppsRelationService extends BaseJpaService<AppsRelation, AppsRelationDao> {
}

+ 14 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/OauthClientDetailsService.java

@ -0,0 +1,14 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.OauthClientDetailsDao;
import com.yihu.jw.entity.ehr.oauth2.OauthClientDetails;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
/**
 * Created by progr1mmer on 2018/1/23.
 */
@Service
public class OauthClientDetailsService extends BaseJpaService<OauthClientDetails, OauthClientDetailsDao> {
}

+ 44 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/apps/service/UserAppService.java

@ -0,0 +1,44 @@
package com.yihu.jw.basic.apps.service;
import com.yihu.jw.basic.apps.dao.UserAppDao;
import com.yihu.jw.entity.ehr.apps.UserApp;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * @author yeshijie
 * @version 1.0
 * @created 2017年2月16日18:04:13
 */
@Service
@Transactional
public class UserAppService extends BaseJpaService<UserApp, UserAppDao> {
    @Autowired
    private UserAppDao userAppRepository;
    public UserApp findByAppIdAndUserId(String appId, String userId){
        return  userAppRepository.findByAppIdAndUserId(appId,userId);
    }
    // 根据用户ID,删除所有的该用户关联的应用授权
    public void delUserAppByUserId(String userId){
        userAppRepository.deleteByUserId(userId);
    }
    /**
     * 根据userIds查询
     * @param userIds
     * @return
     */
    public List<UserApp> findListByUserIds(List<String> userIds){
        return userAppRepository.findByuserId(userIds);
    }
}

+ 26 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/config/TenantConfiguration.java

@ -0,0 +1,26 @@
package com.yihu.ehr.config;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 *   ehr使用 feginClient 调用eip(涉及到app应用,标准等) 时,需要此类,增加请求头信息
 */
@Configuration
public class TenantConfiguration {
    @Value("${eip.tenant}")
    private String tenant;
    @Bean
    public RequestInterceptor tenantInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                requestTemplate.header("tenant_name", tenant);
            }
        };
    }
}

+ 845 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/controller/ConventionalDictEndPoint.java

@ -0,0 +1,845 @@
package com.yihu.jw.basic.dict.controller;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.basic.dict.service.SystemDictEntryService;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import com.yihu.jw.restmodel.ehr.dict.MConventionalDict;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.dict.MDictionaryEntry;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * 惯用字典接口,用于快速提取常用的字典项。
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "Conventional-Dictionaries", description = "获取常用字典项", tags = {"系统字典-惯用字典"})
public class ConventionalDictEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private SystemDictEntryService dictEntryService;
    MConventionalDict getDictModel(Object dictEntry) {
        return convertToModel(dictEntry, MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/getDictionaries", method = RequestMethod.GET)
    @ApiOperation(value = "获取字典列表", notes = "根据查询条件获取字典列表")
    public PageEnvelop searchMConventionalDict(
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts,
            @RequestParam(value = "size", required = false) int size,
            @RequestParam(value = "page", required = false) int page) throws ParseException {
        PageEnvelop listResult = new PageEnvelop();
        List<MConventionalDict> conventionalDictList = dictEntryService.search(null, filters, sorts, page, size);
        if(conventionalDictList != null){
            listResult.setDetailModelList(conventionalDictList);
            listResult.setTotalCount((int)dictEntryService.getCount(filters));
            listResult.setStatus(200);
            listResult.setCurrPage(page);
            listResult.setPageSize(size);
        }else{
            listResult.setStatus(200);
            listResult.setMessage("查询无数据");
            listResult.setTotalCount(0);
        }
        return listResult;
    };
    @RequestMapping(value = "/dictionaries/app_catalog", method = RequestMethod.GET)
    @ApiOperation(value = "获取应用类别字典项", response = MConventionalDict.class)
    public MConventionalDict getAppCatalog(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry appCatalog = dictEntryService.getDictEntry(1, code);
        return getDictModel(appCatalog);
    }
    @RequestMapping(value = "/dictionaries/app_status", method = RequestMethod.GET)
    @ApiOperation(value = "获取应用状态字典项", response = MConventionalDict.class)
    public MConventionalDict getAppStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry appStatus = dictEntryService.getDictEntry(2, code);
        return getDictModel(appStatus);
    }
    @RequestMapping(value = "/dictionaries/gender", method = RequestMethod.GET)
    @ApiOperation(value = "获取性别字典项", response = MConventionalDict.class)
    public MConventionalDict getGender(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry gender = dictEntryService.getDictEntry(3, code);
        return getDictModel(gender);
    }
    @RequestMapping(value = "/dictionaries/martial_status", method = RequestMethod.GET)
    @ApiOperation(value = "获取婚姻状态字典项", response = MConventionalDict.class)
    public MConventionalDict getMartialStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry martialStatus = dictEntryService.getDictEntry(4, code);
        return getDictModel(martialStatus);
    }
    @RequestMapping(value = "/dictionaries/nation", method = RequestMethod.GET)
    @ApiOperation(value = "获取国家字典项", response = MConventionalDict.class)
    public MConventionalDict getNation(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry nation = dictEntryService.getDictEntry(5, code);
        return getDictModel(nation);
    }
    @RequestMapping(value = "/dictionaries/residence_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取人口居住类型字典项", response = MConventionalDict.class)
    public MConventionalDict getResidenceType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry residenceType = dictEntryService.getDictEntry(6, code);
        return getDictModel(residenceType);
    }
    @RequestMapping(value = "/dictionaries/org_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取组织机构类别字典项", response = MConventionalDict.class)
    public MConventionalDict getOrgType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry orgType = dictEntryService.getDictEntry(7, code);
        return getDictModel(orgType);
    }
    @RequestMapping(value = "/dictionaries/settled_way", method = RequestMethod.GET)
    @ApiOperation(value = "获取机构入驻方式字典项", response = MConventionalDict.class)
    public MConventionalDict getSettledWay(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry settledWay = dictEntryService.getDictEntry(8, code);
        return getDictModel(settledWay);
    }
    @RequestMapping(value = "/dictionaries/card_status", method = RequestMethod.GET)
    @ApiOperation(value = "获取卡状态字典项", response = MConventionalDict.class)
    public MConventionalDict getCardStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry cardStatus = dictEntryService.getDictEntry(9, code);
        return getDictModel(cardStatus);
    }
    @RequestMapping(value = "/dictionaries/card_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取卡类别字典项", response = MConventionalDict.class)
    public MConventionalDict getCardType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry cardType = dictEntryService.getDictEntry(10, code);
        return getDictModel(cardType);
    }
    @RequestMapping(value = "/dictionaries/request_state", method = RequestMethod.GET)
    @ApiOperation(value = "获取家庭成员请求消息状态字典项", response = MConventionalDict.class)
    public MConventionalDict getRequestState(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry requestState = dictEntryService.getDictEntry(11, code);
        return getDictModel(requestState);
    }
    @RequestMapping(value = "/dictionaries/key_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取密钥类型字典项", response = MConventionalDict.class)
    public MConventionalDict getKeyType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry keyType = dictEntryService.getDictEntry(12, code);
        return getDictModel(keyType);
    }
    @RequestMapping(value = "/dictionaries/medical_role", method = RequestMethod.GET)
    @ApiOperation(value = "获取医疗角色字典项", response = MConventionalDict.class)
    public MConventionalDict getMedicalRole(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry medicalRole = dictEntryService.getDictEntry(13, code);
        return getDictModel(medicalRole);
    }
    @RequestMapping(value = "/dictionaries/user_role", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户角色字典项", response = MConventionalDict.class)
    public MConventionalDict getUserRole(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry userRole = dictEntryService.getDictEntry(14, code);
        return getDictModel(userRole);
    }
    @RequestMapping(value = "/dictionaries/user_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户类型字典项", response = MConventionalDict.class)
    public MConventionalDict getUserType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry userType = dictEntryService.getDictEntry(15, code);
        return getDictModel(userType);
    }
    @RequestMapping(value = "/dictionaries/3rd_app", method = RequestMethod.GET)
    @ApiOperation(value = "获取连接的第三方应用字典项", response = MConventionalDict.class)
    public MConventionalDict getLoginAddress(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry loginAddress = dictEntryService.getDictEntry(20, code);
        return getDictModel(loginAddress);
    }
    @RequestMapping(value = "/dictionaries/yes_no", method = RequestMethod.GET)
    @ApiOperation(value = "获取是否字典项", response = MConventionalDict.class)
    public MConventionalDict getYesNo(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") boolean code) {
        String resultCode = code ? "true" : "false";
        SystemDictEntry yesNo = dictEntryService.getDictEntry(18, resultCode);
        return getDictModel(yesNo);
    }
    @RequestMapping(value = "/dictionaries/adaption_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取适配类型字典项", response = MConventionalDict.class)
    public MConventionalDict getAdapterType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry adapterType = dictEntryService.getDictEntry(21, code);
        return getDictModel(adapterType);
    }
    @RequestMapping(value = "/dictionaries/std_source_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取标准来源字典项", response = MConventionalDict.class)
    public MConventionalDict getStdSourceType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry stdSourceType = dictEntryService.getDictEntry(22, code);
        return getDictModel(stdSourceType);
    }
    @RequestMapping(value = "/dictionaries/std_source_types", method = RequestMethod.GET)
    @ApiOperation(value = "获取标准来源类型字典项", response = MConventionalDict.class)
    public Collection<MConventionalDict> getStdSourceTypeList(
            @ApiParam(name = "codes", value = "字典代码", defaultValue = "")
            @RequestParam(value = "codes") String[] codes) {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(22, codes);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/user_types", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户类型字典项", response = MConventionalDict.class)
    public Collection<MConventionalDict> getUserTypeList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(15, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/tags", method = RequestMethod.GET)
    @ApiOperation(value = "获取标签字典项", response = MConventionalDict.class)
    public Collection<MConventionalDict> getTagsList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(17, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/record_data_sources", method = RequestMethod.GET)
    @ApiOperation(value = "获取档案数据来源", response = MConventionalDict.class)
    public Collection<MConventionalDict> getRecordDataSourceList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(35, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/indicator_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取指标类型", response = MConventionalDict.class)
    public MConventionalDict getIndicatorType(
        @ApiParam(name = "code", value = "字典代码", defaultValue = "")
        @RequestParam(value = "code") String code) {
            SystemDictEntry indicatorType = dictEntryService.getDictEntry(23, code);
            return getDictModel(indicatorType);
    }
    @RequestMapping(value = "/dictionaries/drug_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取药品类型", response = MConventionalDict.class)
    public MConventionalDict getDrugType(
        @ApiParam(name = "code", value = "字典代码", defaultValue = "")
        @RequestParam(value = "code") String code) {
            SystemDictEntry drugType = dictEntryService.getDictEntry(24, code);
            return getDictModel(drugType);
    }
    @RequestMapping(value = "/dictionaries/drug_flag", method = RequestMethod.GET)
    @ApiOperation(value = "获取药品处方标识", response = MConventionalDict.class)
    public MConventionalDict getDrugFlag(
        @ApiParam(name = "code", value = "字典代码", defaultValue = "")
        @RequestParam(value = "code") String code) {
            SystemDictEntry drugFlag = dictEntryService.getDictEntry(25, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/user_source", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户来源字典项", response = MConventionalDict.class)
    public MConventionalDict getUserSource(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(26, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/family_relationship", method = RequestMethod.GET)
    @ApiOperation(value = "获取家庭关系字典项", response = MConventionalDict.class)
    public MConventionalDict getFamilyRelationship(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(16, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/resource_adapt_scheme", method = RequestMethod.GET)
    @ApiOperation(value = "获取资源适配方案类别字典项", response = MConventionalDict.class)
    public MConventionalDict getResourceAdaptScheme(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(29, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/mete_data_field_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取数据元字段类型字典项", response = MConventionalDict.class)
    public MConventionalDict getMeteDataFieldType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(30, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/business_domain", method = RequestMethod.GET)
    @ApiOperation(value = "获取业务领域字典项", response = MConventionalDict.class)
    public MConventionalDict getBusinessDomain(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(31, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/resource_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取资源分类字典项", response = MConventionalDict.class)
    public MConventionalDict getResourceType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(32, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/resource_access_type", method = RequestMethod.GET)
    @ApiOperation(value = "获取资源访问方式字典项", response = MConventionalDict.class)
    public MConventionalDict getResourceAccessType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(33, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/logical_relationship", method = RequestMethod.GET)
    @ApiOperation(value = "获取逻辑关系", response = MConventionalDict.class)
    public MConventionalDict getLogicalRelationship(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(34, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/logical_relationship_list", method = RequestMethod.GET)
    @ApiOperation(value = "获取逻辑关系", response = MConventionalDict.class)
    public Collection<MConventionalDict> getLogicalRelationshipList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(34, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/record_data_source", method = RequestMethod.GET)
    @ApiOperation(value = "获取档案数据来源,", response = MConventionalDict.class)
    public MConventionalDict getRecordDataSource(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(35, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/archives_audit_status", method = RequestMethod.GET)
    @ApiOperation(value = "档案关联审批状态", response = MConventionalDict.class)
    public MConventionalDict getArchivesAuditStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(36, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/archives_audit_status_list", method = RequestMethod.GET)
    @ApiOperation(value = "档案关联审批状态", response = MConventionalDict.class)
    public Collection<MConventionalDict> getArchivesAuditStatusList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(36, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/archives_manage_status", method = RequestMethod.GET)
    @ApiOperation(value = "档案管理状态", response = MConventionalDict.class)
    public MConventionalDict getArchivesManageStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(37, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/archives_manage_status_list", method = RequestMethod.GET)
    @ApiOperation(value = "档案管理状态", response = MConventionalDict.class)
    public Collection<MConventionalDict> getArchivesManageStatusList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(37, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/application_source", method = RequestMethod.GET)
    @ApiOperation(value = "应用来源", response = MConventionalDict.class)
    public MConventionalDict getApplicationSource(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(38, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/application_source_list", method = RequestMethod.GET)
    @ApiOperation(value = "应用来源", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApplicationSourceList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(38, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/application_menu_type", method = RequestMethod.GET)
    @ApiOperation(value = "应用菜单类型", response = MConventionalDict.class)
    public MConventionalDict getApplicationMenuType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(39, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/application_menu_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "应用菜单类型", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApplicationMenuTypeList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(39, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/open_level", method = RequestMethod.GET)
    @ApiOperation(value = "开放等级", response = MConventionalDict.class)
    public MConventionalDict getOpenLevel(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(40, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/open_level_list", method = RequestMethod.GET)
    @ApiOperation(value = "开放等级", response = MConventionalDict.class)
    public Collection<MConventionalDict> getOpenLevelList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(40, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/audit_level", method = RequestMethod.GET)
    @ApiOperation(value = "审计等级", response = MConventionalDict.class)
    public MConventionalDict getAuditLevel(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(41, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/audit_level_list", method = RequestMethod.GET)
    @ApiOperation(value = "审计等级", response = MConventionalDict.class)
    public Collection<MConventionalDict> getAuditLevelList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(41, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/role_type", method = RequestMethod.GET)
    @ApiOperation(value = "角色组分类", response = MConventionalDict.class)
    public MConventionalDict getRoleType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(42, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/role_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "角色组分类", response = MConventionalDict.class)
    public Collection<MConventionalDict> getRoleTypeList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(42, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/valid_identification", method = RequestMethod.GET)
    @ApiOperation(value = "有效标识", response = MConventionalDict.class)
    public MConventionalDict getValidIdentification(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(43, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/valid_identification_list", method = RequestMethod.GET)
    @ApiOperation(value = "有效标识", response = MConventionalDict.class)
    public Collection<MConventionalDict> getValidIdentificationList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(43, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/api_protocol", method = RequestMethod.GET)
    @ApiOperation(value = "API协议", response = MConventionalDict.class)
    public MConventionalDict getApiProtocol(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(44, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/api_protocol_list", method = RequestMethod.GET)
    @ApiOperation(value = "API协议", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApiProtocolList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(44, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/api_method", method = RequestMethod.GET)
    @ApiOperation(value = "API方法", response = MConventionalDict.class)
    public MConventionalDict getApiMethod(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(45, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/api_method_list", method = RequestMethod.GET)
    @ApiOperation(value = "API方法", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApiMethodList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(45, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/api_type", method = RequestMethod.GET)
    @ApiOperation(value = "API类型", response = MConventionalDict.class)
    public MConventionalDict getApiType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(46, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/api_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "API类型", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApiTypeList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(46, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/api_parameter_type", method = RequestMethod.GET)
    @ApiOperation(value = "API参数类型", response = MConventionalDict.class)
    public MConventionalDict getApiParameterType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(47, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/api_parameter_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "API参数类型", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApiParameterTypeList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(47, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/api_parameter_data_type", method = RequestMethod.GET)
    @ApiOperation(value = "API参数数据类型", response = MConventionalDict.class)
    public MConventionalDict getApiParameterDataType(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(48, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/api_parameter_data_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "API参数数据类型", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApiParameterDataTypeList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(48, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/api_parameter_data_required", method = RequestMethod.GET)
    @ApiOperation(value = "API参数必输标识", response = MConventionalDict.class)
    public MConventionalDict getApiParameterDataRequired(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry drugFlag = dictEntryService.getDictEntry(49, code);
        return getDictModel(drugFlag);
    }
    @RequestMapping(value = "/dictionaries/api_parameter_data_required_list", method = RequestMethod.GET)
    @ApiOperation(value = "API参数必输标识", response = MConventionalDict.class)
    public Collection<MConventionalDict> getApiParameterDataRequiredList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(49, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/cda_type_browser_list", method = RequestMethod.GET)
    @ApiOperation(value = "浏览器用CDA类别清单", response = MConventionalDict.class)
    public Collection<MConventionalDict> getCdaTypeForBrowserList() {
        List<SystemDictEntry> list = dictEntryService.getDictEntries(50, null);
        return convertToModels(list, new ArrayList<MConventionalDict>(list.size()), MConventionalDict.class, null);
    }
    @RequestMapping(value = "/dictionaries/portal_notice_list", method = RequestMethod.GET)
    @ApiOperation(value = "通知公告类别清单", response = MConventionalDict.class)
    public MConventionalDict getPortalNoticeTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(55, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/portal_notice_protal_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "通知公告云类别清单", response = MConventionalDict.class)
    public MConventionalDict getPortalNoticeProtalTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(56, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/portal_resources_platform_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "资源平台类别类别清单", response = MConventionalDict.class)
    public MConventionalDict getPortalResourcesPlatformTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(57, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/portal_resources_develop_lan_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "资源应用开发环境类别清单", response = MConventionalDict.class)
    public MConventionalDict getPortalResourcesDevelopLanTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(58, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/portal_messageRemind_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "消息提醒类别清单", response = MConventionalDict.class)
    public MConventionalDict getMessageRemindTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(59, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/portal_columnRequest_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "栏目请求方式清单", response = MConventionalDict.class)
    public MConventionalDict getColumnRequestTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(60, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/medicalCard_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "就诊卡类型", response = MConventionalDict.class)
    public MConventionalDict getMedicalCardTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry noticeType = dictEntryService.getDictEntry(66, code);
        return getDictModel(noticeType);
    }
    @RequestMapping(value = "/dictionaries/dimension_main_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "指标主维度类型", response = MConventionalDict.class)
    MConventionalDict getDimensionMainTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code){
        SystemDictEntry type = dictEntryService.getDictEntry(72, code);
        return getDictModel(type);
    };
    @RequestMapping(value = "/dictionaries/dimension_slave_type_list", method = RequestMethod.GET)
        @ApiOperation(value = "指标从维度类型", response = MConventionalDict.class)
        MConventionalDict getDimensionSlaveTypeList(
                @ApiParam(name = "code", value = "字典代码", defaultValue = "")
                @RequestParam(value = "code") String code){
            SystemDictEntry type = dictEntryService.getDictEntry(73, code);
            return getDictModel(type);
        };
        @RequestMapping(value = "/dictionaries/dimension_status_list", method = RequestMethod.GET)
        @ApiOperation(value = "指标维度状态", response = MConventionalDict.class)
        MConventionalDict getDimensionStatusList(
                @ApiParam(name = "code", value = "字典代码", defaultValue = "")
                @RequestParam(value = "code") String code)  {
            SystemDictEntry type = dictEntryService.getDictEntry(74, code);
            return getDictModel(type);
    };
    @RequestMapping(value = "/dictionaries/tj_data_source_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "指标统计数据资源", response = MConventionalDict.class)
    MConventionalDict getTjDataSourceTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code){
        SystemDictEntry type = dictEntryService.getDictEntry(75, code);
        return getDictModel(type);
    };
    @RequestMapping(value = "/dictionaries/tj_data_save_list", method = RequestMethod.GET)
    @ApiOperation(value = "指标统计数据存储", response = MConventionalDict.class)
    MConventionalDict getTjDataSaveList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(76, code);
        return getDictModel(type);
    };
    @RequestMapping(value = "/dictionaries/tj_quota_exec_type_list", method = RequestMethod.GET)
    @ApiOperation(value = "指标统计指标管理", response = MConventionalDict.class)
    MConventionalDict getTjQuotaExecTypeList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(77, code);
        return getDictModel(type);
    };
    @RequestMapping(value = "/dictionaries/tj_quota_data_level_list", method = RequestMethod.GET)
    @ApiOperation(value = "指标统计存储方式", response = MConventionalDict.class)
    MConventionalDict getTjQuotaDataLevelList(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(78, code);
        return getDictModel(type);
    };
    @RequestMapping(value = "/dictionaries/org_dept_detail_display_status", method = RequestMethod.GET)
    @ApiOperation(value = "是否显示", response = MConventionalDict.class)
    MConventionalDict getOrgDeptDetailDisplayStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(79, code);
        return getDictModel(type);
    }
    @RequestMapping(value = "/dictionaries/org_dept_detail_py_code", method = RequestMethod.GET)
    @ApiOperation(value = "科室类型", response = MConventionalDict.class)
    MConventionalDict getOrgDeptDetailPyCode(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(80, code);
        return getDictModel(type);
    }
    @RequestMapping(value = "/dictionaries/org_dept_detail_glory_id", method = RequestMethod.GET)
    @ApiOperation(value = "科室荣誉", response = MConventionalDict.class)
    MConventionalDict getOrgDeptDetailGloryId(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(81, code);
        return getDictModel(type);
    };
    @RequestMapping(value ="/GetAlldictionariesByDictId",method = RequestMethod.GET)
    @ApiOperation(value = "获取卡状态所有字典项")
    public PageEnvelop GetAlldictionariesByDictId() throws Exception{
        long dictId=66;
        int page=0;
        int size=1000;
        PageEnvelop re = new PageEnvelop();
        Page<SystemDictEntry> cardList = dictEntryService.findByDictId(dictId, page,size);
        if(cardList!=null) {
            re.setDetailModelList(cardList.getContent());
            re.setTotalCount(cardList.getTotalPages());
            re.setPageSize(size);
            re.setCurrPage(page);
        }
        return re;
    }
    @RequestMapping(value = "/dictionaries/tj_quota_log_status", method = RequestMethod.GET)
    @ApiOperation(value = "指标日志状态", response = MConventionalDict.class)
    MConventionalDict getTjQuotaLogStatus(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntry(82, code);
        return getDictModel(type);
    }
    @RequestMapping(value = "/dictionaries/tj_quota_algorithm", method = RequestMethod.GET)
    @ApiOperation(value = "指标算法", response = MConventionalDict.class)
    public MConventionalDict getTjQuotaAlgorithm(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code) {
        SystemDictEntry type = dictEntryService.getDictEntryByValueAndDictId(code,93);
        return getDictModel(type);
    }
    @RequestMapping(value = ServiceApi.SystemDict.getDictEntryByDictId,method = RequestMethod.POST)
    @ApiOperation("根据字典代码获取字典项列表")
    public  List<MDictionaryEntry> getDictEntryByDictId(
            @ApiParam(name="dictId",value="dictId",defaultValue = "")
            @RequestParam(value ="dictId")  String dictId) throws Exception {
        List<SystemDictEntry> DictEntrys = dictEntryService.getDictEntries(Long.parseLong(dictId),null);
        return (List<MDictionaryEntry>)convertToModels(DictEntrys,new ArrayList<MDictionaryEntry>(DictEntrys.size()),MDictionaryEntry.class,null);
    }
}

+ 165 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/controller/SystemDictEndPoint.java

@ -0,0 +1,165 @@
package com.yihu.jw.basic.dict.controller;
import com.yihu.jw.basic.dict.service.SystemDictService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.entity.ehr.dict.SystemDict;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.phonics.PinyinUtil;
import com.yihu.jw.restmodel.ehr.dict.MSystemDict;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * Created by linaz on 2015/8/12.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "Dictionary", description = "系统全局字典管理", tags = {"系统字典-系统全局字典管理"})
public class SystemDictEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private SystemDictService dictService;
    @ApiOperation(value = "获取字典列表", response = MSystemDict.class, responseContainer = "List")
    @RequestMapping(value = ServiceApi.SystemDict.Crud, method = RequestMethod.GET)
    public Collection<MSystemDict> getDictionaries(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) Integer size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        page = reducePage(page);
        if (StringUtils.isEmpty(filters)) {
            Page<SystemDict> systemDictPage = dictService.getDictList(sorts, page, size);
            pagedResponse(request, response, systemDictPage.getTotalElements(), page, size);
            return convertToModels(systemDictPage.getContent(), new ArrayList<>(systemDictPage.getNumber()), MSystemDict.class, fields);
        } else {
            List<SystemDict> systemDictList = dictService.search(fields, filters, sorts, page, size);
            pagedResponse(request, response, dictService.getCount(filters), page, size);
            return convertToModels(systemDictList, new ArrayList<>(systemDictList.size()), MSystemDict.class, fields);
        }
    }
    @ApiOperation(value = "创建字典", response = SystemDict.class)
    @RequestMapping(value = ServiceApi.SystemDict.Crud, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop createDictionary(
            @ApiParam(name = "dictionary", value = "字典JSON结构")
            @RequestBody SystemDict dict) throws IOException {
        if (StringUtils.isEmpty(dict.getName())) {
            return failed("字典名称不能为空");
        }
        if (StringUtils.isEmpty(dict.getPhoneticCode())) {
            dict.setPhoneticCode(PinyinUtil.getPinYinHeadChar(dict.getName(), true));
        }
        if (StringUtils.isEmpty(dict.getCode())) {
            dict.setCode(dict.getPhoneticCode());
        }
        SystemDict systemDict = dictService.createDict(dict);
        return success(systemDict);
    }
    @ApiOperation(value = "获取字典", response = MSystemDict.class)
    @RequestMapping(value = ServiceApi.SystemDict.FindById, method = RequestMethod.GET)
    public SystemDict getDictionary(
            @ApiParam(name = "id", value = "字典ID", defaultValue = "")
            @PathVariable(value = "id") long id) {
        SystemDict dict = dictService.retrieve(id);
        if (dict == null) {
            throw new ApiException("字典不存在",ErrorCode.NOT_FOUND.value() );
        }
        return dict;
    }
    @ApiOperation(value = "获取字典", response = SystemDict.class)
    @RequestMapping(value = ServiceApi.SystemDict.FindByPhoneticCode, method = RequestMethod.GET)
    public SystemDict getDictionaryByPhoneticCode(
            @ApiParam(name = "phoneticCode", value = "拼音编码", required = true)
            @PathVariable(value = "phoneticCode") String phoneticCode) {
        SystemDict dict = dictService.findByPhoneticCode(phoneticCode);
        if (dict == null) {
            throw new ApiException("字典不存在",ErrorCode.NOT_FOUND.value());
        }
        return dict;
    }
    @ApiOperation(value = "更新字典")
    @RequestMapping(value = ServiceApi.SystemDict.Crud, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Envelop updateDictionary(
            @ApiParam(name = "dictionary", value = "字典JSON结构")
            @RequestBody SystemDict dict) throws Exception {
        SystemDict oldDict = dictService.getOne(dict.getId());
        if (null == oldDict) {
            return failed("字典不存在", ErrorCode.OBJECT_NOT_FOUND.value());
        }
        if (StringUtils.isEmpty(dict.getName())) {
            return failed("字典名称不能为空");
        }
        if (!oldDict.getName().equals(dict.getName()) && dictService.findByField("name", dict.getName()).size() > 0) {
            return failed("字典名称在系统中已存在");
        }
        if (StringUtils.isEmpty(dict.getPhoneticCode())) {
            dict.setPhoneticCode(PinyinUtil.getPinYinHeadChar(dict.getName(), true));
        }
        if (StringUtils.isEmpty(dict.getCode())) {
            dict.setCode(dict.getPhoneticCode());
        }
        oldDict.setName(dict.getName());
        oldDict.setPhoneticCode(dict.getPhoneticCode());
        oldDict.setCode(dict.getCode());
        dictService.updateDict(oldDict);
        return success(oldDict);
    }
    @ApiOperation(value = "删除字典")
    @RequestMapping(value = ServiceApi.SystemDict.DeleteById, method = RequestMethod.DELETE)
    public Boolean deleteDictionary(
            @ApiParam(name = "id", value = "字典ID")
            @PathVariable(value = "id") long id) throws Exception{
        dictService.deleteDict(id);
        return true;
    }
    @RequestMapping(value = ServiceApi.SystemDict.CheckName, method = RequestMethod.GET)
    @ApiOperation(value = "判断提交的字典名称是否已经存在")
    public boolean isDictNameExists(
            @ApiParam(name = "dict_name", value = "字典名称")
            @RequestParam(value = "dict_name") String dictName){
        return dictService.isDictNameExists(dictName);
    }
    @RequestMapping(value = ServiceApi.SystemDict.CheckCode, method = RequestMethod.GET)
    @ApiOperation(value = "判断提交的字典编码是否已经存在")
    public boolean checkCode(
            @ApiParam(name = "code", value = "编码")
            @RequestParam(value = "code") String code) {
        if (dictService.findByField("code", code).size() > 0) {
            return true;
        }
        return false;
    }
}

+ 206 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/controller/SystemDictEntryEndPoint.java

@ -0,0 +1,206 @@
package com.yihu.jw.basic.dict.controller;
import com.yihu.jw.basic.dict.service.SystemDictEntryService;
import com.yihu.jw.basic.dict.service.SystemDictService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.entity.ehr.dict.DictEntryKey;
import com.yihu.jw.entity.ehr.dict.SystemDict;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.dict.MDictionaryEntry;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author Sand
 * @version 1.0
 * @created 2016.02.15 18:25
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "DictionaryEntry", description = "系统全局字典项管理", tags = {"系统字典-系统全局字典项管理"})
public class SystemDictEntryEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private SystemDictService dictService;
    @Autowired
    private SystemDictEntryService systemDictEntryService;
    @ApiOperation(value = "获取字典项列表")
    @RequestMapping(value = "/dictionaries/entries", method = RequestMethod.GET)
    public List<MDictionaryEntry> getDictEntries(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) Integer size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<SystemDictEntry> systemDictEntryList = systemDictEntryService.search(fields,filters,sorts,page,size);
        pagedResponse(request, response,systemDictEntryService.getCount(filters), page, size);
        return (List<MDictionaryEntry>)convertToModels(systemDictEntryList,new ArrayList<MDictionaryEntry>(systemDictEntryList.size()),MDictionaryEntry.class,null);
    }
    @ApiOperation(value = "创建字典项")
    @RequestMapping(value = "/dictionaries/entries", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public MDictionaryEntry createDictEntry (
            @ApiParam(name = "entry", value = "字典JSON结构")
            @RequestBody String entryJson) throws IOException{
        SystemDictEntry entry = toEntity(entryJson, SystemDictEntry.class);
        SystemDict systemDict = dictService.retrieve(entry.getDictId());
        if (systemDict == null) {
            throw new ApiException("所属字典不存在",ErrorCode.NOT_FOUND.value());
        }
        int nextSort = systemDictEntryService.getNextSN(entry.getDictId());
        entry.setSort(nextSort);
        systemDictEntryService.createDictEntry(entry);
        return convertToModel(entry, MDictionaryEntry.class, null);
    }
    @ApiOperation(value = "获取字典项")
    @RequestMapping(value = "/dictionaries/{dict_id}/entries/{code}", method = RequestMethod.GET)
    public MDictionaryEntry getDictEntry(
            @ApiParam(name = "dict_id", value = "字典ID", required = true)
            @PathVariable(value = "dict_id") long dictId,
            @ApiParam(name = "code", value = "字典项代码", required = true)
            @PathVariable(value = "code") String code) {
        SystemDictEntry systemDictEntry = systemDictEntryService.getDictEntry(dictId, code);
        return convertToModel(systemDictEntry, MDictionaryEntry.class);
    }
    @ApiOperation(value = "删除字典项")
    @RequestMapping(value = "/dictionaries/{dict_id}/entries/{code}", method = RequestMethod.DELETE)
    public Object deleteDictEntry(
            @ApiParam(name = "dict_id", value = "字典ID", defaultValue = "")
            @PathVariable(value = "dict_id") long dictId,
            @ApiParam(name = "code", value = "字典ID", defaultValue = "")
            @PathVariable(value = "code") String code) throws Exception{
        systemDictEntryService.deleteDictEntry(dictId, code);
        return true;
    }
    @ApiOperation(value = "修改字典项")
    @RequestMapping(value = "/dictionaries/entries", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public MDictionaryEntry updateDictEntry(
            @ApiParam(name = "entry", value = "字典JSON结构")
            @RequestBody String entryJson) throws IOException {
        SystemDictEntry entry = toEntity(entryJson, SystemDictEntry.class);
        SystemDictEntry temp = systemDictEntryService.retrieve(new DictEntryKey(entry.getCode(), entry.getDictId()));
        if (null == temp) {
            throw new ApiException("字典项不存在",ErrorCode.NOT_FOUND.value());
        }
        systemDictEntryService.saveDictEntry(entry);
        return convertToModel(entry, MDictionaryEntry.class, null);
    }
    @RequestMapping(value = "/dictionaries/existence/{dict_id}" , method = RequestMethod.GET)
    @ApiOperation(value = "根据dictId和code判断提交的字典项名称是否已经存在")
    public boolean isDictEntryCodeExists(
            @ApiParam(name = "dict_id", value = "dict_id", defaultValue = "")
            @PathVariable(value = "dict_id") long dictId,
            @ApiParam(name = "code", value = "code", defaultValue = "")
            @RequestParam(value = "code") String code){
        return systemDictEntryService.isDictContainEntry(dictId, code);
    }
    @RequestMapping(value ="/dictionaries/systemDictEntryList/{dict_id}",method = RequestMethod.GET)
    @ApiOperation(value = "根据dictId获取所有字典项")
    public PageEnvelop GetSystemDictEntryListByDictId(
            @ApiParam(name = "dict_id", value = "dict_id", defaultValue = "")
            @PathVariable(value = "dict_id") long dictId) throws Exception{
        int page=0;
        int size=1000;
        PageEnvelop re = new PageEnvelop(page,size);
        Page<SystemDictEntry> cardList = systemDictEntryService.findByDictId(dictId, page,size);
        if(cardList!=null) {
            re.setDetailModelList(cardList.getContent());
            re.setTotalCount(cardList.getTotalPages());
        }
        return re;
    }
    @RequestMapping(value ="/dictionary/entryList/{dictId}", method = RequestMethod.GET)
    @ApiOperation(value = "根据dictId获取所有字典项")
    public Envelop listByDictId(
            @ApiParam(name = "dictId", value = "dictId", required =  true)
            @PathVariable(value = "dictId") long dictId) {
        ListEnvelop envelop = new ListEnvelop();
        int page = 0;
        int size = 1000;
        //ListResult re = new ListResult(page, size);
        Page<SystemDictEntry> page1 = systemDictEntryService.findByDictId(dictId, page,size);
        if(page1 != null) {
            envelop.setDetailModelList(page1.getContent());
            envelop.setStatus(200);
        }
        return envelop;
    }
    @ApiOperation(value = "未登录获取字典项")
    @RequestMapping(value = ServiceApi.SystemDict.GetDictEntryByDictIdAndEntryCode, method = RequestMethod.GET)
    public Envelop getDictEntryByDictIdAndEntryCode(
            @ApiParam(name = "dictId", value = "字典ID", required = true)
            @RequestParam(value = "dictId") long dictId,
            @ApiParam(name = "code", value = "字典项代码", required = true)
            @RequestParam(value = "code") String code) {
        ObjEnvelop envelop =new ObjEnvelop();
        SystemDictEntry systemDictEntry = systemDictEntryService.getDictEntry(dictId, code);
        MDictionaryEntry mDictionaryEntry=convertToModel(systemDictEntry, MDictionaryEntry.class);
        envelop.setObj(mDictionaryEntry);
        envelop.setStatus(200);
        return envelop;
    }
    @RequestMapping(value = ServiceApi.SystemDict.getDictEntryCodeAndValueByDictId, method = RequestMethod.GET)
    @ApiOperation("根据字典id获取所有字典项的code和值")
    public Envelop getDictEntryCodeAndValueByDictId(
            @ApiParam(name = "dictId", value = "字典id")
            @RequestParam(value = "dictId", required = false) String dictId) throws Exception {
        ObjEnvelop envelop = new ObjEnvelop();
        Map<String, String> map = new HashMap<>();
        List list = systemDictEntryService.getDictEntryCodeAndValueByDictId(dictId);
        String code = "";
        String value = "";
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            if (null != obj[0] && null != obj[1]) {
                code = obj[0].toString();
                value = obj[1].toString();
                map.put(code, value);
            }
        }
        envelop.setStatus(200);
        envelop.setObj(map);
        return envelop;
    }
}

+ 59 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/dao/SystemDictEntryRepository.java

@ -0,0 +1,59 @@
package com.yihu.jw.basic.dict.dao;
import com.yihu.jw.entity.ehr.dict.DictEntryKey;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * 字典项DAO。
 *
 * @author Sand
 * @version 1.0
 * @created 2017.01.30 14:43
 */
public interface SystemDictEntryRepository extends JpaRepository<SystemDictEntry, DictEntryKey> {
    List<SystemDictEntry> findByDictId(long dictId);
    Page<SystemDictEntry> findByDictId(long dictId, Pageable pageable);
    Page<SystemDictEntry> findByDictIdAndValueLike(long dictId, String value, Pageable pageable);
    @Modifying
    void deleteByDictId(long dictId);
    @Modifying
    void deleteByCodeAndDictId(String code,long dictId);
    /**
     * 获取字典项下一排序号.
     *
     * @param dictId
     * @return
     */
    @Query("select max(entry.sort) from SystemDictEntry entry where entry.dictId = :dictId")
    Integer getNextEntrySN(@Param("dictId") long dictId);
    /**
     * 批量获取字典项列表.
     *
     * @param dictId
     * @param codes
     * @return
     */
    @Query("select entry from SystemDictEntry entry where entry.dictId = :dictId and entry.code in (:codes) order by entry.sort asc")
    List<SystemDictEntry> findByDictIdAndCodes(@Param("dictId") long dictId, @Param("codes") String[] codes);
    @Query("select entry from SystemDictEntry entry where entry.dictId = :dictId and entry.value = :value")
    List<SystemDictEntry> findByDictIdAndValue(@Param("dictId") long dictId, @Param("value") String value);
    List<SystemDictEntry> findByDictIdAndCode(@Param("dictId") long dictId, @Param("code") String code);
}

+ 27 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/dao/SystemDictRepository.java

@ -0,0 +1,27 @@
package com.yihu.jw.basic.dict.dao;
import com.yihu.jw.entity.ehr.dict.SystemDict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
/**
 * 字典CRUD操作接口使用 JpaRepository 中的方法,除非有特殊需要再添加自定义方法。
 *
 * @author CWS
 * @version 1.0
 * @created 2015.07.30 14:43
 */
public interface SystemDictRepository extends JpaRepository<SystemDict, Long> {
    SystemDict findByName(String name);
    Page<SystemDict> findByNameOrPhoneticCodeOrderByNameAsc(String name, String phoneticCode, Pageable pageable);
    @Query("select max(dict.id) from SystemDict dict where 1=1")
    long getNextId();
    SystemDict findByPhoneticCode(String phoneticCode);
}

+ 158 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/service/SystemDictEntryService.java

@ -0,0 +1,158 @@
package com.yihu.jw.basic.dict.service;
import com.yihu.jw.basic.dict.dao.SystemDictEntryRepository;
import com.yihu.jw.entity.ehr.dict.DictEntryKey;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 字典项服务。
 *
 * @author Sand
 * @version 1.0
 * @created 2016.02.14 14:49
 */
@Service
@Transactional
public class SystemDictEntryService extends BaseJpaService<SystemDictEntry, SystemDictEntryRepository> {
    @Autowired
    private SystemDictEntryRepository systemDictEntryRepository;
    /**
     * 下一字典项排序号。
     *
     * @param dictId
     * @return
     */
    public int getNextSN(long dictId) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        Integer nextSort = repo.getNextEntrySN(dictId);
        return null == nextSort ? 1 : nextSort + 1;
    }
    /**
     * 获取所有字典项。对于大字典,若不分页效率可能会很低。
     *
     * @param dictId 字典ID
     * @param page   分页,-1 表示查找全部
     * @param size   页大小, page 为 -1 时忽略此参数
     * @return
     */
    public Page<SystemDictEntry> getDictEntries(long dictId, int page, int size) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        return repo.findByDictId(dictId, page == -1 ? null : PageRequest.of(page, size));
    }
    /**
     * 获取简易字典项列表.
     *
     * @param dictId
     * @param codes  字典项代码列表,为空返回所有字典项. 但对于大字典效率会很低.
     * @return
     */
    public List<SystemDictEntry> getDictEntries(long dictId, String[] codes) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        if (codes == null) {
            return repo.findByDictId(dictId);
        } else {
            return repo.findByDictIdAndCodes(dictId, codes);
        }
    }
    /**
     * 获取字典项。
     *
     * @param dictId
     * @param code
     * @return
     */
    public SystemDictEntry getDictEntry(long dictId, String code) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        return repo.getOne(new DictEntryKey(code, dictId));
    }
    public SystemDictEntry getDictEntryByValueAndDictId(String value, long dictId) {
        List<SystemDictEntry> systemDictEntryList = systemDictEntryRepository.findByDictIdAndValue(dictId, value);
        if (null != systemDictEntryList && systemDictEntryList.size() > 0) {
            return systemDictEntryList.get(0);
        }
        return null;
    }
    /**
     * 按字典ID与字典项值查找字典项.
     *
     * @param dictId
     * @param value
     * @param page
     * @param size
     * @return
     */
    public Page<SystemDictEntry> findByDictIdAndValueLike(long dictId, String value, int page, int size) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        return repo.findByDictIdAndValueLike(dictId, value, PageRequest.of(page, size));
    }
    /**
     * 按字典ID查找字典项.
     *
     * @param dictId
     * @param page
     * @param size
     * @return
     */
    public Page<SystemDictEntry> findByDictId(long dictId, int page, int size) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        return repo.findByDictId(dictId, PageRequest.of(page, size));
    }
    public boolean isDictContainEntry(long dictId, String code) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        SystemDictEntry systemDictEntry = repo.getOne(new DictEntryKey(code, dictId));
        return systemDictEntry != null;
    }
    public SystemDictEntry saveDictEntry(SystemDictEntry systemDictEntry) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        return repo.save(systemDictEntry);
    }
    public void createDictEntry(SystemDictEntry systemDictEntry) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        repo.save(systemDictEntry);
    }
    public void deleteDictEntry(long dictId, String code) {
        SystemDictEntryRepository repo = (SystemDictEntryRepository) getJpaRepository();
        repo.deleteByCodeAndDictId(code, dictId);
    }
    /**
     * 根据字典id获取字典项编码和值
     */
    public List getDictEntryCodeAndValueByDictId(String dict_id) {
        String sql = "SELECT code,value FROM system_dict_entries where dict_id=:dict_id";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameter("dict_id", dict_id);
        return sqlQuery.list();
    }
}

+ 77 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/dict/service/SystemDictService.java

@ -0,0 +1,77 @@
package com.yihu.jw.basic.dict.service;
import com.yihu.jw.basic.dict.dao.SystemDictEntryRepository;
import com.yihu.jw.basic.dict.dao.SystemDictRepository;
import com.yihu.jw.entity.ehr.dict.SystemDict;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
 * 系统字典管理器.
 *
 * @author Sand
 * @version 1.0
 * @created 2015.07.30 11:46
 */
@Service
@Transactional
public class SystemDictService extends BaseJpaService<SystemDict, SystemDictRepository> {
    @Autowired
    private SystemDictRepository dictRepo;
    @Autowired
    private SystemDictEntryRepository entryRepo;
    public Page<SystemDict> getDictList(String sorts, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, parseSorts(sorts));
        return dictRepo.findAll(pageable);
    }
    public SystemDict createDict(SystemDict dict) {
        dict.setCreateDate(new Date());
        dict.setName(dict.getName());
        dictRepo.save(dict);
        return dict;
    }
    public void updateDict(SystemDict dict) {
        dictRepo.save(dict);
    }
    public void deleteDict(long dictId) {
        entryRepo.deleteByDictId(dictId);
        dictRepo.deleteById(dictId);
    }
    public boolean isDictNameExists(String name) {
        SystemDict systemDict = dictRepo.findByName(name);
        return systemDict != null;
    }
    public Page<SystemDict> searchDict(String name, String phoneticCode, int page, int size) {
        return dictRepo.findByNameOrPhoneticCodeOrderByNameAsc(name, phoneticCode, PageRequest.of(page, size));
    }
    public long getNextId() {
        long id = dictRepo.getNextId()+1;
        return id;
    }
    public SystemDict findByPhoneticCode(String code) {
        return dictRepo.findByPhoneticCode(code);
    }
    public SystemDict getOne(long id) {
        return  dictRepo.getOne(id);
    }
}

+ 175 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/controller/FileResourceEndPoint.java

@ -0,0 +1,175 @@
package com.yihu.jw.basic.fileresource.controller;
import com.yihu.jw.basic.fileresource.service.FileResource;
import com.yihu.jw.basic.fileresource.service.FileResourceManager;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.entity.ehr.id.BizObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/**
 * @author linaz
 * @created 2016.05.12 8:53
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "files", description = "文件管理接口", tags = {"文件管理接口"})
public class FileResourceEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private FileResourceManager fileResourceManager;
    @Value("${fast-dfs.public-server}")
    private String fastDfsPublicServers;
    @RequestMapping(value = "/files_upload", method = RequestMethod.POST)
    @ApiOperation(value = "上传文件")
    public String fileUpload(
            @ApiParam(name = "file_str", value = "文件字符串", required = true)
            @RequestBody String fileStr,
            @ApiParam(name = "file_name", value = "文件名", required = true)
            @RequestParam(value = "file_name") String fileName,
            @ApiParam(name = "json_data", value = "文件资源属性", required = true)
            @RequestParam(value = "json_data") String jsonData) throws Exception {
        FileResource fileResource = toEntity(jsonData, FileResource.class);
        fileResource.setId(getObjectId(BizObject.FileResource));
        return fileResourceManager.saveFileResource(fileStr, fileName, fileResource);
    }
    @RequestMapping(value = "/files_upload_returnUrl", method = RequestMethod.POST)
    @ApiOperation(value = "上传文件,并返回存储相对路径")
    public String fileUploadReturnUrl(
            @ApiParam(name = "file_str", value = "文件字符串", required = true)
            @RequestBody String fileStr,
            @ApiParam(name = "file_name", value = "文件名", required = true)
            @RequestParam(value = "file_name") String fileName,
            @ApiParam(name = "json_data", value = "文件资源属性", required = true)
            @RequestParam(value = "json_data") String jsonData) throws Exception {
            FileResource fileResource = toEntity(jsonData, FileResource.class);
            fileResource.setId(getObjectId(BizObject.FileResource));
            return fileResourceManager.saveFileResourceReturnUrl(fileStr, fileName, fileResource);
    }
    @RequestMapping(value = "/files_upload_returnHttpUrl", method = RequestMethod.POST)
    @ApiOperation(value = "上传文件,并返回存储绝对路径")
    public String fileUploadReturnHttpUrl(
            @ApiParam(name = "file_str", value = "文件字符串", required = true)
            @RequestBody String fileStr,
            @ApiParam(name = "file_name", value = "文件名", required = true)
            @RequestParam(value = "file_name") String fileName,
            @ApiParam(name = "json_data", value = "文件资源属性", required = true)
            @RequestParam(value = "json_data") String jsonData) throws Exception {
        FileResource fileResource = toEntity(jsonData, FileResource.class);
        fileResource.setId(getObjectId(BizObject.FileResource));
        return fileResourceManager.saveFileResourceReturnHttpUrl(fileStr, fileName, fileResource);
    }
    @RequestMapping(value = "/files", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除资源表对应关系,并且删除fastdfs相对应文件")
    public boolean filesDelete(
            @ApiParam(name = "object_id", value = "文件字符串", required = true)
            @RequestParam(value = "object_id") String objectId) throws Exception {
        List<FileResource> fileResources = fileResourceManager.findByObjectId(objectId);
        return fileResourceManager.deleteFileResource(fileResources);
    }
    @RequestMapping(value = "/image_delete", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除资源表对应关系,并且删除fastdfs相对应文件")
    public boolean filesDeleteByPath(
            @ApiParam(name = "storagePath", value = "文件路径", required = true)
            @RequestParam(value = "storagePath") String storagePath) throws Exception {
        String s = java.net.URLDecoder.decode(storagePath, "UTF-8");
        List<FileResource> fileResources = fileResourceManager.findByStoragePath(s);
        return fileResourceManager.deleteFileResource(fileResources);
    }
    @RequestMapping(value = "/files_download", method = RequestMethod.GET)
    @ApiOperation(value = "下载文件")
    public List<String> filesDownload(
            @ApiParam(name = "object_id", value = "文件字符串", required = true)
            @RequestParam(value = "object_id") String objectId,
            @ApiParam(name = "mime", value = "所有者", required = true)
            @RequestParam(value = "mime", required = false) String mime) throws Exception {
        List<FileResource> fileResources;
        if (StringUtils.isEmpty(mime))
            fileResources = fileResourceManager.findByObjectId(objectId);
        else
            fileResources = fileResourceManager.findByObjectIdAndMime(objectId, mime);
        List<String> filesStrs = new ArrayList<>();
        for (FileResource fileResource : fileResources) {
            String storagePath = fileResource.getStoragePath();
            String groupName = storagePath.split(":")[0];
            String remoteFileName = storagePath.split(":")[1];
            byte[] bytes = fastDFSUtil.download(groupName, remoteFileName);
            String fileStream = new String(Base64.getEncoder().encode(bytes));
            filesStrs.add(fileStream);
        }
        return filesStrs;
    }
    @RequestMapping(value = "/files_path", method = RequestMethod.GET)
    @ApiOperation(value = "获取文件路径")
    public List<String> getFilePath(
            @ApiParam(name = "object_id", value = "文件字符串", required = true)
            @RequestParam(value = "object_id") String objectId) throws Exception {
        List<FileResource> fileResources = fileResourceManager.findByObjectId(objectId);
        List<String> filesStrs = new ArrayList<>();
        for (FileResource fileResource : fileResources) {
            String storagePath = fileResource.getStoragePath();
            storagePath = URLEncoder.encode(storagePath, "ISO8859-1");
            filesStrs.add(storagePath);
        }
        return filesStrs;
    }
    @RequestMapping(value = "/image_view", method = RequestMethod.GET)
    @ApiOperation(value = "下载文件")
    public String imageView(
            @ApiParam(name = "storagePath", value = "文件路径", required = true)
            @RequestParam(value = "storagePath") String storagePath) throws Exception {
        String s = java.net.URLDecoder.decode(storagePath, "UTF-8");
        String groupName = s.split(":")[0];
        String remoteFileName = s.split(":")[1];
        byte[] bytes = fastDFSUtil.download(groupName, remoteFileName);
        String fileStream = new String(Base64.getEncoder().encode(bytes));
        return fileStream;
    }
    @ApiOperation(value = "根据文件ID,获取文件的真实访问路径")
    @RequestMapping(value = "/file/getRealPathById", method = RequestMethod.GET)
    public String getRealPathById(
            @ApiParam(name = "fileId", value = "文件ID", required = true)
            @RequestParam(value = "fileId") String fileId) throws Exception {
        String s = java.net.URLDecoder.decode(fileId, "UTF-8");
        String path = fileResourceManager.getStoragePathById(s);
        path = path.replace(":", "/");
        path = fastDfsPublicServers + "/" + path;
        return path;
    }
    @ApiOperation(value = "根据文件的存储路径,获取文件的真实访问路径")
    @RequestMapping(value = "/file/getRealPathByStoragePath", method = RequestMethod.GET)
    public String getRealPathByStoragePath(
            @ApiParam(name = "storagePath", value = "文件存储路径", required = true)
            @RequestParam(value = "storagePath") String storagePath) throws Exception {
        String realPath = fastDfsPublicServers + "/" + storagePath.replace(":", "/");
        return realPath;
    }
}

+ 101 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/service/FileResource.java

@ -0,0 +1,101 @@
package com.yihu.jw.basic.fileresource.service;
import javax.persistence.*;
import java.util.Date;
/**
 * @author linaz
 * @created 2016.05.12 8:53
 */
@Entity
@Table(name = "file_resource")
@Access(value = AccessType.PROPERTY)
public class FileResource {
    private String id;                   // objectId
    private String storagePath;          // FDS path
    private String mime;                 // user/org/patient 冗余字段,后继图片管理用
    private String objectId;             // userId/orgCode/patientId 各类编号都是唯一
    private String purpose;                // face/credentials  用途 头像 资质认证
    private Date createDate;
    private String createUser;
    private Date updateDate;
    private String updateUser;
    public static  final String MINE_ORG ="org";
    public static  final String MINE_USER ="user";
    public static  final String MINE_PATIENT ="patient";
    @Id
    @Column(name = "id", unique = true, nullable = false)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Column(name = "storage_path",  nullable = true)
    public String getStoragePath() {
        return storagePath;
    }
    public void setStoragePath(String storagePath) {
        this.storagePath = storagePath;
    }
    @Column(name = "mime",  nullable = true)
    public String getMime() {
        return mime;
    }
    public void setMime(String mime) {
        this.mime = mime;
    }
    @Column(name = "object_id",  nullable = true)
    public String getObjectId() {
        return objectId;
    }
    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }
    @Column(name = "purpose",  nullable = true)
    public String getPurpose() {
        return purpose;
    }
    public void setPurpose(String usage) {
        this.purpose = purpose;
    }
    @Column(name = "create_date",  nullable = true)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "create_user",  nullable = true)
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    @Column(name = "update_date",  nullable = true)
    public Date getUpdateDate() {
        return updateDate;
    }
    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }
    @Column(name = "update_user",  nullable = true)
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
}

+ 106 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/service/FileResourceManager.java

@ -0,0 +1,106 @@
package com.yihu.jw.basic.fileresource.service;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;
/**
 * @author linaz
 * @created 2016.05.12 8:53
 */
@Service
@Transactional
public class FileResourceManager extends BaseJpaService<FileResource, XFileResourceRepository> {
    @Autowired
    private XFileResourceRepository resourceRepository;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Value("${fast-dfs.public-server}")
    private String fastDfsPublicServers;
    public String saveFileResource(String fileStr, String fileName, FileResource fileResource) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(fileStr);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        ObjectNode objectNode = fastDFSUtil.upload(inputStream, fileExtension, "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        String path = groupName.substring(1,groupName.length()-1) + ":" + remoteFileName.substring(1,remoteFileName.length()-1);
        //保存到resource表中
        fileResource.setStoragePath(path);
        return resourceRepository.save(fileResource).getId();
    }
    public String saveFileResourceReturnUrl(String fileStr, String fileName, FileResource fileResource) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(fileStr);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        ObjectNode objectNode = fastDFSUtil.upload(inputStream, fileExtension, "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        String path = groupName.substring(1,groupName.length()-1) + ":" + remoteFileName.substring(1,remoteFileName.length()-1);
        //   保存到resource表中
        fileResource.setStoragePath(path);
        resourceRepository.save(fileResource).getId();
        return path ;
    }
    public String saveFileResourceReturnHttpUrl(String fileStr, String fileName, FileResource fileResource) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(fileStr);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        ObjectNode objectNode = fastDFSUtil.upload(inputStream, fileExtension, "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        String path = groupName.substring(1,groupName.length()-1) + ":" + remoteFileName.substring(1,remoteFileName.length()-1);
        //   保存到resource表中
        fileResource.setStoragePath(path);
        resourceRepository.save(fileResource).getId();
        path = path.replace(":","/");
        return fastDfsPublicServers +"/"+path ;
    }
    public List<FileResource> findByObjectId(String objectId) {
        return resourceRepository.findByObjectId(objectId);
    }
    public List<FileResource> findByObjectIdAndMime(String objectId, String mime) {
        return resourceRepository.findByObjectIdAndMime(objectId, mime);
    }
    public List<FileResource> findByStoragePath(String storagePath) {
        return resourceRepository.findByStoragePath(storagePath);
    }
    public boolean deleteFileResource(List<FileResource> fileResources) throws Exception {
        for(FileResource fileResource : fileResources){
            //删除表数据
            resourceRepository.deleteById(fileResource.getId());
            //删除fastdfs上的文件
            String storagePath = fileResource.getStoragePath();
            String groupName = storagePath.split(":")[0];
            String remoteFileName = storagePath.split(":")[1];
            fastDFSUtil.delete(groupName,remoteFileName);
        }
        return true;
    }
    public String getStoragePathById(String id) {
        FileResource file= resourceRepository.getOne(id);
        String storage_path=file.getStoragePath();
        return storage_path;
    }
}

+ 19 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/fileresource/service/XFileResourceRepository.java

@ -0,0 +1,19 @@
package com.yihu.jw.basic.fileresource.service;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
 * @author linaz
 * @created 2016.05.12 8:53
 */
public interface XFileResourceRepository extends JpaRepository<FileResource, String> {
    List<FileResource> findByObjectId(String objectId);
    List<FileResource> findByStoragePath(String storagePath);
    List<FileResource> findByObjectIdAndMime(String objectId, String mime);
}

+ 272 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgDeptEndPoint.java

@ -0,0 +1,272 @@
package com.yihu.jw.basic.org.controller;
import com.yihu.jw.entity.ehr.org.OrgDept;
import com.yihu.jw.entity.ehr.org.OrgDeptDetail;
import com.yihu.jw.entity.ehr.org.Organization;
import com.yihu.jw.basic.org.service.OrgDeptDetailService;
import com.yihu.jw.basic.org.service.OrgMemberRelationService;
import com.yihu.jw.basic.org.service.OrgService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.org.MOrgDept;
import com.yihu.jw.restmodel.ehr.org.MOrgDeptData;
import com.yihu.jw.restmodel.ehr.org.MOrgDeptDetail;
import com.yihu.jw.basic.org.service.OrgDeptService;
import com.yihu.jw.util.file.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/15.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "orgDept", description = "组织机构部门管理服务", tags = {"机构管理-部门管理服务"})
public class OrgDeptEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private OrgDeptService orgDeptService;
    @Autowired
    private OrgMemberRelationService relationService;
    @Autowired
    private OrgDeptDetailService deptDetailService;
    @Autowired
    private OrgService orgService;
    @RequestMapping(value = "/orgDept/getAllOrgDepts", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有部门列表")
    public List<MOrgDept> getAllOrgDepts() throws Exception {
        String filters = "delFlag=0";
        String sorts = "+sortNo";
        List<OrgDept> orgDepts = orgDeptService.search(filters,sorts);
        return (List<MOrgDept>) convertToModels(orgDepts, new ArrayList<MOrgDept>(orgDepts.size()), MOrgDept.class, null);
    }
    @RequestMapping(value = "/orgDept/list", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据条件查询机构下的部门列表")
    public List<MOrgDept> searchOrgDepts(
            @ApiParam(name = "orgId", value = "机构ID")
            @RequestParam(value = "orgId", required = true) String orgId) throws Exception {
        List<OrgDept> orgDepts = orgDeptService.searchByOrgId(orgId);
        return (List<MOrgDept>) convertToModels(orgDepts, new ArrayList<MOrgDept>(orgDepts.size()), MOrgDept.class, null);
    }
    @RequestMapping(value = "/orgDept/childs", method = RequestMethod.POST)
    @ApiOperation(value = "根据父级部门ID查询其下的子部门列表")
    public List<MOrgDept> searchChildOrgDepts(
            @ApiParam(name = "parentDeptId", value = "父级部门ID")
            @RequestParam(value = "parentDeptId", required = true) Integer parentDeptId
    ) throws Exception {
        List<OrgDept> orgDepts = orgDeptService.searchByParentId(parentDeptId);
        return (List<MOrgDept>) convertToModels(orgDepts, new ArrayList<MOrgDept>(orgDepts.size()), MOrgDept.class, null);
    }
    @RequestMapping(value = "/orgDept/detail", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询部门&科室详情")
    public MOrgDept searchDeptDetail(
            @ApiParam(name = "deptId", value = "部门ID")
            @RequestParam(value = "deptId", required = true) Integer deptId
    ) throws Exception {
        OrgDept dept = orgDeptService.searchBydeptId(deptId);
        MOrgDept mOrgDept = convertToModel(dept, MOrgDept.class);
        if (dept != null) {
            OrgDeptDetail orgDeptDetail = deptDetailService.searchByDeptId(Integer.valueOf(dept.getId()));
            MOrgDeptDetail mOrgDeptDetail = convertToModel(orgDeptDetail, MOrgDeptDetail.class);
            mOrgDept.setDeptDetail(mOrgDeptDetail);
        }
        return mOrgDept;
    }
    @RequestMapping(value = "/orgDept", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增部门")
    public MOrgDept saveOrgDept(
            @ApiParam(name = "deptJsonData", value = "新增部门json信息")
            @RequestBody String deptJsonData
    )  {
        try {
            OrgDept dept = toEntity(deptJsonData, OrgDept.class);
            dept = orgDeptService.saveOrgDept(dept);
            return convertToModel(dept, MOrgDept.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(value = "/orgDept", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改部门&科室详情")
    public MOrgDept updateOrgDept(
            @ApiParam(name = "deptJsonData", value = "部门&科室详情json信息")
            @RequestBody String deptJsonData
    )  {
        try {
            OrgDept dept = toEntity(deptJsonData, OrgDept.class);
            dept = orgDeptService.updateDept(dept);
            return convertToModel(dept, MOrgDept.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(value = "/orgDept/getCountByDeptName", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "检查机构下部门相同名称的个数")
    public int getCountByDeptName(
            @ApiParam(name = "orgId", value = "机构ID")
            @RequestParam(value = "orgId", required = true) Integer orgId,
            @ApiParam(name = "name", value = "部门名称")
            @RequestParam(value = "name", required = true) String name
    ) throws Exception {
        return orgDeptService.getCountByOrgIdAndName(orgId.toString(), name);
    }
    @RequestMapping(value = "/orgDept/resetName", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改部门名称")
    public MOrgDept resetDeptName(
            @ApiParam(name = "deptId", value = "部门ID")
            @RequestParam(value = "deptId", required = true) Integer deptId,
            @ApiParam(name = "name", value = "新部门名称")
            @RequestParam(value = "name", required = true) String name
    ) throws Exception {
        OrgDept dept = orgDeptService.updateOrgDeptName(deptId, name);
        return convertToModel(dept, MOrgDept.class);
    }
    @RequestMapping(value = "/orgDept/delete", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除部门" ,notes = "可以根据前端需求修改该接口,添加判断部门下是否有成员")
    public boolean deleteOrgDept(
            @ApiParam(name = "deptId", value = "部门ID")
            @RequestParam(value = "deptId", required = true) Integer deptId
    ) throws Exception {
        orgDeptService.deleteOrgDept(deptId);
        return true;
    }
    @RequestMapping(value = "/orgDept/changeSort", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "部门排序交换" ,notes = "交换两个部门的排序位置")
    public boolean changeSort(
            @ApiParam(name = "preDeptId", value = "第一个部门ID")
            @RequestParam(value = "preDeptId", required = true) Integer preDeptId,
            @ApiParam(name = "afterDeptId", value = "第二个部门ID")
            @RequestParam(value = "afterDeptId", required = true) Integer afterDeptId
    ) throws Exception {
        orgDeptService.changeOrgDeptSort(preDeptId, afterDeptId);
        return true;
    }
    @RequestMapping(value = "/orgDept/checkMembers", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询部门下是否有成员" ,notes = "可以根据前端需求修改该接口,和删除部门接口合并")
    public boolean isHasMember(
            @ApiParam(name = "deptId", value = "部门ID")
            @RequestParam(value = "deptId", required = true) Integer deptId
    ) throws Exception {
        boolean succ = relationService.hadMemberRelation(deptId);
        return succ;
    }
    /* ****************************************** excel 导入数据相关 *******************************************************  */
    //TODO  无用可去除
    @RequestMapping(value = "/orgDept/importDept", method = RequestMethod.POST)
    @ApiOperation(value = "导入部门信息", notes = "通过Excel文件导入部门信息到数据库(包含父部门ID)")
    public List<Map<Object,Object>> importDeptByExcel(
            @ApiParam(name = "pack", value = "部门数据excel文件", allowMultiple = true)
            @RequestPart() MultipartFile pack) throws Exception {
        List<Map<Object,Object>> list = ExcelUtils.readExcel(pack.getInputStream(),pack.getOriginalFilename());
        boolean b = orgDeptService.importDataByExcel(list);
        System.out.println(list.toString());
        return list;
    }
    @RequestMapping(value = "/orgDept/importDept2", method = RequestMethod.POST)
    @ApiOperation(value = "导入部门信息", notes = "通过Excel文件导入部门信息到数据库;excel头内容,orgId,parentName,name")
    public List<Map<Object,Object>> importDeptByExcel2(
            @ApiParam(name = "pack", value = "部门数据excel文件", allowMultiple = true)
            @RequestPart() MultipartFile pack) throws Exception {
        List<Map<Object,Object>> list = ExcelUtils.readExcel(pack.getInputStream(),pack.getOriginalFilename());
        boolean b = orgDeptService.importDataByExce2l(list);
        System.out.println(list.toString());
        return list;
    }
    @RequestMapping(value =ServiceApi.Org.getUserOrglistByUserId, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据用户ID获取部门列表")
    public List<String> getUserOrglistByUserId(
            @ApiParam(name = "userId", value = "用户ID")
            @RequestParam(value = "userId", required = true) String userId) throws Exception {
        List<String> orgDepts = orgDeptService.searchByUserId(userId);
        return orgDepts;
    }
    @RequestMapping(value =ServiceApi.Org.GetOrgDeptsDate, method = RequestMethod.GET)
    @ApiOperation(value = "根据机构id获取机构及部门列表")
    public MOrgDeptData getOrgDeptsDate(
            @ApiParam(name = "orgId", value = "机构ID")
            @RequestParam(value = "orgId") String orgId) throws Exception {
        List<MOrgDeptData> orgDeptData = new ArrayList<>();
        MOrgDeptData mOrgDeptData = new MOrgDeptData();
        Organization organization = orgService.getOrgById(orgId);
        if (null != organization) {
            mOrgDeptData.setId(new Long(organization.getId()).intValue());
            mOrgDeptData.setName(organization.getFullName());
            List<OrgDept> orgDepts = orgDeptService.searchByOrgId(orgId);
            if (null != orgDepts && orgDepts.size() > 0) {
                for (OrgDept dept : orgDepts) {
                    MOrgDeptData data = new MOrgDeptData();
                    data.setId(dept.getId());
                    data.setName(dept.getName());
                    orgDeptData.add(data);
                }
            }
        }
        mOrgDeptData.setChildren(orgDeptData);
        return mOrgDeptData;
    }
    @RequestMapping(value = "/orgDept/getOrgDeptByDeptName", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据机构id及部门名称获取部门id")
    public MOrgDept getOrgDeptByDeptName(
            @ApiParam(name = "orgId", value = "机构ID")
            @RequestParam(value = "orgId", required = true) Integer orgId,
            @ApiParam(name = "name", value = "部门名称")
            @RequestParam(value = "name", required = true) String name
    ) throws Exception {
        OrgDept dept = orgDeptService.getOrgDeptByDeptName(orgId.toString(), name);
        return convertToModel(dept, MOrgDept.class);
    }
    @RequestMapping(value =ServiceApi.Org.getUserOrgCodelistByUserId, method = RequestMethod.GET)
    @ApiOperation(value = "根据用户ID获取机构code")
    public List<String> getUserOrgCodelistByUserId(
            @ApiParam(name = "userId", value = "用户ID")
            @RequestParam(value = "userId", required = true) String userId) throws Exception {
        List<String> orgDepts = orgDeptService.searchByUserId(userId);
        List<Long> longList=new ArrayList<>();
        orgDepts.forEach(s -> {
            longList.add(Long.parseLong(s));
        });
        List<String> organizationList = orgService.getOrgListById(longList);
        return organizationList;
    }
}

+ 79 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgDeptImportEndPoint.java

@ -0,0 +1,79 @@
package com.yihu.jw.basic.org.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.org.OrgDept;
import com.yihu.jw.basic.org.service.OrgDeptImportService;
import com.yihu.jw.basic.org.service.OrgDeptService;
import com.yihu.jw.basic.org.service.OrgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * Created by Administrator on 2017/7/15.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "orgDept", description = "机构&部门批量导入接口", tags = {"基础信息 - 机构&部门批量导入接口"})
public class OrgDeptImportEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private OrgDeptImportService orgDeptImportService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private OrgDeptService orgDeptService;
    @RequestMapping(value = "/orgDept/batch", method = RequestMethod.POST)
    @ApiOperation("批量导入机构&部门")
    public boolean createOrgDeptsBatch(
            @ApiParam(name = "orgDepts", value = "JSON", defaultValue = "")
            @RequestBody String orgDepts) throws Exception{
        List models = objectMapper.readValue(orgDepts, new TypeReference<List>() {});
        orgDeptImportService.addOrgDeptBatch(models);
        return true;
    }
    @RequestMapping(value = "/code/existence",method = RequestMethod.POST)
    @ApiOperation("获取已存在部门编号")
    public List codeExistence(
            @ApiParam(name = "code", value = "", defaultValue = "")
            @RequestBody String code) throws Exception {
        List codes = orgDeptImportService.codeExistence(toEntity(code, String[].class));
        return  codes;
    }
    @RequestMapping(value = "/name/existence",method = RequestMethod.POST)
    @ApiOperation("获取已存在部门名称")
    public List nameExistence(
            @ApiParam(name = "name", value = "", defaultValue = "")
            @RequestBody String name) throws Exception {
        List names = orgDeptImportService.nameExistence(toEntity(name, String[].class));
        return  names;
    }
    @RequestMapping(value = "/orgCode/existence",method = RequestMethod.POST)
    @ApiOperation("获取已存在的机构代码")
    public List orgCodeExistence(
            @ApiParam(name = "orgCode", value = "", defaultValue = "")
            @RequestBody String orgCode) throws Exception {
        List orgCodes = orgService.orgCodeExistence(toEntity(orgCode, String[].class));
        return orgCodes;
    }
    @RequestMapping(value = "/orgDept/code/existence", method = RequestMethod.GET)
    @ApiOperation("根据过滤条件判断是否存在")
    public boolean isExistence(
            @ApiParam(name="filters",value="filters",defaultValue = "")
            @RequestParam(value="filters") String filters) throws Exception {
        List<OrgDept> orgDepts = orgDeptService.search("",filters,"", 1, 1);
        return orgDepts!=null && orgDepts.size()>0;
    }
}

+ 645 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgEndPoint.java

@ -0,0 +1,645 @@
package com.yihu.jw.basic.org.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.jw.basic.address.service.AddressDictService;
import com.yihu.jw.entity.ehr.org.Organization;
import com.yihu.jw.basic.security.service.UserSecurityService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.phonics.PinyinUtil;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.address.AddressDict;
import com.yihu.jw.entity.ehr.security.UserKey;
import com.yihu.jw.entity.ehr.security.UserSecurity;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.restmodel.ehr.org.MOrganization;
import com.yihu.jw.entity.ehr.org.OrgDept;
import com.yihu.jw.basic.org.service.OrgDeptService;
import com.yihu.jw.basic.org.service.OrgService;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
/**
 * @author zlf
 * @version 1.0
 * @created 2015.08.10 17:57
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "org", description = "组织机构管理服务", tags = {"机构管理-机构管理服务"})
public class OrgEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private OrgService orgService;
    @Autowired
    private UserSecurityService userSecurityService;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private OrgDeptService orgDeptService;
    @Autowired
    private AddressDictService addressDictService;
    @RequestMapping(value = "/organizations/getAllOrgs", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有机构列表")
    public List<MOrganization> getAllOrgs() throws Exception {
        List<MOrganization> orgs = orgService.search(null);
        return orgs;
    }
    /**
     * 机构列表查询
     *
     * @param fields
     * @param filters
     * @param sorts
     * @param size
     * @param page
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/organizations/list", method = RequestMethod.POST)
    @ApiOperation(value = "根据条件查询机构列表")
    public List<MOrganization> searchOrgs(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,secret,url,createTime")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "-createDate")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<Organization> organizationList = orgService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, orgService.getCount(filters), page, size);
        return (List<MOrganization>) convertToModels(organizationList, new ArrayList<MOrganization>(organizationList.size()), MOrganization.class, fields);
    }
    /**
     * 机构列表查询
     *
     * @param fields
     * @param filters
     * @param sorts
     * @param size
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/organizations/searchForCombo", method = RequestMethod.GET)
    @ApiOperation(value = "根据条件查询机构列表")
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "searchParm", value = "关键字搜索")
            @RequestParam(value = "searchParm", required = false) String searchParm,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page) throws Exception {
        filters = filters == null ? "" : filters;
        if (StringUtils.isNotEmpty(searchParm)) {
            filters += "orgCode?" + searchParm + " g1;fullName?" + searchParm + " g1;";
        }
        List<Organization> list = orgService.search(fields, filters, sorts, page, size);
        int count = (int) orgService.getCount(filters);
        Envelop envelop = getPageResult(list, count, page, size);
        return envelop;
    }
    /**
     * 删除机构
     *
     * @param orgCode
     * @return
     */
    @RequestMapping(value = "/organizations/{org_code}", method = RequestMethod.DELETE)
    @ApiOperation(value = "根据机构代码删除机构")
    public boolean deleteOrg(
            @ApiParam(name = "org_code", value = "机构代码", defaultValue = "")
            @PathVariable(value = "org_code") String orgCode) throws Exception {
        orgService.delete(orgCode);
        return true;
    }
    /**
     * 创建机构
     *
     * @param orgJsonData
     * @throws Exception
     */
    @RequestMapping(value = "/organizations", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建机构")
    public MOrganization create(
            @ApiParam(name = "mOrganizationJsonData", value = "机构代码", defaultValue = "")
            @RequestBody String orgJsonData) throws Exception {
        Organization org = toEntity(orgJsonData, Organization.class);
        org.setCreateDate(new Date());
        org.setActivityFlag(1);
        org.setPyCode(PinyinUtil.getPinYinHeadChar(org.getFullName(), false));
        Organization organization = orgService.save(org);
        String orgId = orgService.getOrgIdByOrgCode(organization.getOrgCode());
        //添加默认部门
        OrgDept dept = new OrgDept();
        dept.setOrgId(String.valueOf(orgId));
        dept.setCode(String.valueOf(orgId) + "1");
        dept.setName("未分配");
        orgDeptService.saveOrgDept(dept);
        return convertToModel(org, MOrganization.class);
    }
    @RequestMapping(value = "organizations", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改机构")
    public MOrganization update(
            @ApiParam(name = "mOrganizationJsonData", value = "机构代码", defaultValue = "")
            @RequestBody String orgJsonData) throws Exception {
        Organization org = toEntity(orgJsonData, Organization.class);
        org.setPyCode(PinyinUtil.getPinYinHeadChar(org.getFullName(), false));
        orgService.save(org);
        return convertToModel(org, MOrganization.class);
    }
    /**
     * 根据机构代码获取机构
     *
     * @param orgCode
     * @return
     */
    @RequestMapping(value = "/organizations/{org_code}", method = RequestMethod.GET)
    @ApiOperation(value = "根据机构代码获取机构")
    public MOrganization getOrg(
            @ApiParam(name = "org_code", value = "机构代码", defaultValue = "")
            @PathVariable(value = "org_code") String orgCode) throws Exception {
        Organization org = orgService.getOrg(orgCode);
        MOrganization orgModel = convertToModel(org, MOrganization.class);
        return orgModel;
    }
    /**
     * 根据机构ID获取机构
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/organizations/getOrgById/{org_id}", method = RequestMethod.GET)
    @ApiOperation(value = "根据机构ID获取机构")
    public MOrganization getOrgById(
            @ApiParam(name = "org_id", value = "机构代码", defaultValue = "")
            @PathVariable(value = "org_id") String orgId) throws Exception {
        Organization org = orgService.getOrgById(orgId);
        MOrganization orgModel = convertToModel(org, MOrganization.class);
        return orgModel;
    }
    /**
     * 根据机构代码列表批量查询机构
     *
     * @param orgCodes
     * @return
     */
    @RequestMapping(value = "/organizations/org_codes", method = RequestMethod.GET)
    @ApiOperation(value = "根据机构代码列表批量查询机构")
    public List<MOrganization> getOrgs(
            @ApiParam(name = "org_codes", value = "机构代码", defaultValue = "")
            @RequestParam(value = "org_codes") String[] orgCodes) throws Exception {
        List<String> orgCodeList = Arrays.asList(orgCodes);
        List<Organization> organizationList = orgService.findByOrgCodes(orgCodeList);
        return (List<MOrganization>) convertToModels(organizationList, new ArrayList<MOrganization>(organizationList.size()), MOrganization.class, "");
    }
    /**
     * 根据管理员登录帐号获取机构
     *
     * @param adminLoginCode
     * @return
     */
    @RequestMapping(value = "/organizations/{org_code}/admin/{admin_login_code}", method = RequestMethod.GET)
    @ApiOperation(value = "根据管理员登录帐号获取机构")
    public MOrganization getOrgByAdminLoginCode(
            @ApiParam(name = "org_code", value = "管理员登录帐号", defaultValue = "")
            @PathVariable(value = "org_code") String orgCode,
            @ApiParam(name = "admin_login_code", value = "机构代码", defaultValue = "")
            @PathVariable(value = "admin_login_code") String adminLoginCode) throws Exception {
        Organization org = orgService.getOrgByAdminLoginCode(orgCode, adminLoginCode);
        MOrganization orgModel = convertToModel(org, MOrganization.class);
        return orgModel;
    }
    /**
     * 根据name获取机构orgCodes
     *
     * @param name
     * @return
     */
    @ApiOperation(value = "根据名称获取机构编号列表")
    @RequestMapping(value = "/organizations/name", method = RequestMethod.GET)
    public List<String> getIdsByName(
            @ApiParam(name = "name", value = "机构名称", defaultValue = "")
            @RequestParam(value = "name") String name) {
        List<String> orgCodes = orgService.getCodesByName(name);
        return orgCodes;
    }
    @ApiOperation(value = "根据地区代码获取机构列表")
    @RequestMapping(value = "/organizations/areas/{area}", method = RequestMethod.GET)
    public List<MOrganization> getOrganizationByAreaCode(
            @ApiParam(name = "area", value = "地区代码", defaultValue = "")
            @PathVariable(value = "area") String area) {
        List<Organization> organizationList = orgService.findByOrgArea(area);
        return (List<MOrganization>) convertToModels(organizationList, new ArrayList<MOrganization>(organizationList.size()), MOrganization.class, "");
    }
    /**
     * 跟新机构激活状态
     *
     * @param orgCode
     * @return
     */
    @RequestMapping(value = "organizations/{org_code}/{activity_flag}", method = RequestMethod.PUT)
    @ApiOperation(value = "跟新机构激活状态")
    public boolean activity(
            @ApiParam(name = "org_code", value = "机构代码", defaultValue = "")
            @PathVariable(value = "org_code") String orgCode,
            @ApiParam(name = "activity_flag", value = "状态", defaultValue = "")
            @PathVariable(value = "activity_flag") int activityFlag) throws Exception {
        Organization org = orgService.getOrg(orgCode);
        if (org.getActivityFlag() == 1) {
            org.setActivityFlag(0);
        } else {
            org.setActivityFlag(1);
        }
        orgService.save(org);
        return true;
    }
    /**
     * 根据地址获取机构下拉列表
     *
     * @param province
     * @param city
     * @param district
     * @return
     */
    @RequestMapping(value = "/organizations/geography", method = RequestMethod.GET)
    @ApiOperation(value = "根据地址获取机构下拉列表")
    public List<MOrganization> getOrgsByAddress(
            @ApiParam(name = "province", value = "省")
            @RequestParam(value = "province") String province,
            @ApiParam(name = "city", value = "市")
            @RequestParam(value = "city", required = false) String city,
            @ApiParam(name = "district", value = "县")
            @RequestParam(value = "district", required = false) String district) {
        List<Organization> orgList = orgService.searchByAddress(province, city, district);
        if (orgList != null && orgList.size() > 0) {
            return (List<MOrganization>) convertToModels(orgList, new ArrayList<MOrganization>(orgList.size()), MOrganization.class, null);
        } else {
            return null;
        }
    }
    @RequestMapping(value = "/organizations/key", method = RequestMethod.POST)
    @ApiOperation(value = "机构分发密钥")
    public Map<String, String> distributeKey(
            @ApiParam(name = "org_code", value = "机构代码")
            @RequestParam(value = "org_code") String orgCode) throws Exception {
        UserSecurity key = userSecurityService.getKeyByOrgCode(orgCode);
        Map<String, String> keyMap = new HashMap<>();
        if (key != null) {
            List<UserKey> keyMaps = userSecurityService.getKeyMapByOrgCode(orgCode);
            userSecurityService.deleteKey(keyMaps);
        }
        key = userSecurityService.createKeyByOrgCode(orgCode);
        String validTime = DateFormatUtils.format(key.getFromDate(), "yyyy-MM-dd")
                + "~" + DateFormatUtils.format(key.getExpiryDate(), "yyyy-MM-dd");
        keyMap.put("publicKey", key.getPublicKey());
        keyMap.put("validTime", validTime);
        keyMap.put("startTime", DateFormatUtils.format(key.getFromDate(), "yyyy-MM-dd"));
        return keyMap;
    }
    @RequestMapping(value = "/organizations/existence/{org_code}", method = RequestMethod.GET)
    @ApiOperation(value = "判断提交的机构代码是否已经存在")
    boolean isOrgCodeExists(
            @ApiParam(name = "org_code", value = "org_code", defaultValue = "")
            @PathVariable(value = "org_code") String orgCode) {
        return orgService.isExistOrg(orgCode);
    }
    @RequestMapping(value = "/organizations/checkSunOrg", method = RequestMethod.PUT)
    @ApiOperation(value = "判断机构是否已经是子机构")
    boolean checkSunOrg(
            @ApiParam(name = "org_pId", value = "org_pId", defaultValue = "")
            @RequestParam(value = "org_pId") String orgPid,
            @ApiParam(name = "org_id", value = "org_id", defaultValue = "")
            @RequestParam(value = "org_id") String orgId) {
        return orgService.checkSunOrg(orgPid, orgId);
    }
    /**
     * 机构资质上传
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/organizations/images", method = RequestMethod.POST)
    @ApiOperation(value = "上传头像,把图片转成流的方式发送")
    public String uploadImages(
            @ApiParam(name = "jsonData", value = "头像转化后的输入流")
            @RequestBody String jsonData) throws Exception {
        if (jsonData == null) {
            return null;
        }
        String date = URLDecoder.decode(jsonData, "UTF-8");
        String[] fileStreams = date.split(",");
        String is = URLDecoder.decode(fileStreams[0], "UTF-8").replace(" ", "+");
        byte[] in = Base64.getDecoder().decode(is);
        String pictureName = fileStreams[1].substring(0, fileStreams[1].length() - 1);
        String fileExtension = pictureName.substring(pictureName.lastIndexOf(".") + 1).toLowerCase();
        String description = null;
        if ((pictureName != null) && (pictureName.length() > 0)) {
            int dot = pictureName.lastIndexOf('.');
            if ((dot > -1) && (dot < (pictureName.length()))) {
                description = pictureName.substring(0, dot);
            }
        }
        InputStream inputStream = new ByteArrayInputStream(in);
        ObjectNode objectNode = fastDFSUtil.upload(inputStream, fileExtension, description);
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
//        String path = "{\"groupName\":" + groupName + ",\"remoteFileName\":" + remoteFileName + "}";
        String path = groupName.substring(1, groupName.length() - 1) + ":" + remoteFileName.substring(1, remoteFileName.length() - 1);
        //返回文件路径
        return path;
    }
    /**
     * 机构资质下载
     *
     * @return
     */
    @RequestMapping(value = "/organizations/images", method = RequestMethod.GET)
    @ApiOperation(value = "下载头像")
    public String downloadPicture(
            @ApiParam(name = "group_name", value = "分组", defaultValue = "")
            @RequestParam(value = "group_name") String groupName,
            @ApiParam(name = "remote_file_name", value = "服务器头像名称", defaultValue = "")
            @RequestParam(value = "remote_file_name") String remoteFileName) throws Exception {
        byte[] bytes = fastDFSUtil.download(groupName, remoteFileName);
        String fileStream = new String(Base64.getEncoder().encode(bytes));
        String imageStream = URLEncoder.encode(fileStream, "UTF-8");
        return imageStream;
    }
    @RequestMapping(value = "/organizations/getAllSaasOrgs", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有机构列表")
    public List<Organization> getAllSaasOrgs(
            @ApiParam(name = "saasName", value = "名称", defaultValue = "")
            @RequestParam(value = "saasName", required = false) String saasName) throws Exception {
        List<Organization> orgs = orgService.getAllSaasOrgs(saasName);
        return orgs;
    }
    /**
     * 根据机构ID获取机构
     *
     * @param userOrgCode
     * @return
     */
    @RequestMapping(value = "/organizations/getOrgListById", method = RequestMethod.GET)
    @ApiOperation(value = "根据机构ID获取机构")
    public List<String> getOrgListById(
            @ApiParam(name = "userOrgCode", value = "机构代码", defaultValue = "")
            @RequestParam(value = "userOrgCode") List<Long> userOrgCode) throws Exception {
        List<String> organizationList = orgService.getOrgListById(userOrgCode);
        return organizationList;
    }
    @RequestMapping(value = "/organizations/getAllOrgsNoPaging", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有机构列表不分页")
    public List<MOrganization> getAllOrgsNoPaging() throws Exception {
        List<MOrganization> orgs = orgService.search(null);
        return orgs;
    }
    @RequestMapping(value = "/organizations/batch", method = RequestMethod.POST)
    @ApiOperation("批量导入机构")
    public boolean createOrgBatch(
            @ApiParam(name = "orgs", value = "JSON", defaultValue = "")
            @RequestBody String orgs) throws Exception {
        List models = objectMapper.readValue(orgs, new TypeReference<List>() {
        });
        orgService.addOrgBatch(models);
        return true;
    }
    @RequestMapping(value = ServiceApi.Org.getseaOrgsByOrgCode, method = RequestMethod.POST)
    @ApiOperation("根据机构code获取机构code和name")
    public Map<String, String> seaOrgsByOrgCode(
            @ApiParam(name = "org_codes", value = "机构org_codes", defaultValue = "")
            @RequestBody String org_codes) throws Exception {
        Map<String, String> map = new HashMap<>();
        List<Object> list = (List<Object>) orgService.orgExist(toEntity(org_codes, String[].class));
        for (int i = 0; i < list.size(); i++) {
            Object[] objectList = (Object[]) list.get(i);
            if (null != objectList[0] && null != objectList[1]) {
                map.put(objectList[0].toString(), objectList[1].toString());
            }
        }
        return map;
    }
    ;
    @RequestMapping(value = "/organizations/getHospital", method = RequestMethod.GET)
    @ApiOperation(value = "查询所有经纬度医院列表")
    public ListEnvelop getHospital() throws Exception {
        ListEnvelop envelop = new ListEnvelop();
        try {
            List<Organization> orgs = orgService.getHospital();
            envelop.setStatus(200);
            envelop.setDetailModelList(orgs);
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setStatus(-1);
            envelop.setMessage(e.getMessage());
        }
        return envelop;
    }
    @RequestMapping(value = "/organizations/getOrgListByAddressPid", method = RequestMethod.GET)
    @ApiOperation(value = "根据区域查询机构列表")
    public Envelop getOrgListByAddressPid(
            @ApiParam(name = "pid", value = "区域id", defaultValue = "")
            @RequestParam(value = "pid") Integer pid,
            @ApiParam(name = "fullName", value = "机构名称", defaultValue = "")
            @RequestParam(value = "fullName", required = false) String fullName) {
        ListEnvelop envelop = new ListEnvelop();
        try {
            List<Organization> orgList;
            if (StringUtils.isEmpty(fullName)) {
                orgList = orgService.getOrgListByAddressPid(pid);
            } else {
                orgList = orgService.getOrgListByAddressPidAndParam(pid, fullName);
            }
            envelop.setStatus(200);
            envelop.setDetailModelList(orgList);
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setStatus(-1);
            envelop.setMessage(e.getMessage());
        }
        return envelop;
    }
    @RequestMapping(value = "/organizations/getOrgListTreeByAddressPid", method = RequestMethod.GET)
    @ApiOperation(value = "根据区域、机构区县查询机构列表")
    public List<Map<String, Object>> getOrgListTreeByAddressPid(
            @ApiParam(name = "pid", value = "区域id", defaultValue = "")
            @RequestParam(value = "pid") Integer pid) {
        List<Map<String, Object>> listMap = new ArrayList<>();
        try {
            List<AddressDict> addList = addressDictService.getPidToAddr(pid);
            List<Organization> orgList;
            for (AddressDict addressDict : addList) {
                List<Map<String, Object>> childListMap = new ArrayList<>();
                Map<String, Object> allMap = new HashMap<>();
                allMap.put("text", "全部机构");
                childListMap.add(allMap);
                Map<String, Object> map = new HashMap<>();
                map.put("text", addressDict.getName());
                map.put("value", addressDict.getId());
                orgList = orgService.getOrgListByAddressPidAndOrgArea(pid, addressDict.getId() + "");
                if (null != orgList && orgList.size() > 0) {
                    orgList.forEach(one -> {
                        Map<String, Object> childMap = new HashMap<>();
                        childMap.put("text", one.getFullName());
                        childMap.put("value", one.getOrgCode());
                        childListMap.add(childMap);
                    });
                }
                map.put("children", childListMap);
                listMap.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listMap;
    }
    @RequestMapping(value = ServiceApi.Org.getOrgCodeAndFullName, method = RequestMethod.GET)
    @ApiOperation("获取所有机构的机构组织机构代码和名称")
    public Envelop getOrgCodeAndFullName(
            @ApiParam(name = "field", value = "作为key值得字段")
            @RequestParam(value = "field", required = false) String field) throws Exception {
        ObjEnvelop envelop = new ObjEnvelop();
        Map<String, String> map = new HashMap<>();
        List list = orgService.getOrgCodeAndFullName(field);
        String orgCode = "";
        String fullName = "";
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            if (null != obj[0] && null != obj[1]) {
                orgCode = obj[0].toString();
                fullName = obj[1].toString();
                map.put(orgCode, fullName);
            }
        }
        envelop.setStatus(200);
        envelop.setObj(map);
        return envelop;
    }
    @RequestMapping(value = "/getAdressByLocation", method = RequestMethod.GET)
    @ApiOperation("地址处理111111")
    public Map<String, String> getAdressByLocation(String location) {
        Map<String, String> map = new HashMap<>();
        String[] temp = null;
        temp = location.split("省");
        String str ="";
        for(int i=0;i<temp.length;i++){
            if(temp[0].indexOf("省")>0){
                //不包括直辖市、自治区
                map.put("provinceName", temp[0]+"省");
            }
            str=temp[temp.length-1];
        }
        if (StringUtils.isNotEmpty(str)) {
            temp = str.split("市");
            str=temp[temp.length-1];
            if(temp.length>2){
                map.put("cityName", temp[0]+"市");
                map.put("district", temp[1]+"市");
                map.put("street", temp[2]);
            }else if(temp.length>1){
                map.put("cityName", temp[0]+"市");
                map.put("district", temp[1]);
                temp = str.split("县");
                if (temp.length>1) {
                    map.put("district", temp[0]+"县");
                    map.put("street", temp[1]);
                }else{
                    temp = str.split("区");
                    if (temp.length>1) {
                        map.put("district", temp[0]+"区");
                        map.put("street", temp[1]);
                    }else {
                        map.put("street", temp[0]);
                    }
                }
            }else{
                temp = str.split("县");
                if (temp.length>1) {
                    map.put("district", temp[0]+"县");
                    map.put("street", temp[1]);
                }else{
                    temp = str.split("区");
                    if (temp.length>1) {
                        map.put("district", temp[0]+"区");
                        map.put("street", temp[1]);
                    }else {
                        map.put("street", temp[0]);
                    }
                }
            }
        }
        return map;
    }
}

+ 232 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgHealthCategoryEndPoint.java

@ -0,0 +1,232 @@
package com.yihu.jw.basic.org.controller;
import com.yihu.jw.entity.ehr.org.OrgHealthCategory;
import com.yihu.jw.basic.org.service.OrgHealthCategoryService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.org.MOrgHealthCategory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 卫生机构类别 接口
 *
 * @author 张进军
 * @date 2017/12/21 12:00
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "卫生机构类别接口", tags = {"机构管理--卫生机构类别接口"})
public class OrgHealthCategoryEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private OrgHealthCategoryService orgHealthCategoryService;
    @ApiOperation("根据ID获取卫生机构类别")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.GetById, method = RequestMethod.GET)
    public ObjEnvelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Long id) {
        ObjEnvelop envelop = new ObjEnvelop();
        envelop.setStatus(-1);
        try {
            MOrgHealthCategory mOrgHealthCategory = convertToModel(orgHealthCategoryService.getById(id), MOrgHealthCategory.class);
            envelop.setObj(mOrgHealthCategory);
            envelop.setStatus(200);
            envelop.setMessage("成功获取卫生机构类别。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("获取卫生机构类别发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("获取所有的卫生机构类别")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.FindAll, method = RequestMethod.GET)
    public ListEnvelop findAll() {
        ListEnvelop envelop = new ListEnvelop();
        envelop.setStatus(-1);
        try {
            List<OrgHealthCategory> list = orgHealthCategoryService.findAll();
            envelop.setDetailModelList(list);
            envelop.setStatus(200);
            envelop.setMessage("成功获取所有的卫生机构类别。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("获取所有的卫生机构类别发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取卫生机构类别")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.Search, method = RequestMethod.GET)
    public ListEnvelop search(
            @ApiParam(name = "codeName", value = "卫生机构类别编码或名称")
            @RequestParam(value = "codeName", required = false) String codeName) {
        ListEnvelop envelop = new ListEnvelop();
        envelop.setStatus(-1);
        try {
            List<OrgHealthCategory> resultList = new ArrayList<>();
            // 获取最顶层的卫生机构类别集合
            List<OrgHealthCategory> topNodeList = orgHealthCategoryService.getChildrenByPid(-1L);
            if (topNodeList.size() == 0) {
                envelop.setDetailModelList(resultList);
                return envelop;
            }
            // 暂存最顶层卫生机构类别中,满足条件的集合
            List<OrgHealthCategory> topNodeListIn = new ArrayList<>();
            // 暂存最顶层卫生机构类别中,不满足条件的集合
            List<OrgHealthCategory> topNodeListOut = new ArrayList<>();
            if (StringUtils.isEmpty(codeName)) {
                resultList = orgHealthCategoryService.getTreeByParents(topNodeList);
                envelop.setDetailModelList(resultList);
                return envelop;
            }
            for (OrgHealthCategory reportCategory : topNodeList) {
                if (reportCategory.getCode().contains(codeName) || reportCategory.getName().contains(codeName)) {
                    topNodeListIn.add(reportCategory);
                    continue;
                }
                topNodeListOut.add(reportCategory);
            }
            if (topNodeListIn.size() != 0) {
                List<OrgHealthCategory> inList = orgHealthCategoryService.getTreeByParents(topNodeListIn);
                resultList.addAll(inList);
            }
            List<OrgHealthCategory> outList = orgHealthCategoryService.getTreeByParentsAndCodeName(topNodeListOut, codeName);
            resultList.addAll(outList);
            envelop.setDetailModelList(resultList);
            envelop.setStatus(200);
            envelop.setMessage("成功获取卫生机构类别。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("获取卫生机构类别发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增卫生机构类别")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.Save, method = RequestMethod.POST)
    public ObjEnvelop add(
            @ApiParam(value = "卫生机构类别JSON", required = true)
            @RequestBody String entityJson) {
        ObjEnvelop envelop = new ObjEnvelop();
        envelop.setStatus(-1);
        try {
            OrgHealthCategory newEntity = objectMapper.readValue(entityJson, OrgHealthCategory.class);
            newEntity.setTopPid(orgHealthCategoryService.getTopPidByPid(newEntity.getPid()));
            newEntity = orgHealthCategoryService.save(newEntity);
            MOrgHealthCategory mOrgHealthCategory = convertToModel(newEntity, MOrgHealthCategory.class);
            envelop.setObj(mOrgHealthCategory);
            envelop.setStatus(200);
            envelop.setMessage("成功新增卫生机构类别。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("新增卫生机构类别发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新卫生机构类别")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.Save, method = RequestMethod.PUT)
    public ObjEnvelop update(
            @ApiParam(value = "卫生机构类别JSON", required = true)
            @RequestBody String entityJson) {
        ObjEnvelop envelop = new ObjEnvelop();
        envelop.setStatus(-1);
        try {
            OrgHealthCategory updateEntity = objectMapper.readValue(entityJson, OrgHealthCategory.class);
            updateEntity = orgHealthCategoryService.save(updateEntity);
            MOrgHealthCategory mOrgHealthCategory = convertToModel(updateEntity, MOrgHealthCategory.class);
            envelop.setObj(mOrgHealthCategory);
            envelop.setStatus(200);
            envelop.setMessage("成功更新卫生机构类别。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("更新卫生机构类别发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除卫生机构类别")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "卫生机构类别ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setStatus(-1);
        try {
            orgHealthCategoryService.delete(id);
            envelop.setStatus(200);
            envelop.setMessage("成功删除卫生机构类别。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("删除卫生机构类别发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证卫生机构类别编码是否唯一")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.IsUniqueCode, method = RequestMethod.GET)
    public Envelop isUniqueCode(
            @ApiParam(name = "id", value = "卫生机构类别ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "code", value = "卫生机构类别编码", required = true)
            @RequestParam(value = "code") String code) {
        Envelop envelop = new Envelop();
        envelop.setStatus(-1);
        try {
            Integer result = orgHealthCategoryService.isUniqueCode(id, code);
            envelop.setStatus(result);
            if (result==-1) {
                envelop.setMessage("该卫生机构类别编码已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证卫生机构类别名称是否唯一")
    @RequestMapping(value = ServiceApi.Org.HealthCategory.IsUniqueName, method = RequestMethod.GET)
    public Envelop isUniqueName(
            @ApiParam(name = "id", value = "卫生机构类别ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "code", value = "卫生机构类别名称", required = true)
            @RequestParam(value = "name") String name) {
        Envelop envelop = new Envelop();
        envelop.setStatus(-1);
        try {
            Integer result = orgHealthCategoryService.isUniqueName(id, name);
            envelop.setStatus(result);
            if (result==-1) {
                envelop.setMessage("该卫生机构类别名称已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setMessage("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 328 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgMemberRelationEndPoint.java

@ -0,0 +1,328 @@
package com.yihu.jw.basic.org.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.ehr.user.User;
import com.yihu.jw.basic.user.service.UserService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.ehr.org.MJkzlOrgMemberRelation;
import com.yihu.jw.restmodel.ehr.org.MOrgDeptData;
import com.yihu.jw.restmodel.ehr.org.MOrgDeptJson;
import com.yihu.jw.restmodel.ehr.org.MOrgMemberRelation;
import com.yihu.jw.entity.ehr.org.OrgMemberRelation;
import com.yihu.jw.basic.org.service.OrgMemberRelationService;
import com.yihu.jw.restmodel.web.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/16.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "orgDeptMember", description = "组织机构部门成员管理服务", tags = {"机构管理-部门成员管理"})
public class OrgMemberRelationEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private OrgMemberRelationService relationService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrgMemberRelationService orgMemberRelationService;
    @RequestMapping(value = "/orgDeptMember/getAllOrgDeptMember", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有成员列表")
    public List<MOrgMemberRelation> getAllOrgDeptMember(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters",required = false) String filters
    ) throws Exception {
        filters= filters +";status=0";
        List<OrgMemberRelation> orgMemberRelations = relationService.search(filters);
        return (List<MOrgMemberRelation>) convertToModels(orgMemberRelations, new ArrayList<MOrgMemberRelation>(orgMemberRelations.size()), MOrgMemberRelation.class, null);
    }
    @RequestMapping(value = "/orgDeptMember/getAllOrgDeptMemberDistinct", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询所有成员列表去重复")
    public List<MOrgMemberRelation> getAllOrgDeptMemberDistinct(
            @ApiParam(name = "orgId", value = "机构ID", defaultValue = "")
            @RequestParam(value = "orgId",required = false) String orgId,
            @ApiParam(name = "searchNm", value = "关键字查询", defaultValue = "")
            @RequestParam(value = "searchNm",required = false) String searchNm
    ) throws Exception {
        List<OrgMemberRelation> orgMemberRelations = relationService.getAllOrgDeptMemberDistinct(orgId,searchNm);
        return (List<MOrgMemberRelation>) convertToModels(orgMemberRelations, new ArrayList<MOrgMemberRelation>(orgMemberRelations.size()), MOrgMemberRelation.class, null);
    }
    @RequestMapping(value = "/orgDeptMember/list", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据条件 查询部门下成员列表")
    public List<MOrgMemberRelation> searchOrgDeptMembers(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,deptId,deptName,dutyName,userName")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters",required = false) String filters,
            @ApiParam(name = "sorts", value = "排序", defaultValue = "+userName,+id")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        List<OrgMemberRelation> orgMemRelations = relationService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, relationService.getCount(filters), page, size);
        return (List<MOrgMemberRelation>) convertToModels(orgMemRelations, new ArrayList<MOrgMemberRelation>(orgMemRelations.size()), MOrgMemberRelation.class, fields);
    }
    @RequestMapping(value = "/orgDeptMember/getOrgDeptMembers", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据条件 查询机构成员列表去重复")
    public List<MOrgMemberRelation> getOrgDeptMembers(
            @ApiParam(name = "orgId", value = "机构ID", defaultValue = "")
            @RequestParam(value = "orgId", required = false) String orgId,
            @ApiParam(name = "searchParm", value = "关键字查询", defaultValue = "")
            @RequestParam(value = "searchParm",required = false) String searchParm,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        List<OrgMemberRelation> orgMemRelations = relationService.getOrgDeptMembers(orgId,searchParm,size,page);
        Long totalCount = Long.parseLong(relationService.getOrgDeptMembersInt(orgId,searchParm).toString());
        pagedResponse(request,response,totalCount,page,size);
        return (List<MOrgMemberRelation>) convertToModels(orgMemRelations, new ArrayList<MOrgMemberRelation>(orgMemRelations.size()), MOrgMemberRelation.class,"userId,userName");
    }
    @RequestMapping(value ="orgDeptMember/admin/{memRelationId}", method = RequestMethod.GET)
    @ApiOperation(value = "获取部门成员信息")
    public MOrgMemberRelation getMessageRemindInfo(
            @ApiParam(name = "memRelationId", value = "", defaultValue = "")
            @PathVariable(value = "memRelationId") Long memRelationId) {
        OrgMemberRelation orgMemberRelation = relationService.getOrgMemberRelation(memRelationId);
        MOrgMemberRelation mOrgMemberRelation   = convertToModel(orgMemberRelation, MOrgMemberRelation.class);
        return mOrgMemberRelation;
    }
    @RequestMapping(value = "/orgDeptMember", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增部门成员")
    public MOrgMemberRelation saveOrgDeptMember(
            @ApiParam(name = "memberRelationJsonData", value = "新增部门成员信息")
            @RequestBody String memberRelationJsonData
    ) throws Exception {
        OrgMemberRelation memberRelation = toEntity(memberRelationJsonData, OrgMemberRelation.class);
        memberRelation.setStatus(0);
        relationService.save(memberRelation);
        return convertToModel(memberRelation, MOrgMemberRelation.class);
    }
    @RequestMapping(value = "/updateOrgDeptMemberParent", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改部门成员上级成员")
    public boolean updateOrgDeptMember(
            @ApiParam(name = "memberRelationJsonData", value = "修改部门成员信息")
            @RequestBody String memberRelationJsonData
    ) throws Exception {
        OrgMemberRelation memberRelation = toEntity(memberRelationJsonData, OrgMemberRelation.class);
        relationService.updateOrgDeptMemberParent(memberRelation);
        return true;
    }
    @RequestMapping(value = "/orgDeptMember/updateStatus", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改部门成员状态" )
    public boolean updateStatusOrgDeptMember(
            @ApiParam(name = "memberRelationId", value = "部门成员ID")
            @RequestParam(value = "memberRelationId", required = true) Integer memberRelationId,
            @ApiParam(name = "status", value = "状态", defaultValue = "")
            @RequestParam(value = "status") int status
    ) throws Exception {
        relationService.updateStatusDeptMember(memberRelationId,status);
        return true;
    }
    @RequestMapping(value = "/orgDeptMember/delete", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除部门成员" )
    public boolean deleteOrgDeptMember(
            @ApiParam(name = "memberRelationId", value = "部门成员ID")
            @RequestParam(value = "memberRelationId", required = true) Integer memberRelationId
    ) throws Exception {
        relationService.deleteDeptMember(memberRelationId);
        return true;
    }
    @RequestMapping(value = "/orgDeptMember/getCountByUserId", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "检查机构下部门相同用户的个数")
    public int getCountByUserId(
            @ApiParam(name = "orgId", value = "机构ID")
            @RequestParam(value = "orgId", required = true) Integer orgId,
            @ApiParam(name = "userId", value = "用户ID")
            @RequestParam(value = "userId", required = true) String userId,
            @ApiParam(name = "deptId", value = "部门ID")
            @RequestParam(value = "deptId", required = true) Integer deptId
    ) throws Exception {
        return relationService.getCountByOrgIdAndUserId(orgId.toString(), userId, deptId);
    }
    @RequestMapping(value = "/orgDeptMember/getOrgIds", method = RequestMethod.GET)
    @ApiOperation(value = "根据userId获取orgId列表")
    public List<String> getOrgIds(String userId) {
        List<String> list = relationService.getOrgIds(userId);
        return list;
    }
    @RequestMapping(value = "/orgDeptMember/getDeptIds", method = RequestMethod.GET)
    @ApiOperation(value = "根据userId获取DeptId列表")
    public List<Integer> getDeptIds(String userId) {
        List<Integer> list = relationService.getDeptIds(userId);
        return list;
    }
    @RequestMapping(value = "/orgDeptMember/getByUserId", method = RequestMethod.GET)
    @ApiOperation(value = "根据userId获取orgDeptJson列表")
    public List<MOrgDeptJson> getByUserId(
            @ApiParam(name = "userId", value = "用户id")
            @RequestParam(value = "userId") String userId) {
        List<OrgMemberRelation> memberRelationList = relationService.getByUserId(userId);
        List<MOrgDeptJson> list = new ArrayList<>();
        for (OrgMemberRelation r : memberRelationList) {
            MOrgDeptJson orgDeptJson = new MOrgDeptJson();
            orgDeptJson.setOrgId(r.getOrgId());
            orgDeptJson.setDeptIds(r.getDeptId() + "");
            list.add(orgDeptJson);
        }
        return list;
    }
    @RequestMapping(value = ServiceApi.Users.GetOrgAndDeptRelation, method = RequestMethod.GET)
    @ApiOperation(value = "根据userId获取机构及部门列表")
    public List<MOrgDeptData> getOrgAndDeptRelation(
            @ApiParam(name = "userId", value = "用户id")
            @RequestParam(value = "userId") String userId) {
        List<OrgMemberRelation> memberRelationList = relationService.getByUserId(userId);
        List<MOrgDeptData> list = new ArrayList<>();
        Map<String,MOrgDeptData> mOrgDeptDataMap = new HashMap<>();
        //将机构与部门实装到 MOrgDeptData 对象中
        for (OrgMemberRelation r : memberRelationList) {
            //机构
            MOrgDeptData mOrg =new MOrgDeptData();
            mOrg.setId(Integer.valueOf(r.getOrgId()));
            mOrg.setName(r.getOrgName());
            //若存在该机构,则判断是否存在部门,若部门存在则不做处理,否则添加部门。
            if(null != mOrgDeptDataMap.get(r.getOrgId())){
                //部门
                MOrgDeptData mOrgDept =new MOrgDeptData();
                mOrgDept.setId(r.getDeptId());
                mOrgDept.setName(r.getDeptName());
                List<MOrgDeptData> childrenList = mOrgDeptDataMap.get(r.getOrgId()).getChildren();
                //JAVA 8直接用流的方法将list转换成map
                Map<Integer, MOrgDeptData> mapOrgDeptData = childrenList.stream().collect(Collectors.toMap(MOrgDeptData::getId, (p) -> p));
                if(null == mapOrgDeptData.get(mOrgDept.getId())){
                    childrenList.add(mOrgDept);
                }
            }else{
                //部门
                MOrgDeptData mOrgDept = new MOrgDeptData();
                mOrgDept.setId(r.getDeptId());
                mOrgDept.setName(r.getDeptName());
                List<MOrgDeptData> childrenList = new ArrayList<>();
                childrenList.add(mOrgDept);
                mOrg.setChildren(childrenList);
                //该机构不存在,则添加该机构
                mOrgDeptDataMap.put(r.getOrgId(),mOrg);
            }
        }
        Collection<MOrgDeptData> mOrgDeptDataCollection = mOrgDeptDataMap.values();
        list = new ArrayList<MOrgDeptData>(mOrgDeptDataCollection);
        return list;
    }
    @RequestMapping(value ="orgDeptMember/admin/listOrgDeptMemberByOrgIdAndDeptId", method = RequestMethod.GET)
    @ApiOperation(value = "根据部门id获取部门成员信息")
    public List<MOrgMemberRelation> listOrgDeptMemberByOrgIdAndDeptId(
            @ApiParam(name = "deptId", value = "", defaultValue = "")
            @RequestParam(value = "deptId") Integer deptId) {
        List<OrgMemberRelation> orgMemberRelations  = relationService.getOrgMemberByDeptId(deptId);
        return (List<MOrgMemberRelation>) convertToModels(orgMemberRelations, new ArrayList<MOrgMemberRelation>(orgMemberRelations.size()), MOrgMemberRelation.class, null);
    }
    @RequestMapping(value = "/orgDeptMember/getJkzlOrgIds", method = RequestMethod.GET)
    @ApiOperation(value = "根据userId获取总部orgId列表")
    public ObjEnvelop getJkzlOrgIds(
            @ApiParam(name = "userId", value = "用户id")
            @RequestParam(value = "userId", required = false) String userId,
            @ApiParam(name = "loginCode", value = "用户登录账号")
            @RequestParam(value = "loginCode", required = false) String loginCode) throws Exception{
        ObjEnvelop envelop = new ObjEnvelop();
        String seaUserId="";
        if(StringUtils.isNotEmpty(userId)){
            seaUserId = userId;
        } else if(StringUtils.isNotEmpty(loginCode)){
             List<User> users = userService.getUserForLogin(loginCode);
             if(null != users && users.size()>0){
                 seaUserId = users.get(0).getId();
             }else{
                 envelop.setMessage("用户不存在!");
                 envelop.setStatus(-1);
                 return envelop;
             }
        }else {
            envelop.setMessage("用户id和登录账户不能同时为空!");
            envelop.setStatus(-1);
            return envelop;
        }
        //医生在总部库中的对应关系
        MJkzlOrgMemberRelation mJkzlOrgMemberRelation = new MJkzlOrgMemberRelation();
        List<OrgMemberRelation> memberRelationList = relationService.getByUserId(seaUserId);
        if(null != memberRelationList && memberRelationList.size()>0){
            OrgMemberRelation  orgMemberRelation = memberRelationList.get(0);
            mJkzlOrgMemberRelation.setJkzlDoctorSn(orgMemberRelation.getJkzlDoctorSn());
            mJkzlOrgMemberRelation.setJkzlDoctorUid(orgMemberRelation.getJkzlDoctorUid());
            mJkzlOrgMemberRelation.setJkzlHosDeptId(orgMemberRelation.getJkzlHosDeptId());
            mJkzlOrgMemberRelation.setJkzlUserId(orgMemberRelation.getJkzlUserId());
        }
        String jkzlOrgId = relationService.getJkzlOrgIds(seaUserId);
        mJkzlOrgMemberRelation.setJkzlHosId(jkzlOrgId);
        envelop.setObj(mJkzlOrgMemberRelation);
        envelop.setStatus(200);
        return envelop;
    }
    @RequestMapping(value = "/orgDeptMember/getOrgDepts", method = RequestMethod.GET)
    @ApiOperation(value = "根据userId获取总部orgId列表")
    public Envelop getOrgDepts(
            @ApiParam(name = "userId", value = "用户id")
            @RequestParam(value = "userId", required = false) String userId) throws Exception{
        ListEnvelop envelop = new ListEnvelop();
        List<OrgMemberRelation> orgMemberRelations = new ArrayList<>();
        orgMemberRelations = orgMemberRelationService.getByUserId(userId);
        if(orgMemberRelations != null && orgMemberRelations.size()>0){
            envelop.setStatus(200);
            envelop.setDetailModelList(orgMemberRelations);
        }else {
            envelop.setStatus(200);
        }
        return envelop;
    }
}

+ 143 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/controller/OrgSaasEndPoint.java

@ -0,0 +1,143 @@
package com.yihu.jw.basic.org.controller;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.address.service.AddressDictService;
import com.yihu.jw.entity.ehr.org.OrgSaas;
import com.yihu.jw.entity.ehr.org.Organization;
import com.yihu.jw.basic.org.service.OrgSaasService;
import com.yihu.jw.basic.org.service.OrgService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.address.AddressDict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
 *
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "OrgSaas", description = "机构saas", tags = {"机构saas"})
public class OrgSaasEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private OrgSaasService orgSaasService;
    @Autowired
    private AddressDictService addressDictService;
    @Autowired
    private OrgService orgService;
    /**
     * 根据机构获取saas机构数据
     * @param orgCode
     * @return
     */
    @RequestMapping(value = "/OrgSaasByOrg", method = RequestMethod.GET)
    @ApiOperation(value = "根据机构获取saas机构数据")
    public ListEnvelop getOrgSaasByorgCode(
            @ApiParam(name = "orgCode", value = "机构", defaultValue = "")
            @RequestParam(value = "orgCode", required = false) String orgCode,
            @ApiParam(name = "type", value = "类别", defaultValue = "")
            @RequestParam(value = "type", required = false) String type,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception  {
        ListEnvelop result = new ListEnvelop();
        List<Object> OrgSaasList = orgSaasService.getOrgSaasByorgCode(orgCode,type);
        result.setDetailModelList(OrgSaasList);
        result.setStatus(200);
        return result;
    }
    /**
     * 机构授权检查并保存
     * @return
     */
    @RequestMapping(value = "/orgSaasSave", method = RequestMethod.POST)
    @ApiOperation(value = "机构授权检查,如果被授权的机构或者区域在指定机构总不存在,这新增这条记录,否则返回地址id")
    public boolean saveOrgSaas(
            @ApiParam(name = "orgCode", value = "机构", defaultValue = "")
            @RequestParam(value = "orgCode", required = false) String orgCode,
            @ApiParam(name = "type", value = "类别", defaultValue = "")
            @RequestParam(value = "type", required = false) String type,
            @ApiParam(name = "jsonData", value = "json数据", defaultValue = "")
            @RequestBody  String jsonData) throws Exception{
        //根据机构code和type值删除既存数据
     //   orgSaasService.deleteOrgSaas(orgCode,type);
        ObjectMapper objectMapper = new ObjectMapper();
        String[] jsonDatalist=jsonData.split("jsonData=");
        //将json串转换成对象,放进list里面
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, OrgSaas.class);
       List<OrgSaas> models = objectMapper.readValue(jsonDatalist[1],javaType);
        String addressId ="";
        boolean saveFlag=false;
        addressId=orgSaasService.saveOrgSaas(models,orgCode,type);
        if((models.size()>0&&addressId!=null)||!(models.size()>0)){
            saveFlag=true;
        }
        return saveFlag;
    }
    /**
     * 根据用户的机构id,获取Saas化的机构或者区域id
     * @param userOrgCode
     * @return
     */
    @RequestMapping(value = ServiceApi.Org.getUserOrgSaasByUserOrgCode, method = RequestMethod.GET)
    @ApiOperation(value = "根据用户的机构id,获取Saas化的机构或者区域id")
    public List<String> getUserOrgSaasByUserOrgCode(
            @ApiParam(name = "userOrgCode", value = "用户所在机构")
            @RequestParam(value = "userOrgCode", required = false)  List<String> userOrgCode,
            @ApiParam(name = "type", value = "saas类型")
            @RequestParam(value = "type", required = false) String type) throws Exception  {
        List<String> OrgSaasList = orgSaasService.getOrgSaasCodeByorgCode(userOrgCode, type);
        return OrgSaasList;
    }
    // ----------------------------- 用户登陆根据地区获取层级机构权限 ------------------------------------
    @RequestMapping(value = ServiceApi.Org.ChildOrgSaasByAreaCode, method = RequestMethod.POST)
    @ApiOperation(value = "根据地区获取层级机构权限")
    public List<String> childOrgSaasByAreaCode (
            @ApiParam(name = "area", value = "地区列表", required = true)
            @RequestParam(value = "area") String area) throws Exception  {
        if (StringUtils.isEmpty(area)) {
            return new ArrayList<>();
        }
        String [] areaArr = area.split(",");
        List<String> orgSaas = new ArrayList<>();
        for (String _area : areaArr) {
            AddressDict addressDict = addressDictService.findById(_area);
            String province = "";
            String city = "";
            String district = "";
            if (addressDict.getLevel() == 1){
                province =  addressDict.getName();
            } else if (addressDict.getLevel() == 2){
                city =  addressDict.getName();
            } else if (addressDict.getLevel() == 3){
                district =  addressDict.getName();
            }
            List<Organization> orgList = orgService.searchByAddress(province, city, district);
            orgList.forEach(item -> {
                if (!orgSaas.contains(item)) {
                    orgSaas.add(item.getOrgCode());
                }
            });
        }
        return orgSaas;
    }
}

+ 17 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/LdapEntriesRepository.java

@ -0,0 +1,17 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.LdapEntries;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * @author add by HZY at 20170309
 */
public interface LdapEntriesRepository extends JpaRepository<LdapEntries, Long> {
    LdapEntries findByOcMapIdAndKeyval(Integer ocMapId,Long keyval) throws Exception;
    @Query(value = "select a.user_id from users a where a.id=?1 and a.activated='1'",nativeQuery = true)
    String getUserIdById(String id) throws Exception;
}

+ 23 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgDeptDetailRepository.java

@ -0,0 +1,23 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.OrgDeptDetail;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/24.
 */
public interface OrgDeptDetailRepository extends JpaRepository<OrgDeptDetail,Integer> {
    @Query("select deptDetail from OrgDeptDetail deptDetail where deptDetail.deptId = :deptId order by deptDetail.insertTime desc ")
    List<OrgDeptDetail> searchByDeptId(@Param("deptId") Integer deptId);
    @Query("select deptDetail from OrgDeptDetail deptDetail where deptDetail.id = :id ")
    OrgDeptDetail findOrgDeptDetailsById(@Param("id") Integer id);
}

+ 37 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgDeptRepository.java

@ -0,0 +1,37 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.OrgDept;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/15.
 */
public interface OrgDeptRepository extends JpaRepository<OrgDept, Integer> {
    @Query("select dept from OrgDept dept where dept.parentDeptId = :parentDeptId order by dept.sortNo desc ")
    List<OrgDept> searchByParentDeptId(@Param("parentDeptId") Integer parentDeptId);
    @Query("select dept from OrgDept dept where dept.orgId = :orgId and dept.delFlag=0 order by dept.sortNo desc ")
    List<OrgDept> searchByOrgId(@Param("orgId") String orgId);
    @Query("select dept from OrgDept dept where dept.orgId = :orgId and dept.name=:name and dept.delFlag=0 order by dept.sortNo desc ")
    List<OrgDept> searchByOrgIdAndName(@Param("orgId") String orgId,@Param("name") String name);
    @Query("select dept from OrgDept dept where dept.orgId=?1 and dept.parentDeptId = ?2 and dept.delFlag = 0 order by dept.sortNo desc ")
    List<OrgDept> findByOrgIdAndParentDeptId(String orgId,Integer parentDeptId);
    @Query("select case when  max(dept.sortNo) is null then 1 else max(dept.sortNo) end from OrgDept dept where dept.parentDeptId = :parentDeptId")
    int searchParentIdOfMaxSortNo(@Param("parentDeptId") Integer parentDeptId);
    @Query("select dept.id from OrgDept dept where dept.code = :code and dept.delFlag = 0")
    List<Integer> findIdByCode(@Param("code") String code);
    @Query("select dept from OrgDept dept where dept.orgId = :orgId and dept.code=:code and dept.delFlag=0 order by dept.sortNo desc ")
    List<OrgDept> searchByOrgIdAnddeptCode(@Param("orgId") String orgId,@Param("code") String code);
}

+ 30 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgHealthCategoryDao.java

@ -0,0 +1,30 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.OrgHealthCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * 卫生机构类别 DAO
 *
 * @author 张进军
 * @date 2017/12/21 12:00
 */
public interface OrgHealthCategoryDao extends JpaRepository<OrgHealthCategory, Long> {
    @Query(" FROM OrgHealthCategory rmc WHERE rmc.id <> :id AND rmc.code = :code ")
    OrgHealthCategory isUniqueCode(@Param("id") Integer id, @Param("code") String code);
    @Query(" FROM OrgHealthCategory rmc WHERE rmc.id <> :id AND rmc.name = :name ")
    OrgHealthCategory isUniqueName(@Param("id") Integer id, @Param("name") String name);
    @Query(" FROM OrgHealthCategory rc WHERE rc.pid = :pid ")
    List<OrgHealthCategory> getChildrenByPid(@Param("pid") Long pid);
    @Query(" FROM OrgHealthCategory rc WHERE rc.pid = null ")
    List<OrgHealthCategory> getTopParents();
}

+ 61 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgMemberRelationRepository.java

@ -0,0 +1,61 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.OrgMemberRelation;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.domain.Page;
import java.util.List;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/16.
 */
public interface OrgMemberRelationRepository extends JpaRepository<OrgMemberRelation,Integer> {
    @Query("select relation from OrgMemberRelation relation where relation.deptId = :deptId ")
    List<OrgMemberRelation> searchByDeptId(@Param("deptId") Integer deptId);
    @Query("select count(relation.id) from OrgMemberRelation relation where relation.status = 0 and relation.deptId= :deptId")
    public Integer countByDeptId(@Param("deptId") Integer deptId);
    @Query("select r from OrgMemberRelation r where r.status=0 and r.orgId =?1")
    List<OrgMemberRelation> findByOrgId(String orgId);
    @Query("select r from OrgMemberRelation r where r.status=0 and r.orgId = :orgId and r.userId=:userId and r.deptId = :deptId")
    List<OrgMemberRelation> searchByOrgIdAndUserId(@Param("orgId") String orgId,@Param("userId") String userId, @Param("deptId") Integer deptId);
    @Query("select r.orgId from OrgMemberRelation r where r.status=0 and r.userId = :userId")
    List<String> findOrgIdByUserId(@Param("userId") String userId);
    @Query("select r.userId from OrgMemberRelation r where r.status=0 and r.orgId = :orgId")
    List<String> findUserIdByOrgId(@Param("orgId") List<String> orgId);
    @Query("select distinct(r.orgId) from OrgMemberRelation r where r.userId = :userId and r.status=0")
    List<String> searchByUserId(@Param("userId") String userId);
    @Query("select r.deptId from OrgMemberRelation r where r.status=0 and r.userId = :userId")
    List<Integer> findDeptIdByUserId(@Param("userId") String userId);
    @Modifying
    @Query("update OrgMemberRelation r set r.status = 1 where r.userId = :userId and r.orgId in (:orgId)")
    void updateByOrgId(@Param("orgId") String[] orgId, @Param("userId") String userId);
    @Modifying
    @Query("delete from OrgMemberRelation r where r.userId = :userId")
    void deleteOrgMemberRelationByUserId(@Param("userId") String userId);
    @Query("select r from OrgMemberRelation r where r.status = 0 and r.userId = :userId")
    List<OrgMemberRelation> findByUserId(@Param("userId") String userId);
    Page<OrgMemberRelation> findByOrgIdAndUserNameLike( String orgId,String userName,Pageable pageable);
    @Query("select r from OrgMemberRelation r where r.status=0  and r.deptId = :deptId")
    List<OrgMemberRelation> getOrgMemberByDeptId(@Param("deptId") Integer deptId);
}

+ 46 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrgSaasRepository.java

@ -0,0 +1,46 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.OrgSaas;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface OrgSaasRepository extends JpaRepository<OrgSaas, Integer> {
    //根据机构获取saas机构数据
    @Query("select os.id,os.orgCode,os.type,os.saasCode,os.saasName from OrgSaas os where  os.orgCode = :orgCode and os.type = :type")
    List<Object> getOrgSaasByorgCode(@Param("orgCode") String orgCode, @Param("type") String type);
    //新增查询数据是否存在
    @Query("select os.id,os.orgCode,os.type,os.saasCode,os.saasName from OrgSaas os where  os.orgCode = :orgCode and os.type = :type and os.saasCode = :saasCode")
    List<OrgSaas> getOrgSaasByorgCode(@Param("orgCode") String orgCode, @Param("type") String type,@Param("saasCode") String saasCode);
    //根据机构和类别删除既存数据
    @Modifying
    @Query("delete from OrgSaas os where os.orgCode = :orgCode and os.type=:type")
    void deleteOrgSaas(@Param("orgCode") String orgCode, @Param("type") String type);
    @Query("select os.saasName from OrgSaas os where os.type = 1 and os.orgCode = :orgCode")
    List<String> findSaasName(@Param("orgCode") String orgCode);
    @Query("select os.saasName from OrgSaas os where os.type = 2 and os.orgCode = :orgCode")
    List<String> findSaasNameByType(@Param("orgCode") String orgCode);
    @Query("select os.saasCode from OrgSaas os where os.type = 1 and os.orgCode = :orgCode")
    List<String> findSaasCode(@Param("orgCode") String orgCode);
    @Query("select os.saasCode from OrgSaas os where os.type = 2 and os.orgCode = :orgCode")
    List<String> findSaasCodeByType(@Param("orgCode") String orgCode);
    //根据机构获取saas机构数据
    @Query("select os.saasCode from OrgSaas os where  os.orgCode in (:orgCode) and os.type = :type")
    List<String> getOrgSaasCodeByorgCode(@Param("orgCode")  List<String> orgCode, @Param("type") String type);
}

+ 79 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/dao/OrganizationRepository.java

@ -0,0 +1,79 @@
package com.yihu.jw.basic.org.dao;
import com.yihu.jw.entity.ehr.org.Organization;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface OrganizationRepository extends JpaRepository<Organization, String> {
    @Query("select org from Organization org where org.location in (:geographyIds) and org.activityFlag=1")
    List<Organization> searchByAddress(@Param("geographyIds") List<String> geographyIds);
    @Query("select org.orgCode from Organization org where org.fullName like %:name% or org.shortName like %:name%")
    List<String> fingIdsByFullnameOrShortName(@Param("name") String name);
    @Query("select org from Organization org where org.admin = :adminLoginCode and org.orgCode = :orgCode")
    List<Organization>findByOrgAdmin(@Param("orgCode")  String orgCode,@Param("adminLoginCode")  String adminLoginCode);
    @Query("select org from Organization org where org.orgCode in (:orgCodes)")
    List<Organization> findByOrgCodes(@Param("orgCodes") List<String> orgCodes);
    @Query("select org from Organization org where cast(org.administrativeDivision as string) like ?1")
    List<Organization> findByArea(String area);
    @Query("select org from Organization org where org.activityFlag=1")
    List<Organization> findAllOrg();
    @Query("select org from Organization org where org.id=:orgId")
    List<Organization> findOrgById(@Param("orgId") long orgId);
    @Query("select org from Organization org where org.orgCode=:orgCode")
    List<Organization> findOrgByCode(@Param("orgCode") String orgCode);
    @Query("select org from Organization org where org.id=:orgId and org.parentHosId=:orgPId")
    List<Organization> checkSunOrg(@Param("orgPId") int orgPId,@Param("orgId")  long orgId);
    @Query("select org from Organization org where org.fullName like %:name% or org.shortName like %:name%")
    List<Organization> fingorgByFullnameOrShortName(@Param("name") String name);
    @Query("select org.id from Organization org where org.orgCode = :orgCode")
    List<Long> getOrgIdByOrgCode(@Param("orgCode") String orgCode);
    @Query("select org.orgCode from Organization org where org.id = :orgId")
    String findOrgCodeByOrgId(@Param("orgId") Long orgId);
    @Query("select org.orgCode from Organization org where org.fullName in (:fullName)")
    List<String> findOrgCodeByFullName(@Param("fullName") List<String> fullName);
    @Query("select org.id from Organization org where org.orgCode  in (:orgCode) ")
    List<Long> findOrgIdByOrgCodeList(@Param("orgCode") List<String> orgCode);
    @Query("select org.orgCode from Organization org where org.id in(:orgId)")
    List<String> findOrgListById(@Param("orgId") List<Long> orgId);
    @Query("select org from Organization org where org.id in (:orgId)")
    List<Organization> findOrgByIds(@Param("orgId") long[] orgId);
    @Query("select org.id from Organization org where org.orgCode in(:orgCode)")
    List<String> getIdByOrgCode(@Param("orgCode") List<String> orgCode);
    @Query("select org from Organization org where org.orgType='Hospital' and org.ing !='' and  org.ing is not null and org.lat!='' and org.lat is not null" )
    List<Organization> getHospital();
    @Query(value = "SELECT org.* from Organizations org WHERE org.administrative_division in(SELECT id from address_dict where pid = :pid)", nativeQuery = true)
    List<Organization> getOrgListByAddressPid(@Param("pid") Integer pid);
    @Query(value = "SELECT org.* from Organizations org WHERE org.administrative_division in(SELECT id from address_dict where pid = :pid) and org.full_name like %:fullName%", nativeQuery = true)
    List<Organization> getOrgListByAddressPidAndParam(@Param("pid") Integer pid, @Param("fullName") String fullName);
    @Query(value = "SELECT org.* from Organizations org WHERE org.administrative_division in(SELECT id from address_dict where pid = :pid) and org.administrative_division = :orgArea", nativeQuery = true)
    List<Organization> getOrgListByAddressPidAndOrgArea(@Param("pid") Integer pid, @Param("orgArea") String orgArea);
}

+ 56 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgDeptDetailService.java

@ -0,0 +1,56 @@
package com.yihu.jw.basic.org.service;
import com.yihu.jw.basic.org.dao.OrgDeptDetailRepository;
import com.yihu.jw.entity.ehr.org.OrgDeptDetail;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.SQLQuery;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 机构- 部门下科室业务类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/15.
 */
@Service
@Transactional(rollbackFor = {ServiceException.class})
public class OrgDeptDetailService extends BaseJpaService<OrgDeptDetail, OrgDeptDetailRepository> {
    @Autowired
    private OrgDeptDetailRepository deptDetailRepository;
    public OrgDeptDetail searchByDeptId(Integer deptId) {
        List<OrgDeptDetail> orgDeptDetails = deptDetailRepository.searchByDeptId(deptId);
        if (orgDeptDetails != null && orgDeptDetails.size() > 0) {
            return orgDeptDetails.get(0);
        } else {
            return null;
        }
    }
    public String searchByOrgNameAndDeptName(String orgName,String deptName){
        String orgDeptDetailPlace = "";
        String sql = "select odd.* from org_dept_detail odd JOIN org_dept od on odd.dept_id=od.id JOIN organizations o on od.org_id =o.id where o.full_name=:orgName AND  od.name =:deptName";
        SQLQuery query = currentSession().createSQLQuery(sql);
        query.setParameter("orgName", orgName);
        query.setParameter("deptName", deptName);
        List<Object> list  = query.list();
        if(null != list && list.size()>0){
            Object[] obj = (Object[]) list.get(0);
            orgDeptDetailPlace = obj[11] == null ? "":obj[11].toString();
        }
        return  orgDeptDetailPlace;
    }
    public  OrgDeptDetail findOrgDeptDetailsById(int id){
        return  deptDetailRepository.findOrgDeptDetailsById(id);
    }
}

+ 109 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgDeptImportService.java

@ -0,0 +1,109 @@
package com.yihu.jw.basic.org.service;
import com.yihu.jw.entity.ehr.org.Organization;
import com.yihu.jw.basic.org.dao.OrgDeptRepository;
import com.yihu.jw.entity.ehr.org.OrgDept;
import com.yihu.jw.entity.ehr.org.OrgDeptDetail;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * Created by Administrator on 2017/7/15.
 */
@Service
@Transactional
public class OrgDeptImportService extends BaseJpaService<OrgDept,OrgDeptRepository> {
    @Autowired
    private OrgService orgService;
    @Autowired
    private OrgDeptService orgDeptService;
    @Autowired
    private OrgDeptDetailService orgDeptDetailService;
    public List codeExistence(String[] code) {
        String sql = "SELECT code FROM Org_Dept WHERE code in(:code)";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameterList("code", code);
        return sqlQuery.list();
    }
    public List nameExistence(String[] name) {
        String sql = "SELECT name FROM Org_Dept WHERE name in(:name)";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameterList("name", name);
        return sqlQuery.list();
    }
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean addOrgDeptBatch(List<Map<String, Object>> orgDepts) {
        Map<String, Object> map;
        for(int i=1; i <= orgDepts.size(); i++){
            map = orgDepts.get(i-1);
            String parentDeptId = map .get("parentDeptId").toString();
            Integer parentId = orgDeptService.getParentIdByCode(parentDeptId);
            String orgId = orgService.getOrgIdByOrgCode(map .get("orgCode").toString());
            int sortNo = orgDeptService.searchParentIdOfMaxSortNo(parentId) + i;
            OrgDept newOrgDept = new OrgDept();
            newOrgDept.setParentDeptId(parentId);
            newOrgDept.setOrgId(orgId);
            newOrgDept.setCode(map .get("code").toString());
            newOrgDept.setName(map .get("name").toString());
            newOrgDept.setDelFlag(0);
            newOrgDept.setSortNo(sortNo);
            OrgDept save = orgDeptService.save(newOrgDept);
            Organization org = orgService.getOrg(map.get("orgCode").toString());
            if (null != org && "Hospital".equalsIgnoreCase(org.getOrgType())) {
                String gloryId = map.get("gloryId").toString();
                String[] arr = gloryId.split(",");
                String ids = "";
                for (String s : arr) {
                    switch (s) {
                        case "国家重点科室" :
                            ids += 1 + ",";
                            break;
                        case "省级重点科室" :
                            ids += 2 + ",";
                            break;
                        case "医院特色专科" :
                            ids += 3 + ",";
                            break;
                    }
                }
                ids = "".equals(ids) ? "" : ids.substring(0,ids.length()-1);
                String pyCode = map .get("pyCode").toString();
                OrgDeptDetail orgDeptDetail = new OrgDeptDetail();
                orgDeptDetail.setDeptId(save.getId());
                orgDeptDetail.setCode(UUID.randomUUID().toString().replace("-",""));
                orgDeptDetail.setName(map .get("name").toString());
                orgDeptDetail.setPhone(map .get("phone").toString());
                orgDeptDetail.setGloryId(ids);
                orgDeptDetail.setOrgId(orgId);
                orgDeptDetail.setIntroduction(map .get("introduction").toString());
                orgDeptDetail.setPlace(map .get("place").toString());
                orgDeptDetail.setPyCode("门诊科室".equals(pyCode) ? 1 + "" : 2 + "");
                orgDeptDetail.setDisplayStatus(0);
                orgDeptDetail.setInsertTime(new Timestamp(new Date().getTime()));
                orgDeptDetail.setUpdateTime(new Timestamp(new Date().getTime()));
                orgDeptDetail.setSortNo(sortNo);
                orgDeptDetailService.save(orgDeptDetail);
            }
        }
        return true;
    }
    private Object null2Space(Object o){
        return o==null? "" : o;
    }
}

+ 287 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgDeptService.java

@ -0,0 +1,287 @@
package com.yihu.jw.basic.org.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.org.dao.OrgDeptDetailRepository;
import com.yihu.jw.basic.org.dao.OrgDeptRepository;
import com.yihu.jw.basic.org.dao.OrgMemberRelationRepository;
import com.yihu.jw.entity.ehr.org.OrgDept;
import com.yihu.jw.entity.ehr.org.OrgDeptDetail;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * 机构- 部门业务类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/15.
 */
@Service
@Transactional(rollbackFor = {ServiceException.class})
public class OrgDeptService extends BaseJpaService<OrgDept, OrgDeptRepository> {
    @Autowired
    private OrgDeptRepository orgDeptRepository;
    @Autowired
    private OrgDeptDetailRepository deptDetailRepository;
    @Autowired
    protected ObjectMapper objectMapper;
    @Autowired
    protected OrgMemberRelationRepository orgMemberRelationRepository;
    public OrgDept searchBydeptId(Integer deptId) {
        return orgDeptRepository.getOne(deptId);
    }
    public OrgDept searchByOrgIdAndName(String orgId,String name) {
        List<OrgDept> orgDepts = orgDeptRepository.searchByOrgIdAndName(orgId, name);
        if (orgDepts!=null && !orgDepts.isEmpty()){
            return orgDepts.get(0);
        }else {
            return null;
        }
    }
    public int getCountByOrgIdAndName(String orgId,String name) {
        List<OrgDept> orgDepts = orgDeptRepository.searchByOrgIdAndName(orgId, name);
        if (orgDepts!=null && !orgDepts.isEmpty()){
            return orgDepts.size();
        }else {
            return 0;
        }
    }
    public List<OrgDept> searchByOrgId(String orgId) {
        return orgDeptRepository.searchByOrgId(orgId);
    }
    public List<OrgDept> searchByParentId(Integer parentDeptId) {
        return orgDeptRepository.searchByParentDeptId(parentDeptId);
    }
    public int searchParentIdOfMaxSortNo(Integer parentDeptId) {
        return orgDeptRepository.searchParentIdOfMaxSortNo(parentDeptId);
    }
    public OrgDept saveOrgDept(OrgDept dept) {
        dept.setDelFlag(0);
        dept.setSortNo(searchParentIdOfMaxSortNo(dept.getParentDeptId())+1);
        OrgDeptDetail deptDetail = dept.getDeptDetail();
        OrgDept save = orgDeptRepository.save(dept);
        if (deptDetail != null) {
            deptDetail.setDeptId(save.getId());
            deptDetail.setUpdateTime(new Timestamp(new Date().getTime()));
            deptDetail.setInsertTime(new Timestamp(new Date().getTime()));
            deptDetailRepository.save(deptDetail);
        }
        return dept;
    }
    public OrgDept updateOrgDeptName(Integer deptId, String name) {
        OrgDept dept = orgDeptRepository.getOne(deptId);
        dept.setName(name);
        orgDeptRepository.save(dept);
        return dept;
    }
    public OrgDept updateDept(OrgDept dept) {
        OrgDeptDetail deptDetail = dept.getDeptDetail();
        if (deptDetail != null) {
            deptDetail.setUpdateTime(new Timestamp(new Date().getTime()));
//            deptDetail.setInsertTime(new Timestamp(new Date().getTime()));
            deptDetailRepository.save(deptDetail);
        }
        orgDeptRepository.save(dept);
        return dept;
    }
    public OrgDept deleteOrgDept(Integer deptId) {
        OrgDept dept = orgDeptRepository.getOne(deptId);
        dept.setDelFlag(1);
        orgDeptRepository.save(dept);
        return dept;
    }
    /**
     * 交换部门排序
     *
     * @param deptId1
     * @return
     */
    public void changeOrgDeptSort(Integer deptId1, Integer deptId2) {
        OrgDept orgDept1 = orgDeptRepository.getOne(deptId1);
        OrgDept orgDept2 = orgDeptRepository.getOne(deptId2);
        Integer sortNo1 = orgDept1.getSortNo();
        orgDept1.setSortNo(orgDept2.getSortNo());
        orgDeptRepository.save(orgDept1);
        orgDept2.setSortNo(sortNo1);
        orgDeptRepository.save(orgDept2);
    }
    //Excel导入部门信息(有deptId的导入)
    public boolean importDataByExcel(List<Map<Object, Object>> list) {
        boolean succ = false;
        if (!list.isEmpty()) {
            try {
                int i=1;
                for (Map<Object, Object> map : list) {
                    String mapJson = objectMapper.writeValueAsString(map);
                    OrgDept dept = objectMapper.readValue(mapJson, OrgDept.class);
                    dept.setSortNo(i);
                    orgDeptRepository.save(dept);
                    i++;
                }
                succ = true;
            } catch (Exception e) {
                succ = false;
                e.printStackTrace();
            }
        }
        return succ;
    }
    //Excel导入部门信息(只有部门名称的导入)
    public boolean importDataByExce2l(List<Map<Object, Object>> list) {
        boolean succ = false;
        if (!list.isEmpty()) {
            try {
                OrgDept dept = null;
                int i=1;
                for (Map<Object, Object> map : list) {
                    dept = new OrgDept();
                    Object parentName = map.get("parentName");
                    String name = map.get("name").toString();
                    String orgId =  map.get("orgId").toString();
                    if (parentName!=null && !parentName.toString().isEmpty()){
                        //查询父部门ID ,未存在则添加
                        OrgDept parent = searchByOrgIdAndName(orgId, parentName.toString());
                        if (parent == null){
                            parent = new OrgDept();
                            parent.setOrgId(orgId);
                            parent.setCode(UUID.randomUUID().toString());
                            parent.setName(parentName.toString());
                            parent.setDelFlag(0);
                            orgDeptRepository.save(parent);
                        }
                        dept.setParentDeptId(parent.getId());
                        //保存部门信息
                    }
                    dept.setOrgId(orgId);
                    dept.setCode(UUID.randomUUID().toString());
                    dept.setName(name);
                    dept.setDelFlag(0);
                    dept.setSortNo(i);
                    orgDeptRepository.save(dept);
                    i++;
                }
                succ = true;
            } catch (Exception e) {
                succ = false;
                e.printStackTrace();
            }
        }
        return succ;
    }
    /**
     * 导入部门成员关系
     * @param list
     * @return
     */
    public boolean importDeptMembers(List<Map<Object, Object>> list) {
        boolean succ = false;
        if (!list.isEmpty()) {
            try {
                OrgDept dept = null;
                for (Map<Object, Object> map : list) {
                    dept = new OrgDept();
                    Object parentDeptName = map.get("parentDeptName");
                    String deptName = map.get("deptName").toString();
                    String orgId =  map.get("orgId").toString();
                    if (parentDeptName!=null && !parentDeptName.toString().isEmpty()){
                        //查询父部门ID ,未存在则添加
                        OrgDept parent = searchByOrgIdAndName(orgId, parentDeptName.toString());
                        if (parent == null){
                            parent = new OrgDept();
                            parent.setOrgId(orgId);
                            parent.setCode(UUID.randomUUID().toString());
                            parent.setName(parentDeptName.toString());
                            parent.setDelFlag(0);
                            orgDeptRepository.save(parent);
                        }
                        dept.setParentDeptId(parent.getId());
                        //保存部门信息
                    }
                    dept.setOrgId(orgId);
                    dept.setCode(UUID.randomUUID().toString());
                    dept.setName(deptName);
                    dept.setDelFlag(0);
                    orgDeptRepository.save(dept);
                }
                succ = true;
            } catch (Exception e) {
                succ = false;
                e.printStackTrace();
            }
        }
        return succ;
    }
    public int getOrgDeptByOrgIdAndName(String orgId,String name) {
        List<OrgDept> orgDepts = orgDeptRepository.searchByOrgIdAndName(orgId, name);
        if (orgDepts!=null && !orgDepts.isEmpty()){
            OrgDept orgDept=orgDepts.get(0);
            return orgDept.getId();
        }else {
            return 0;
        }
    }
    public List<String> searchByUserId(String userId) {
        return orgMemberRelationRepository.searchByUserId(userId);
    }
    public Integer getParentIdByCode(String code) {
        List<Integer> list = orgDeptRepository.findIdByCode(code);
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return 0;
    }
    public OrgDept getOrgDeptByDeptName(String orgId,String name) {
        List<OrgDept> orgDepts = orgDeptRepository.searchByOrgIdAndName(orgId, name);
        if (orgDepts!=null && !orgDepts.isEmpty()){
            return orgDepts.get(0);
        }else {
            return null;
        }
    }
    public int getOrgDeptByOrgIdAndDeptCode(String orgId,String code) {
        List<OrgDept> orgDepts = orgDeptRepository.searchByOrgIdAnddeptCode(orgId, code);
        if (orgDepts!=null && !orgDepts.isEmpty()){
            OrgDept orgDept=orgDepts.get(0);
            return orgDept.getId();
        }else {
            return 0;
        }
    }
}

+ 169 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgHealthCategoryService.java

@ -0,0 +1,169 @@
package com.yihu.jw.basic.org.service;
import com.yihu.jw.entity.ehr.org.OrgHealthCategory;
import com.yihu.jw.basic.org.dao.OrgHealthCategoryDao;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
 * 卫生机构类别 Service
 *
 * @author 张进军
 * @date 2017/12/21 12:00
 */
@Service
@Transactional
public class OrgHealthCategoryService extends BaseJpaService<OrgHealthCategory, OrgHealthCategoryDao> {
    @Autowired
    OrgHealthCategoryDao orgHealthCategoryDao;
    public OrgHealthCategory getById(Long id) {
        return orgHealthCategoryDao.getOne(id);
    }
    public List<OrgHealthCategory> findAll() {
        return orgHealthCategoryDao.findAll();
    }
    @Transactional(readOnly = false)
    public OrgHealthCategory save(OrgHealthCategory orgHealthCategory) {
        return orgHealthCategoryDao.save(orgHealthCategory);
    }
    @Transactional(readOnly = false)
    public void delete(Long id) {
        List<OrgHealthCategory> descendantList = this.getDescendantIds(id);
        descendantList.add(this.getById(id));
        orgHealthCategoryDao.deleteInBatch(descendantList);
    }
    public Integer isUniqueCode(Integer id, String code) {
        OrgHealthCategory OrgHealthCategory = orgHealthCategoryDao.isUniqueCode(id, code);
        if (OrgHealthCategory == null) {
            return 200;
        } else {
            return -1;
        }
    }
    public Integer isUniqueName(Integer id, String name) {
        OrgHealthCategory OrgHealthCategory = orgHealthCategoryDao.isUniqueName(id, name);
        if (OrgHealthCategory == null) {
            return 200;
        } else {
            return -1;
        }
    }
    /**
     * 根据父级ID,获取其子节点;父级ID为 -1 时,返回顶级节点。
     *
     * @param pid 父级ID。
     * @return 子节点集合
     */
    public List<OrgHealthCategory> getChildrenByPid(Long pid) {
        List<OrgHealthCategory> children = new ArrayList<>();
        if (pid == -1) {
            children = orgHealthCategoryDao.getTopParents();
        } else {
            children = orgHealthCategoryDao.getChildrenByPid(pid);
        }
        return children;
    }
    /**
     * 根据ID获取其所有后代ID
     *
     * @param pid 父节点ID
     * @return 所有后代ID
     */
    private List<OrgHealthCategory> getDescendantIds(Long pid) {
        List<OrgHealthCategory> idList = new ArrayList<>();
        List<OrgHealthCategory> children = this.getChildrenByPid(pid);
        for (OrgHealthCategory child : children) {
            idList.add(child);
            idList.addAll(getDescendantIds(child.getId()));
        }
        return idList;
    }
    /**
     * 根据父级集合,递归获取父级及其自子级集合,形成树形结构
     *
     * @param parentList 父级集合
     * @return 父级及其子集的树形结构数据
     */
    public List<OrgHealthCategory> getTreeByParents(List<OrgHealthCategory> parentList) {
        List<OrgHealthCategory> resultList = new ArrayList<>();
        for (int i = 0; i < parentList.size(); i++) {
            OrgHealthCategory parent = parentList.get(i);
            List<OrgHealthCategory> childList = this.getChildrenByPid(parent.getId());
            List<OrgHealthCategory> childTreeList = getTreeByParents(childList);
            parent.setChildren(childTreeList);
            resultList.add(parent);
        }
        return resultList;
    }
    /**
     * 递归不满足条件的父级集合,获取其满足条件的子集,并返回子集及其父级的树形结构
     *
     * @param parents  不满足条件的父级集合
     * @param codeName 编码或名称
     * @return 满足条件的子集及其父级的树形结构
     */
    public List<OrgHealthCategory> getTreeByParentsAndCodeName(List<OrgHealthCategory> parents, String codeName) throws ParseException {
        List<OrgHealthCategory> treeData = new ArrayList<>();
        for (OrgHealthCategory parent : parents) {
            Long parentId = parent.getId();
            List<OrgHealthCategory> childrenTree = new ArrayList<>();
            List<OrgHealthCategory> children = this.getChildrenByPid(parentId);
            if (children.size() == 0) continue;
            // 获取满足条件的子节点
            String filters = "pid=" + parentId + ";code?" + codeName + " g1;name?" + codeName + " g1;";
            List<OrgHealthCategory> childrenIin = (List<OrgHealthCategory>) this.search(filters);
            if (childrenIin.size() != 0) {
                childrenTree.addAll(getTreeByParents(childrenIin));
            }
            // 递归不满足条件的子节点
            children.removeAll(childrenIin);
            if (children.size() != 0) {
                childrenTree.addAll(getTreeByParentsAndCodeName(children, codeName));
            }
            if (childrenTree.size() != 0) {
                parent.setChildren(childrenTree);
                treeData.add(parent);
            }
        }
        return treeData;
    }
    /**
     * 根据父级主键获取其最顶级节点主键
     *
     * @param pid 父级主键
     * @return 对应的最顶级节点主键
     */
    public Long getTopPidByPid(Long pid) {
        if (pid == null) {
            return null;
        } else {
            OrgHealthCategory entity = this.getById(pid);
            if (entity.getPid() != null) {
                pid = getTopPidByPid(entity.getPid());
            }
            return pid;
        }
    }
}

+ 208 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgMemberRelationService.java

@ -0,0 +1,208 @@
package com.yihu.jw.basic.org.service;
import com.yihu.jw.basic.org.dao.OrgMemberRelationRepository;
import com.yihu.jw.entity.ehr.org.OrgMemberRelation;
import com.yihu.jw.basic.user.service.DoctorService;
import com.yihu.jw.basic.user.service.UserService;
import com.yihu.jw.restmodel.ehr.org.MOrgDeptData;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/2/16.
 */
@Service
@Transactional
public class OrgMemberRelationService extends BaseJpaService<OrgMemberRelation, OrgMemberRelationRepository> {
    @Autowired
    private OrgMemberRelationRepository relationRepository;
    @Autowired
    private OrgService orgService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private UserService userService;
    public List<OrgMemberRelation> searchByDeptId(Integer deptId) {
        return relationRepository.searchByDeptId(deptId);
    }
    /**
     * 部门 是否存在成员
     * @param deptId    部门id
     * @return
     */
    public boolean hadMemberRelation(Integer deptId){
        Integer count = relationRepository.countByDeptId(deptId);
        if (count!=null && count>0){
            return true;
        }else {
            return false;
        }
    }
    public OrgMemberRelation updateStatusDeptMember(Integer memRelationId,int status){
        OrgMemberRelation relation = relationRepository.getOne(memRelationId);
        relation.setStatus(status);
        relationRepository.save(relation);
        return relation;
    }
    public void deleteDeptMember(Integer memRelationId){
        relationRepository.deleteById(memRelationId);
    }
    public OrgMemberRelation getOrgMemberRelation(Long memRelationId) {
        OrgMemberRelation relation = relationRepository.getOne(Integer.valueOf( String.valueOf(memRelationId) ) );
        return relation;
    }
    public int getCountByOrgIdAndUserId(String orgId,String userId, Integer deptId) {
        List<OrgMemberRelation> orgOrgMemberRelations = relationRepository.searchByOrgIdAndUserId(orgId, userId, deptId);
        if (orgOrgMemberRelations!=null && !orgOrgMemberRelations.isEmpty()){
            return orgOrgMemberRelations.size();
        }else {
            return 0;
        }
    }
    public List<String> getOrgIds(String userId) {
        List<String> userIds = relationRepository.findOrgIdByUserId(userId);
        return userIds;
    }
    public List<String> getOrgCodes(String userId) {
        List<String> orgIds = this.getOrgIds(userId);
        List<String> orgCodes = new ArrayList<>();
        for (String s : orgIds) {
            String orgCode = orgService.getOrgCodeByOrgId(Long.valueOf(s));
            orgCodes.add(orgCode);
        }
        return orgCodes;
    }
    public List<String> getUserIdByOrgId(List<String> orgId) {
        return relationRepository.findUserIdByOrgId(orgId);
    }
    public List<Integer> getDeptIds(String userId) {
        List<Integer> deptIds = relationRepository.findDeptIdByUserId(userId);
        return deptIds;
    }
    public void updateByOrgId(String[] orgId,String userId) {
        relationRepository.updateByOrgId(orgId, userId);
    }
    public List<OrgMemberRelation> getByUserId(String userId) {
        List<OrgMemberRelation> relationList = relationRepository.findByUserId(userId);
        return relationList;
    }
    /**
     *  查询机构人员去重复  分页
     * @param orgId
     * @param searchParm
     * @param size
     * @param page
     * @return
     */
    public List<OrgMemberRelation> getOrgDeptMembers(String orgId,String searchParm, int size, int page) {
        Session session = entityManager.unwrap(Session.class);
        String sql="select distinct r.userId as userId,r.userName as userName from OrgMemberRelation r where r.status=0 and r.orgId=:orgId and r.userName like :searchParm";
        Query query = session.createQuery(sql);
        query.setResultTransformer(Transformers.aliasToBean(OrgMemberRelation.class));
        query.setString("orgId", orgId);
        query.setString("searchParm","%"+searchParm+"%");
        query.setMaxResults(size);
        query.setFirstResult((page - 1) * size);
        List<OrgMemberRelation> list;
        list = query.list();
        return list;
    }
    /**
     *  查询机构人员数量去重复
     * @param orgId
     * @param searchParm
     * @return
     */
    public Integer getOrgDeptMembersInt(String orgId,String searchParm) {
        Session session = entityManager.unwrap(Session.class);
        String sql="select count(distinct r.userId) from OrgMemberRelation r where r.status=0 and r.orgId=:orgId and r.userName like :searchParm";
        Query query = session.createQuery(sql);
        query.setString("orgId", orgId);
        query.setString("searchParm","%"+searchParm+"%");
        return ((Long)query.list().get(0)).intValue();
    }
    /**
     *  查询机构人员去重复
     * @param orgId
     * @param searchParm
     * @return
     */
    public List<OrgMemberRelation> getAllOrgDeptMemberDistinct(String orgId,String searchParm) {
        Session session = entityManager.unwrap(Session.class);
        String sql="select distinct r.orgId as orgId,r.orgName as orgName,coalesce(r.parentUserId,'') as parentUserId,coalesce(r.parentUserName,'') as parentUserName," +
                " r.userId as userId,r.userName as userName  from OrgMemberRelation r" +
                " where r.status=0 and r.orgId=:orgId and r.userName like :searchParm";
        Query query = session.createQuery(sql);
        query.setResultTransformer(Transformers.aliasToBean(OrgMemberRelation.class));
        query.setString("orgId", orgId);
        query.setString("searchParm","%"+searchParm+"%");
        List<OrgMemberRelation> list = query.list();
        return list;
    }
    /**
     * 修改上级成员
     * @param model
     */
    public void updateOrgDeptMemberParent(OrgMemberRelation model){
        List<OrgMemberRelation> relationList = relationRepository.findByUserId(model.getUserId());
        for(OrgMemberRelation item : relationList){
            item.setParentUserId(model.getParentUserId());
            item.setParentUserName(model.getParentUserName());
            save(item);
        }
    }
    public List<OrgMemberRelation> getOrgMemberByDeptId(Integer deptId) {
        List<OrgMemberRelation> orgOrgMemberRelations = relationRepository.getOrgMemberByDeptId(deptId);
        return orgOrgMemberRelations;
    }
    public String getJkzlOrgIds(String userId) {
        //根据用户id获取医生表orgId
        List<String> orgIds = orgService.getEhrOrgIdsByUserId(userId);
        String jkzlOrgId="";
        if(orgIds.size() > 0){
            String[] orgIdsStr = orgIds.toArray(new String[orgIds.size()]);
            List<String>  jkzlOrgIds = orgService.getJkzlOrgIdsByEhrOrgId(orgIdsStr);
            if(jkzlOrgIds.size()>0){
                jkzlOrgId = jkzlOrgIds.get(0);
            }
        }
        return jkzlOrgId;
    }
    public void deleteOrgMemberRelationByUserId(String userId) {
        relationRepository.deleteOrgMemberRelationByUserId(userId);
    }
}

+ 91 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgSaasService.java

@ -0,0 +1,91 @@
package com.yihu.jw.basic.org.service;
import com.yihu.jw.basic.org.dao.OrgSaasRepository;
import com.yihu.jw.entity.ehr.org.OrgSaas;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 机构授权
 * @author zdm
 * @version 1.0
 * @created 2017-5-26
 */
@Transactional
@Service
public class OrgSaasService extends BaseJpaService<OrgSaas,OrgSaasRepository>{
    @Autowired
    private OrgSaasRepository oOrgSaasRepository;
    /**
     * 根据机构获取saas机构数据
     * @param orgCode
     * @param type
     * @return
     */
	public List<Object> getOrgSaasByorgCode(String orgCode,String type){
        List<Object> OrgSaasList = oOrgSaasRepository.getOrgSaasByorgCode(orgCode,type);
        return OrgSaasList;
	}
    public List<OrgSaas> isOrgSaasExist(OrgSaas orgSaas) throws Exception {
        List<OrgSaas> OrgSaasList = oOrgSaasRepository.getOrgSaasByorgCode(orgSaas.getOrgCode(),orgSaas.getType(),orgSaas.getSaasCode());
        return OrgSaasList;
    }
    /**
     * 机构授权检查并保存
     * 返回新地址id
     * @param orgSaaslist
     * @param orgCode
     * @param type
     */
    public String saveOrgSaas(List<OrgSaas> orgSaaslist,String orgCode,String type) {
        String id="";
        oOrgSaasRepository.deleteOrgSaas(orgCode,type);
        if(orgSaaslist.size()>0){
            for(OrgSaas os:orgSaaslist){
                id=oOrgSaasRepository.save(os).getId().toString();
            }
        }
        return id;
    }
    public void deleteOrgSaas(String orgCode,String type) {
        oOrgSaasRepository.deleteOrgSaas(orgCode,type);
    }
    public List<String> getSaasName(String orgCode, String type) {
        if ("1".equals(type)) {
            return oOrgSaasRepository.findSaasName(orgCode);
        }
        return oOrgSaasRepository.findSaasNameByType(orgCode);
    }
    public List<String> getSaasCode(String orgCode, String type) {
        if ("1".equals(type)) {
            return oOrgSaasRepository.findSaasCode(orgCode);
        }
        return oOrgSaasRepository.findSaasCodeByType(orgCode);
    }
    /**
     * 根据机构获取saas机构数据
     * @param orgCode
     * @param type
     * @return
     */
    public List<String> getOrgSaasCodeByorgCode( List<String> orgCode, String type){
        List<String> OrgSaasList = oOrgSaasRepository.getOrgSaasCodeByorgCode(orgCode,type);
        return OrgSaasList;
    }
}

+ 427 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/org/service/OrgService.java

@ -0,0 +1,427 @@
package com.yihu.jw.basic.org.service;
import com.yihu.jw.basic.address.service.AddressService;
import com.yihu.jw.basic.org.dao.OrganizationRepository;
import com.yihu.jw.entity.ehr.org.OrgDept;
import com.yihu.jw.entity.ehr.org.Organization;
import com.yihu.jw.entity.ehr.address.Address;
import com.yihu.jw.restmodel.ehr.org.MOrgDeptJson;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.jw.entity.ehr.id.BizObject;
import com.yihu.jw.entity.ehr.id.ObjectId;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 组织机构管理器.
 *
 * @author Sand
 * @version 1.0
 */
@Service
@Transactional
public class OrgService extends BaseJpaService<Organization, OrganizationRepository> {
    @Autowired
    private OrganizationRepository organizationRepository;
    @Autowired
    private AddressService addressService;
    @Autowired
    private OrgDeptService orgDeptService;
    @Value("${deploy.region}")
    Short deployRegion = 3502;
    public OrgService() {
    }
    public Organization getOrg(String orgCode) {
        List<Organization> list = organizationRepository.findOrgByCode(orgCode);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
    public Organization getOrgById(String orgId) {
        List<Organization> list = organizationRepository.findOrgById(Long.valueOf(orgId));
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
    public Organization getOrgByAdminLoginCode(String orgCode, String adminLoginCode) {
        List<Organization> list = organizationRepository.findByOrgAdmin(orgCode, adminLoginCode);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
//    public Organization saveOrg(Organization org) {
//        return save(org);
//    }
    public Boolean isExistOrg(String orgCode) {
        Organization org = organizationRepository.getOne(orgCode);
        return org != null;
    }
    public Boolean checkSunOrg(String orgPid, String orgId) {
        List<Organization> orgs = organizationRepository.checkSunOrg(Integer.valueOf(orgPid), Long.valueOf(orgId));
        if (orgs != null && orgs.size() > 0) {
            return true;
        }
        return false;
    }
    public void delete(String orgCode) {
        organizationRepository.deleteById(orgCode);
    }
    public List<Organization> searchByAddress(String province, String city, String district) {
        List<String> geographyIds = addressService.searchList(province, city, district);
        if (geographyIds != null && geographyIds.size() > 0) {
            List<Organization> orgs = organizationRepository.searchByAddress(geographyIds);
            return orgs;
        } else {
            return new ArrayList<>();
        }
    }
    public List<String> getCodesByName(String name) {
        List<String> codes = organizationRepository.fingIdsByFullnameOrShortName(name);
        return codes;
    }
    public List<Organization> findByOrgCodes(List<String> orgCodes) {
        return organizationRepository.findByOrgCodes(orgCodes);
    }
    public List<Organization> findByOrgArea(String area) {
        return organizationRepository.findByArea(area + "%");
    }
    public List<Organization> getAllSaasOrgs(String name) {
        List<Organization> codes = organizationRepository.fingorgByFullnameOrShortName(name);
        return codes;
    }
    public List orgCodeExistence(String[] orgCode) {
        String sql = "SELECT org_code FROM organizations WHERE org_code in(:orgCode)";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameterList("orgCode", orgCode);
        return sqlQuery.list();
    }
    public String getOrgIdByOrgCode(String orgCode) {
        List<Long> orgId = organizationRepository.getOrgIdByOrgCode(orgCode);
        if (null != orgId && orgId.size() > 0) {
            return Long.toString(orgId.get(0));
        }
        return null;
    }
    public String getOrgCodeByOrgId(Long orgId) {
        return organizationRepository.findOrgCodeByOrgId(orgId);
    }
    public List<String> getOrgCodeByFullName(List<String> fullName) {
        List<String> list = organizationRepository.findOrgCodeByFullName(fullName);
        return list;
    }
    public List<String> getOrgIdByOrgCodeList(List<String> orgCode) {
        List<Long> orgId = organizationRepository.findOrgIdByOrgCodeList(orgCode);
        List<String> orgIdList = new ArrayList<>();
        if (null != orgId && orgId.size() > 0) {
            for (Long l : orgId) {
                orgIdList.add(Long.toString(l));
                return orgIdList;
            }
        }
        return null;
    }
    public List<String> getOrgListById(List<Long> orgId) {
        List<String> list = organizationRepository.findOrgListById(orgId);
        return list;
    }
    protected String getObjectId(BizObject bizObject) {
        return new ObjectId(deployRegion, bizObject).toString();
    }
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean addOrgBatch(List<Map<String, Object>> orgDepts) {
        Map<String, Object> map;
        Address geography = null;
        List<Address> geographies = null;
        try {
            for (int i = 1; i <= orgDepts.size(); i++) {
                map = orgDepts.get(i - 1);
                String addressId = "";
                //保存地址到addresses---start
                geography = new Address();
                if (geography.getCountry() == null) {
                    geography.setCountry("中国");
                }
                Map<String, String> adressMap = getAdressByLocation(map.get("location").toString());
                geography.setProvince(adressMap.get("provinceName").toString());
                geography.setCity(adressMap.get("cityName").toString());
                geography.setDistrict(adressMap.get("district").toString());
                geography.setTown(adressMap.get("town").toString());
                geography.setStreet(adressMap.get("street").toString());
                geographies = addressService.isGeographyExist(geography);
                if (geographies == null || geographies.size() == 0) {
                    geography.setId(getObjectId(BizObject.Geography));
                    addressId = addressService.saveAddress(geography);
                } else {
                    addressId = geographies.get(0).getId();
                }
                //保存地址到addresses---end
                Organization organization = new Organization();
//                organization.setId(Long.parseLong(map.get("id").toString()));
                organization.setFullName(null2Space(map.get("fullName")));
                organization.setBasicUnitFlag(null2Space(map.get("basicUnitFlag")));
                organization.setParentHosId(nullSpaceOfInteger(map.get("parentHosId")));
                organization.setActivityFlag(nullSpaceOfInteger(map.get("activityFlag")));
                organization.setOrgChanges(null2Space(map.get("orgChanges")));
                organization.setOrgCode(null2Space(map.get("orgCode")));
                organization.setHosManageType(null2Space(map.get("hosManageType")));
                organization.setHosEconomic(null2Space(map.get("hosEconomic")));
                organization.setHosTypeId(null2Space(map.get("hosTypeId")));
                organization.setHosTypeName(null2Space(map.get("hosTypeName")));
                organization.setAdministrativeDivision(nullSpaceOfInteger(map.get("administrativeDivision")));
                organization.setStreetId(null2Space(map.get("streetId")));
                organization.setLevelId(null2Space(map.get("levelId")));
                organization.setHosHierarchy(null2Space(map.get("hosHierarchy")));
                organization.setHostUnit(null2Space(map.get("hostUnit")));
                organization.setAscriptionType(nullSpaceOfInteger(map.get("ascriptionType")));
                organization.setDischargePatientFlag(null2Space(map.get("dischargePatientFlag")));
                organization.setReportingClinicFlag(null2Space(map.get("reportingClinicFlag")));
                organization.setReportingVillageClinicFlag(null2Space(map.get("reportingVillageClinicFlag")));
                organization.setReportingOrg(null2Space(map.get("reportingOrg")));
                organization.setFoundingTime(null2Space(map.get("foundingTime")));
                organization.setRegisteredCapital(null2Space(map.get("registeredCapital")));
                organization.setLegalPerson(null2Space(map.get("legalPerson")));
                organization.setBranchOrgFlag(null2Space(map.get("branchOrgFlag")));
                organization.setLocation(addressId);
                organization.setPostalcode(null2Space(map.get("postalcode")));
                organization.setTel(null2Space(map.get("tel")));
                organization.setEmail(null2Space(map.get("email")));
                organization.setDomainName(null2Space(map.get("domainName")));
                organization.setRegistrationNumber(null2Space(map.get("registrationNumber")));
                organization.setRegistrationRatificationAgency(null2Space(map.get("registrationRatificationAgency")));
                organization.setCertificateDate(null2Space(map.get("certificateDate")));
                organization.setOperator(null2Space(map.get("operator")));
                organization.setEntryStaff(null2Space(map.get("entryStaff")));
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                organization.setCreateTime(df.format(new Date()));
                organization.setCancelTime(null2Space(map.get("cancelTime")));
                organization.setUpdateTime(df.parse(null2Space(map.get("updateTime"))));
                organization.setTermValidityStart(null2Space(map.get("termValidityStart")));
                organization.setTermValidityEnd(null2Space(map.get("termValidityEnd")));
                organization.setCreateDate(new Date());
                organization.setJkzlOrgId(null2Space(map.get("jkzlOrgId")));
                //未提供核定床位,默认0
                organization.setBerth(0);
                /****************2018年3月27日  新增和总部同步字段 结束*******************/
                Organization org = organizationRepository.save(organization);
                List<Long> orgList = organizationRepository.getOrgIdByOrgCode(organization.getOrgCode());
                Long Id = new Long(1);
                if (orgList.size() > 0) {
                    for (Long o : orgList) {
                        Id = o;
                    }
                }
                OrgDept dept = new OrgDept();
                dept.setOrgId(String.valueOf(Id));
                dept.setCode(String.valueOf(Id) + "1");
                dept.setName("未分配");
                orgDeptService.saveOrgDept(dept);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 查询机构是否已存在, 返回已存在机构code、name
     */
    public List orgExist(String[] org_codes) {
        String sql = "SELECT org_code, full_name FROM organizations WHERE org_code in(:org_codes)";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameterList("org_codes", org_codes);
        return sqlQuery.list();
    }
    public List<Organization> getHospital() {
        List<Organization> list = organizationRepository.getHospital();
        return list;
    }
    public List<Organization> getOrgListByAddressPid(Integer pid) {
        List<Organization> list = organizationRepository.getOrgListByAddressPid(pid);
        return list;
    }
    public List<Organization> getOrgListByAddressPidAndParam(Integer pid, String fullName) {
        List<Organization> list = organizationRepository.getOrgListByAddressPidAndParam(pid, fullName);
        return list;
    }
    public List<Organization> getOrgListByAddressPidAndOrgArea(Integer pid, String orgArea) {
        List<Organization> list = organizationRepository.getOrgListByAddressPidAndOrgArea(pid, orgArea);
        return list;
    }
    /**
     * 根据用户id获取医生所在的机构id
     *
     * @param userId
     * @return
     */
    public List getEhrOrgIdsByUserId(String userId) {
        String sql = "SELECT d.org_id FROM doctors d  JOIN  users u WHERE d.id = u.doctor_id AND u.id = :userId";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameter("userId", userId);
        return sqlQuery.list();
    }
    public List getJkzlOrgIdsByEhrOrgId(String[] orgIds) {
        String sql = "SELECT jkzl_org_id FROM organizations WHERE id in(:orgIds) AND  jkzl_org_id IS NOT NULL";
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        sqlQuery.setParameterList("orgIds", orgIds);
        return sqlQuery.list();
    }
    public List<String> getOrgList(List<MOrgDeptJson> orgDeptJsonList) {
        List<Long> orgId = new ArrayList<>();
        for (MOrgDeptJson org : orgDeptJsonList) {
            orgId.add(Long.parseLong(org.getOrgId()));
        }
        if (orgId.size() > 0) {
            List<String> orgList = organizationRepository.findOrgListById(orgId);
            return orgList;
        }
        return null;
    }
    /**
     * 查询所有机构的组织机构代码和全称
     */
    public List getOrgCodeAndFullName(String field) {
        String sql = "";
        if (field.equals("id")) {
            sql = "SELECT org_code,id FROM organizations";
        } else {
            sql = "SELECT org_code,full_name FROM organizations";
        }
        SQLQuery sqlQuery = currentSession().createSQLQuery(sql);
        return sqlQuery.list();
    }
    /**
     * 根据机构的地址拆分保存
     */
    public Map<String, String> getAdressByLocation(String location) {
        Map<String, String> map = new HashMap<>();
        map.put("provinceName", "");
        map.put("cityName", "");
        map.put("district", "");
        map.put("street", "");
        map.put("town", "");
        String[] temp = null;
        temp = location.split("省");
        String str = "";
        for (int i = 0; i < temp.length; i++) {
            if (temp[0].indexOf("省") > 0) {
                //不包括直辖市、自治区
                map.put("provinceName", temp[0] + "省");
            }
            str = temp[temp.length - 1];
        }
        if (StringUtils.isNotEmpty(str)) {
            temp = str.split("市");
            str = temp[temp.length - 1];
            if (temp.length > 2) {
                map.put("cityName", temp[0] + "市");
                map.put("district", temp[1] + "市");
                map.put("street", temp[2]);
            } else if (temp.length > 1) {
                map.put("cityName", temp[0] + "市");
                map.put("district", temp[1]);
                temp = str.split("县");
                if (temp.length > 1) {
                    map.put("district", temp[0] + "县");
                    map.put("street", temp[1]);
                } else {
                    temp = str.split("区");
                    if (temp.length > 1) {
                        map.put("district", temp[0] + "区");
                        map.put("street", temp[1]);
                    } else {
                        map.put("street", temp[0]);
                    }
                }
            } else {
                temp = str.split("县");
                if (temp.length > 1) {
                    map.put("district", temp[0] + "县");
                    map.put("street", temp[1]);
                } else {
                    temp = str.split("区");
                    if (temp.length > 1) {
                        map.put("district", temp[0] + "区");
                        map.put("street", temp[1]);
                    } else {
                        map.put("street", temp[0]);
                    }
                }
            }
        }
        return map;
    }
    private String null2Space(Object o) {
        return o == null ? "" : o.toString();
    }
    private Integer nullSpaceOfInteger(Object o) {
        if(o != null&&StringUtils.isNotEmpty(o.toString())){
            return  Integer.valueOf(o.toString());
        }else{
            return 0 ;
        }
    }
}

+ 110 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/AuthenticationEndPoint.java

@ -0,0 +1,110 @@
package com.yihu.jw.basic.patient.controller;
import com.yihu.jw.entity.ehr.patient.Authentication;
import com.yihu.jw.basic.patient.service.AuthenticationService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.patient.MAuthentication;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/6/22
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "authentication", description = "人口身份认证申请", tags = {"人口管理-成人口身份认证申请"})
public class AuthenticationEndPoint extends EnvelopRestEndpoint {
    @Autowired
    AuthenticationService authenticationService;
    @RequestMapping(value = ServiceApi.Patients.Authentications, method = RequestMethod.GET)
    @ApiOperation(value = "人口身份认证申请列表")
    public Collection<MAuthentication> search(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        List ls = authenticationService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, authenticationService.getCount(filters), page, size);
        return convertToModels(ls, new ArrayList<>(), MAuthentication.class, fields);
    }
    @RequestMapping(value = ServiceApi.Patients.Authentications, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增认证申请")
    public MAuthentication add(
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody Authentication model) throws Exception{
        model.setApplyDate(new Date());
        return getModel( authenticationService.save(model) );
    }
    @RequestMapping(value = ServiceApi.Patients.Authentications, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改认证申请")
    public MAuthentication update(
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody Authentication model) throws Exception{
        model.setAuditDate(new Date());
        return getModel(authenticationService.save(model));
    }
    @RequestMapping(value = ServiceApi.Patients.Authentication, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除认证申请")
    public boolean delete(
            @ApiParam(name = "id", value = "编号", defaultValue = "")
            @PathVariable(value = "id") int id) throws Exception{
        authenticationService.delete(id);
        return true;
    }
    @RequestMapping(value = ServiceApi.Patients.Authentications, method = RequestMethod.DELETE)
    @ApiOperation(value = "批量删除认证申请")
    public boolean batchDelete(
            @ApiParam(name = "ids", value = "编号集", defaultValue = "")
            @RequestParam(value = "ids") Integer[] ids) throws Exception{
        return authenticationService.delete(ids) > 0;
    }
    @RequestMapping(value = ServiceApi.Patients.Authentication, method = RequestMethod.GET)
    @ApiOperation(value = "获取认证申请信息")
    public MAuthentication getInfo(
            @ApiParam(name = "id", value = "档案关联编号", defaultValue = "")
            @PathVariable(value = "id") int id) throws Exception{
        return getModel(authenticationService.retrieve(id));
    }
    protected MAuthentication getModel(Authentication o){
        return convertToModel(o, MAuthentication.class);
    }
}

+ 168 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/CardEndPoint.java

@ -0,0 +1,168 @@
package com.yihu.jw.basic.patient.controller;
import com.yihu.jw.entity.ehr.patient.AbstractCard;
import com.yihu.jw.basic.patient.service.CardManager;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.patient.MAbstractCard;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by zqb on 2015/8/20.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "cards", description = "卡管理", tags = {"人口管理-就诊卡管理(旧)"})
public class CardEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private CardManager cardManager;
    /**
     * 根据身份证好查询相对应的卡列表
     * @param idCardNo
     * @param number
     * @param cardType
     * @param page
     * @param rows
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cards/id_card_no",method = RequestMethod.GET)
    @ApiOperation(value = "根据身份证好查询相对应的卡列表")
    public List<MAbstractCard> searchCardBinding(
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @RequestParam(value = "id_card_no") String idCardNo,
            @ApiParam(name = "number", value = "卡号", defaultValue = "")
            @RequestParam(value = "number") String number,
            @ApiParam(name = "card_type", value = "卡类别", defaultValue = "")
            @RequestParam(value = "card_type") String cardType,
            @ApiParam(name = "page", value = "当前页", defaultValue = "")
            @RequestParam(value = "page") Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows") Integer rows,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("type","bind_card");
        conditionMap.put("idCardNo",idCardNo);
        conditionMap.put("number",number);
        conditionMap.put("cardType",cardType);
        conditionMap.put("page",page);
        conditionMap.put("rows",rows);
        List<AbstractCard> cardAbstractCardList = cardManager.searchAbstractCard(conditionMap);
        Long totalCount = Long.parseLong(cardManager.searchCardInt(conditionMap).toString());
        pagedResponse(request, response, totalCount, page, rows);
        return (List<MAbstractCard>)convertToModels(cardAbstractCardList,new ArrayList<MAbstractCard>(cardAbstractCardList.size()), MAbstractCard.class, null);
//        List<MAbstractCard> mAbstractCards = (List<MAbstractCard>)convertToModels(cardAbstractCardList,new ArrayList<MAbstractCard>(cardAbstractCardList.size()), MAbstractCard.class, null);
//        return getResult(mAbstractCards,totalCount);
    }
    /**
     * 查询未绑定的卡列表
     * @param number
     * @param cardType
     * @param page
     * @param rows
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cards",method = RequestMethod.GET)
    @ApiOperation(value = "查询未绑定的卡列表")
    public List<MAbstractCard> searchCardUnBinding(
            @ApiParam(name = "number",required = true,value = "卡号", defaultValue = "")
            @RequestParam(value = "number",required = true) String number,
            @ApiParam(name = "card_type", value = "卡类别", defaultValue = "")
            @RequestParam(value = "card_type",required = false) String cardType,
            @ApiParam(name = "page", value = "当前页", defaultValue = "")
            @RequestParam(value = "page") Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows") Integer rows,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("type","not_bound_card");
        conditionMap.put("number",number);
        conditionMap.put("cardType",cardType);
        conditionMap.put("page",page);
        conditionMap.put("rows",rows);
//        List<AbstractCard> cardBrowseModelList = cardManager.searchAbstractCard(conditionMap);
//        List<MAbstractCard> mAbstractCards = (List<MAbstractCard>)convertToModels(cardBrowseModelList,new ArrayList<MAbstractCard>(cardBrowseModelList.size()), MAbstractCard.class, null);
//        Integer totalCount = cardManager.searchCardInt(conditionMap, false);
//        return getResult(mAbstractCards, totalCount);
        List<AbstractCard> cardAbstractCardList = cardManager.searchAbstractCard(conditionMap);
        Long totalCount = Long.parseLong(cardManager.searchCardInt(conditionMap).toString());
        pagedResponse(request, response, totalCount, page, rows);
        return (List<MAbstractCard>)convertToModels(cardAbstractCardList,new ArrayList<MAbstractCard>(cardAbstractCardList.size()), MAbstractCard.class, null);
    }
    /**
     * 根据卡号和卡类型查找卡
     * @param id
     * @param cardType
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cards/card_type/{id}",method = RequestMethod.GET)
    @ApiOperation(value = "根据卡号和卡类型查找卡")
    public MAbstractCard getCard(
            @ApiParam(name = "id", value = "卡号", defaultValue = "")
            @PathVariable(value = "id") String id,
            @ApiParam(name = "card_type", value = "卡类别", defaultValue = "")
            @RequestParam(value = "card_type") String cardType) throws Exception{
        AbstractCard card = cardManager.getCard(id, cardType);
        return convertToModel(card,MAbstractCard.class);
    }
    /**
     * 根据卡编号和卡类型解绑卡
     * @param id
     * @param cardType
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cards/card_type/{id}",method = RequestMethod.PUT)
    @ApiOperation(value = "根据卡号和卡类型解绑卡")
    public boolean detachCard(
            @ApiParam(name = "id", value = "卡号", defaultValue = "")
            @PathVariable(value = "id") String id,
            @ApiParam(name = "card_type", value = "卡类别", defaultValue = "")
            @RequestParam(value = "card_type") String cardType) throws Exception{
        AbstractCard card = cardManager.getCard(id, cardType);
        return cardManager.detachCard(card);
    }
    /**
     * 根据卡编号,身份证号,卡类型绑定卡
     * @param id
     * @param idCardNo
     * @param cardType
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cards/attach/{id}",method = RequestMethod.PUT)
    @ApiOperation(value = "根据卡编号(卡主键,卡的唯一标识),身份证号,卡类型绑定卡")
    public boolean attachCard(
            @ApiParam(name = "id", value = "卡号", defaultValue = "")
            @PathVariable(value = "id") String id,
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @RequestParam(value = "id_card_no") String idCardNo,
            @ApiParam(name = "card_type", value = "卡类别", defaultValue = "")
            @RequestParam(value = "card_type") String cardType) throws Exception{
        AbstractCard card = cardManager.getCard(id, cardType);
        return cardManager.attachCardWith(card, idCardNo);
    }
}

+ 112 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/FamiliesEndPoint.java

@ -0,0 +1,112 @@
package com.yihu.jw.basic.patient.controller;
import com.yihu.jw.entity.ehr.patient.Families;
import com.yihu.jw.basic.patient.service.FamiliesService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.family.MFamilies;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 *
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "families", description = "家庭关系管理接口", tags = {"人口管理-家庭关系管理接口"})
public class FamiliesEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private FamiliesService familiesService;
    @RequestMapping(value = ServiceApi.Families.Families, method = RequestMethod.GET)
    @ApiOperation(value = "获取家庭关系列表")
    public Collection<MFamilies> searchFamilies(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws ParseException {
        //过滤条件为空
        if(StringUtils.isEmpty(filters))
        {
            Page<Families> families = familiesService.getFamilies(sorts,reducePage(page),size);
            pagedResponse(request,response,families.getTotalElements(),page,size);
            return convertToModels(families.getContent(),new ArrayList<>(families.getNumber()),MFamilies.class,fields);
        }
        else
        {
            List<Families> families = familiesService.search(fields,filters,sorts,page,size);
            pagedResponse(request,response,familiesService.getCount(filters),page,size);
            return convertToModels(families,new ArrayList<>(families.size()),MFamilies.class,fields);
        }
    }
    @RequestMapping(value = ServiceApi.Families.Families, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建家庭关系")
    public MFamilies createFamily(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws Exception {
        Families families = toEntity(jsonData,Families.class);
        //families.setId(getObjectId((BizObject.Families)));
        families = familiesService.createFamilies(families);
        return convertToModel(families,MFamilies.class);
    }
    @RequestMapping(value = ServiceApi.Families.Families, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改家庭关系")
    public MFamilies updateFamily(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws Exception {
        Families families = toEntity(jsonData,Families.class);
        familiesService.updateFamilies(families);
        return convertToModel(families,MFamilies.class);
    }
    @RequestMapping(value = ServiceApi.Families.Family, method = RequestMethod.GET)
    @ApiOperation(value = "根据id获取家庭关系")
    public MFamilies getFamily(
            @ApiParam(name = "id", value = "", defaultValue = "")
            @PathVariable(value = "id") String id) {
        Families families = familiesService.getFamiliesById(id);
        return convertToModel(families,MFamilies.class);
    }
    @RequestMapping(value = ServiceApi.Families.Family, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除家庭关系")
    public boolean deleteFamily(
            @ApiParam(name = "id", value = "用户编号", defaultValue = "")
            @PathVariable(value = "id") String id) throws Exception {
        familiesService.delete(id);
        return true;
    }
}

+ 119 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/MembersEndPoint.java

@ -0,0 +1,119 @@
package com.yihu.jw.basic.patient.controller;
import com.yihu.jw.entity.ehr.patient.Members;
import com.yihu.jw.basic.patient.service.MembersService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.ehr.family.MMembers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 *
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "members", description = "家庭成员管理接口", tags = {"人口管理-家庭成员管理接口"})
public class MembersEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private MembersService membersService;
    @RequestMapping(value = ServiceApi.Families.FamiliesMembers, method = RequestMethod.GET)
    @ApiOperation(value = "获取家庭成员列表")
    public Collection<MMembers> searchMembers(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws ParseException {
        if(StringUtils.isEmpty(filters))
        {
            Page<Members> members = membersService.getMembers(sorts,reducePage(page),size);
            pagedResponse(request,response,members.getTotalElements(),page,size);
            return convertToModels(members.getContent(),new ArrayList<>(members.getNumber()),MMembers.class,fields);
        }
        else
        {
            List<Members> members = membersService.search(fields,filters,sorts,page,size);
            pagedResponse(request,response,membersService.getCount(filters),page,size);
            return convertToModels(members,new ArrayList<>(members.size()),MMembers.class,fields);
        }
    }
    @RequestMapping(value = ServiceApi.Families.FamilyMembers, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建家庭成员")
    public MMembers createMember(
            @ApiParam(name = "families_id", value = "家庭关系ID", defaultValue = "")
            @PathVariable(value = "families_id") String familiesId,
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws Exception {
        Members mb = toEntity(jsonData,Members.class);
        //mb.setId(getObjectId(BizObject.Members));
        mb.setFamilyId(familiesId);
        mb = membersService.createMembers(mb);
        return convertToModel(mb,MMembers.class);
    }
    @RequestMapping(value = ServiceApi.Families.FamilyMembers, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改家庭成员")
    public MMembers updateMember(
            @ApiParam(name = "families_id", value = "家庭关系ID", defaultValue = "")
            @PathVariable(value = "families_id") String familiesId,
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws Exception {
        Members mb = toEntity(jsonData,Members.class);
        mb.setFamilyId(familiesId);
        membersService.updateMembers(mb);
        return convertToModel(mb,MMembers.class);
    }
    @RequestMapping(value = ServiceApi.Families.FamilyMember, method = RequestMethod.GET)
    @ApiOperation(value = "根据id获取家庭成员")
    public MMembers getMember(
            @ApiParam(name = "families_id", value = "家庭关系ID", defaultValue = "")
            @PathVariable(value = "families_id") String familiesId,
            @ApiParam(name = "id_card_no", value = "", defaultValue = "")
            @PathVariable(value = "id_card_no") String id_card_no) {
        Members mb = membersService.getMembers(familiesId,id_card_no);
        return convertToModel(mb,MMembers.class);
    }
    @RequestMapping(value = ServiceApi.Families.FamilyMember, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除家庭成员")
    public boolean deleteMember(
            @ApiParam(name = "families_id", value = "家庭关系ID", defaultValue = "")
            @PathVariable(value = "families_id") String familiesId,
            @ApiParam(name = "id_card_no", value = "用户编号", defaultValue = "")
            @PathVariable(value = "id_card_no") String id_card_no) throws Exception {
        membersService.deleteMembers(familiesId,id_card_no);
        return true;
    }
}

+ 234 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/PatientArchiveEndPoint.java

@ -0,0 +1,234 @@
package com.yihu.jw.basic.patient.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.patient.service.ArchiveApplyService;
import com.yihu.jw.basic.patient.service.ArchiveRelationService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.patient.ArchiveApply;
import com.yihu.jw.entity.ehr.patient.ArchiveRelation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
/**
 * Created by hzp on 2017/04/01.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(description = "用户档案认领管理", tags = {"人口管理-用户档案认领管理"})
public class PatientArchiveEndPoint extends EnvelopRestEndpoint {
    @Autowired
    ArchiveApplyService archiveApplyService;
    @Autowired
    ArchiveRelationService archiveRelationService;
    @Autowired
    ObjectMapper objectMapper;
    @RequestMapping(value = ServiceApi.Patients.GetArchiveList, method = RequestMethod.GET)
    @ApiOperation(value = "根据查询条件查询档案列表(arApply)")
    public PageEnvelop getApplyList(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        PageEnvelop listResult = new PageEnvelop();
        List<ArchiveApply> applyList = archiveApplyService.search(fields, filters, sorts, page, size);
        if(applyList != null){
            listResult.setDetailModelList(applyList);
            listResult.setTotalCount((int)archiveApplyService.getCount(filters));
            listResult.setStatus(200);
            listResult.setCurrPage(page);
            listResult.setPageSize(size);
        }else{
            listResult.setStatus(200);
            listResult.setMessage("查询无数据");
            listResult.setTotalCount(0);
        }
        return listResult;
    }
    @RequestMapping(value = ServiceApi.Patients.GetArchiveRelationList, method = RequestMethod.GET)
    @ApiOperation(value = "根据查询条件查询档案关联列表(arRelation)")
    public PageEnvelop getArRelationList(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        PageEnvelop listResult = new PageEnvelop();
        List<ArchiveRelation> arRelationList = archiveRelationService.search(fields, filters, sorts, page, size);
        if(arRelationList != null){
            listResult.setDetailModelList(arRelationList);
            listResult.setTotalCount((int)archiveRelationService.getCount(filters));
            listResult.setStatus(200);
            listResult.setCurrPage(page);
            listResult.setPageSize(size);
        }else{
            listResult.setStatus(200);
            listResult.setMessage("查询无数据");
            listResult.setTotalCount(0);
        }
        return listResult;
    }
    @RequestMapping(value = ServiceApi.Patients.GetArchiveRelation,method = RequestMethod.GET)
    @ApiOperation(value = "档案关联详情")
    public ObjEnvelop getArRelation(
            @ApiParam(name = "applyId", value = "applyId", defaultValue = "")
            @PathVariable(value = "applyId") long applyId) throws Exception{
        ObjEnvelop obj = archiveRelationService.getArRelation(applyId);
        return success("获取档案关联详情成功!",obj);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveApplyList,method = RequestMethod.GET)
    @ApiOperation(value = "个人档案认领列表")
    public PageEnvelop archiveApplyList(
            @ApiParam(name = "userId", value = "用户ID", defaultValue = "")
            @RequestParam(value = "userId", required = false) String userId,
            @ApiParam(name = "status", value = "审核状态 -1审核不通过 0待审核 1审核通过", defaultValue = "0")
            @RequestParam(value = "status",required = false) String status,
            @ApiParam(name = "page", value = "当前页(从0开始)", defaultValue = "")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows", required = false) Integer rows) throws Exception{
        return archiveApplyService.archiveApplyList(userId, status, page, rows);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveApply,method = RequestMethod.GET)
    @ApiOperation(value = "档案认领详情")
    public ObjEnvelop getArchiveApply(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id", required = false) Long id) throws Exception{
        ArchiveApply obj = archiveApplyService.getArchiveApply(id);
        return success("获取档案认领详情成功!",obj);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveApply,method = RequestMethod.POST)
    @ApiOperation(value = "档案认领申请(临时卡)新增/修改")
    public ObjEnvelop archiveApply(
            @ApiParam(name = "data", value = "json数据", defaultValue = "")
            @RequestBody String data) throws Exception{
        ArchiveApply obj = objectMapper.readValue(data,ArchiveApply.class);
        obj.setStatus("0");
        obj.setApplyDate(new Date());
        obj = archiveApplyService.archiveApply(obj);
        return success("档案认领申请成功!",obj);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveApply,method = RequestMethod.DELETE)
    @ApiOperation(value = "档案认领删除")
    public Envelop archiveApplyDelete(
            @ApiParam(name = "id", value = "档案认领ID", defaultValue = "")
            @RequestParam(value = "id", required = false) Long id) throws Exception{
        archiveApplyService.archiveApplyDelete(id);
        return success("档案认领删除成功!");
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveApplyListManager,method = RequestMethod.GET)
    @ApiOperation(value = "管理员--档案认领列表")
    public PageEnvelop archiveApplyListManager(
            @ApiParam(name = "status", value = "审核状态 -1审核不通过 0待审核 1审核通过", defaultValue = "0")
            @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "page", value = "当前页(从0开始)", defaultValue = "")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows", required = false) Integer rows) throws Exception{
        return archiveApplyService.archiveApplyListManager(status, page, rows);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveVerifyManager,method = RequestMethod.GET)
    @ApiOperation(value = "管理员--档案认领审核操作")
    public Envelop archiveVerifyManager(
            @ApiParam(name = "id", value = "档案认领ID", defaultValue = "")
            @RequestParam(value = "id", required = false) Long id,
            @ApiParam(name = "status", value = "审核状态 2 审核不通过 0待审核 1审核通过", defaultValue = "")
            @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "auditor", value = "审核者", defaultValue = "")
            @RequestParam(value = "auditor", required = false) String auditor,
            @ApiParam(name = "auditReason", value = "审核不通过原因", defaultValue = "")
            @RequestParam(value = "auditReason",required = false) String auditReason,
            @ApiParam(name = "archiveRelationIds", value = "档案关联ID,多条用逗号分隔", defaultValue = "")
            @RequestParam(value = "archiveRelationIds", required = false) String archiveRelationIds) throws Exception{
        return archiveApplyService.archiveVerifyManager(id,status, auditor,auditReason,archiveRelationIds);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveList,method = RequestMethod.GET)
    @ApiOperation(value = "个人档案列表")
    public PageEnvelop archiveList(
            @ApiParam(name = "idCardNo", value = "身份证号码", defaultValue = "")
            @RequestParam(value = "idCardNo", required = false) String idCardNo,
            @ApiParam(name = "page", value = "当前页(从0开始)", defaultValue = "")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows", required = false) Integer rows) throws Exception{
        return archiveRelationService.archiveList(idCardNo, page, rows);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveUnbind,method = RequestMethod.GET)
    @ApiOperation(value = "管理员--通过卡号获取未认领档案")
    public PageEnvelop archiveUnbind(
            @ApiParam(name = "cardNo", value = "就诊卡号", defaultValue = "")
            @RequestParam(value = "cardNo",required = false) String cardNo,
            @ApiParam(name = "page", value = "当前页(从0开始)", defaultValue = "")
            @RequestParam(value = "page",required = false) Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows",required = false) Integer rows) throws Exception{
        return archiveRelationService.archiveUnbind(cardNo, page, rows);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveRelation,method = RequestMethod.POST)
    @ApiOperation(value = "新建档案关联")
    public ObjEnvelop archiveRelation(
            @ApiParam(name = "data", value = "json数据", defaultValue = "")
            @RequestBody String data) throws Exception{
        ArchiveRelation relation = objectMapper.readValue(data,ArchiveRelation.class);
        archiveRelationService.archiveRelation(relation);
        return success("新建档案关联成功!", relation);
    }
}

+ 344 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/PatientCardsEndPoint.java

@ -0,0 +1,344 @@
package com.yihu.jw.basic.patient.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.basic.patient.service.ArchiveRelationService;
import com.yihu.jw.basic.patient.service.MedicalCardsService;
import com.yihu.jw.basic.patient.service.UserCardsService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.patient.ArchiveRelation;
import com.yihu.jw.entity.ehr.patient.MedicalCards;
import com.yihu.jw.entity.ehr.patient.UserCards;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by hzp on 2017/04/01.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(description = "用户卡管理", tags = {"人口管理-就诊卡管理"})
public class PatientCardsEndPoint extends EnvelopRestEndpoint {
    @Autowired
    UserCardsService userCardsService;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    MedicalCardsService medicalCardsService;
    @Autowired
    ArchiveRelationService archiveRelationService;
    // ----------------------- 就诊卡基本信息管理 ------------------------------
    @RequestMapping(value = ServiceApi.Patients.GetUserCards, method = RequestMethod.GET)
    @ApiOperation(value = "获取用户卡认证列表信息")
    public Collection<UserCards> getUserCards(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<UserCards> cards = userCardsService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, userCardsService.getCount(filters), page, size);
        return convertToModels(cards, new ArrayList<>(cards.size()), UserCards.class, fields);
    }
    @RequestMapping(value = ServiceApi.Patients.CardList,method = RequestMethod.GET)
    @ApiOperation(value = "获取个人卡列表")
    public PageEnvelop cardList(
            @ApiParam(name = "userId", value = "用户ID", defaultValue = "")
            @RequestParam(value = "userId",required = false) String userId,
            @ApiParam(name = "cardType", value = "卡类别", defaultValue = "")
            @RequestParam(value = "cardType",required = false) String cardType,
            @ApiParam(name = "page", value = "当前页(从0开始)", defaultValue = "")
            @RequestParam(value = "page",required = false) Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows",required = false) Integer rows) throws Exception{
        return userCardsService.cardList(userId, cardType, page, rows);
    }
    @RequestMapping(value = ServiceApi.Patients.CardApply,method = RequestMethod.GET)
    @ApiOperation(value = "卡认证详情")
    public ObjEnvelop getCardApply(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id) throws Exception{
        UserCards card = userCardsService.getCardApply(id);
        return success("获取卡认证详情成功!",card);
    }
    @RequestMapping(value = ServiceApi.Patients.CardApply,method = RequestMethod.POST)
    @ApiOperation(value = "卡认证申请新增/修改")
    public ObjEnvelop cardApply(
            @ApiParam(name = "data", value = "json数据", defaultValue = "")
            @RequestBody String data,
            @ApiParam(name = "operator", value = "操作者", defaultValue = "")
            @RequestParam(value = "operator",required = false) String operator) throws Exception{
        UserCards card = objectMapper.readValue(data,UserCards.class);
        //新增
        if(card.getId()==null || card.getId()==0)
        {
            card.setCreater(operator);
            card.setCreateDate(new Date());
            card.setAuditStatus("0");
        }
        else{
            card.setUpdater(operator);
            card.setUpdateDate(new Date());
        }
        card = userCardsService.cardApply(card);
        return success("保存卡认证申请成功!",card);
    }
    @RequestMapping(value = ServiceApi.Patients.CardApply,method = RequestMethod.DELETE)
    @ApiOperation(value = "卡认证申请删除")
    public Envelop cardApplyDelete(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id) throws Exception{
        userCardsService.cardApplyDelete(id);
        return success("卡认证申请删除成功!");
    }
    @RequestMapping(value = ServiceApi.Patients.CardApplyListManager,method = RequestMethod.GET)
    @ApiOperation(value = "管理员--卡认证列表")
    public PageEnvelop cardApplyListManager(
            @ApiParam(name = "status", value = "卡状态 -1审核不通过 0待审核 1审核通过", defaultValue = "0")
            @RequestParam(value = "status",required = false) String status,
            @ApiParam(name = "cardType", value = "卡类别", defaultValue = "")
            @RequestParam(value = "cardType",required = false) String cardType,
            @ApiParam(name = "page", value = "当前页(从0开始)", defaultValue = "")
            @RequestParam(value = "page",required = false) Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows",required = false) Integer rows) throws Exception{
        return userCardsService.cardApplyListManager(status, cardType, page, rows);
    }
    @RequestMapping(value = ServiceApi.Patients.CardVerifyManager,method = RequestMethod.POST)
    @ApiOperation(value = "管理员--卡认证审核操作")
    public Envelop cardVerifyManager(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id,
            @ApiParam(name = "status", value = "status", defaultValue = "")
            @RequestParam(value = "status",required = false) String status,
            @ApiParam(name = "auditor", value = "审核者", defaultValue = "")
            @RequestParam(value = "auditor",required = false) String auditor,
            @ApiParam(name = "auditReason", value = "审核不通过原因", defaultValue = "")
            @RequestParam(value = "auditReason",required = false) String auditReason) throws Exception{
        return userCardsService.cardVerifyManager(id,status,auditor,auditReason);
    }
    @RequestMapping(value = ServiceApi.Patients.ArchiveRelationManager,method = RequestMethod.GET)
    @ApiOperation(value = "管理员--卡关联档案审核操作")
    Envelop archiveRelationManager(
            @ApiParam(name = "cardId", value = "cardId", defaultValue = "")
            @RequestParam(value = "cardId",required = false) Long cardId,
            @ApiParam(name = "archiveRelationIds", value = "档案关联ID,多条用逗号分隔", defaultValue = "")
            @RequestParam(value = "archiveRelationIds", required = false) String archiveRelationIds)throws Exception{
        return userCardsService.archiveRelationManager(cardId,archiveRelationIds);
    };
    @RequestMapping(value = ServiceApi.Patients.CardBindManager,method = RequestMethod.POST)
    @ApiOperation(value = "管理员--后台绑卡操作")
    public ObjEnvelop cardBindManager(
            @ApiParam(name = "data", value = "json数据", defaultValue = "")
            @RequestBody String data,
            @ApiParam(name = "operator", value = "操作者", defaultValue = "")
            @RequestParam(value = "operator",required = false) String operator) throws Exception{
        UserCards card = objectMapper.readValue(data,UserCards.class);
        card.setStatus("1");
        card.setCreater(operator);
        card.setCreateDate(new Date());
        card.setAuditor(operator);
        card.setAuditDate(new Date());
        card = userCardsService.cardBindManager(card);
        return success("后台绑卡成功!",card);
    }
    // ----------------------- 就诊卡基本信息管理 ------------------------------
    @RequestMapping(value = ServiceApi.Patients.GetMCards, method = RequestMethod.GET)
    @ApiOperation(value = "获取就诊卡列表信息")
    public Collection<MedicalCards> getMCards(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<MedicalCards> cards = medicalCardsService.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, medicalCardsService.getCount(filters), page, size);
        return convertToModels(cards, new ArrayList<>(cards.size()), MedicalCards.class, fields);
    }
    @RequestMapping(value = ServiceApi.Patients.GetMCard,method = RequestMethod.GET)
    @ApiOperation(value = "就诊卡详情")
    public ObjEnvelop getMCard(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id) throws Exception{
        MedicalCards card = medicalCardsService.getMCard(id);
        return success("获取卡认证详情成功!",card);
    }
    @RequestMapping(value = ServiceApi.Patients.MCardSave,method = RequestMethod.POST)
    @ApiOperation(value = "就诊卡新增/修改")
    public ObjEnvelop mCardSave(
            @ApiParam(name = "data", value = "json数据", defaultValue = "")
            @RequestBody String data,
            @ApiParam(name = "operator", value = "操作者", defaultValue = "")
            @RequestParam(value = "operator",required = false) String operator) throws Exception{
        MedicalCards card = objectMapper.readValue(data,MedicalCards.class);
        if(card.getId()==null || card.getId()==0 )
        {
            card.setCreater(operator);
            card.setCreateDate(new Date());
            //card.setStatus("0");
        }else{
            card.setUpdater(operator);
            card.setUpdateDate(new Date());
        }
        card = medicalCardsService.save(card);
        return success("保存就诊卡成功!",card);
    }
    @RequestMapping(value = ServiceApi.Patients.MCardDel,method = RequestMethod.DELETE)
    @ApiOperation(value = "就诊卡删除")
    public Envelop mCardDelete(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id) throws Exception{
        medicalCardsService.delete(id);
        return success("就诊卡删除成功!");
    }
    @RequestMapping(value = ServiceApi.Patients.MCardCheckCardNo, method = RequestMethod.PUT)
    @ApiOperation(value = "校验卡是否唯一")
    int getCountByCardNo(
            @ApiParam(name = "cardNo", value = "卡号")
            @RequestParam(value = "cardNo", required = true) String cardNo){
        try {
            String filters = "cardNo="+cardNo;
            return (int)medicalCardsService.getCount(filters);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 1;
    };
    @RequestMapping(value = ServiceApi.Patients.MCardGetMutiCardNo, method = RequestMethod.PUT)
    @ApiOperation(value = "查询导入时重复卡列表")
    List<MedicalCards> getBycardNoStr(
            @ApiParam(name = "cardNoStr", value = "卡号字符串")
            @RequestParam(value = "cardNoStr", required = true) String cardNoStr
    ){
            return medicalCardsService.getBycardNoStr(cardNoStr);
    };
    @RequestMapping(value = ServiceApi.Patients.MCarddataBatch, method = RequestMethod.POST)
    @ApiOperation("批量创建就诊卡")
    boolean createPatientCardsPatch(
            @RequestBody String medicalCars,
            @ApiParam(name = "operator", value = "操作者", defaultValue = "")
    @RequestParam(value = "operator",required = false) String operator) throws Exception{
        List<Map<String, String>> models = new ArrayList<>();
        models = objectMapper.readValue(medicalCars, new TypeReference<List>() {});
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for(int i=1; i<=models.size(); i++) {
            MedicalCards cards = new MedicalCards();
            map.clear();
            map = models.get(i - 1);
            cards.setCardType(map.get("cardType"));
            cards.setCardNo(map.get("cardNo"));
            cards.setReleaseOrg(map.get("releaseOrg"));
            if(!StringUtils.isEmpty(map.get("releaseDate"))){
                cards.setReleaseDate(sdf.parse(map.get("releaseDate")));
            }
            if(!StringUtils.isEmpty(map.get("validityDateBegin"))){
                cards.setValidityDateBegin(sdf.parse(map.get("validityDateBegin")));
            }
            if(!StringUtils.isEmpty(map.get("validityDateEnd"))){
                cards.setValidityDateEnd(sdf.parse(map.get("validityDateEnd")));
            }
            cards.setDescription(map.get("description"));
            cards.setStatus(map.get("status"));
            cards.setCreateDate(new Date());
            cards.setCreater(operator);
            medicalCardsService.save(cards);
        }
        return true;
    };
    @RequestMapping(value = ServiceApi.Patients.FindArchiveRelation,method = RequestMethod.POST)
    @ApiOperation(value = "档案关联详情")
    ObjEnvelop findArchiveRelation(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id) throws Exception{
        ArchiveRelation archiveRelation = archiveRelationService.getOne(id);
        return success("获取档案关联详情成功!",archiveRelation);
    }
    @RequestMapping(value = ServiceApi.Patients.UpdateArchiveRelation,method = RequestMethod.POST)
    @ApiOperation(value = "档案关联新增/修改")
    ObjEnvelop updateArchiveRelation(
            @ApiParam(name = "data", value = "", defaultValue = "")
            @RequestBody String data)throws Exception{
        ArchiveRelation archiveRelation= objectMapper.readValue(data,ArchiveRelation.class);
        archiveRelation = archiveRelationService.save(archiveRelation);
        return success("保存档案关联成功!",archiveRelation);
    }
    @RequestMapping(value =  ServiceApi.Patients.DelArchiveRelation, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除档案关联", notes = "根据档案关联id")
    Envelop delArchiveRelation(
            @ApiParam(name = "id", value = "id", defaultValue = "")
            @RequestParam(value = "id",required = false) Long id) throws Exception{
        archiveRelationService.delete(id);
        return success("档案关联删除成功!");
    }
}

+ 538 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/controller/PatientEndPoint.java

@ -0,0 +1,538 @@
package com.yihu.jw.basic.patient.controller;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.jw.entity.ehr.patient.DemographicId;
import com.yihu.jw.basic.patient.service.DemographicService;
import com.yihu.jw.entity.ehr.user.Doctors;
import com.yihu.jw.entity.ehr.user.RoleUser;
import com.yihu.jw.entity.ehr.user.User;
import com.yihu.jw.basic.user.service.DoctorService;
import com.yihu.jw.basic.user.service.RoleUserService;
import com.yihu.jw.basic.user.service.UserService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.jw.phonics.PinyinUtil;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.entity.ehr.patient.DemographicInfo;
import com.yihu.jw.exception.ApiException;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.restmodel.ehr.patient.MDemographicInfo;
import com.yihu.jw.restmodel.ehr.patient.MPatientInfo;
import com.yihu.jw.util.date.DateTimeUtil;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.util.log.LogService;
import com.yihu.utils.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.csource.common.MyException;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
/**
 * Created by zqb on 2015/8/14.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "patient", description = "人口管理", tags = {"人口管理"})
public class PatientEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private DemographicService demographicService;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private RoleUserService roleUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private DoctorService doctorService;
    /**
     * 根据条件查询人口信息
     * @param search
     * @param province
     * @param city
     * @param district
     * @param page
     * @param rows
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations",method = RequestMethod.GET)
    @ApiOperation(value = "根据条件查询人")
    public List<MDemographicInfo> searchPatient(
            @ApiParam(name = "search", value = "搜索内容", defaultValue = "")
            @RequestParam(value = "search",required = false) String search,
            @ApiParam(name = "home_province", value = "省", defaultValue = "")
            @RequestParam(value = "home_province",required = false) String province,
            @ApiParam(name = "home_city", value = "市", defaultValue = "")
            @RequestParam(value = "home_city",required = false) String city,
            @ApiParam(name = "home_district", value = "县", defaultValue = "")
            @RequestParam(value = "home_district",required = false) String district,
            @ApiParam(name = "page", value = "当前页", defaultValue = "")
            @RequestParam(value = "page") Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows") Integer rows,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("search", search);
        conditionMap.put("page", page);
        conditionMap.put("pageSize", rows);
        conditionMap.put("province", province);
        conditionMap.put("city", city);
        conditionMap.put("district", district);
//        List<DemographicInfo> demographicInfos = demographicService.searchPatient(conditionMap);
//        Integer totalCount = demographicService.searchPatientTotalCount(conditionMap);
//
//        List<MDemographicInfo> mDemographicInfos = (List<MDemographicInfo>)convertToModels(demographicInfos,new ArrayList<MDemographicInfo>(demographicInfos.size()), MDemographicInfo.class, null);
//        return getResult(mDemographicInfos,totalCount);
        List<DemographicInfo> demographicInfos = demographicService.searchPatient(conditionMap);
        Long totalCount =Long.parseLong(demographicService.searchPatientTotalCount(conditionMap).toString());
        pagedResponse(request, response, totalCount, page, rows);
        return (List<MDemographicInfo>)convertToModels(demographicInfos,new ArrayList<MDemographicInfo>(demographicInfos.size()), MDemographicInfo.class, null);
    }
    /**
     * 根据身份证号删除人
     * @param idCardNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations/{id_card_no}",method = RequestMethod.DELETE)
    @ApiOperation(value = "根据身份证号删除人")
    public boolean deletePatient(
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @PathVariable(value = "id_card_no") String idCardNo) throws Exception{
        demographicService.delete(idCardNo);
        return true;
    }
    /**
     * 根据身份证号查找人
     * @param idCardNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations/{id_card_no}",method = RequestMethod.GET)
    @ApiOperation(value = "根据身份证号查找人")
    public MDemographicInfo getPatient(
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @PathVariable(value = "id_card_no") String idCardNo) throws Exception{
        DemographicInfo demographicInfo = demographicService.getDemographicInfo(idCardNo);
        MDemographicInfo demographicModel = convertToModel(demographicInfo,MDemographicInfo.class);
        return demographicModel;
    }
    @RequestMapping(value = "/populations/{id_card_no}/register",method = RequestMethod.GET)
    @ApiOperation(value = "根据身份证号判断病人是否注册")
    public boolean isRegistered(
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @PathVariable(value = "id_card_no") String idCardNo) throws Exception{
        MDemographicInfo demographicInfo = getPatient(idCardNo);
        return  demographicInfo!=null;
    }
    /**
     * 根据前端传回来的json新增一个人口信息
     * @param jsonData
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations",method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据前端传回来的json创建一个人口信息")
    public MDemographicInfo createPatient(
            @ApiParam(name = "json_data", value = "身份证号", defaultValue = "")
            @RequestBody String jsonData) throws Exception{
        DemographicInfo demographicInfo = toEntity(jsonData, DemographicInfo.class);
        String pwd = "12345678";
        if(!StringUtils.isEmpty(demographicInfo.getIdCardNo())&&demographicInfo.getIdCardNo().length()>9){
            pwd=demographicInfo.getIdCardNo().substring(demographicInfo.getIdCardNo().length()-8);
            demographicInfo.setPassword(DigestUtils.md5Hex(pwd));
        }else{
            demographicInfo.setPassword(DigestUtils.md5Hex(pwd));
        }
        demographicInfo.setRegisterTime(new Date());
        demographicService.savePatient(demographicInfo);
        return convertToModel(demographicInfo,MDemographicInfo.class);
    }
    /**
     * 根据前端传回来的json修改人口信息
     * @param patientModelJsonData
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations",method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "根据前端传回来的json修改人口信息")
    public MDemographicInfo updatePatient(
            @ApiParam(name = "patient_model_json_data", value = "身份证号", defaultValue = "")
            @RequestBody String patientModelJsonData) throws Exception{
        DemographicInfo demographicInfo = toEntity(patientModelJsonData, DemographicInfo.class);
        DemographicInfo old = demographicService.getDemographicInfo(demographicInfo.getIdCardNo());
        if (old == null) {
            throw new ApiException("该对象没找到",ErrorCode.NOT_FOUND.value());
        }
        BeanUtils.copyProperties(demographicInfo, old, "registerTime");
        demographicService.savePatient(old);
        //同时修改用户信息
        String telNo = demographicInfo.getTelephoneNo();
        JSONObject object = new JSONObject(telNo);
        String tel = object.getString("联系电话");
        User user = userService.getUserByIdCardNo(demographicInfo.getIdCardNo());
        if (!StringUtils.isEmpty(user)) {
            user.setRealName(demographicInfo.getName());
            user.setGender(demographicInfo.getGender());
            user.setTelephone(tel.substring(1,tel.length() - 1));
            user.setMartialStatus(demographicInfo.getMartialStatus());
            user.setBirthday(DateUtil.toString(demographicInfo.getBirthday()));
            userService.save(user);
        }
        Doctors doctors = doctorService.getByIdCardNo(demographicInfo.getIdCardNo());
        if (!StringUtils.isEmpty(doctors)) {
            doctors.setName(demographicInfo.getName());
            doctors.setPyCode(PinyinUtil.getPinYinHeadChar(demographicInfo.getName(), false));
            doctors.setSex(demographicInfo.getGender());
            doctors.setPhone(tel.substring(1,tel.length() - 1));
            doctorService.save(doctors);
        }
        return convertToModel(demographicInfo,MDemographicInfo.class);
    }
    /**
     * 初始化密码
     * @param idCardNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations/password/{id_card_no}",method = RequestMethod.PUT)
    @ApiOperation(value = "初始化密码",notes = "用户忘记密码时重置密码,初始密码为12345678")
    public boolean resetPass(
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @PathVariable(value = "id_card_no") String idCardNo) throws Exception{
        demographicService.resetPass(idCardNo);
        return true;
    }
    /**
     * 人口信息头像图片上传
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/populations/picture",method = RequestMethod.POST)
    @ApiOperation(value = "上传头像,把图片转成流的方式发送")
    public String uploadPicture(
            @ApiParam(name = "jsonData", value = "头像转化后的输入流")
            @RequestBody String jsonData ) throws IOException {
        if(jsonData == null){
            return null;
        }
        String date = URLDecoder.decode(jsonData,"UTF-8");
        String[] fileStreams = date.split(",");
        String is = URLDecoder.decode(fileStreams[0],"UTF-8").replace(" ","+");
        byte[] in = Base64.getDecoder().decode(is);
        String pictureName = fileStreams[1].substring(0,fileStreams[1].length()-1);
        String fileExtension = pictureName.substring(pictureName.lastIndexOf(".") + 1).toLowerCase();
        String description = null;
        if ((pictureName != null) && (pictureName.length() > 0)) {
            int dot = pictureName.lastIndexOf('.');
            if ((dot > -1) && (dot < (pictureName.length()))) {
                description = pictureName.substring(0, dot);
            }
        }
        String path = null;
        try {
//            FileOutputStream fileOutputStream = new FileOutputStream(new File("F:\\m\\"+pictureName));
//            fileOutputStream.write(in);
//            fileOutputStream.flush();
//            fileOutputStream.close();
            InputStream inputStream = new ByteArrayInputStream(in);
            ObjectNode objectNode = fastDFSUtil.upload(inputStream, fileExtension, description);
            String groupName = objectNode.get("groupName").toString();
            String remoteFileName = objectNode.get("remoteFileName").toString();
//            path = "{\"groupName\":" + groupName + ",\"remoteFileName\":" + remoteFileName + "}";
            path = groupName.substring(1,groupName.length()-1) + ":" + remoteFileName.substring(1,remoteFileName.length()-1);
        } catch (Exception e) {
            LogService.getLogger(DemographicInfo.class).error("人口头像图片上传失败;错误代码:"+e);
        }
        //返回文件路径
        return path;
    }
    /**
     * 人口信息头像图片下载
     * @return
     * @throws IOException
     * @throws MyException
     */
    @RequestMapping(value = "/populations/picture",method = RequestMethod.GET)
    @ApiOperation(value = "下载头像")
    public String downloadPicture(
            @ApiParam(name = "group_name", value = "分组", defaultValue = "")
            @RequestParam(value = "group_name") String groupName,
            @ApiParam(name = "remote_file_name", value = "服务器头像名称", defaultValue = "")
            @RequestParam(value = "remote_file_name") String remoteFileName) throws Exception {
        String imageStream = null;
        try {
            byte[] bytes = fastDFSUtil.download(groupName,remoteFileName);
            String fileStream = Base64.getEncoder().encodeToString(bytes);
            imageStream = URLEncoder.encode(fileStream,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            LogService.getLogger(DemographicInfo.class).error("人口头像图片下载失败;错误代码:" + e);
        }
        return imageStream;
    }
    @RequestMapping(value = "/populations/is_exist/{id_card_no}",method = RequestMethod.GET)
    @ApiOperation(value = "判断身份证是否存在")
    public boolean isExistIdCardNo(
            @ApiParam(name = "id_card_no", value = "身份证号", defaultValue = "")
            @PathVariable(value = "id_card_no") String idCardNo) throws Exception {
        return demographicService.getDemographicInfo(idCardNo) != null;
    }
    @RequestMapping(value = "/populations/telphoneNumberIs_exist/{telphone_number}",method = RequestMethod.GET)
    @ApiOperation(value = "判断电话号码是否存在")
    public boolean isExisttelphoneNumber(
            @ApiParam(name = "telphone_number", value = "电话号码", defaultValue = "")
            @PathVariable(value = "telphone_number") String telphoneNumber) throws Exception {
        return demographicService.getDemographicInfoBytelephoneNo(telphoneNumber) != null;
    }
    /**
     * 用户信息 查询(添加查询条件修改)
     * @param search
     * @param province
     * @param city
     * @param district
     * @param page
     * @param rows
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populationsByParams",method = RequestMethod.GET)
    @ApiOperation(value = "用户信息 查询(添加查询条件修改)")
    public List<MDemographicInfo> searchPatientByParams(
            @ApiParam(name = "search", value = "搜索内容", defaultValue = "")
            @RequestParam(value = "search",required = false) String search,
            @ApiParam(name = "gender", value = "性别", defaultValue = "")
            @RequestParam(value = "gender") String gender,
            @ApiParam(name = "home_province", value = "省", defaultValue = "")
            @RequestParam(value = "home_province",required = false) String province,
            @ApiParam(name = "home_city", value = "市", defaultValue = "")
            @RequestParam(value = "home_city",required = false) String city,
            @ApiParam(name = "home_district", value = "县", defaultValue = "")
            @RequestParam(value = "home_district",required = false) String district,
            @ApiParam(name = "searchRegisterTimeStart", value = "注册开始时间", defaultValue = "")
            @RequestParam(value = "searchRegisterTimeStart") String searchRegisterTimeStart,
            @ApiParam(name = "searchRegisterTimeEnd", value = "注册结束时间", defaultValue = "")
            @RequestParam(value = "searchRegisterTimeEnd") String searchRegisterTimeEnd,
            @ApiParam(name = "page", value = "当前页", defaultValue = "")
            @RequestParam(value = "page") Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows") Integer rows,
            HttpServletRequest request,HttpServletResponse response) throws Exception{
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("search", search);
        conditionMap.put("page", page);
        conditionMap.put("pageSize", rows);
        conditionMap.put("province", province);
        conditionMap.put("city", city);
        conditionMap.put("district", district);
        conditionMap.put("gender", gender);
        Date startDate = DateTimeUtil.simpleDateTimeParse(searchRegisterTimeStart);
        Date endDate = DateTimeUtil.simpleDateTimeParse(searchRegisterTimeEnd);
        if(null!=endDate){
            Calendar calendar   =   new GregorianCalendar();
            calendar.setTime(endDate);
            calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
            endDate=calendar.getTime();   //日期往后推一天
        }
        conditionMap.put("startDate", startDate);
        conditionMap.put("endDate", endDate);
        List<DemographicInfo> demographicInfos = demographicService.searchPatientByParams(conditionMap);
        Long totalCount =Long.parseLong(demographicService.searchPatientByParamsTotalCount(conditionMap).toString());
        pagedResponse(request, response, totalCount, page, rows);
        return (List<MDemographicInfo>)convertToModels(demographicInfos,new ArrayList<MDemographicInfo>(demographicInfos.size()), MDemographicInfo.class, null);
    }
    @RequestMapping(value = "/populationsByParams2",method = RequestMethod.GET)
    @ApiOperation(value = "用户信息 查询(添加查询条件修改)")
    public List<MDemographicInfo> searchPatientByParams2(
            @ApiParam(name = "search", value = "搜索内容", defaultValue = "")
            @RequestParam(value = "search",required = false) String search,
            @ApiParam(name = "gender", value = "性别", defaultValue = "")
            @RequestParam(value = "gender") String gender,
            @ApiParam(name = "home_province", value = "省", defaultValue = "")
            @RequestParam(value = "home_province",required = false) String province,
            @ApiParam(name = "home_city", value = "市", defaultValue = "")
            @RequestParam(value = "home_city",required = false) String city,
            @ApiParam(name = "home_district", value = "县", defaultValue = "")
            @RequestParam(value = "home_district",required = false) String district,
            @ApiParam(name = "searchRegisterTimeStart", value = "注册开始时间", defaultValue = "")
            @RequestParam(value = "searchRegisterTimeStart") String searchRegisterTimeStart,
            @ApiParam(name = "searchRegisterTimeEnd", value = "注册结束时间", defaultValue = "")
            @RequestParam(value = "searchRegisterTimeEnd") String searchRegisterTimeEnd,
            @ApiParam(name = "districtList", value = "区域", defaultValue = "")
            @RequestParam(value = "districtList") String districtList,
            @ApiParam(name = "page", value = "当前页", defaultValue = "")
            @RequestParam(value = "page") Integer page,
            @ApiParam(name = "rows", value = "行数", defaultValue = "")
            @RequestParam(value = "rows") Integer rows,
            HttpServletRequest request,HttpServletResponse response) throws Exception{
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("search", search);
        conditionMap.put("page", page);
        conditionMap.put("pageSize", rows);
        conditionMap.put("province", province);
        conditionMap.put("city", city);
        conditionMap.put("district", district);
        conditionMap.put("gender", gender);
        conditionMap.put("districtList", districtList);
        Date startDate = DateTimeUtil.simpleDateTimeParse(searchRegisterTimeStart);
        Date endDate = DateTimeUtil.simpleDateTimeParse(searchRegisterTimeEnd);
        if(null!=endDate){
            Calendar calendar   =   new GregorianCalendar();
            calendar.setTime(endDate);
            calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
            endDate=calendar.getTime();   //日期往后推一天
        }
        conditionMap.put("startDate", startDate);
        conditionMap.put("endDate", endDate);
        //        List<DemographicInfo> demographicInfos = demographicService.searchPatient(conditionMap);
        //        Integer totalCount = demographicService.searchPatientTotalCount(conditionMap);
        //        List<MDemographicInfo> mDemographicInfos = (List<MDemographicInfo>)convertToModels(demographicInfos,new ArrayList<MDemographicInfo>(demographicInfos.size()), MDemographicInfo.class, null);
        //        return getResult(mDemographicInfos,totalCount);
        List<DemographicInfo> demographicInfos = demographicService.searchPatientByParams2(conditionMap);
        Long totalCount =Long.parseLong(demographicService.searchPatientByParamsTotalCount2(conditionMap).toString());
        pagedResponse(request, response, totalCount, page, rows);
        return (List<MDemographicInfo>)convertToModels(demographicInfos,new ArrayList<MDemographicInfo>(demographicInfos.size()), MDemographicInfo.class, null);
    }
    /**
     * 居民信息-角色授权-角色组保存
     * @return
     */
    @RequestMapping(value = "/appUserRolesSave", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "居民信息-角色授权-角色组保存")
    public String saveRoleUser(
            @ApiParam(name = "userId", value = "机构", defaultValue = "")
            @RequestParam(value = "userId", required = false) String userId,
            @ApiParam(name = "jsonData", value = "json数据", defaultValue = "")
            @RequestBody String jsonData) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
//        String[] jsonDatalist=jsonData.split("jsonData=");
        //将json串转换成对象,放进list里面
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, RoleUser.class);
        List<RoleUser> models = objectMapper.readValue(jsonData,javaType);
        return roleUserService.saveRoleUser(models,userId);
    }
    //--------------------------------- zuul --------------------------
    /**
     *
     * @param search
     * @param gender
     * @param homeAddress
     * @param searchRegisterTimeStart
     * @param searchRegisterTimeEnd
     * @param page
     * @param rows
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/populations/byParams", method = RequestMethod.GET)
    @ApiOperation(value = "用户信息 查询(添加查询条件修改)")
    public Envelop searchPatientByParams(
            @ApiParam(name = "search", value = "搜索内容")
            @RequestParam(value = "search", required = false) String search,
            @ApiParam(name = "gender", value = "性别")
            @RequestParam(value = "gender", required = false) String gender,
            @ApiParam(name = "homeAddress", value = "省")
            @RequestParam(value = "homeAddress",required = false) String homeAddress,
            @ApiParam(name = "searchRegisterTimeStart", value = "注册开始时间")
            @RequestParam(value = "searchRegisterTimeStart", required = false) String searchRegisterTimeStart,
            @ApiParam(name = "searchRegisterTimeEnd", value = "注册结束时间")
            @RequestParam(value = "searchRegisterTimeEnd", required = false) String searchRegisterTimeEnd,
            @ApiParam(name = "page", value = "当前页", required = true)
            @RequestParam(value = "page") Integer page,
            @ApiParam(name = "rows", value = "行数", required = true)
            @RequestParam(value = "rows") Integer rows) throws Exception{
        List<DemographicInfo> demographicInfoList = demographicService.search(search, gender, homeAddress, searchRegisterTimeStart, searchRegisterTimeEnd, page, rows);
        List<MPatientInfo> mPatientInfoList = new ArrayList<>(demographicInfoList.size());
        demographicInfoList.forEach(item -> {
            MPatientInfo mPatientInfo = new MPatientInfo();
            mPatientInfo.setIdCardNo(item.getIdCardNo());
            mPatientInfo.setName(item.getName());
            mPatientInfo.setGender(item.getGender());
            if (item.getTelephoneNo() != null) {
                try {
                    //联系电话
                    String tag = "联系电话";
                    Map<String, String> telephoneNo = objectMapper.readValue(item.getTelephoneNo(), Map.class);
                    mPatientInfo.setTelephoneNo(telephoneNo.get(tag));
                } catch (Exception e) {
                    mPatientInfo.setTelephoneNo(item.getTelephoneNo());
                }
            } else {
                mPatientInfo.setTelephoneNo("");
            }
            mPatientInfo.setHomeAddress(item.getHomeAddress());
            mPatientInfo.setRegisterTime(item.getRegisterTime());
            User user = userService.getUserByIdCardNo(item.getIdCardNo());
            if (user != null) {
                mPatientInfo.setUserId(user.getId());
            }
            mPatientInfoList.add(mPatientInfo);
        });
        Integer count = demographicService.count(search, gender, homeAddress, searchRegisterTimeStart, searchRegisterTimeEnd);
        Envelop envelop = getPageResult(mPatientInfoList, count, page, rows);
        return envelop;
    }
}

+ 13 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XAbstractPhysicalCardRepository.java

@ -0,0 +1,13 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.PhysicalCard;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface XAbstractPhysicalCardRepository extends JpaRepository<PhysicalCard, String> {
}

+ 20 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XAbstractVirtualCardRepository.java

@ -0,0 +1,20 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.VirtualCard;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface XAbstractVirtualCardRepository extends JpaRepository<VirtualCard, String> {
    @Query("select abstractVirtualCard from VirtualCard abstractVirtualCard where 1=1")
    public List<VirtualCard> getOrgByCode(@Param("orgCode") String orgCode);
}

+ 20 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XArchiveApplyDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.ArchiveApply;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Created by hzp on 2017/4/5.
 */
public interface XArchiveApplyDao extends JpaRepository<ArchiveApply,Long> {
    Page<ArchiveApply> findByUserId(String userId, Pageable pageable);
    Page<ArchiveApply> findByUserIdAndStatus(String userId, String status, Pageable pageable);
    Page<ArchiveApply> findByStatus(String status, Pageable pageable);
}

+ 57 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XArchiveRelationDao.java

@ -0,0 +1,57 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.ArchiveRelation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.Date;
import java.util.List;
/**
 * Created by hzp on 2017/4/5.
 */
public interface XArchiveRelationDao extends JpaRepository<ArchiveRelation,Long> {
    Page<ArchiveRelation> findByIdCardNo(String idCardNo, Pageable pageable);
    Page<ArchiveRelation> findByCardNo(String cardNo, Pageable pageable);
    @Query("select a from ArchiveRelation a where a.status=0 and a.cardNo=:cardNo and a.name = :name")
    List<ArchiveRelation> findByCardNoAndName(@Param("cardNo") String cardNo, @Param("name") String name);
    ArchiveRelation findByApplyId(long applyId);
    ArchiveRelation findByProfileId(String profileId);
    @Query("select count(ar.id) from ArchiveRelation ar where ar.identifyFlag = 1")
    int findIdentifyCount();
    @Query("select count(ar.id) from ArchiveRelation ar where ar.identifyFlag = 0")
    int findUnIdentifyCount();
    @Query("select count(ar.id) from ArchiveRelation ar")
    int findArchiveCount();
    @Query("select count(ar.id) from ArchiveRelation ar where ar.eventType = 0")
    int findOutPatientCount();
    @Query("select count(ar.id) from ArchiveRelation ar where ar.eventType = 1")
    int findInPatientCount();
    @Query("select count(ar.id) from ArchiveRelation ar where ar.eventType = 2")
    int findPhysicalCount();
    @Query("select count(ar.id) from ArchiveRelation ar where ar.eventType = 0 or ar.eventType = 1")
    int findInAndOutPatientCount();
    //今日入库
    @Query("select count(ar.id) from ArchiveRelation ar where ar.createDate >= :curDate")
    int findTodayInWarehouseCount(@Param("curDate") Date curDate);
    //累计就诊人次--每日新增
    @Query("select count(ar.id) from ArchiveRelation ar where ar.identifyFlag = 1 and ar.eventDate >= :curDate")
    int FindDailyAdd(@Param("curDate") Date curDate);
}

+ 13 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XAuthenticationRepository.java

@ -0,0 +1,13 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.Authentication;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/6/22
 */
public interface XAuthenticationRepository extends JpaRepository<Authentication, Integer> {
}

+ 25 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XDemographicInfoRepository.java

@ -0,0 +1,25 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.DemographicInfo;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface XDemographicInfoRepository extends JpaRepository<DemographicInfo, String> {
    @Query("select demographicInfo from DemographicInfo demographicInfo where 1=1")
    public List<DemographicInfo> getOrgByCode(@Param("orgCode") String orgCode);
    @Query("select demographicInfo from DemographicInfo demographicInfo where demographicInfo.telephoneNo=:telephoneNo")
    public List<DemographicInfo> getDemographicInfoByTelephoneNo(@Param("telephoneNo") String telephoneNo);
    @Query("select demographicInfo from DemographicInfo demographicInfo where demographicInfo.idCardNo = :idCardNo")
    List<DemographicInfo> getDemographicInfoByIdCardNo(@Param("idCardNo") String idCardNo);
}

+ 13 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XFamiliesRepository.java

@ -0,0 +1,13 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.Families;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface XFamiliesRepository extends JpaRepository<Families, String> {
}

+ 7 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XJsonArchiveDao.java

@ -0,0 +1,7 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.report.JsonArchives;
import org.springframework.data.jpa.repository.JpaRepository;
public interface XJsonArchiveDao extends JpaRepository<JsonArchives, Long> {
}

+ 19 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XMedicalCardsDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.MedicalCards;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * Created by hzp on 2017/4/5.
 */
public interface XMedicalCardsDao extends JpaRepository<MedicalCards,Long> {
    @Query("select mc from MedicalCards mc where mc.cardNo in (:cardNoStr)")
    List<MedicalCards> getBycardNoStr(@Param("cardNoStr") String[] cardNoStr);
}

+ 23 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XMembersRepository.java

@ -0,0 +1,23 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.Members;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.16 15:10
 */
public interface XMembersRepository extends JpaRepository<Members, String> {
    void deleteByFamilyId(String familyId);
    void deleteByFamilyIdAndIdCardNo(String familyId, String idCardNo);
    List<Members> findByFamilyId(String familyId);
    Members findByFamilyIdAndIdCardNo(String familyId, String idCardNo);
}

+ 22 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/dao/XUserCardsDao.java

@ -0,0 +1,22 @@
package com.yihu.jw.basic.patient.dao;
import com.yihu.jw.entity.ehr.patient.UserCards;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
/**
 * Created by hzp on 2017/4/5.
 */
public interface XUserCardsDao extends JpaRepository<UserCards,Long> {
    Page<UserCards> findByUserId(String userId, Pageable pageable);
    Page<UserCards> findByUserIdAndCardType(String userId, String cardType, Pageable pageable);
    Page<UserCards> findByStatusAndCardType(String status, String cardType, Pageable pageable);
    Page<UserCards> findByStatus(String status, Pageable pageable);
    Page<UserCards> findByCardType(String cardType, Pageable pageable);
}

+ 49 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/feign/ConventionalDictClient.java

@ -0,0 +1,49 @@
//package com.yihu.jw.basic.patient.feign;
//
//import com.yihu.ehr.constants.ApiVersion;
//import com.yihu.ehr.constants.MicroServices;
//import com.yihu.jw.restmodel.ehr.dict.MConventionalDict;
//import org.springframework.cloud.netflix.feign.FeignClient;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import springfox.documentation.annotations.ApiIgnore;
//
//import java.util.Collection;
//import java.util.List;
//
//import static org.springframework.web.bind.annotation.RequestMethod.GET;
//
///**
// * Created by Administrator on 2016/1/4.
// */
////@FeignClient(name = MicroServices.Dictionary)
////@ApiIgnore
//@Deprecated
//public interface ConventionalDictClient {
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/martial_status", method = GET )
//    MConventionalDict getMartialStatus(@RequestParam(value = "code") String code);
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/gender", method = GET )
//    MConventionalDict getGender(@RequestParam(value = "code") String code);
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/user_type", method = GET )
//    MConventionalDict getUserType(@RequestParam(value = "code") String code);
//
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/residence_type", method = GET )
//    MConventionalDict getResidenceType(@RequestParam(value = "code") String code);
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/card_status", method = GET )
//    MConventionalDict getCardStatus(@RequestParam(value = "code") String code);
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/card_type", method = GET )
//    MConventionalDict getCardType(@RequestParam(value = "code") String code);
//
//
//    @RequestMapping(value = ApiVersion.Version1_0+"/dictionaries/std_source_types", method = GET )
//    Collection<MConventionalDict> getStdSourceTypeList(@RequestParam(value = "codes") List<String> codes);
//
//
//}
//

+ 28 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/feign/PatientArchiveClient.java

@ -0,0 +1,28 @@
//package com.yihu.jw.basic.patient.feign;
//
//import com.yihu.ehr.constants.ApiVersion;
//import com.yihu.ehr.constants.MicroServices;
//import com.yihu.ehr.constants.ServiceApi;
//import com.yihu.jw.restmodel.ehr.common.Result;
//import com.yihu.jw.restmodel.web.Envelop;
//import org.springframework.cloud.netflix.feign.FeignClient;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import springfox.documentation.annotations.ApiIgnore;
//
//
///**
// * Created by hzp on 2016/4/17.
// */
//@FeignClient(name = MicroServices.PackageResolve)
//@ApiIgnore
//public interface PatientArchiveClient {
//
//
//    @RequestMapping(value = ApiVersion.Version1_0 + ServiceApi.PackageResolve.ArchiveRelation, method = RequestMethod.POST)
//    Envelop archiveRelation(@RequestParam(value = "profileId") String profileId, @RequestParam(value = "idCardNo") String idCardNo);
//
//
//
//}

+ 158 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/ArchiveApplyService.java

@ -0,0 +1,158 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.patient.dao.XArchiveApplyDao;
import com.yihu.jw.basic.patient.dao.XArchiveRelationDao;
import com.yihu.jw.entity.ehr.patient.ArchiveApply;
import com.yihu.jw.entity.ehr.patient.ArchiveRelation;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.Date;
/**
 * 档案申领实现类.
 *
 */
@Transactional
@Service
public class ArchiveApplyService extends BaseJpaService<ArchiveApply, XArchiveApplyDao> {
    @Autowired
    private XArchiveApplyDao archiveApplyDao;
    @Autowired
    private XArchiveRelationDao archiveRelationDao;
//    @Autowired
//    private PatientArchiveClient patientArchiveClient;
    /**
     * 个人档案认领列表
     */
    public PageEnvelop archiveApplyList(String userId,String status,Integer page,Integer rows) throws Exception{
        PageEnvelop re = new PageEnvelop(page,rows);
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        PageRequest pageRequest  = PageRequest.of(page, rows, sort);
        Page<ArchiveApply> list = null;
        if(!StringUtils.isEmpty(status))
        {
            list = archiveApplyDao.findByUserIdAndStatus(userId,status,pageRequest);
        }
        else{
            list = archiveApplyDao.findByUserId(userId,pageRequest);
        }
        if(list!=null) {
            re.setDetailModelList(list.getContent());
            re.setTotalCount(list.getTotalPages());
        }
        return re;
    }
    /**
     * 卡认证申请新增/修改
     */
    public ArchiveApply getArchiveApply(Long id) throws Exception{
        return archiveApplyDao.getOne(id);
    }
    /**
     * 卡认证申请新增/修改
     */
    public ArchiveApply archiveApply(ArchiveApply card) throws Exception{
        return archiveApplyDao.save(card);
    }
    /**
     * 卡认证申请删除
     */
    public void archiveApplyDelete(Long id) throws Exception{
        archiveApplyDao.deleteById(id);
    }
    /**
     * 管理员--档案认领列表
     */
    public PageEnvelop archiveApplyListManager(String status, Integer page, Integer rows) throws Exception{
        PageEnvelop re = new PageEnvelop(page,rows);
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        PageRequest pageRequest  = PageRequest.of(page, rows, sort);
        Page<ArchiveApply> list = null;
        if(!StringUtils.isEmpty(status))
        {
            list = archiveApplyDao.findByStatus(status,pageRequest);
        }
        else{
            list = archiveApplyDao.findAll(pageRequest);
        }
        if(list!=null) {
            re.setDetailModelList(list.getContent());
            re.setTotalCount(list.getTotalPages());
        }
        return re;
    }
    /**
     * 管理员--档案认领审核操作
     */
    public Envelop archiveVerifyManager(Long id, String status, String auditor, String auditReason, String archiveRelationIds) throws Exception{
        ArchiveApply apply = archiveApplyDao.getOne(id);
        if(apply!=null){
            String[] ids = archiveRelationIds.replace(",",",").split(",");
            String msg = "";
            for(String idString :ids){
                if(!StringUtils.isEmpty(idString)) {
                    ArchiveRelation relation = archiveRelationDao.getOne(Long.valueOf(idString));
                    if (relation != null) {
                        try {
                            if ("1".equals(apply.getStatus())) {  //审批通过
                                //操作hbase
//                                patientArchiveClient.archiveRelation(relation.getProfileId(), apply.getIdCard());
                                //档案关联绑定
                                relation.setIdCardNo(apply.getIdCard());
                                relation.setStatus("1");
                                relation.setRelationDate(new Date());
                                relation.setApplyId(apply.getId());
                                archiveRelationDao.save(relation);
                            }
                        } catch (Exception ex) {
                            System.out.print(ex.getMessage());
                            msg += "";
                        }
                    } else {
                        return Envelop.getError("不存在该份档案记录!");
                    }
                }
            }
            //档案认领审批
            apply.setStatus(status);
            apply.setAuditDate(new Date());
            apply.setAuditor(auditor);
            apply.setAuditReason(auditReason);
            archiveApplyDao.save(apply);
            if(!StringUtils.isEmpty(msg)){
                return Envelop.getError("archiveRelationId:"+msg+" ");
            }
            return Envelop.getSuccess("档案认领审核成功!");
        }else{
            return Envelop.getError("不存在该条申请记录!");
        }
    }
}

+ 174 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/ArchiveRelationService.java

@ -0,0 +1,174 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.patient.dao.XArchiveRelationDao;
import com.yihu.jw.entity.ehr.patient.ArchiveRelation;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
 * 档案申领实现类.
 *
 */
@Transactional
@Service
public class ArchiveRelationService extends BaseJpaService<ArchiveRelation, XArchiveRelationDao> {
    @Autowired
    private XArchiveRelationDao archiveRelationDao;
//    @Autowired
//    private PatientArchiveClient patientArchiveClient;
    /**
     * 根据申请ID查询档案关联信息
     * @param applyId
     * @return
     * @throws Exception
     */
    public ObjEnvelop getArRelation(long applyId) throws Exception{
        ObjEnvelop re = new ObjEnvelop();
        ArchiveRelation result = archiveRelationDao.findByApplyId(applyId);
        if(result!=null) {
            re.setObj(result);
        }
        return re;
    }
    /**
     * 个人档案列表
     */
    public PageEnvelop archiveList(String idCardNo,Integer page,Integer rows) throws Exception{
        PageEnvelop re = new PageEnvelop(page,rows);
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        PageRequest pageRequest  = PageRequest.of(page, rows, sort);
        Page<ArchiveRelation> list = archiveRelationDao.findByIdCardNo(idCardNo,pageRequest);
        if(list!=null) {
            re.setDetailModelList(list.getContent());
            re.setTotalCount(list.getTotalPages());
        }
        return re;
    }
    /**
     * 管理员--通过卡号获取未认领档案
     */
    public PageEnvelop archiveUnbind(String cardNo, Integer page, Integer rows) throws Exception{
        PageEnvelop re = new PageEnvelop(page,rows);
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        PageRequest pageRequest  = PageRequest.of(page, rows, sort);
        Page<ArchiveRelation> list = archiveRelationDao.findByCardNo(cardNo,pageRequest);
        if(list!=null) {
            re.setDetailModelList(list.getContent());
            re.setTotalCount(list.getTotalPages());
        }
        return re;
    }
    /**
     * 建立档案关联
     */
    public ArchiveRelation archiveRelation(ArchiveRelation relation) throws Exception {
        //根据profileId 判断是否存在
        String profileId = relation.getProfileId();
        ArchiveRelation ar =  archiveRelationDao.findByProfileId(profileId);
        if (ar != null) {
            relation.setId(ar.getId());
        }
        relation = archiveRelationDao.save(relation);
        return relation;
    }
    public ArchiveRelation getOne(Long id) {
        return   archiveRelationDao.getOne(id);
    }
    /**
     * 通过卡号+姓名关联HBase档案
     */
    public void relationByCardNoAndName(String cardNo,String name,String idcard) throws Exception
    {
        List<ArchiveRelation> list = archiveRelationDao.findByCardNoAndName(cardNo,name);
        if(list!=null && list.size()>0)
        {
              for(ArchiveRelation item:list)
              {
                 try {
//                     patientArchiveClient.archiveRelation(item.getProfileId(), idcard);
//                     item.setStatus("1");
//                     item.setRelationDate(new Date());
//                     item.setIdCardNo(idcard);
                 }
                 catch (Exception ex)
                 {
                     System.out.print("ProfileId:"+item.getProfileId()+" relation idcard:" + idcard +"fail!"+ex.getMessage());
                 }
              }
              archiveRelationDao.saveAll(list);
        }
    }
    public int getIdentifyCount() {
        return archiveRelationDao.findIdentifyCount();
    }
    public int getUnIdentifyCount() {
        return archiveRelationDao.findUnIdentifyCount();
    }
    public int getArchiveCount() {
        return archiveRelationDao.findArchiveCount();
    }
    public int getInPatientCount() {
        return archiveRelationDao.findInPatientCount();
    }
    public int getOutPatientCount() {
        return archiveRelationDao.findOutPatientCount();
    }
    public int getPhysicalCount() {
        return archiveRelationDao.findPhysicalCount();
    }
    public int getInAndOutPatientCount() {
        return archiveRelationDao.findInAndOutPatientCount();
    }
    public int getTodayInWarehouseCount() {
        Session session = entityManager.unwrap(Session.class);
        String sql = "select count(id) from Archive_Relation WHERE DATE_FORMAT(create_date,'%Y-%m-%d') = CURDATE()";
        SQLQuery query = session.createSQLQuery(sql);
        Object ob  = (query.list().get(0));
        int result = Integer.parseInt(ob.toString());
        return result;
    }
    public int getDailyAdd() {
        Session session = entityManager.unwrap(Session.class);
        String sql = "select count(id) from Archive_Relation WHERE identify_flag = 1 AND DATE_FORMAT(event_date,'%Y-%m-%d') = CURDATE()";
        SQLQuery query = session.createSQLQuery(sql);
        Object ob  = (query.list().get(0));
        int result = Integer.parseInt(ob.toString());
        return result;
    }
}

+ 19 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/AuthenticationService.java

@ -0,0 +1,19 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.patient.dao.XAuthenticationRepository;
import com.yihu.jw.entity.ehr.patient.Authentication;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/6/22
 */
@Service
@Transactional
public class AuthenticationService extends BaseJpaService<Authentication, XAuthenticationRepository> {
}

+ 184 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/CardManager.java

@ -0,0 +1,184 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.dict.service.SystemDictEntryService;
import com.yihu.jw.basic.patient.dao.XAbstractPhysicalCardRepository;
import com.yihu.jw.basic.patient.dao.XAbstractVirtualCardRepository;
import com.yihu.jw.entity.ehr.dict.SystemDictEntry;
import com.yihu.jw.entity.ehr.patient.AbstractCard;
import com.yihu.jw.entity.ehr.patient.PhysicalCard;
import com.yihu.jw.entity.ehr.patient.VirtualCard;
import com.yihu.ehr.constants.ErrorCode;
import com.yihu.jw.exception.ApiException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;
/**
 * 卡管理实现类.
 *
 * @author Sand
 * @version 1.0
 * @created 25-5月-2015 17:47:57
 */
@Transactional
@Service
public class CardManager {
    @PersistenceContext
    protected EntityManager entityManager;
    @Autowired
    private SystemDictEntryService systemDictEntryService;
    @Autowired
    private XAbstractPhysicalCardRepository abstractPhysicalCardRepository;
    @Autowired
    private XAbstractVirtualCardRepository abstractVirtualCardRepository;
    public AbstractCard getCard(String id, String cardType) {
        AbstractCard card = null;
        SystemDictEntry cardTypeDict = systemDictEntryService.getDictEntry(10, cardType);
        if (!cardTypeDict.getCatalog().equals("VirtualCard")) {
            card = abstractPhysicalCardRepository.getOne(id);
        } else {
            card = abstractVirtualCardRepository.getOne(id);
        }
        return card;
    }
    public List<AbstractCard> searchAbstractCard(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String idCardNo = (String) args.get("idCardNo");
        String number = (String)args.get("number");
        String type = (String) args.get("type");
        String cardType = (String)args.get("cardType");   //","otherCard
        int rows = (Integer)args.get("rows");
        int page = (Integer)args.get("page");
        String sqlPhysical="from PhysicalCard card where (card.number like :number)";
        String sqlVirtual="from VirtualCard card where (card.number like :number)";
        if ("bind_card".equals(type) && !StringUtils.isEmpty(idCardNo)){
            sqlPhysical += " and (card.idCardNo=:idCardNo)";
            sqlVirtual += " and (card.idCardNo=:idCardNo)";
        }else{
            sqlPhysical += " and (card.idCardNo=null or trim(card.idCardNo)='')";
            sqlVirtual += " and (card.idCardNo=null or trim(card.idCardNo)='')";
        }
        if (!StringUtils.isEmpty(cardType)){
            sqlPhysical += " and (card.cardType=:cardType)";
            sqlVirtual += " and (card.cardType=:cardType)";
        }
        Query queryPhysical = session.createQuery(sqlPhysical);
        Query queryVirtual = session.createQuery(sqlVirtual);
        queryPhysical.setString("number", "%"+number+"%");
        queryVirtual.setString("number", "%"+number+"%");
        if (!StringUtils.isEmpty(idCardNo)) {
            queryPhysical.setParameter("idCardNo", idCardNo);
            queryVirtual.setParameter("idCardNo", idCardNo);
        }
        if (!StringUtils.isEmpty(cardType)){
            queryPhysical.setParameter("cardType", cardType);
            queryVirtual.setParameter("cardType", cardType);
        }
        List<AbstractCard> cards;
        queryPhysical.setMaxResults(rows);
        queryPhysical.setFirstResult((page - 1) * rows);
        cards = queryPhysical.list();
        int physicalCount = searchCardInt(args);
        int first;
        if(cards.size()<rows){
            int left = page * rows - physicalCount;
            if(cards.size()==0){
                page = left/rows;
                int tmp = physicalCount%rows;
                first = tmp == 0 ? (page - 1) * rows : rows - tmp;
            }
            else{
                page = 1;
                rows = left>rows?rows:left;
                first = (page - 1) * rows;
            }
            queryVirtual.setFirstResult(first);
            queryVirtual.setMaxResults(rows);
            cards.addAll(queryVirtual.list());
        }
        return cards;
    }
    public Integer searchCardInt(Map<String, Object> args ) {
        Session session = entityManager.unwrap(Session.class);
        String idCardNo = (String) args.get("idCardNo");
        String number = (String)args.get("number");
        String type = (String) args.get("type");
        String cardType = (String)args.get("cardType");   //","otherCard
        String sql="select count(*) from PhysicalCard card where (card.number like :number)";
        if ("bind_card".equals(type) && !StringUtils.isEmpty(idCardNo)){
            sql += " and (card.idCardNo=:idCardNo)";
        }else{
            sql += " and (card.idCardNo=null or trim(idCardNo)='')";
        }
        if (!StringUtils.isEmpty(cardType)){
            sql += " and (card.cardType=:cardType)";
        }
        Query query = session.createQuery(sql);
        query.setString("number", "%"+number+"%");
        if (!StringUtils.isEmpty(idCardNo)) {
            query.setParameter("idCardNo", idCardNo);
        }
        if (!StringUtils.isEmpty(cardType)){
            query.setParameter("cardType", cardType);
        }
        //List<AbstractCard> cards = query.list();
        return ((Long)query.list().get(0)).intValue();
    }
    public boolean detachCard(AbstractCard card) {
        if (StringUtils.isEmpty(card.getIdCardNo())) {
            return true;
        }
        card.setIdCardNo(null);
        return  saveCard(card);
    }
    public boolean isAvailableIdCardNo(String idCardNo){
        return idCardNo != null && idCardNo.length() > 0;
    }
    public boolean attachCardWith(AbstractCard card, String idCardNo) {
        if (!isAvailableIdCardNo(idCardNo)) {
            throw new IllegalArgumentException("无效人口学索引.");
        }
        card.setIdCardNo(idCardNo);
        return save(card);
    }
    public boolean save(AbstractCard card){
        SystemDictEntry cardTypeDict = systemDictEntryService.getDictEntry(10, card.getCardType());
        if(cardTypeDict.getCatalog().equals("VirtualCard")){
            VirtualCard abstractVirtualCard = (VirtualCard) card;
            abstractVirtualCardRepository.save(abstractVirtualCard);
        }else {
            PhysicalCard abstractPhysicalCard = (PhysicalCard)card;
            abstractPhysicalCardRepository.save(abstractPhysicalCard);
        }
        return true;
    }
    public boolean saveCard(AbstractCard card) {
        if (card.getNumber().length() == 0 || card.getCardType() == null) {
            throw new ApiException("卡信息不全, 无法更新");
        } else if (card.getStatus() == systemDictEntryService.getDictEntry(9, "Invalid").getValue()) {
            throw new ApiException("卡已作废, 无法更新");
        }
        return save(card);
    }
}

+ 515 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/DemographicService.java

@ -0,0 +1,515 @@
package com.yihu.jw.basic.patient.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yihu.jw.basic.address.service.AddressService;
import com.yihu.jw.basic.patient.dao.XDemographicInfoRepository;
import com.yihu.jw.entity.ehr.patient.DemographicInfo;
import com.yihu.jw.util.date.DateTimeUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;
/**
 * 人口学索引实现类.
 *
 * @author Sand
 * @version 1.0
 * @created 04-6月-2015 19:53:04
 */
@Service
@Transactional
public class DemographicService extends BaseJpaService {
    @PersistenceContext
    protected EntityManager entityManager;
    @Autowired
    private XDemographicInfoRepository demographicInfoRepository;
    @Autowired
    private AddressService addressService;
    public DemographicInfo getDemographicInfo(String id) {
        DemographicInfo demInfo = demographicInfoRepository.getOne(id);
        return demInfo;
    }
    public DemographicInfo getDemographicInfoBytelephoneNo(String telephoneNo) {
        //{"联系电话":"15965368965"}
        telephoneNo="{\"联系电话\":\""+telephoneNo+"\"}";
        List<DemographicInfo> demInfoList = demographicInfoRepository.getDemographicInfoByTelephoneNo(telephoneNo);
        DemographicInfo demInfo=null;
        if(null!=demInfoList&&demInfoList.size()>0){
            demInfo=demInfoList.get(0);
        }
        return demInfo;
    }
    public void save(DemographicInfo demographicInfo) throws JsonProcessingException {
        demographicInfoRepository.save(demographicInfo);
    }
    public boolean savePatient(DemographicInfo demographicInfo) throws Exception{
        save(demographicInfo);
        return true;
    }
    public List<DemographicInfo> searchPatient(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String search = (String) args.get("search");
        Integer page = (Integer) args.get("page");
        Integer pageSize = (Integer) args.get("pageSize");
        String province = (String) args.get("province");
        String city = (String) args.get("city");
        String district = (String) args.get("district");
        boolean addressNotNull=(!StringUtils.isEmpty(province) || !StringUtils.isEmpty(city) || !StringUtils.isEmpty(district));
        List<String> homeAddressIdList = null;
        String hql = "from DemographicInfo where 1=1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (addressNotNull) {
            homeAddressIdList = addressService.searchList(province,city,district);
            hql += " and homeAddress in (:homeAddressIdList)";
        }
        hql += " order by registerTime desc";
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (addressNotNull) {
            query.setParameterList("homeAddressIdList", homeAddressIdList);
        }
        query.setMaxResults(pageSize);
        query.setFirstResult((page - 1) * pageSize);
        List<DemographicInfo> demographicInfos = query.list();
        return demographicInfos;
    }
    public Integer searchPatientTotalCount(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String search = (String) args.get("search");
        String province = (String) args.get("province");
        String city = (String) args.get("city");
        String district = (String) args.get("district");
        boolean addressNotNull=(!StringUtils.isEmpty(province) || !StringUtils.isEmpty(city) || !StringUtils.isEmpty(district));
        List<String> homeAddressIdList = null;
        String hql = "select count(*) from DemographicInfo where 1=1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (addressNotNull) {
            homeAddressIdList = addressService.searchList(province,city,district);
            hql += " and homeAddress in (:homeAddressIdList)";
        }
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (addressNotNull) {
            query.setParameterList("homeAddressIdList", homeAddressIdList);
        }
        return ((Long)query.list().get(0)).intValue();
    }
    public void delete(String id) {
        demographicInfoRepository.deleteById(id);
    }
    public void resetPass(String id) {
        String pwd = "12345678";
        DemographicInfo demInfo = getDemographicInfo(id);
        demInfo.setPassword(DigestUtils.md5Hex(pwd));
        demographicInfoRepository.save(demInfo);
    }
    public List<DemographicInfo> searchPatientByParams(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String search = (String) args.get("search");
        Integer page = (Integer) args.get("page");
        Integer pageSize = (Integer) args.get("pageSize");
        String province = (String) args.get("province");
        String city = (String) args.get("city");
        String district = (String) args.get("district");
        String gender = (String) args.get("gender");
        Date searchRegisterTimeStart = (Date) args.get("startDate");
        Date searchRegisterTimeEnd = (Date) args.get("endDate");
        boolean addressNotNull=(!StringUtils.isEmpty(province) || !StringUtils.isEmpty(city) || !StringUtils.isEmpty(district));
        List<String> homeAddressIdList = null;
        String hql = "from DemographicInfo where 1=1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (!StringUtils.isEmpty(gender)) {
            hql += " and gender = (:gender)";
        }
        if (addressNotNull) {
            homeAddressIdList = addressService.searchList(province,city,district);
            hql += " and homeAddress in (:homeAddressIdList)";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            hql += " and registerTime>= :searchRegisterTimeStart";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            hql += " and registerTime < :searchRegisterTimeEnd";
        }
        hql += " order by registerTime desc";
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            query.setString("gender", gender);
        }
        if (addressNotNull) {
            query.setParameterList("homeAddressIdList", homeAddressIdList);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            query.setDate("searchRegisterTimeStart",searchRegisterTimeStart);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            query.setDate("searchRegisterTimeEnd", searchRegisterTimeEnd);
        }
        query.setMaxResults(pageSize);
        query.setFirstResult((page - 1) * pageSize);
        List<DemographicInfo> demographicInfos = query.list();
        return demographicInfos;
    }
    public Integer searchPatientByParamsTotalCount(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String search = (String) args.get("search");
        String province = (String) args.get("province");
        String city = (String) args.get("city");
        String district = (String) args.get("district");
        String gender = (String) args.get("gender");
        Date searchRegisterTimeStart = (Date) args.get("startDate");
        Date searchRegisterTimeEnd = (Date) args.get("endDate");
        boolean addressNotNull=(!StringUtils.isEmpty(province) || !StringUtils.isEmpty(city) || !StringUtils.isEmpty(district));
        List<String> homeAddressIdList = null;
        String hql = "select count(*) from DemographicInfo where 1=1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (!StringUtils.isEmpty(gender)) {
            hql += " and gender = (:gender)";
        }
        if (addressNotNull) {
            homeAddressIdList = addressService.searchList(province,city,district);
            hql += " and homeAddress in (:homeAddressIdList)";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            hql += " and registerTime >= :searchRegisterTimeStart";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            hql += " and registerTime < :searchRegisterTimeEnd";
        }
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            query.setString("gender", gender);
        }
        if (addressNotNull) {
            query.setParameterList("homeAddressIdList", homeAddressIdList);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            query.setDate("searchRegisterTimeStart", searchRegisterTimeStart);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            query.setDate("searchRegisterTimeEnd", searchRegisterTimeEnd);
        }
        return ((Long)query.list().get(0)).intValue();
    }
    public List<DemographicInfo> searchPatientByParams2(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String search = (String) args.get("search");
        Integer page = (Integer) args.get("page");
        Integer pageSize = (Integer) args.get("pageSize");
        String province = (String) args.get("province");
        String city = (String) args.get("city");
        String district = (String) args.get("district");
        String gender = (String) args.get("gender");
        String districtList = (String) args.get("districtList");
        List<String> locationList = stringToList(districtList);
        Date searchRegisterTimeStart = (Date) args.get("startDate");
        Date searchRegisterTimeEnd = (Date) args.get("endDate");
        boolean addressNotNull=(!StringUtils.isEmpty(province) || !StringUtils.isEmpty(city) || !StringUtils.isEmpty(district));
        List<String> homeAddressIdList = null;
        String hql = "from DemographicInfo where 1=1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (!StringUtils.isEmpty(gender)) {
            hql += " and gender = (:gender)";
        }
        if (addressNotNull) {
            homeAddressIdList = addressService.searchList(province,city,district);
            hql += " and homeAddress in (:homeAddressIdList)";
        }
        if (!StringUtils.isEmpty(districtList)) {
            hql += " and homeAddress in (:locationList)";
        } else {
            hql += " and homeAddress in ('-1')";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            hql += " and registerTime>= :searchRegisterTimeStart";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            hql += " and registerTime < :searchRegisterTimeEnd";
        }
        hql += " order by registerTime desc";
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            query.setString("gender", gender);
        }
        if (addressNotNull) {
            query.setParameterList("homeAddressIdList", homeAddressIdList);
        }
        if (!StringUtils.isEmpty(districtList)) {
            query.setParameterList("locationList", locationList);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            query.setDate("searchRegisterTimeStart",searchRegisterTimeStart);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            query.setDate("searchRegisterTimeEnd", searchRegisterTimeEnd);
        }
        query.setMaxResults(pageSize);
        query.setFirstResult((page - 1) * pageSize);
        List<DemographicInfo> demographicInfos = query.list();
        return demographicInfos;
    }
    public Integer searchPatientByParamsTotalCount2(Map<String, Object> args) {
        Session session = entityManager.unwrap(Session.class);
        String search = (String) args.get("search");
        String province = (String) args.get("province");
        String city = (String) args.get("city");
        String district = (String) args.get("district");
        String gender = (String) args.get("gender");
        String districtList = (String) args.get("districtList");
        Date searchRegisterTimeStart = (Date) args.get("startDate");
        Date searchRegisterTimeEnd = (Date) args.get("endDate");
        List<String> locationList = stringToList(districtList);
        boolean addressNotNull=(!StringUtils.isEmpty(province) || !StringUtils.isEmpty(city) || !StringUtils.isEmpty(district));
        List<String> homeAddressIdList = null;
        String hql = "select count(*) from DemographicInfo where 1=1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (!StringUtils.isEmpty(gender)) {
            hql += " and gender = (:gender)";
        }
        if (addressNotNull) {
            homeAddressIdList = addressService.searchList(province,city,district);
            hql += " and homeAddress in (:homeAddressIdList)";
        }
        if (!StringUtils.isEmpty(districtList)) {
            hql += " and homeAddress in (:locationList)";
        } else {
            hql += " and homeAddress in ('-1')";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            hql += " and registerTime >= :searchRegisterTimeStart";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            hql += " and registerTime < :searchRegisterTimeEnd";
        }
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            query.setString("gender", gender);
        }
        if (addressNotNull) {
            query.setParameterList("homeAddressIdList", homeAddressIdList);
        }
        if (!StringUtils.isEmpty(districtList)) {
            query.setParameterList("locationList", locationList);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            query.setDate("searchRegisterTimeStart", searchRegisterTimeStart);
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            query.setDate("searchRegisterTimeEnd", searchRegisterTimeEnd);
        }
        return ((Long)query.list().get(0)).intValue();
    }
    private List<String> stringToList(String districtList) {
        List<String> locationList = null;
        if (!StringUtils.isEmpty(districtList)) {
            String[] arr = districtList.split(",");
            locationList = Arrays.asList(arr);
        }
        return locationList;
    }
    public DemographicInfo getDemographicInfoByIdCardNo(String idCardNo) {
        List<DemographicInfo> demInfoList = demographicInfoRepository.getDemographicInfoByIdCardNo(idCardNo);
        DemographicInfo demInfo=null;
        if (null != demInfoList&&demInfoList.size() > 0){
            demInfo=demInfoList.get(0);
        }
        return demInfo;
    }
    //统计年龄段人口数
    public List<Object> getStatisticsDemographicsAgeCount() {
        Session session = entityManager.unwrap(Session.class);;
        String sql = "SELECT count(1), tt.age  from(  " +
                " SELECT t1.id ,  " +
                "  ELT(   CEIL(  FLOOR( TIMESTAMPDIFF(MONTH, STR_TO_DATE(t1.id ,'%Y%m%d'), CURDATE())/12) /10+1 ), " +
                " '0-1','1-10','11-20','21-30','31-40','41-50','51-60','61-70','71-80','81-90','> 90') as age from ( "+
                " SELECT CASE when length(id)=15  then CONCAT('19',substr(id ,7,6)) ELSE substr(id ,7,8) end  id  from demographics t )t1 "+
                " )tt WHERE tt.age is not null  GROUP BY tt.age";
        SQLQuery query = session.createSQLQuery(sql);
        return query.list();
    }
    /**
     * 居民信息列表
     * @param search 匹配身份证号码或者姓名
     * @param gender 性别
     * @param homeAddress 家庭住址
     * @param searchRegisterTimeStart 注册开始时间
     * @param searchRegisterTimeEnd 注册结束时间
     * @param page 页码
     * @param size 页数
     * @return
     * @throws Exception
     */
    public List<DemographicInfo> search (String search,
                                String gender,
                                String homeAddress,
                                String searchRegisterTimeStart,
                                String searchRegisterTimeEnd,
                                Integer page,
                                Integer size) throws Exception {
        Session session = entityManager.unwrap(Session.class);
        String hql = "from DemographicInfo where 1 = 1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (!StringUtils.isEmpty(gender)) {
            hql += " and gender = (:gender)";
        }
        if (!StringUtils.isEmpty(homeAddress)) {
            hql += " and homeAddress like :homeAddress";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            hql += " and registerTime>= :searchRegisterTimeStart";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            hql += " and registerTime < :searchRegisterTimeEnd";
        }
        hql += " order by registerTime desc";
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            query.setString("gender", gender);
        }
        if (!StringUtils.isEmpty(homeAddress)) {
            query.setString("homeAddress", "%" + homeAddress + "%");
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            query.setDate("searchRegisterTimeStart",  DateTimeUtil.simpleDateTimeParse(searchRegisterTimeStart));
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            Date endDate = DateTimeUtil.simpleDateTimeParse(searchRegisterTimeEnd);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(endDate);
            calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
            endDate = calendar.getTime();   //日期往后推一天
            query.setDate("searchRegisterTimeEnd", endDate);
        }
        query.setMaxResults(size);
        query.setFirstResult((page - 1) * size);
        List<DemographicInfo> demographicInfos = query.list();
        return demographicInfos;
    }
    //统计年龄段人口数
    public Integer count (String search,
                          String gender,
                          String homeAddress,
                          String searchRegisterTimeStart,
                          String searchRegisterTimeEnd) throws Exception {
        Session session = entityManager.unwrap(Session.class);
        String hql = "select count(*) from DemographicInfo where 1 = 1";
        if (!StringUtils.isEmpty(search)) {
            hql += " and ((id like :search) or (name like :search))";
        }
        if (!StringUtils.isEmpty(gender)) {
            hql += " and gender = (:gender)";
        }
        if (!StringUtils.isEmpty(homeAddress)) {
            hql += " and homeAddress like :homeAddress";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            hql += " and registerTime>= :searchRegisterTimeStart";
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            hql += " and registerTime < :searchRegisterTimeEnd";
        }
        Query query = session.createQuery(hql);
        if (!StringUtils.isEmpty(search)) {
            query.setString("search", "%" + search + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            query.setString("gender", gender);
        }
        if (!StringUtils.isEmpty(homeAddress)) {
            query.setString("homeAddress", "%" + homeAddress + "%");
        }
        if (!StringUtils.isEmpty(searchRegisterTimeStart)) {
            query.setDate("searchRegisterTimeStart",  DateTimeUtil.simpleDateTimeParse(searchRegisterTimeStart));
        }
        if (!StringUtils.isEmpty(searchRegisterTimeEnd)) {
            Date endDate = DateTimeUtil.simpleDateTimeParse(searchRegisterTimeEnd);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(endDate);
            calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
            endDate = calendar.getTime();   //日期往后推一天
            query.setDate("searchRegisterTimeEnd", endDate);
        }
        return ((Long)query.list().get(0)).intValue();
    }
}

+ 94 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/FamiliesService.java

@ -0,0 +1,94 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.patient.dao.XFamiliesRepository;
import com.yihu.jw.basic.patient.dao.XMembersRepository;
import com.yihu.jw.entity.ehr.patient.Families;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
 * 用户管理接口实现类.
 *
 * @author Lyr
 * @version 1.0
 * @updated 18-4月-2016 10:30:00
 */
@Service
@Transactional
public class FamiliesService extends BaseJpaService<Families, XFamiliesRepository> {
    @Autowired
    private XFamiliesRepository familiesRep;
    @Autowired
    private XMembersRepository membersRep;
    /*
     * 获取家庭列表
     *
     * @param sorts 排序字段
     * @param page 页码
     * @param size 每页大小
     * @return Page<Families> 家庭列表
     */
    public Page<Families> getFamilies(String sorts, int page, int size)
    {
        Pageable pageable =  PageRequest.of(page,size,parseSorts(sorts));
        return familiesRep.findAll(pageable);
    }
    /*
     * 根据家庭ID获取家庭
     *
     * @param id 家庭ID
     * @Families 家庭
     */
    public Families getFamiliesById(String id)
    {
        Families families = familiesRep.getOne(id);
        return families;
    }
    /*
     * 创建家庭
     *
     * @param families 家庭
     * @return Families 家庭
     */
    public Families createFamilies(Families families)
    {
        families.setCreateDate(new Date());
        return familiesRep.save(families);
    }
    /*
     * 更新家庭
     *
     * @param families 家庭
     */
    public void updateFamilies(Families families)
    {
        familiesRep.save(families);
    }
    /*
     * 删除家庭
     *
     * @param id 家庭ID
     */
    public void deleteFamilies(String id)
    {
        membersRep.deleteByFamilyId(id);
        familiesRep.deleteById(id);
    }
}

+ 48 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/MedicalCardsService.java

@ -0,0 +1,48 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.patient.dao.XMedicalCardsDao;
import com.yihu.jw.entity.ehr.patient.MedicalCards;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 卡管理实现类.
 *
 */
@Transactional
@Service
public class MedicalCardsService extends BaseJpaService<MedicalCards, XMedicalCardsDao> {
    @Autowired
    private XMedicalCardsDao medicalCardsDao;
    /**
     * 就诊卡新增&修改
     */
    public MedicalCards MCardCreate(MedicalCards card) throws Exception{
        return medicalCardsDao.save(card);
    }
    /**
     * 就诊卡删除
     */
    public void MCardDel(Long id) throws Exception{
        medicalCardsDao.deleteById(id);
    }
    /**
     * 就诊卡详细信息
     */
    public MedicalCards getMCard(Long id) throws Exception{
        return medicalCardsDao.getOne(id);
    }
    public List<MedicalCards> getBycardNoStr(String cardNoStr) {
        String [] cardNos = cardNoStr.split(",");
        List<MedicalCards> medicalCardses = medicalCardsDao.getBycardNoStr(cardNos);
        return medicalCardses;
    }
}

+ 113 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/MembersService.java

@ -0,0 +1,113 @@
package com.yihu.jw.basic.patient.service;
import com.yihu.jw.basic.patient.dao.XMembersRepository;
import com.yihu.jw.entity.ehr.patient.Members;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
 * 用户管理接口实现类.
 *
 * @author Lyr
 * @version 1.0
 * @updated 18-4月-2016 10:30:00
 */
@Service
@Transactional
public class MembersService extends BaseJpaService<Members, XMembersRepository> {
    @Autowired
    private XMembersRepository membersRep;
    /*
     * 获取家庭成员列表
     *
     * @param sorts 排序字段
     * @param page 页码
     * @param size 每页大小
     * @return Page<Members> 家庭成员列表
     */
    public Page<Members> getMembers(String sorts, int page, int size)
    {
        Pageable pageable =  PageRequest.of(page,size,parseSorts(sorts));
        return membersRep.findAll(pageable);
    }
    /*
     * 根据家庭成员ID获取成员
     *
     * @param id 家庭成员ID
     * @Families 家庭成员
     */
    public Members getMembers(String familyId, String idCardNo)
    {
        Members members = membersRep.findByFamilyIdAndIdCardNo(familyId,idCardNo);
        return members;
    }
    /*
     * 根据家庭ID获取家庭成员
     *
     * @param familyId 家庭ID
     * @return Page<Members> 家庭成员列表
     */
    public List<Members> getMembersByFamilyId(String familyId)
    {
        List<Members> members = membersRep.findByFamilyId(familyId);
        return members;
    }
    /*
     * 创建家庭成员
     *
     * @param families 家庭成员
     * @return Families 家庭成员
     */
    public Members createMembers(Members members)
    {
        members.setCreateDate(new Date());
        return membersRep.save(members);
    }
    /*
     * 更新家庭成员
     *
     * @param families 家庭成员
     */
    public void updateMembers(Members members)
    {
        membersRep.save(members);
    }
    /*
     * 删除家庭成员
     *
     * @param id 家庭成员ID
     */
    public void deleteMembers(String familyId,String idCardNo)
    {
        membersRep.deleteByFamilyIdAndIdCardNo(familyId,idCardNo);
    }
    /*
     * 根据家庭ID删除家庭成员
     *
     * @param familyId 家庭ID
     */
    public void deleteMembersByFamilyId(String familyId)
    {
        membersRep.deleteByFamilyId(familyId);
    }
}

+ 0 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/patient/service/UserCardsService.java


Vissa filer visades inte eftersom för många filer har ändrats