This commit is contained in:
주수현
2025-06-25 08:06:10 +09:00
215 changed files with 8036 additions and 2014 deletions

View File

@@ -112,6 +112,14 @@ recycle 의 demo 가 궁금하다면 아래 URL 에서 확인 해주세요.
-Dspring.datasource.url=jdbc:postgresql://15.165.180.203:5432/korea_research
-Dspring.datasource.username=ko_research
-Dspring.datasource.password=koresearch1@#4
-Daes.secret-key=092HW829O0A0AVR0
-Dpath.upload.storage=SFTP
-Dpath.upload.sftp.public=/home/etribe/data/upload
-Dpath.upload.sftp.tmpdir=${user.home}/upload/tmpdir
-Dfile.upload.sftp.ip=115.68.193.117
-Dfile.upload.sftp.id=etribe
-Dfile.upload.sftp.password=Etribe@3415
-Dfile.upload.sftp.port=22
```
## JDBC 및 데이터 핸들링 구성 옵션

View File

@@ -1,5 +1,6 @@
package app.module.admin.config.adapters.web.interceptor;
import app.module.admin.config.application.util.AdminUtil;
import app.module.core.config.adapters.web.interceptor.model.URITopTierVO;
import app.module.core.config.application.enums.AppType;
import app.module.core.config.application.exception.NoMatchingURIException;
@@ -76,16 +77,16 @@ public class AdminURIInterceptor implements HandlerInterceptor {
// 활성 프로파일 가져오기 TODO 2차 오픈시 삭제 예정
modelAndView.addObject("activeProfile", activeProfiles);
String roleId = AdminUtil.getLoginUserRole();
if (!CommonUtil.isAjaxRequest(request)) {
URITopTier topTierOutput = topTierPortIn.connect(AppType.ADMIN);
URITopTier topTierOutput = topTierPortIn.connectRoleId(AppType.ADMIN,roleId);
modelAndView.addObject("topNode", recursiveMapping(topTierOutput));
if (modelAndView.getModelMap().getAttribute("currentURI") == null) {
modelAndView.addObject("currentURI", request.getAttribute("currentURI"));
}
modelAndView.addObject(
"menuHierarchy", uriAncestryPortIn.connect(AppType.ADMIN, request.getRequestURI()));
modelAndView.addObject("menuHierarchy", uriAncestryPortIn.connect(AppType.ADMIN, request.getRequestURI()));
if (cloudFrontDomain != null && bucketFolder != null) {
modelAndView.addObject("S3URL", "https://" + cloudFrontDomain + bucketFolder);

View File

@@ -1,7 +1,9 @@
package app.module.admin.config.application.enums;
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
@Getter
@RequiredArgsConstructor
@@ -10,4 +12,10 @@ public enum ManagementType {
CALL("전화상담"),
ETC("기타");
private final String desc;
@JsonCreator
public static ManagementType from(String value) {
if (!StringUtils.hasText(value)) return null;
return ManagementType.valueOf(value.toUpperCase());
}
}

View File

@@ -65,17 +65,18 @@ public class AdminAuthSuccessEvent {
"security.password.change.notify", adminUser.getRemainPasswordDays()));
}
// 로그인 활성화 기록 생성
// loggedInUserSavePortIn.connect(
// LoggedInUserSaveCmd.builder()
// .loggedInUserId(
// LoggedInUserIdSaveCmd.builder()
// .appType(AppType.ADMIN)
// .id(authentication.getName())
// .build())
// .clientIP(CommonUtil.getClientIP(request))
// .lastLoggedInAt(LocalDateTime.now())
// .build());
// 로그인 이력 쌓기
loggedInUserSavePortIn.connect(
LoggedInUserSaveCmd.builder()
.loggedInUserId(
LoggedInUserIdSaveCmd.builder()
.appType(AppType.ADMIN)
.id(authentication.getName())
.build())
.clientIP(CommonUtil.getClientIP(request))
.lastLoggedInAt(LocalDateTime.now())
.build());
}
@EventListener

View File

@@ -46,6 +46,7 @@ public class AdminDetailsService implements UserDetailsService {
adminUser.getPassword(),
adminUser.getRoles().stream().map(CoreRole::getId).findFirst().orElse(null),
adminUser.getRegionMainCode(),
adminUser.getLastLoginIp(),
!accountDisabled,
true,
isCredentialsNonExpired(adminUser.getPasswordUpdatedAt()),

View File

@@ -10,6 +10,7 @@ public class AdminUser extends User {
private Long seq;
private String roleId;
private String regionMainCode;
private String lastLoginIp;
private long remainPasswordDays;
public AdminUser(
@@ -18,6 +19,7 @@ public class AdminUser extends User {
String password,
String roleId,
String regionMainCode,
String lastLoginIp,
boolean enabled,
boolean accountNonExpired,
boolean credentialsNonExpired,
@@ -35,6 +37,7 @@ public class AdminUser extends User {
this.seq = seq;
this.roleId = roleId;
this.regionMainCode = regionMainCode;
this.lastLoginIp = lastLoginIp;
this.remainPasswordDays = remainPasswordDays;
}
}

View File

@@ -53,4 +53,14 @@ public class AdminUtil {
AdminUser user = (AdminUser) authentication.getPrincipal();
return user.getRegionMainCode().isEmpty() ? null : user.getRegionMainCode();
}
public static String getLoginUserLastIp() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !(authentication.getPrincipal() instanceof AdminUser)) {
return null;
}
AdminUser user = (AdminUser) authentication.getPrincipal();
return user.getLastLoginIp();
}
}

View File

@@ -18,7 +18,6 @@ public class GetDailyExpenseRecords {
private String quantity;
private String unitCode;
private String unitText;
private String unitSelf;
private String price;
private String estimatedValue;
private String updatedBy;

View File

@@ -15,7 +15,6 @@ public class GetDailyFarmingRecords {
private String productName;
private String usage;
private BigDecimal quantity;
private String unitCode;
private String unitText;
private String estimatedValue;
private String updatedBy;

View File

@@ -21,7 +21,6 @@ public class GetDailyIncomeRecords {
private BigDecimal quantity;
private String unitCode;
private String unitText;
private String unitSelf;
private String price;
private String estimatedValue;
private String updatedBy;

View File

@@ -14,11 +14,9 @@ public class GetDailyWorkRecords {
private String itemName;
private String workName;
private String workLandArea;
private String areaUnitCodeText;
private String areaUnitSelf;
private String areaUnitText;
private String harvestQuantity;
private String harvestUnitCodeText;
private String harvestUnitSelf;
private String harvestUnitText;
private String ownerTime;
private String spouseTime;
private String familyMHours;

View File

@@ -0,0 +1,19 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.persistence;
import app.module.core.config.application.annotation.DeleteCommand;
import lombok.RequiredArgsConstructor;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain.RemoveHouseholdVisitInfosCmd;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.RemoveHouseholdVisitInfosPortOut;
import org.springframework.stereotype.Repository;
@Repository
@RequiredArgsConstructor
class RemoveHouseholdVisitInfosDao implements RemoveHouseholdVisitInfosPortOut {
private final RemoveHouseholdVisitInfosMapper mapper;
@Override
@DeleteCommand
public void operate(RemoveHouseholdVisitInfosCmd cmd) {
mapper.removeHouseholdVisitInfos(cmd);
}
}

View File

@@ -0,0 +1,9 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.persistence;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain.RemoveHouseholdVisitInfosCmd;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface RemoveHouseholdVisitInfosMapper {
void removeHouseholdVisitInfos(RemoveHouseholdVisitInfosCmd cmd);
}

View File

@@ -0,0 +1,38 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.web;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.RemoveHouseholdVisitInfosPortIn;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain.RemoveHouseholdVisitInfosCmd;
import app.module.core.config.application.util.MessageUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.BindingResult;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.web.model.RemoveHouseholdVisitInfosReqVO;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.web.model.RemoveHouseholdVisitInfosResVO;
@RestController
@RequiredArgsConstructor
class RemoveHouseholdVisitInfosController {
private final MessageUtil messageUtil;
private final RemoveHouseholdVisitInfosPortIn portIn;
@DeleteMapping(path = "/api/visitInfo/remove")
ResponseEntity<?> operate(
@Valid @RequestBody RemoveHouseholdVisitInfosReqVO reqVO,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(bindingResult);
}
portIn.operate(
new RemoveHouseholdVisitInfosCmd(reqVO.getHouseholdSeq(), reqVO.getRemoveIds()));
return ResponseEntity.status(HttpStatus.OK).body(new RemoveHouseholdVisitInfosResVO(
messageUtil.getMessage("operation.common.remove.done")));
}
}

View File

@@ -0,0 +1,17 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.web.model;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode
public class RemoveHouseholdVisitInfosReqVO {
private Long householdSeq;
private List<Long> removeIds;
}

View File

@@ -0,0 +1,14 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.web.model;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class RemoveHouseholdVisitInfosResVO {
private String message;
}

View File

@@ -0,0 +1,7 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain.RemoveHouseholdVisitInfosCmd;
public interface RemoveHouseholdVisitInfosPortIn {
void operate(RemoveHouseholdVisitInfosCmd cmd);
}

View File

@@ -0,0 +1,7 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain.RemoveHouseholdVisitInfosCmd;
public interface RemoveHouseholdVisitInfosPortOut {
void operate(RemoveHouseholdVisitInfosCmd cmd);
}

View File

@@ -0,0 +1,18 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application;
import lombok.RequiredArgsConstructor;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain.RemoveHouseholdVisitInfosCmd;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.RemoveHouseholdVisitInfosPortIn;
import app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.RemoveHouseholdVisitInfosPortOut;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
class RemoveHouseholdVisitInfosService implements RemoveHouseholdVisitInfosPortIn {
private final RemoveHouseholdVisitInfosPortOut portOut;
@Override
public void operate(RemoveHouseholdVisitInfosCmd cmd) {
portOut.operate(cmd);
}
}

View File

@@ -0,0 +1,16 @@
package app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.ports.application.domain;
import app.module.core.config.adapters.persistence.component.AuditCommand;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public class RemoveHouseholdVisitInfosCmd extends AuditCommand {
private Long householdSeq;
private List<Long> removeIds;
}

View File

@@ -0,0 +1,28 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.persistence;
import app.module.core.config.application.util.AuditUtil;
import lombok.RequiredArgsConstructor;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain.SaveHouseholdVisitInfoCmd;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.SaveHouseholdVisitInfoPortOut;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@RequiredArgsConstructor
class SaveHouseholdVisitInfoDao implements SaveHouseholdVisitInfoPortOut {
private final SaveHouseholdVisitInfoMapper mapper;
@Override
@Transactional
public void operate(SaveHouseholdVisitInfoCmd cmd) {
if (cmd.getVisitInfoId() != null) {
mapper.findById(cmd.getHouseholdSeq())
.ifPresentOrElse(
v -> mapper.updateHouseholdVisitInfo(AuditUtil.update(cmd)),
() -> { throw new IllegalArgumentException("방문정보가 없습니다."); }
);
} else {
mapper.createHouseholdVisitInfo(AuditUtil.create(cmd));
}
}
}

View File

@@ -0,0 +1,12 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.persistence;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain.SaveHouseholdVisitInfoCmd;
import java.util.Optional;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SaveHouseholdVisitInfoMapper {
Optional<Long> findById(Long id);
void createHouseholdVisitInfo(SaveHouseholdVisitInfoCmd cmd);
void updateHouseholdVisitInfo(SaveHouseholdVisitInfoCmd cmd);
}

View File

@@ -0,0 +1,47 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.SaveHouseholdVisitInfoPortIn;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain.SaveHouseholdVisitInfoCmd;
import app.module.core.config.application.util.MessageUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.BindingResult;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.model.SaveHouseholdVisitInfoReqVO;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.model.SaveHouseholdVisitInfoResVO;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.validator.SaveHouseholdVisitInfoValidator;
@RestController
@RequiredArgsConstructor
class SaveHouseholdVisitInfoController {
private final SaveHouseholdVisitInfoValidator validator;
private final SaveHouseholdVisitInfoPortIn portIn;
private final MessageUtil messageUtil;
@PostMapping(path = "/api/visitInfo/save")
ResponseEntity<?> operate(
@Valid @RequestBody SaveHouseholdVisitInfoReqVO reqVO,
BindingResult bindingResult) {
validator.validate(reqVO, bindingResult);
if (bindingResult.hasErrors()) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
.body(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
portIn.operate(new SaveHouseholdVisitInfoCmd(
reqVO.getVisitInfoId(),
reqVO.getHouseholdSeq(),
reqVO.getVisitDate(),
reqVO.getManagementType().name(),
reqVO.getContent(),
reqVO.getIsGiftSent()));
return ResponseEntity.status(HttpStatus.OK).body(
new SaveHouseholdVisitInfoResVO(messageUtil.getMessage("operation.common.save.done")));
}
}

View File

@@ -0,0 +1,25 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.model;
import app.module.admin.config.application.enums.ManagementType;
import com.fasterxml.jackson.annotation.JsonFormat;
import groovy.transform.NamedParam;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode
public class SaveHouseholdVisitInfoReqVO {
private Long visitInfoId;
private Long householdSeq;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date visitDate;
private ManagementType managementType;
private String content;
private Boolean isGiftSent;
}

View File

@@ -0,0 +1,14 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.model;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class SaveHouseholdVisitInfoResVO {
private String message;
}

View File

@@ -0,0 +1,45 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.validator;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.web.model.SaveHouseholdVisitInfoReqVO;
import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class SaveHouseholdVisitInfoValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return SaveHouseholdVisitInfoReqVO.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
SaveHouseholdVisitInfoReqVO vo = (SaveHouseholdVisitInfoReqVO) target;
if (vo.getHouseholdSeq() == null) {
errors.reject("householdSeq", "임가 정보가 없습니다.");
return;
}
if (vo.getVisitDate() == null) {
errors.reject("visitDate", "방문일자를 입력해 주세요.");
return;
}
if (vo.getVisitDate().after(new Date())) {
errors.reject("visitDate", "미래 날짜는 입력할 수 없습니다.");
return;
}
if (vo.getManagementType() == null) {
errors.reject("managementType", "방문조사 유형을 선택해 주세요.");
}
if (!StringUtils.hasText(vo.getContent())) {
errors.reject("content", "내용을 입력해 주세요.");
}
}
}

View File

@@ -0,0 +1,7 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain.SaveHouseholdVisitInfoCmd;
public interface SaveHouseholdVisitInfoPortIn {
void operate(SaveHouseholdVisitInfoCmd cmd);
}

View File

@@ -0,0 +1,7 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain.SaveHouseholdVisitInfoCmd;
public interface SaveHouseholdVisitInfoPortOut {
void operate(SaveHouseholdVisitInfoCmd cmd);
}

View File

@@ -0,0 +1,18 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application;
import lombok.RequiredArgsConstructor;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain.SaveHouseholdVisitInfoCmd;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.SaveHouseholdVisitInfoPortIn;
import app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.SaveHouseholdVisitInfoPortOut;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
class SaveHouseholdVisitInfoService implements SaveHouseholdVisitInfoPortIn {
private final SaveHouseholdVisitInfoPortOut portOut;
@Override
public void operate(SaveHouseholdVisitInfoCmd cmd) {
portOut.operate(cmd);
}
}

View File

@@ -0,0 +1,19 @@
package app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.ports.application.domain;
import app.module.core.config.adapters.persistence.component.AuditCommand;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public class SaveHouseholdVisitInfoCmd extends AuditCommand {
private Long visitInfoId;
private Long householdSeq;
private Date visitDate;
private String managementType;
private String content;
private Boolean isGiftSent;
}

View File

@@ -54,6 +54,11 @@ public class ResearcherDao implements ResearcherPortOut {
return new PageImpl<>(result, pageable, total);
}
@Override
public VisitHouseholdPercentageDto selectVisitHouseholdPercentage(ResearchersDetailReqVO reqVO) {
return researcherMapper.selectVisitHouseholdPercentage(reqVO);
}
@Override
public Page<ResearchersHouseholdVisitDto> visitHouseholdList(ResearchersDetailReqVO reqVO) {
List<ResearchersHouseholdVisitDto> result = researcherMapper.visitHouseholdList(reqVO);

View File

@@ -22,6 +22,7 @@ public interface ResearcherMapper {
ResearchersHouseholdVisitDto visitHouseholdDetail(Integer id);
Long visitHouseholdListCountAll(ResearchersDetailReqVO reqVO);
Integer updateVisitHousehold(ResearchersVisitDetailReqVO reqVO);
VisitHouseholdPercentageDto selectVisitHouseholdPercentage(ResearchersDetailReqVO reqVO);
Integer visitHouseholdDelete(@Param("selectIds") List<Integer> selectIds,@Param("deletedBy") String deletedBy);
void deleteHouseholdResearcherMapping(@Param("researcherSeq") Integer researcherSeq, @Param("householdSeq") Integer householdSeq, @Param("deletedBy") String deletedBy);
Integer insertHouseholdResearcherMapping(@Param("researcherSeq") Integer researcherSeq, @Param("householdSeq") Integer householdSeq, @Param("createdBy") String createdBy);

View File

@@ -0,0 +1,14 @@
package app.module.admin.usecase.researcher.adpaters.persistence.model;
import lombok.Data;
@Data
public class VisitHouseholdPercentageDto {
private Integer totalHouseholdCount;
private Integer firstVisitCount;
private Integer secondVisitCount;
private Integer giftSentCount;
private Double firstVisitPercentage;
private Double secondVisitPercentage;
private Double giftSentPercentage;
}

View File

@@ -29,6 +29,11 @@ class ResearcherApiController {
return ResponseEntity.status(HttpStatus.OK).body(researcherPortIn.mappingHouseholdList(reqVO));
}
@GetMapping(path = "/visitHousehold/percentage")
ResponseEntity<?> selectVisitHouseholdPercentage( @ModelAttribute ResearchersDetailReqVO reqVO) {
return ResponseEntity.status(HttpStatus.OK).body(researcherPortIn.selectVisitHouseholdPercentage(reqVO));
}
@GetMapping(path = "/visitHousehold/list")
ResponseEntity<?> visitHouseholdList( @ModelAttribute ResearchersDetailReqVO reqVO) {
return ResponseEntity.status(HttpStatus.OK).body(researcherPortIn.visitHouseholdList(reqVO));

View File

@@ -14,5 +14,5 @@ public class ResearchersVisitDetailReqVO {
private String visitDate;
private ManagementType managementType;
private String content;
private String isGiftSentFlag;
private String isGiftSent;
}

View File

@@ -11,6 +11,7 @@ public interface ResearcherPortIn {
ResearchersDto detail(Integer adminSeq);
Page<ResearchersMappingHouseholdDto> mappingHouseholdList(ResearchersDetailReqVO reqVO);
Page<ResearchersHouseholdVisitDto> visitHouseholdList(ResearchersDetailReqVO reqVO);
VisitHouseholdPercentageDto selectVisitHouseholdPercentage(ResearchersDetailReqVO reqVO);
Integer updateVisitHousehold(ResearchersVisitDetailReqVO reqVO);
ResearchersHouseholdVisitPopUpDto visitHouseholdDetail(Integer id);
Integer visitHouseholdDelete(List<Integer> selectIds);

View File

@@ -10,6 +10,7 @@ public interface ResearcherPortOut {
Page<ResearchersDto> list(ResearchersListReqVO reqVO);
ResearchersDto detail(Integer adminSeq);
Page<ResearchersMappingHouseholdDto> mappingHouseholdList(ResearchersDetailReqVO reqVO);
VisitHouseholdPercentageDto selectVisitHouseholdPercentage(ResearchersDetailReqVO reqVO);
Page<ResearchersHouseholdVisitDto> visitHouseholdList(ResearchersDetailReqVO reqVO);
Integer updateVisitHousehold(ResearchersVisitDetailReqVO reqVO);
ResearchersHouseholdVisitPopUpDto visitHouseholdDetail(Integer id);

View File

@@ -35,6 +35,11 @@ class ResearcherService implements ResearcherPortIn {
return portOut.visitHouseholdList(reqVO);
}
@Override
public VisitHouseholdPercentageDto selectVisitHouseholdPercentage(ResearchersDetailReqVO reqVO) {
return portOut.selectVisitHouseholdPercentage(reqVO);
}
@Override
public Integer updateVisitHousehold(ResearchersVisitDetailReqVO reqVO) {
return portOut.updateVisitHousehold(reqVO);

View File

@@ -44,6 +44,7 @@
AND bat.household_seq = #{householdSeq}
AND bat.month = #{recordMonth}
AND bat.is_deleted = false
ORDER BY bat.created_at
</select>
<select id="getBankAutoTransferExpenseRecords"
@@ -78,5 +79,6 @@
AND bat.household_seq = #{householdSeq}
AND bat.month = #{recordMonth}
AND bat.is_deleted = false
ORDER BY bat.created_at
</select>
</mapper>

View File

@@ -30,8 +30,11 @@
di.source_purpose, /* 수입원(용도) */
di.quantity, /* 수량 */
di.unit_code, /* 단위 코드 */
ui_unit.code_text AS unit_text, /* 단위 코드 텍스트 */
di.unit_self, /* 단위(직접입력) */
CASE
WHEN di.unit_code = 'code.record.unit.self'
THEN di.unit_self
ELSE ui_unit.code_text
END AS unit_text, /* 단위 코드 텍스트 */
di.price, /* 현금 */
di.estimated_value, /* 현물평가액 */
di.updated_by, /* 최종수정자 */
@@ -45,32 +48,39 @@
AND ui_unit.id = di.unit_code
WHERE di.daily_record_seq = #{recordSeq}
AND di.is_deleted = false
ORDER BY di.created_at
</select>
<select id="getDailyWorkRecords"
resultType="app.module.admin.usecase.household.tab.dailyRecord.getDailyRecordStatusDetail.ports.application.domain.GetDailyWorkRecords">
/* getDailyWorkRecords : 일계부 등록 현황 상세 임업노동 투입 내역 조회 */
SELECT dw.id,
dw.item_name, /* 품목명 */
dw.work_name, /* 작업명*/
dw.work_land_area, /* 작업 면적 */
ui_area.code_text AS areaUnitCodeText, /* 작업면적 단위(코드매핑) */
dw.area_unit_self, /* 작업면적 단위(직접입력) */
dw.harvest_quantity, /* 수확량 */
ui_harvest.code_text AS harvestUnitCodeText, /* 수확량 단위 (코드매핑) */
dw.harvest_unit_self, /* 수확량 단위 (직접입력) */
dw.owner_time, /* 경영주 시간 */
dw.spouse_time, /* 배우자 시간 */
dw.family_m_hours, /* 가족노동(남) */
dw.family_f_hours, /* 가족노동(여) */
dw.hired_m_hours, /* 고용노동(남) */
dw.hired_f_hours, /* 고용노동(여) */
dw.shared_m_hours, /* 품앗이(남) */
dw.shared_f_hours, /* 품앗이(여) */
dw.volunteer_m_hours, /* 일손돕기(남) */
dw.volunteer_f_hours, /* 일손돕기(여) */
dw.updated_by, /* 최종수정자 */
dw.updated_at /* 최종수정날짜 */
dw.item_name, /* 품목명 */
dw.work_name, /* 작업명*/
dw.work_land_area, /* 작업 면적 */
CASE
WHEN dw.area_unit_code = 'code.record.unit.self'
THEN dw.area_unit_self
ELSE ui_area.code_text
END AS areaUnitText, /* 작업면적 단위 텍스트 */
dw.harvest_quantity, /* 수확량 */
CASE
WHEN dw.harvest_unit_code = 'code.record.unit.self'
THEN dw.harvest_unit_self
ELSE ui_harvest.code_text
END AS harvestUnitText, /* 수확량 단위 텍스트 */
dw.owner_time, /* 경영주 시간 */
dw.spouse_time, /* 배우자 시간 */
dw.family_m_hours, /* 가족노동(남) */
dw.family_f_hours, /* 가족노동(여) */
dw.hired_m_hours, /* 고용노동(남) */
dw.hired_f_hours, /* 고용노동(여) */
dw.shared_m_hours, /* 품앗이(남) */
dw.shared_f_hours, /* 품앗이(여) */
dw.volunteer_m_hours, /* 일손돕기(남) */
dw.volunteer_f_hours, /* 일손돕기(여) */
dw.updated_by, /* 최종수정자 */
dw.updated_at /* 최종수정날짜 */
FROM daily_work dw
LEFT JOIN uicode ui_area
ON ui_area.parent_id = 'code.record.unit'
@@ -80,6 +90,7 @@
AND ui_harvest.id = dw.harvest_unit_code
WHERE dw.daily_record_seq = #{recordSeq}
AND dw.is_deleted = false
ORDER BY dw.created_at
</select>
<select id="getDailyExpenseRecords"
@@ -92,8 +103,11 @@
de.source_purpose, /* 지출원(용도) */
de.quantity, /* 수량 */
de.unit_code, /* 단위 */
ui_unit.code_text AS unit_text, /* 단위 코드 텍스트 */
de.unit_self, /* 단위(직접입력) */
CASE
WHEN de.unit_code = 'code.record.unit.self'
THEN de.unit_self
ELSE ui_unit.code_text
END AS unit_text, /* 단위 코드 텍스트 */
de.price, /* 현금 */
de.estimated_value, /* 현물평가액 */
de.updated_by, /* 최종수정자 */
@@ -104,6 +118,7 @@
AND ui_unit.id = de.unit_code
WHERE de.daily_record_seq = #{recordSeq}
AND de.is_deleted = false
ORDER BY de.created_at
</select>
<select id="getDailyPowerRecords"
@@ -118,6 +133,7 @@
FROM daily_power dp
WHERE dp.daily_record_seq = #{recordSeq}
AND dp.is_deleted = false
ORDER BY dp.created_at
</select>
<select id="getDailyForestryRecords"
@@ -128,7 +144,11 @@
df.usage, /* 용도 */
df.quantity, /* 수량 */
df.unit_code, /* 단위 코드 */
ui_unit.code_text AS unit_text, /* 단위 코드 텍스트 */
CASE
WHEN df.unit_code = 'code.record.unit.self'
THEN df.unit_self
ELSE ui_unit.code_text
END AS unit_text, /* 단위 코드 텍스트 */
df.estimated_value, /* 현물평가액 */
df.updated_by, /* 최종수정자 */
TO_CHAR(df.updated_at, 'YYYY-MM-DD HH24:MI') AS updated_at /* 최종수정날짜 */
@@ -138,6 +158,7 @@
AND ui_unit.id = df.unit_code
WHERE df.daily_record_seq = #{recordSeq}
AND df.is_deleted = false
ORDER BY df.created_at
</select>
<select id="getDailyFarmingRecords"
@@ -145,14 +166,17 @@
/* getDailyFarmingRecords : 일계부 등록 현황 상세 자가농업 생산물 중 자가소비량 조회 */
SELECT df.id, /* 자가농업 id */
CASE
WHEN df.product_self is not null
WHEN df.product_code = 'code.record.farming.self'
THEN df.product_self
ELSE ui_product.code_text
END AS product_name, /* 생산물명 */
df.usage, /* 용도 */
df.quantity, /* 수량 */
df.unit_code, /* 단위 코드 */
ui_unit.code_text AS unit_text, /* 단위 코드 텍스트 */
CASE
WHEN df.unit_code = 'code.record.unit.self'
THEN df.unit_self
ELSE ui_unit.code_text
END AS unit_text, /* 단위 코드 텍스트 */
df.estimated_value, /* 현물평가액 */
df.updated_by, /* 최종수정자 */
TO_CHAR(df.updated_at, 'YYYY-MM-DD HH24:MI') AS updated_at /* 최종수정날짜 */
@@ -165,6 +189,7 @@
AND ui_unit.id = df.unit_code
WHERE df.daily_record_seq = #{recordSeq}
AND df.is_deleted = false
ORDER BY df.created_at
</select>
</mapper>

View File

@@ -68,5 +68,6 @@
WHERE df.household_seq = #{householdSeq}
AND df.month = #{recordMonth}
AND df.is_deleted = false
ORDER BY df.created_at
</select>
</mapper>

View File

@@ -16,5 +16,7 @@
FROM household_visit hv
WHERE household_seq = #{householdSeq}
AND TO_CHAR(visit_date, 'YYYYMM') = #{recordMonth}
AND hv.is_deleted = false
ORDER BY hv.created_at
</select>
</mapper>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper
namespace="app.module.admin.usecase.household.tab.householdVisit.removeHouseholdVisitInfos.adapters.persistence.RemoveHouseholdVisitInfosMapper">
<update id="removeHouseholdVisitInfos">
/* removeHouseholdVisitInfos : 임가방문정보 삭제 */
UPDATE household_visit
SET <include refid="common.fields.DeleteBaseSet"/>
WHERE id IN
<foreach collection="removeIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
</mapper>

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper
namespace="app.module.admin.usecase.household.tab.householdVisit.saveHouseholdVisitInfo.adapters.persistence.SaveHouseholdVisitInfoMapper">
<insert id="createHouseholdVisitInfo">
/* createHouseholdVisitInfo : 임가방문정보 등록 */
INSERT INTO household_visit
(
household_seq,
visit_date,
management_type,
is_gift_sent,
content,
<include refid="common.fields.CreateUpdateBaseColumns"/>
)
VALUES
(
#{householdSeq},
#{visitDate},
#{managementType},
#{isGiftSent},
#{content},
<include refid="common.fields.CreateUpdateBaseValues"/>
)
</insert>
<update id="updateHouseholdVisitInfo">
/* updateHouseholdVisitInfo : 임가방문정보 수정 */
UPDATE household_visit
SET
visit_date = #{visitDate},
management_type = #{managementType},
is_gift_sent = #{isGiftSent},
content = #{content},
<include refid="common.fields.UpdateBaseSet"/>
WHERE id = #{visitInfoId}
</update>
<select id="findById" resultType="java.lang.Long">
/* findById : 임가방문정보 조회 */
SELECT id
FROM household_visit
WHERE id = #{id}
AND is_deleted = false
</select>
</mapper>

View File

@@ -7,13 +7,15 @@
<insert id="insert" parameterType="app.module.core.config.adapters.persistence.entity.LoggedInUser">
INSERT INTO logged_in_user
(
app_type,
id,
app_type,
login_id,
clientip,
last_logged_in_at
)
VALUES
(
nextval('logged_in_user_seq'),
#{appType},
#{id},
#{clientIP},
@@ -27,7 +29,7 @@
clientip = #{clientIP},
last_logged_in_at = #{lastLoggedInAt}
WHERE app_type = #{appType}
AND id = #{id}
AND login_id = #{id}
</update>
</mapper>

View File

@@ -121,9 +121,8 @@
case rhv.is_gift_sent when false then '전달완료' when true then '-' end is_gift_sent_flag,
rhv.created_at
from household_visit rhv
join researcher_has_household rhh on rhh.household_seq = rhv.household_seq
join household h on rhh.household_seq = h.seq
join admin a on a.seq = rhh.admin_seq
join household h on rhv.household_seq = h.seq
join researcher_has_household rhh on rhh.household_seq = h.seq and rhh.is_deleted = false
where rhv.is_deleted = false
<if test="seq > 0">
and rhh.admin_seq = #{seq}
@@ -134,6 +133,66 @@
LIMIT #{size} OFFSET #{page}*#{size}
</select>
<select id="selectVisitHouseholdPercentage">
with visit_ranking AS (
select
hv.household_seq,
hv.visit_date,
hv.is_gift_sent,
ROW_NUMBER() OVER (PARTITION BY hv.household_seq ORDER BY hv.visit_date ASC) AS visit_rank
from household_visit hv
where TO_CHAR(hv.visit_date, 'YYYYMM') = #{searchMonth}
and hv.is_deleted = FALSE
),
visit_counts AS (
select
COUNT(DISTINCT CASE WHEN vr.visit_rank = 1 THEN vr.household_seq END) AS first_visit_count,
COUNT(DISTINCT CASE WHEN vr.visit_rank = 2 THEN vr.household_seq END) AS second_visit_count,
COUNT(DISTINCT CASE WHEN vr.is_gift_sent = true THEN vr.household_seq END) AS gift_sent_count
from researcher_has_household rhh
left join visit_ranking vr ON rhh.household_seq = vr.household_seq
where rhh.is_deleted = false
and rhh.admin_seq = #{seq}
),
total_households AS (
select COUNT(DISTINCT rhh.household_seq) AS total_household_count
from researcher_has_household rhh
where rhh.is_deleted = false
AND rhh.admin_seq = #{seq}
)
SELECT
th.total_household_count ,
vc.first_visit_count,
vc.second_visit_count,
vc.gift_sent_count,
ROUND(
CASE
WHEN th.total_household_count > 0
THEN (vc.first_visit_count::NUMERIC / th.total_household_count) * 100
ELSE 0
END,
2
) AS first_visit_percentage,
ROUND(
CASE
WHEN th.total_household_count > 0
THEN (vc.second_visit_count::NUMERIC / th.total_household_count) * 100
ELSE 0
END,
2
) AS second_visit_percentage,
ROUND(
CASE
WHEN th.total_household_count > 0
THEN (vc.gift_sent_count::NUMERIC / th.total_household_count) * 100
ELSE 0
END,
2
) AS gift_sent_percentage
FROM total_households th
CROSS JOIN visit_counts vc
</select>
<select id="visitHouseholdListCountAll">
select count(*)
from household_visit rhv

View File

@@ -37,7 +37,7 @@ uri.admin.household.households.view.{{pathVar}}=\uC784\uAC00 \uC0C1\uC138
uri.admin.researcher=\uC870\uC0AC\uC6D0 \uD604\uD669
uri.admin.researcher.researchers=\uC870\uC0AC\uC6D0 \uD604\uD669
uri.admin.researcher.researchers.create=\uC870\uC0AC\uC6D0 \uB4F1\uB85D
uri.admin.researcher.researchers.view.{{pathVar}}=\uC870\uC0AC\uC6D0 \uC0C1\uC138
uri.admin.researcher.{{pathVar}}=\uC870\uC0AC\uC6D0 \uC0C1\uC138
uri.admin.dashboard=\uB300\uC2DC\uBCF4\uB4DC
uri.admin.dashboard.overview=\uB300\uC2DC\uBCF4\uB4DC

View File

@@ -0,0 +1,6 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="2.75" y="3.75" width="14.5" height="12.5" rx="1.25" stroke="#212529" stroke-width="1.5"/>
<path d="M3 7H17" stroke="#212529" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6 2.4668V4.89148" stroke="#212529" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 2.4668V4.89148" stroke="#212529" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 532 B

File diff suppressed because one or more lines are too long

View File

@@ -4704,6 +4704,9 @@ button.swiper-pagination-bullet {
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
gap: 0.8rem;
}
@@ -4827,7 +4830,7 @@ input[type=number] {
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
height: 16rem;
height: 32rem;
border: 1px solid gainsboro;
background-color: #ffffff;
overflow: hidden;
@@ -4984,6 +4987,96 @@ input[type=number] {
color: red;
}
.input-file-group input {
display: none;
}
.input-file-group .file-txt {
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-webkit-justify-content: center;
justify-content: center;
width: 8rem;
height: 3.6rem;
background-color: #495057;
color: #FFFFFF;
font-size: 1.5rem;
font-weight: 600;
border-radius: 0.4rem;
}
.input-file-group .desc {
margin-top: 0.8rem;
display: block;
text-align: left;
font-size: 1.4rem;
color: #868E96;
}
.input-file-group .file-list {
margin-top: 1.6rem;
text-align: left;
}
.input-file-group .file-list li {
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
}
.input-file-group .file-list li .btn-delete {
margin-left: 0.4rem;
padding: 0;
width: 1.6rem;
height: 1.6rem;
background-image: url("../images/common/ico_close_white.svg");
background-color: #CED4DA;
background-repeat: no-repeat;
background-size: 10px 10px;
background-position: center;
border-radius: 0.2rem;
}
.input-file-group .file-list li + li {
margin-top: 0.8rem;
}
input[type=datetime-local] {
position: relative;
background: url("../images/common/ico_calendar.svg") no-repeat right 16px center/20px auto;
}
input[type=datetime-local]::-webkit-calendar-picker-indicator {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: transparent;
color: transparent;
cursor: pointer;
}
.date-range-group {
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
gap: 0.6rem;
}
.date-range-group .component-input {
width: -webkit-fit-content !important;
width: -moz-fit-content !important;
width: fit-content !important;
}
.date-range-group .component-input .input-field {
width: 23rem;
}
/* component checkbox */
.component-input {
/* component checkbox switch */
@@ -6637,6 +6730,9 @@ input[type=number] {
width: 14rem;
}
.filter-wrap .component-btns {
min-width: -webkit-max-content;
min-width: -moz-max-content;
min-width: max-content;
margin-top: auto;
}
.filter-wrap .btn {
@@ -6677,6 +6773,14 @@ input[type=number] {
-webkit-justify-content: space-between;
justify-content: space-between;
}
.table-group .table-tit-group.large {
margin-bottom: 2.4rem;
}
.table-group .table-tit-group.large h3 {
font-size: 2.4rem;
font-weight: 700;
color: #212529;
}
.table-group .table-tit-group h3 {
display: -webkit-box;
display: -webkit-flex;
@@ -6696,6 +6800,9 @@ input[type=number] {
.table-group .table-tit-group .bottom-btn-group {
margin-top: 0;
}
.table-group .table-tit-group .component-select {
width: 14rem;
}
table {
table-layout: fixed;
@@ -6708,6 +6815,9 @@ table a {
table th {
background-color: #f1f3f5 !important;
}
table tr.total {
background-color: #F1F3F5;
}
table .align-right {
text-align: right;
}
@@ -7181,6 +7291,8 @@ table tbody th {
justify-content: space-between;
}
.dounut-chart-area .chart-group {
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
display: -webkit-box;
display: -webkit-flex;
display: flex;
@@ -7193,6 +7305,18 @@ table tbody th {
flex: 1;
background-color: #ffffff;
}
.dounut-chart-area .chart-group.type-green .donut-chart {
background: conic-gradient(#95BA45 -webkit-calc(var(--percent) * 1%), #E9ECEF 0%);
background: conic-gradient(#95BA45 calc(var(--percent) * 1%), #E9ECEF 0%);
}
.dounut-chart-area .chart-group.type-blue .donut-chart {
background: conic-gradient(#00B09B -webkit-calc(var(--percent) * 1%), #E9ECEF 0%);
background: conic-gradient(#00B09B calc(var(--percent) * 1%), #E9ECEF 0%);
}
.dounut-chart-area .chart-group.type-orange .donut-chart {
background: conic-gradient(#FD9E01 -webkit-calc(var(--percent) * 1%), #E9ECEF 0%);
background: conic-gradient(#FD9E01 calc(var(--percent) * 1%), #E9ECEF 0%);
}
.dounut-chart-area .chart-group dl {
color: #212529;
}
@@ -7211,16 +7335,18 @@ table tbody th {
margin-top: 3.2rem;
}
.dounut-chart-area .chart-group dl dd .percent {
margin-right: 2rem;
position: relative;
display: block;
font-size: 5.6rem;
font-weight: 700;
letter-spacing: -1px;
}
.dounut-chart-area .chart-group dl dd .percent::after {
position: absolute;
content: "%";
display: block;
right: -1.8rem;
right: -3.5rem;
top: 0;
}
.dounut-chart-area .chart-group dl dd .d-flex {
@@ -7231,16 +7357,22 @@ table tbody th {
.donut-chart {
--percent: 75;
width: 160px;
height: 160px;
min-width: 16rem;
min-height: 16rem;
width: 16rem;
height: 16rem;
border-radius: 50%;
background: conic-gradient(#95BA45 -webkit-calc(75 * 1%), #E9ECEF 0%);
background: conic-gradient(#95BA45 calc(75 * 1%), #E9ECEF 0%);
background: conic-gradient(#95BA45 -webkit-calc(var(--percent) * 1%), #E9ECEF 0%);
background: conic-gradient(#95BA45 calc(var(--percent) * 1%), #E9ECEF 0%);
background: conic-gradient(#95ba45 0 -webkit-calc(75 * 1%), #e9ecef 0);
background: conic-gradient(#95ba45 0 calc(75 * 1%), #e9ecef 0);
position: relative;
}
@supports (background: conic-gradient(red 0deg, red 0deg 1deg, red 2deg)){
.donut-chart {
background: conic-gradient(#95ba45 0 -webkit-calc(var(--percent) * 1%), #e9ecef 0);
background: conic-gradient(#95ba45 0 calc(var(--percent) * 1%), #e9ecef 0);
}
}
.donut-chart::before {
content: "";
position: absolute;
@@ -7253,6 +7385,100 @@ table tbody th {
background: #fff;
border-radius: 50%;
}
.donut-chart::after {
content: "";
position: absolute;
top: 0;
left: 50%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
width: 0.2rem;
height: 3.5rem;
background: #ffffff;
}
.donut-chart .end-line {
content: "";
position: absolute;
top: 0;
left: 50%;
-webkit-transform: translateX(-50%) rotate(-webkit-calc(var(--percent) * 3.6deg));
transform: translateX(-50%) rotate(calc(var(--percent) * 3.6deg));
-webkit-transform-origin: center 80px;
transform-origin: center 80px;
width: 0.2rem;
height: 3.5rem;
background: #ffffff;
}
.progress-group {
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-webkit-justify-content: center;
justify-content: center;
gap: 2.4rem;
}
.progress-group.type-green .progress::-webkit-progress-value {
background: #95BA45;
border-radius: 0px;
}
.progress-group.type-blue .progress::-webkit-progress-value {
background: #00B09B;
border-radius: 0px;
}
.progress-group.type-orange .progress::-webkit-progress-value {
background: #FD9E01;
border-radius: 0px;
}
.progress-group .progress {
-webkit-box-flex: 1;
-webkit-flex: 1;
flex: 1;
width: 100%;
max-width: 20rem;
height: 0.8rem;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.progress-group .progress::-webkit-progress-bar {
background: #E9ECEF;
border-radius: 12px;
height: 0.8rem;
overflow: hidden;
}
.progress-group .progress::-webkit-progress-value {
background: #95BA45;
border-radius: 0px;
}
.progress-group .detail {
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
}
.progress-group .detail .percent {
position: relative;
padding-right: 1.3rem;
margin-right: 0.4rem;
}
.progress-group .detail .percent::after {
position: absolute;
content: "%";
display: block;
right: 0;
top: 0;
}
.progress-group .detail .d-flex {
gap: 0.2rem;
}
/* https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css */
table.dataTable td.dt-control {

File diff suppressed because one or more lines are too long

View File

@@ -211,7 +211,9 @@ uiUtil.uploadFile = (fileUploadType, input) => {
return;
}
const inputGroup = $(input).parent('.input-group');
const inputGroup = $(input).parent().parent().find('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 uiUtil.uploadFile 메서드를 실행할 수 있습니다.`);
@@ -246,11 +248,11 @@ uiUtil.uploadFile = (fileUploadType, input) => {
inputGroup.find('.invalid-feedback').text('');
// 기존 mappingId 가 있다면 초기화
inputGroup.find('input[name=fileMappingId]').remove();
/* inputGroup.find('input[name=fileMappingId]').remove();*/
// 신규 mappingId 추가
/* // 신규 mappingId 추가
inputGroup.append(
`<input type="hidden" name="fileMappingId" value="${res.id}"/>`);
`<input type="hidden" name="fileMappingId" value="${res.id}"/>`);*/
// 업로드 파일 정보 보이기
uiUtil.showFileInfo(input, res, $(input).attr('accept') === 'image/*');
@@ -274,18 +276,16 @@ uiUtil.uploadFile = (fileUploadType, input) => {
* @param {boolean} showImg 미리보기 이미지 노출 여부
*/
uiUtil.showFileInfo = (input, uploadFile, showImg) => {
const inputGroup = $(input).parent('.input-group');
const inputGroup = $(input).parent().parent().find('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 showFileInfo 메서드를 실행할 수 있습니다.`);
return;
}
inputGroup.find('.fileInfo').remove();
/* inputGroup.find('.fileInfo').remove();*/
inputGroup.append(`
/* inputGroup.append(`
<div class="fileInfo row text-muted fw-normal" style="display: none">
<img src="${showImg ? uploadFile.referURL : ''}" class="w-75 mt-3 mb-3"/>
<ul class="row" style="margin-left: 10px;">
@@ -295,31 +295,28 @@ uiUtil.showFileInfo = (input, uploadFile, showImg) => {
<li class="id">File ID (${uploadFile.id})<span class="btn-sm btn-link fw-bold resetFile" style="cursor:pointer;">삭제</span> </li>
</ul>
</div>
`);
`);*/
inputGroup.append(`
<li class="fileInfo" style="display: none;">
<p><a href="${uploadFile.attachmentURL}">${uploadFile.originName}(${Math.ceil(uploadFile.fileLength / 1024)}KB)</a></p>
<button type="button" class="btn-delete resetFile"><span class="hide-txt ">삭제</span></button>
<input type="hidden" name="fileMappingId" value="${uploadFile.id}" />
</li>`);
const fileInfo = inputGroup.find('.fileInfo');
if (!showImg) {
/* if (!showImg) {
fileInfo.find('img').remove();
}
}*/
// 파일 삭제 함수 정의
inputGroup.find('.resetFile').on('click', () => {
let fileInput = inputGroup.find('input[type=file]');
fileInput.replaceWith(`
<input type="file"
id="${fileInput.attr('id')}"
class="${fileInput.attr('class')}"
accept="${fileInput.attr('accept')}"
name="${fileInput.attr('name')}"
onchange="${fileInput.attr('onchange')}">
`);
inputGroup.find('input[name=fileMappingId]').remove();
inputGroup.find('.fileInfo').fadeOut((evt) => {
$(evt.target).remove();
inputGroup.find('.resetFile').on('click', function () {
const $fileInfo = $(this).closest('.fileInfo');
$fileInfo.fadeOut(function () {
$(this).remove();
});
return false;
});

View File

@@ -105,7 +105,7 @@
<!-- 자식 children 가 있는 경우 -->
<th:block th:if="${#lists.size(menu.children) > 0}">
<a th:href="${menu.uri}" th:text="${#messages.msg(menu.id)}">메뉴명</a>
<a href="#" th:text="${#messages.msg(menu.id)}" >메뉴명</a>
<th:block th:insert="~{this :: subMenuFrag}"
th:with="subMenus = ${menu.children}, addSubMenuClass = false">
</th:block>
@@ -133,7 +133,7 @@
</ul>
<div class="header-right">
<p class="user"><strong sec:authentication="name">로그인 사용자명</strong>님 안녕하세요</p>
<span class="user-ip">111.11.111.111</span>
<span class="user-ip" th:text="${@adminUtil.getLoginUserLastIp}">111.11.111.111</span>
<button class="btn-logout" onclick="location.href='/logout'">로그아웃</button>
</div>
</div>

View File

@@ -10,11 +10,11 @@
<div class="modal-header">
<h3 class="modal-tit" >임가 매핑</h3>
</div>
<div class="modal-content">
<div class="modal-content-inner">
<section class="filter-wrap">
<div class="form-area">
<form autocomplete="off" method="get" name="reqHouseholdForm" id="reqHouseholdForm">
<form autocomplete="off" method="get" name="reqHouseholdForm" id="reqHouseholdForm">
<div class="modal-content">
<div class="modal-content-inner">
<section class="filter-wrap">
<div class="form-area">
<input type="hidden" name="page" th:field="*{reqVO.page}"/>
<input type="hidden" name="researcherSeq" id="researcherSeq" th:value="${researcherSeq}">
<input type="hidden" name="regionMainCode" th:value="${regionMainCode}">
@@ -89,54 +89,55 @@
</div>
</div>
</div>
</form>
</div>
<div class="component-btns">
<div class="btns-row">
<button type="button" class="btn" onclick="resetSearchForm()">
<span class="btn-txt">초기화</span>
</button>
<button type="button" class="btn btn-primary" th:onclick="|searchHouseholdList(0,${regionMainCode})|">
<span class="btn-txt">검색</span>
</button>
</div>
</div>
</section>
<section>
<p class="input-label" style="font-size: 16px;">
총 <span id="mappingHouseholdTotalElements"></span>건
</p>
<table id="householdTable">
<thead>
<tr>
<th>선택</th>
<th>임가번호</th>
<th>경영주명</th>
<th>휴대폰번호</th>
<th>실사</th>
<th>지역</th>
<th>세부지역</th>
<th>조사원</th>
</tr>
</thead>
<tbody id="mappingHousehold-list"></tbody>
</table>
<!-- 페이지네이션 -->
<div class="row paging"></div>
<!-- 등록 버튼 -->
<div class="component-btns bottom-btn-group" th:fragment="modalButtons">
<div class="btns-row align-right">
<button type="button" class="btn btn-primary" onclick="registerHouseholds()">
<span class="btn-txt">등록</span>
</button>
</div>
</div>
</section>
<div class="component-btns">
<div class="btns-row">
<button type="button" class="btn" onclick="resetSearchForm()">
<span class="btn-txt">초기화</span>
</button>
<button type="button" class="btn btn-primary" th:onclick="|searchHouseholdList(0,${regionMainCode})|">
<span class="btn-txt">검색</span>
</button>
</div>
</div>
</section>
<section>
<p class="input-label" style="font-size: 16px;">
총 <span id="mappingHouseholdTotalElements"></span>건
</p>
<table id="householdTable">
<thead>
<tr>
<th>선택</th>
<th>임가번호</th>
<th>경영주명</th>
<th>휴대폰번호</th>
<th>실사</th>
<th>지역</th>
<th>세부지역</th>
<th>조사원</th>
</tr>
</thead>
<tbody id="mappingHousehold-list"></tbody>
</table>
<!-- 페이지네이션 -->
<div class="row paging"></div>
<!-- 등록 버튼 -->
<div class="component-btns bottom-btn-group" th:fragment="modalButtons">
<div class="btns-row align-right">
<button type="button" class="btn btn-primary" onclick="registerHouseholds()">
<span class="btn-txt">등록</span>
</button>
</div>
</div>
</section>
</div>
<button class="modal-close"></button>
</div>
<button class="modal-close"></button>
</div>
</form>
</div>
</div>
</div>

View File

@@ -14,11 +14,11 @@
<tr>
<th>제목<i class="ico-required-mark" role="img" aria-label="필수">*</i></th>
<td colspan="3">
<div class="component-input">
<div class="input-field">
<input type="text" name="title" id="title" placeholder="">
</div>
<div class="component-input">
<div class="input-field">
<input type="text" name="title" id="title" placeholder="">
</div>
</div>
</td>
</tr>
<tr>
@@ -28,20 +28,28 @@
</td>
</tr>
<tr>
<th>첨부파일<i class="ico-required-mark" role="img" aria-label="필수">*</i></th>
<th>첨부파일</th>
<td colspan="3">
<div class="input-file-group">
<label for="file" class="input-file-btn">
<input type="file" name="multipartAttachments" id="file" onchange="uiUtil.uploadFile('NOTICE', this);" >
<span class="file-txt">파일첨부</span>
</label>
<p class="desc">첨부 가능 파일 형식: 문서(pdf, docx, xlsx, pptx, hwp), 이미지(jpg, jpeg, png, gif), 기타(zip,
csv, txt) / 파일당 최대 5MB까지 등록 가능합니다.</p>
<ul class="file-list input-group" id="noticeAttachments">
</ul>
</div>
</td>
<!-- <td colspan="3">
<div class="btns-row align-left publicFileInputs">
<button type="button" class="btn btn-secondary" onclick="addFileInput();">
<span class="btn-txt">다건 파일 첨부</span>
</button>
</div>
</td>
</td>-->
</tr>
<tr>
<th>게시기간<i class="ico-required-mark" role="img" aria-label="필수">*</i></th>
<td colspan="2">
@@ -57,11 +65,9 @@
</div>
</div>
</div>
</td>
<td></td>
</tr>
<tr>
<th>노출여부<i class="ico-required-mark" role="img" aria-label="필수">*</i></th>
<td>
@@ -75,8 +81,6 @@
<td></td>
<td></td>
</tr>
</tbody>
</table>
@@ -102,7 +106,6 @@
<script th:inline="javascript">
$(".flatpickr").flatpickr({
dateFormat: "Y-m-d\\TH:i",
// altInput: true,
@@ -111,6 +114,7 @@
enableTime: true,
time_24hr: true
});
</script>
<script th:inline="javascript">
@@ -120,13 +124,11 @@
history.back();
}
const gotoList = () => {
location.href = '/communication/notices';
}
function addFileInput() {
/* function addFileInput() {
const inputGroup = $(`
<div class="input-group w-50">
<input class="form-control mb-2" type="file" name="multipartAttachments"
@@ -142,7 +144,7 @@
return inputGroup;
}
*/
const getNotice = () => {
const f = document.reqForm;
@@ -167,11 +169,10 @@
f.visible.value = res.visible;
res.uploadFiles.forEach((uploadFile) => {
let inputGroup = addFileInput();
inputGroup.append(`<input type="hidden" name="fileMappingId" value="${uploadFile.id}"/>`);
uiUtil.showFileInfo(inputGroup.find('input[type=file]'), uploadFile, false);
let inputGroup = $('#noticeAttachments');
/* let inputGroup = addFileInput();
inputGroup.append(`<input type="hidden" name="fileMappingId" value="${uploadFile.id}"/>`);*/
uiUtil.showFileInfo(inputGroup, uploadFile, false);
});
}
});
@@ -180,9 +181,6 @@
// 상세정보 얻기
getNotice();
const goSave = () => {
const f = document.reqForm;

View File

@@ -380,7 +380,8 @@
// 현재 로그인한 유저의 역할
const isResearcher = f.userRole.value === 'ROLE_RESEARCHER';
const colspanLength = isResearcher ? 13 : 15;
// const colspanLength = isResearcher ? 13 : 15; <!-- TODO : 2차 오픈 -->
const colspanLength = isResearcher ? 10 : 12;
// 조사원일 경우 조사원이름, 번호 칼럼 hide
$('.hide-role-researcher').toggle(!isResearcher);

View File

@@ -4,8 +4,8 @@
<div class="layer-wrap" th:fragment="modalFragment">
<form autocomplete="off" method="get" name="reqVisitForm">
<input name="page" value="0" type="hidden"/>
<input name="size" value="10" type="hidden">
<input type="hidden" name="visitInfoId">
<input type="hidden" name="householdSeq">
<div class="component-modal mypage-wrap modal01 modal-visit-info" data-props-dimm-click="true" data-state="close">
<div class="modal-dimm"></div>
@@ -18,7 +18,7 @@
</div>
<div class="modal-content">
<div class="modal-content-inner">
<table class="type-form">
<table class="type-form confirm">
<tbody>
<tr>
@@ -90,7 +90,7 @@
<div class="component-btns bottom-btn-group">
<div class="btns-row align-right">
<button type="button" class="btn btn-primary" onclick="">
<button type="button" class="btn btn-primary" onclick="goVisitInfoSave();">
<span class="btn-txt">등록</span>
</button>
</div>
@@ -106,27 +106,34 @@
</form>
<script th:inline="javascript">
// form 초기화
const resetForm = () => {
const form = document.forms['reqVisitForm'];
const form = document.reqVisitForm;
if (!form) return;
const today = new Date().toISOString().slice(0, 10);
form.visitDate.value = today;
form.visitInfoId.value = '';
form.managementType.value = '';
form.content.value = '';
document.getElementById('isGiftSent_N').checked = true;
if (datepickerInstance) {
datepickerInstance.setDate(new Date(), { render: true });
}
}
</script>
<script th:inline="javascript">
// 임가방문정보 모달창 띄우기
const showVisitInfoModal = (id) => {
document.querySelector(".modal-visit-info").ui.open();
const f = document.reqVisitForm;
f.householdSeq.value = householdSeq;
resetForm();
if(id != null) {
f.visitInfoId.value = id;
ajaxUtil._ajaxMethod(
'/api/visitInfo/' + id,
`/api/visitInfo/${id}`,
{},
(response) => {
console.log("임가방문정보 상세 응답값 : ", response);
@@ -139,21 +146,77 @@
'json'
);
}
document.querySelector(".modal-visit-info").ui.open();
}
// 임가방문정보 상세 값 set
const setFormData = (data) => {
const form = document.forms['reqVisitForm'];
const form = document.reqVisitForm;
if (!form) return;
// 폼에 값 세팅
form.visitDate.value = data.visitDate || '';
form.managementType.value = data.managementType || '';
form.content.value = data.content || '';
// 라디오 버튼 처리
document.getElementById('isGiftSent_Y').checked = data.isGiftSent === true;
document.getElementById('isGiftSent_N').checked = data.isGiftSent === false;
// 날짜 세팅
if (datepickerInstance && data.visitDate) {
datepickerInstance.setDate(new Date(data.visitDate), { render: true });
}
}
</script>
<script>
// 임가방문정보 등록
const goVisitInfoSave = () => {
const f = document.reqVisitForm;
let dataOj = $(f).serializeObject();
console.log("dataOj", dataOj);
ajaxUtil._ajaxMethod(
'/api/visitInfo/save',
JSON.stringify(dataOj),
(response) => { // 성공
alert("등록이 완료되었습니다.");
document.querySelector(".modal-visit-info").ui.close();
getVisitInfo(0);
},
function (code, rstData) {
if(code == 422) alert(rstData.responseText);
if(code == 400) alert(rstData.responseJSON.message); //임가번호 중복체크
},
'post',
'json',
{ handle422Type: 'alert' }
);
}
</script>
<script>
let datepickerInstance = null;
document.addEventListener('DOMContentLoaded', function () {
const $el = document.querySelector('.component-datepicker');
const datepicker = etUI.components.DatepickerComp();
datepicker.core.init($el, {
dateSelectCallback: function (selectedDate) {
console.log('선택된 날짜:', selectedDate);
}
});
datepickerInstance = datepicker.getDatepickerInstance();
// 초기 상태 오늘 날짜로
if (datepickerInstance) {
datepickerInstance.setDate(new Date(), { render: true });
}
});
</script>
</div>
</html>

View File

@@ -0,0 +1,175 @@
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{layout/layout}">
<div class="layer-wrap" th:fragment="tabFragment">
<div class="tab-content bank-auto-transfer" data-tab-value="tab3">
<div class="content-inner">
<div class="content-inner">
<!-- 수입 -->
<section class="table-group">
<div class="table-tit-group">
<h3>수입 <strong>(<span id="bankIncomeCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group">
<div class="btns-row align-right">
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-bank-income">
<thead>
<tr>
<th>선택</th>
<th>재배형태</th>
<th>수입의 종류</th>
<th>대상</th>
<th>수입원</th>
<th>수량</th>
<th>단위</th>
<th>현금(원)</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<!-- 지출 -->
<section class="table-group">
<div class="table-tit-group">
<h3>지출 <strong>(<span id="bankExpenseCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group">
<div class="btns-row align-right">
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-bank-expense">
<thead>
<tr>
<th>선택</th>
<th>지출의 종류</th>
<th>용도</th>
<th>수량</th>
<th>단위</th>
<th>현금(원)</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
</div>
</div>
</div>
<script th:inline="javascript">
// 은행자동이체내역 조회
const getBankAutoTransfer = () => {
const f = document.reqForm;
ajaxUtil._ajaxMethod(
'/api/household/bankAutoTransfer',
{
householdSeq: f.householdSeq.value,
recordMonth: f.recordMonth.value
},
(response) => { // 성공
console.log("은행자동이체내역 조회 : ", response);
gridBankIncomeTable(response.incomes);
gridBankExpenseTable(response.expenses);
},
function (code, rstData) { // 실패
console.log("error : ", code);
},
'get',
'json'
);
}
// 은행자동이체내역 수입 테이블 그리기
const gridBankIncomeTable = (data) => {
const tbody = $('#table-bank-income tbody');
tbody.empty();
$('#bankIncomeCount').text(data.length);
if(data.length === 0) {
tbody.append(`<tr><td colspan="8" style="text-align: center;">등록된 내용이 없습니다.</td></tr>`);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td>${ifNullHyphen(item.cropText)}</td> <!-- 재배형태 -->
<td class="underline">${ifNullHyphen(item.categoryText)}</td> <!-- 수입의 종류 -->
<td>${ifNullHyphen(item.target)}</td><!-- 대상 -->
<td>${ifNullHyphen(item.sourcePurpose)}</td><!-- 수입원 -->
<td class="align-right">${ifNullHyphen(item.count)}</td><!-- 수량 -->
<td>${ifNullHyphen(item.unitText)}</td><!-- 단위 -->
<td class="align-right">${formatNumberWithComma(item.price)}</td><!-- 현금(원) -->
</tr>
`;
});
tbody.append(tmpl);
}
// 은행자동이체내역 수출 테이블 그리기
const gridBankExpenseTable = (data) => {
const tbody = $('#table-bank-expense tbody');
tbody.empty();
$('#bankExpenseCount').text(data.length);
if(data.length === 0) {
tbody.append(`<tr><td colspan="6" style="text-align: center;">등록된 내용이 없습니다.</td></tr>`);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td class="underline">${ifNullHyphen(item.categoryText)}</td> <!-- 지출의 종류 -->
<td>${ifNullHyphen(item.sourcePurpose)}</td><!-- 용도 -->
<td class="align-right">${ifNullHyphen(item.count)}</td><!-- 수량 -->
<td>${ifNullHyphen(item.unitText)}</td><!-- 단위 -->
<td class="align-right">${formatNumberWithComma(item.price)}</td><!-- 현금(원) -->
</tr>
`;
});
tbody.append(tmpl);
}
</script>
</div>
</html>

View File

@@ -0,0 +1,642 @@
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{layout/layout}">
<div class="layer-wrap" th:fragment="tabFragment">
<div class="tab-content daily-record" data-tab-value="tab1" >
<!-- 일계부 등록 현황 리스트 -->
<div class="daily-record-content daily-record-list">
<div class="content-inner">
<article class="summary-area">
<ul>
<li>
<p>작성완료</p>
<span><strong id="doneCount">6</strong>건</span>
</li>
<li>
<p>미작성</p>
<span><strong id="emptyCount">6</strong>건</span>
</li>
<li>
<p>미완료</p>
<span><strong id="incompleteCount">6</strong>건</span>
</li>
<li>
<p>대기</p>
<span><strong id="waitingCount">6</strong>건</span>
</li>
<li>
<p>완료율</p>
<span><strong id="progressPercent">56.12</strong>%</span>
</li>
</ul>
</article>
<table>
<thead>
<tr>
<th>입력날짜</th>
<th>완료상태</th>
<th>수입</th>
<th>노동투입</th>
<th>지출</th>
<th>동력사용시간</th>
<th>임업 자가소비량</th>
<th>농업 자가소비량</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- 일계부 등록 현황 상세 -->
<div class="daily-record-content daily-record-detail" style="display: none;">
<div class="content-inner">
<!-- 수입 -->
<section class="table-group">
<div class="table-tit-group">
<h3>수입 <strong>(<span id="incomeCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">영수증 다운로드 <i class="ico-download" aria-hidden="true"></i></span>
</button>
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-income">
<thead>
<tr>
<th>선택</th>
<th>외상판매</th>
<th>재배형태</th>
<th>수입의 종류</th>
<th>수입원</th>
<th>수량</th>
<th>단위</th>
<th>현금(원)</th>
<th>현물평가액</th>
<th>최종 수정자</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<!-- 임업노동 투입 내역 -->
<section class="table-group">
<div class="table-tit-group">
<h3>임업노동 투입 내역 <strong>(<span id="workCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-work">
<thead>
<tr>
<th colspan="7"></th>
<th colspan="10">노동투입시간</th>
<th colspan="1"></th>
</tr>
<tr>
<th>선택</th>
<th>품목명</th>
<th>작업명</th>
<th>작업 면적</th>
<th>단위</th>
<th>수확량</th>
<th>단위</th>
<th>경영주</th>
<th>배우자</th>
<th>가족노동(남)</th>
<th>가족노동(여)</th>
<th>고용노동(남)</th>
<th>고용노동(여)</th>
<th>품앗이(남)</th>
<th>품앗이(여)</th>
<th>일손돕기(남)</th>
<th>일손돕기(여)</th>
<th>최종 수정자</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<!-- 지출 -->
<section class="table-group">
<div class="table-tit-group">
<h3>지출 <strong>(<span id="expenseCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">영수증 다운로드 <i class="ico-download" aria-hidden="true"></i></span>
</button>
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-expense">
<thead>
<tr>
<th>선택</th>
<th>외상 또는 카드구입</th>
<th>지출의 종류</th>
<th>용도</th>
<th>수량</th>
<th>단위</th>
<th>현금(원)</th>
<th>현물평가액</th>
<th>최종 수정자</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<!-- 동력사용시간 -->
<section class="table-group">
<div class="table-tit-group">
<h3>동력사용시간 <strong>(<span id="powerCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-power">
<thead>
<tr>
<th>선택</th>
<th>명칭</th>
<th>자가 사용시간</th>
<th>임가 사용시간</th>
<th>최종 수정자</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<!-- 자가임업 -->
<section class="table-group">
<div class="table-tit-group">
<h3>자가임업 생산물 중 자가소비량 <strong>(<span id="forestryCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-forestry">
<thead>
<tr>
<th>선택</th>
<th>생산물</th>
<th>용도</th>
<th>수량</th>
<th>단위</th>
<th>현물평가액</th>
<th>최종 수정자</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<!-- 자가농업 -->
<section class="table-group">
<div class="table-tit-group">
<h3>자가농업 생산물 중 자가소비량 <strong>(<span id="farmingCount">0</span>건)</strong></h3>
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="table-farming">
<thead>
<tr>
<th>선택</th>
<th>생산물</th>
<th>용도</th>
<th>수량</th>
<th>단위</th>
<th>현물평가액</th>
<th>최종 수정자</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
</div>
</div>
</div>
<script th:inline="javascript">
// 일계부 등록 현황 리스트 조회
const getDailyRecords = () => {
const f = document.reqForm;
ajaxUtil._ajaxMethod(
'/api/household/dailyRecordsStatus',
{
householdSeq: f.householdSeq.value,
recordMonth: f.recordMonth.value
},
function(response) { // 성공
console.log("일계부 현황 리스트 조회 : ", response);
const listArea = $('.tab-content .daily-record-list');
const detailArea = $('.tab-content .daily-record-detail');
const tbody = listArea.find('tbody');
detailArea.hide();
listArea.show();
tbody.empty();
$('#doneCount').text(response.summary.doneCount);
$('#emptyCount').text(response.summary.emptyCount);
$('#incompleteCount').text(response.summary.incompleteCount);
$('#waitingCount').text(response.summary.waitingCount);
$('#progressPercent').text(response.summary.progressPercent);
let tmpl = '';
$(response.dailyRecords).each((idx, item) => {
tmpl +=
`
<tr>
<td class="underline"><a href="javascript:void(0);" onclick="getDailyRecordsView(${item.id});">${item.dayGroup}</a></td>
<td>
<span class="tag ${statusInfoMap[item.allStatusType].className}">
${statusInfoMap[item.allStatusType].label}
</span>
</td> <!-- 완료상태 -->
<td>${item.incomeStatus}</td><!-- 수입 -->
<td>${item.workStatus}</td><!-- 노동투입 -->
<td>${item.expenseStatus}</td><!-- 지출 -->
<td>${item.powerStatus}</td><!-- 동력사용시간 -->
<td>${item.forestryStatus}</td><!-- 임업 자가소비량 -->
<td>${item.farmingStatus}</td><!-- 농업 자가소비량 -->
</tr>
`;
});
tbody.append(tmpl);
},
function (code, rstData) { // 실패
console.log("error : ", code);
},
'get',
'json'
);
}
// 임산물 등록 현황 상세
const getDailyRecordsView = (id) => {
if(id == null) {
alert('등록 내역이 없습니다.');
return;
}
const listArea = $('.tab-content .daily-record-list');
const detailArea = $('.tab-content .daily-record-detail');
listArea.hide();
detailArea.show();
ajaxUtil._ajaxMethod(
'/api/household/dailyRecordStatus',
{ recordSeq: id },
function(response) { // 성공
console.log("일계부 등록 상세 데이터 : ", response);
gridIncomeTable(response.status.incomeStatus, response.incomes);
gridWorkTable(response.status.workStatus, response.works);
gridExpenseTable(response.status.expenseStatus, response.expenses);
gridPowerTable(response.status.powerStatus, response.powers);
gridForestryTable(response.status.forestryStatus, response.forestries);
gridFarmingTable(response.status.farmingStatus, response.farmings);
},
function (code, rstData) { // 실패
console.log("error : ", code);
},
'get',
'json'
);
}
// 수입 테이블 그리기
const gridIncomeTable = (status, data) => {
const tbody = $('#table-income tbody');
tbody.empty();
$('#incomeCount').text(data.length);
if(data.length === 0) {
noDataDaily(tbody, status, 10);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td>${item.isCredit ? "Y" : "N"}</td> <!-- 외상판매 -->
<td>${ifNullHyphen(item.cropText)}</td><!-- 재배형태 -->
<td class="underline">${ifNullHyphen(item.incomeKind)}</td><!-- 수입의 종류 -->
<td>${ifNullHyphen(item.sourcePurpose)}</td><!-- 수입원 -->
<td class="align-right">${ifNullHyphen(item.quantity)}</td><!-- 수량 -->
<td>${ifNullHyphen(item.unitText)}</td><!-- 단위 -->
<td class="align-right">${formatNumberWithComma(item.price)}</td><!-- 현금(원) -->
<td class="align-right">${formatNumberWithComma(item.estimatedValue)}</td><!-- 현물평가액 -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
</tr>
`;
});
tbody.append(tmpl);
}
// 임업노동 테이블 그리기
const gridWorkTable = (status, data) => {
const tbody = $('#table-work tbody');
tbody.empty();
$('#workCount').text(data.length);
if(data.length === 0) {
noDataDaily(tbody, status, 18);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td class="underline">${ifNullHyphen(item.itemName)}</td><!-- 품목명 -->
<td>${ifNullHyphen(item.workName)}</td><!-- 작업명 -->
<td class="align-right">${ifNullHyphen(item.workLandArea)}</td><!-- 작업면적 -->
<td>${ifNullHyphen(item.areaUnitText)}</td><!-- 작업면적 단위 -->
<td class="align-right">${ifNullHyphen(item.harvestQuantity)}</td><!-- 수확량 -->
<td>${ifNullHyphen(item.harvestUnitText)}</td><!-- 수확량 단위 -->
<td>${ifNullHyphen(item.ownerTime)}</td><!-- 경영주 시간 -->
<td>${ifNullHyphen(item.spouseTime)}</td><!-- 배우자 시간 -->
<td>${ifNullHyphen(item.familyMHours)}</td><!-- 가족노동(남) -->
<td>${ifNullHyphen(item.familyFHours)}</td><!-- 가족노동(여) -->
<td>${ifNullHyphen(item.hiredMHours)}</td><!-- 고용노동(남) -->
<td>${ifNullHyphen(item.hiredFHours)}</td><!-- 고용노동(여) -->
<td>${ifNullHyphen(item.sharedMHours)}</td><!-- 품앗이(남) -->
<td>${ifNullHyphen(item.sharedFHours)}</td><!-- 품앗이(여) -->
<td>${ifNullHyphen(item.volunteerMHours)}</td><!-- 일손돕기(남) -->
<td>${ifNullHyphen(item.volunteerFHours)}</td><!-- 일손돕기(여) -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
</tr>
`;
});
tbody.append(tmpl);
}
// 지출 테이블 그리기
const gridExpenseTable = (status, data) => {
const tbody = $('#table-expense tbody');
tbody.empty();
$('#expenseCount').text(data.length);
if(data.length === 0) {
noDataDaily(tbody, status, 9);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td>${item.isCredit ? "Y" : "N"}</td> <!-- 외상 또는 카드구입 -->
<td class="underline">${ifNullHyphen(item.expenseKind)}</td><!-- 지출의 종류 -->
<td>${ifNullHyphen(item.sourcePurpose)}</td><!-- 용도 -->
<td class="align-right">${ifNullHyphen(item.quantity)}</td><!-- 수량 -->
<td>${ifNullHyphen(item.unitText)}</td><!-- 단위 -->
<td class="align-right">${formatNumberWithComma(item.price)}</td><!-- 현금(원) -->
<td class="align-right">${formatNumberWithComma(item.estimatedValue)}</td><!-- 현물평가액 -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
</tr>
`;
});
tbody.append(tmpl);
}
// 동력사용시간 테이블 그리기
const gridPowerTable = (status, data) => {
const tbody = $('#table-power tbody');
tbody.empty();
$('#powerCount').text(data.length);
if(data.length === 0) {
noDataDaily(tbody, status, 5);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td class="underline">${ifNullHyphen(item.equipmentName)}</td> <!-- 명칭 -->
<td>${ifNullHyphen(item.ownedHours)}</td><!-- 자가 사용시간 -->
<td>${ifNullHyphen(item.leasedHours)}</td><!-- 임가 사용시간 -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
</tr>
`;
});
tbody.append(tmpl);
}
// 자가임업 테이블 그리기
const gridForestryTable = (status, data) => {
const tbody = $('#table-forestry tbody');
tbody.empty();
$('#forestryCount').text(data.length);
if(data.length === 0) {
noDataDaily(tbody, status, 7);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td class="underline">${ifNullHyphen(item.productName)}</td> <!-- 생산물 -->
<td>${ifNullHyphen(item.usage)}</td><!-- 용도 -->
<td class="align-right">${ifNullHyphen(item.quantity)}</td><!-- 수량 -->
<td>${ifNullHyphen(item.unitText)}</td><!-- 단위 -->
<td class="align-right">${formatNumberWithComma(item.estimatedValue)}</td><!-- 현물평가액 -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
</tr>
`;
});
tbody.append(tmpl);
}
// 자가농업 테이블 그리기
const gridFarmingTable = (status, data) => {
const tbody = $('#table-farming tbody');
tbody.empty();
$('#farmingCount').text(data.length);
if(data.length === 0) {
noDataDaily(tbody, status, 7);
return;
}
let tmpl = '';
$(data).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td class="underline">${ifNullHyphen(item.productName)}</td> <!-- 생산물 -->
<td>${ifNullHyphen(item.usage)}</td><!-- 용도 -->
<td class="align-right">${ifNullHyphen(item.quantity)}</td><!-- 수량 -->
<td>${ifNullHyphen(item.unitText)}</td><!-- 단위 -->
<td class="align-right">${formatNumberWithComma(item.estimatedValue)}</td><!-- 현물평가액 -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
</tr>
`;
});
tbody.append(tmpl);
}
</script>
</div>
</html>

View File

@@ -0,0 +1,121 @@
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{layout/layout}">
<div class="layer-wrap" th:fragment="tabFragment">
<div class="tab-content forest-product" data-tab-value="tab2">
<div class="content-inner">
<section class="table-group">
<div class="table-tit-group">
<h3></h3>
<div class="component-btns bottom-btn-group">
<div class="btns-row align-right">
<button type="button" class="btn small">
<span class="btn-txt">등록여부</span>
</button>
<button type="button" class="btn small btn-secondary">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="forest-product">
<thead>
<tr>
<th colspan="7"></th>
<th colspan="4">주생산물</th>
<th colspan="4">부생산물</th>
</tr>
<tr>
<th>선택</th>
<th>지번</th>
<th>지목</th>
<th>읍면동</th>
<th>가능면적(평)</th>
<th>재배작물명</th>
<th>면적(평)</th>
<th>수확량</th>
<th>단위</th>
<th>판매량</th>
<th>단위</th>
<th>수확량</th>
<th>단위</th>
<th>판매량</th>
<th>단위</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
</div>
</div>
<script th:inline="javascript">
// 임산물 현황 탭 조회
const getForestProductsStatus = () => {
const f = document.reqForm;
ajaxUtil._ajaxMethod(
'/api/household/forestProducts',
{
householdSeq: f.householdSeq.value,
recordMonth: f.recordMonth.value
},
(response) => { // 성공
console.log("임산물 현황 리스트 조회 : ", response);
const tbody = $('.tab-content.forest-product tbody');
tbody.empty();
if(response.forestProducts.length === 0) {
noDataMonthly(tbody, response.status, 15);
return;
}
let tmpl = '';
$(response.forestProducts).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="temp_checkbox_000${item.id}" name="temp_checkbox_000${item.id}" value="${item.id}">
</label>
</div>
</td>
<td>${ifNullHyphen(item.streetNum)}</td> <!-- 지번 -->
<td>${ifNullHyphen(item.landType)}</td><!-- 지목 -->
<td>${ifNullHyphen(item.town)}</td><!-- 읍면동 -->
<td>${ifNullHyphen(item.availableArea)}</td><!-- 가능면적(평) -->
<td>${ifNullHyphen(item.cropName)}</td><!-- 재배작물명 -->
<td>${ifNullHyphen(item.landArea)}</td><!-- 면적(평) -->
<td class="align-right">${ifNullHyphen(item.mainYield)}</td><!-- 주생산물 수확량 -->
<td>${ifNullHyphen(item.mainYieldUnitText)}</td><!-- 주생산물 수확량 단위 -->
<td class="align-right">${ifNullHyphen(item.mainSaleAmount)}</td><!-- 주생산물 판매량 -->
<td>${ifNullHyphen(item.mainSaleAmountUnitText)}</td><!-- 주생산물 판매량 단위 -->
<td class="align-right">${ifNullHyphen(item.subYield)}</td><!-- 부생산물 수확량 -->
<td>${ifNullHyphen(item.subYieldUnitText)}</td><!-- 부생산물 수확량 단위 -->
<td class="align-right">${ifNullHyphen(item.subSaleAmount)}</td><!-- 부생산물 판매량 -->
<td>${ifNullHyphen(item.subSaleAmountUnitText)}</td><!-- 부생산물 판매량 단위 -->
</tr>
`;
});
tbody.append(tmpl);
},
function (code, rstData) { // 실패
console.log("error : ", code);
},
'get',
'json'
);
}
</script>
</div>
</html>

View File

@@ -0,0 +1,129 @@
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{layout/layout}">
<div class="layer-wrap" th:fragment="tabFragment">
<div class="tab-content household-visit" data-tab-value="tab4">
<div class="content-inner">
<section class="table-group">
<div class="table-tit-group">
<h3></h3>
<div class="component-btns bottom-btn-group">
<div class="btns-row align-right">
<button type="button" class="btn small btn-secondary" onclick="goDeleteVisitInfo();">
<span class=" btn-txt">삭제</span>
</button>
<button type="button" class="btn small btn-primary" onclick="showVisitInfoModal();">
<span class="btn-txt">추가</span>
</button>
</div>
</div>
</div>
<table id="household-visit">
<thead>
<tr>
<th>선택</th>
<th>방문일</th>
<th>관리분야</th>
<th>내용</th>
<th>최종 수정자</th>
<th>답례품 전달</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
</div>
</div>
<script th:inline="javascript">
// 임가방문정보 조회
const getVisitInfo = () => {
const f = document.reqForm;
ajaxUtil._ajaxMethod(
'/api/household/visitInfos',
{
householdSeq: f.householdSeq.value,
recordMonth: f.recordMonth.value
},
(response) => { // 성공
console.log("임가 방문정보 조회 : ", response);
const tbody = $('.tab-content.household-visit tbody');
tbody.empty();
if(response.length === 0) {
tbody.append(`<tr><td colspan="6" style="text-align: center;">등록이 필요합니다.</td></tr>`);
return;
}
let tmpl = '';
$(response).each((idx, item) => {
tmpl +=
`
<tr>
<td>
<div class="component-input">
<label class="checkbox-inner">
<input type="checkbox" id="removeIds_${item.id}" name="removeIds" value="${item.id}">
</label>
</div>
</td>
<td>${ifNullHyphen(item.visitDate)}</td> <!-- 방문일 -->
<td>${ifNullHyphen(managementType[item.managementType])}</td> <!-- 관리분야 -->
<td class="underline"><a href="javascript:void(0);" onclick="showVisitInfoModal(${item.id});">${ifNullHyphen(item.content)}</a></td> <!-- 내용 -->
<td>
${item.updatedBy}<br>
(${item.updatedAt})
</td><!-- 최종 수정자 -->
<td>${item.isGiftSent ? "전달 완료" : "미전달"}</td> <!-- 답례품 전달 -->
</tr>
`;
});
tbody.append(tmpl);
},
function (code, rstData) { // 실패
console.log("error : ", code);
},
'get',
'json'
);
}
// 임가방문정보 삭제
const goDeleteVisitInfo = () => {
const infoIds = $('input[name=removeIds]:checked');
if(infoIds.length <= 0) {
alert("임가방문정보를 선택해주세요.");
return
}
if(confirm("선택하신 내용을 삭제하시겠습니까? 삭제한 항목은 복구할 수 없습니다.")) {
const f = document.reqForm;
let dataOj = $(f).serializeObject();
console.log("dataOj", dataOj);
ajaxUtil._ajaxMethod(
'/api/visitInfo/remove',
JSON.stringify(dataOj),
(response) => { // 성공
alert("방문정보가 삭제되었습니다.");
getVisitInfo(0);
},
function (code, rstData) {
if(code == 422) alert(rstData.responseText);
},
'delete',
'json',
{ handle422Type: 'alert' }
);
}
}
</script>
</div>
</html>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -32,7 +32,7 @@
</tr>
</tbody>
</table>
<div class="component-btns bottom-btn-group">
<div class="component-btns bottom-btn-group" th:unless="${activeProfile != 'local'}">
<div class="btns-row align-right">
<button type="button" class="btn">
<span class="btn-txt">정보수정</span>
@@ -97,6 +97,22 @@
</div>
<div class="tab-content" data-tab-value="tab2" th:unless="${activeProfile != 'local'}">
<div class="content-inner">
<article class="summary-area">
<ul>
<li>
<p>당월 1차 방문</p>
<span><strong id="firstVisitCount">6</strong>/<strong class="totalHouseholdCount">6</strong>(<strong id="firstVisitPercentage">6</strong>%)</span>
</li>
<li>
<p>당월 2차 방문</p>
<span><strong id="secondVisitCount">6</strong>/<strong class="totalHouseholdCount">6</strong>(<strong id="secondVisitPercentage">6</strong>%)</span>
</li>
<li>
<p>답례품 전달</p>
<span><strong id="giftSentCount">6</strong>/<strong class="totalHouseholdCount">6</strong>(<strong id="giftSentPercentage">6</strong>%)</span>
</li>
</ul>
</article>
<section class="table-group">
<div class="table-tit-group">
<h3>총 <strong id="household-visit-totalElements"></strong>건</h3>
@@ -108,24 +124,25 @@
</div>
</div>
</div>
<table>
<thead>
<tr>
<th>
<input onchange="toggleCheckbox(this);" type="checkbox"/>
</th>
<th>임가번호</th>
<th>경영주명</th>
<th>방문일</th>
<th>관리분야</th>
<th>내용</th>
<th>작성일</th>
<th>답례품 전달</th>
</tr>
</thead>
<tbody id="household-visit-list">
</tbody>
</table>
<table>
<thead>
<tr>
<th>
<input onchange="toggleCheckbox(this);" type="checkbox"/>
</th>
<th>임가번호</th>
<th>경영주명</th>
<th>방문일</th>
<th>관리분야</th>
<th>내용</th>
<th>작성일</th>
<th>답례품 전달</th>
</tr>
</thead>
<tbody id="household-visit-list">
</tbody>
</table>
</section>
</div>
</div>
@@ -169,6 +186,7 @@
if (!form.searchMonth.value) {
form.searchMonth.value = '[[${currentMonth}]]'; // 기본값 복원
}
getVisitHouseholdPercentage();
getHouseholdVisitList(0);
}
});
@@ -198,7 +216,7 @@
tbody.append(
`
<tr data-id="${ct.seq}">
<td class="underline"><a href="">${ct.householdNum}</a></td>
<td><a href="#">${ct.householdNum}</a></td>
<td>${ct.ownerName || '-'}</td>
<td>${ct.phone || '-'}</td>
<td>${ct.regionMainCodeName || '-'}</td>
@@ -241,6 +259,35 @@
);
}
// 임가 방문 퍼센트
const getVisitHouseholdPercentage=()=>{
const f = document.householdReqForm;
let dataObj = {
seq: f.seq.value,
searchMonth: f.searchMonth.value,
};
ajaxUtil._ajaxMethod(
'/api/researcher/visitHousehold/percentage',
dataObj,
function (response) {
$('#firstVisitCount').text(response.firstVisitCount);
$('#secondVisitCount').text(response.secondVisitCount);
$('#giftSentCount').text(response.giftSentCount);
$('#firstVisitPercentage').text(response.firstVisitPercentage);
$('#secondVisitPercentage').text(response.secondVisitPercentage);
$('#giftSentPercentage').text(response.giftSentPercentage);
$('.totalHouseholdCount').text(response.totalHouseholdCount);
},
function (code, rstData) {
},
'get',
'json',
null
);
}
// 임가 방문 정보
const getHouseholdVisitList = (pageNo) => {
const f = document.householdReqForm;
@@ -271,7 +318,7 @@
<input class="form-check-input" name="selectIds" type="checkbox" value="${ct.id}"/>
</label>
</td>
<td class="underline"><a href="#" onclick="showHouseholdModal2(${ct.id});">${ct.householdNum}</a></td>
<td><a href="#" onclick="showHouseholdModal2(${ct.id});">${ct.householdNum}</a></td>
<td>${ct.ownerName}</td>
<td>${ct.visitDate}</td>
<td>${ct.managementType}</td>
@@ -346,7 +393,7 @@
JSON.stringify(selectIds),
function (response) {
if(response > 0){
alert('선택한 임가정보가 삭제되었습니다.');
alert('선택한 임가 방문 정보가 삭제되었습니다.');
getHouseholdVisitList(document.householdReqForm.page.value);
} else {
alert('삭제에 실패했습니다.');

View File

@@ -15,60 +15,75 @@
<section>
<form autocomplete="off" method="get" name="householdVisitReqForm" >
<input type="hidden" name="id" id="id" />
<table class="type-form confirm" >
<tbody id="household-visit-detail">
<tr>
<th>방문일</th>
<td>
<input id="visitDate" class="flatpickr" name="visitDate" type="text" placeholder="방문일을 선택하세요"/>
</td>
<th>관리분야</th>
<td>
<select id="managementType" name="managementType">
<option value="">선택하세요</option>
</select>
</td>
</tr>
<tr>
<th>내용</th>
<td>
<div class="component-input">
<div class="input-textarea-field">
<textarea id="content" name="content" class="textarea" placeholder=""></textarea>
<table class="type-form confirm" >
<tbody id="household-visit-detail">
<tr>
<th>방문일</th>
<td>
<div class="component-datepicker">
<div class="component-input">
<div class="input-field">
<input type="text" class="datepicker-btn-trigger" name="visitDate" id="visitDate" aria-label="시작일"
placeholder="방문일을 입력해주세요" />
<span class="input-field-btn datepicker-state">
<span class="hide-txt">달력</span>
<i class="ico-calendar ico-normal" aria-hidden="true"></i>
</span>
</div>
</div>
</div>
</div>
</td>
</tr>
<tr>
<th>답례품 전달</th>
<td>
<div class="component-input">
<label class="radio-inner">
<input type="radio" id="is_gift_sent_y" name="isGiftSent">
<span class="radio-item">
<span class="radio-txt">전달</span>
</span>
</label>
</div>
<div class="component-input">
<label class="radio-inner">
<input type="radio" id="is_gift_sent_n" name="isGiftSent">
<span class="radio-item">
<span class="radio-txt">미전달</span>
</span>
</label>
</div>
</td>
</tr>
</tbody>
</table>
<div class="component-btns bottom-btn-group" th:fragment="modalButtons">
<div class="btns-row align-right">
<button type="button" class="btn btn-primary" onclick="updateHouseholdVisit()">
<span class="btn-txt">수정</span>
</button>
</td>
<th>관리분야</th>
<td>
<div class="d-flex">
<div class="component-select">
<select id="managementType" name="managementType" class="select-list" required>
<option value="">선택하세요</option>
</select>
</div>
</div>
</td>
</tr>
<tr>
<th>내용</th>
<td colspan="5">
<div class="component-input">
<div class="input-textarea-field">
<textarea id="textarea_note" class="textarea" name="content" placeholder=""></textarea>
</div>
</div>
</td>
</tr>
<tr>
<th>답례품 전달</th>
<td class="radio-group">
<div class="component-input">
<label class="radio-inner">
<input type="radio" id="is_gift_sent_y" name="isGiftSent">
<span class="radio-item">
<span class="radio-txt">전달</span>
</span>
</label>
</div>
<div class="component-input">
<label class="radio-inner">
<input type="radio" id="is_gift_sent_n" name="isGiftSent">
<span class="radio-item">
<span class="radio-txt">미전달</span>
</span>
</label>
</div>
</td>
</tr>
</tbody>
</table>
<div class="component-btns bottom-btn-group" th:fragment="modalButtons">
<div class="btns-row align-right">
<button type="button" class="btn btn-primary" onclick="updateHouseholdVisit()">
<span class="btn-txt">수정</span>
</button>
</div>
</div>
</div>
</form>
</section>
</div>
@@ -86,8 +101,22 @@
});
const showHouseholdModal2 = (seq) => {
document.querySelector(".modal02").ui.open();
initFlatpickr();
const modal = document.querySelector(".modal02");
modal.ui.open();
const $el = document.querySelector('.component-datepicker');
const datepicker = etUI.components.DatepickerComp();
datepicker.core.init($el, {
dateSelectCallback: function (selectedDate) {
console.log('선택된 날짜:', selectedDate);
}
});
datepickerInstance = datepicker.getDatepickerInstance();
// 초기 상태 오늘 날짜로
if (datepickerInstance) {
datepickerInstance.setDate(new Date(), { render: true });
}
ajaxUtil._ajaxMethod(
'/api/researcher/visitHousehold/'+seq,
@@ -112,13 +141,15 @@
const setFormData = (data) => {
// 폼 필드에 데이터 세팅
const f = document.householdVisitReqForm;
if (data.visitDate) {
const visitDate = data.visitDate.substring(0, 10); // 'YYYY-MM-DD' 형식
if (visitDatePicker) {
f.visitDate.value = visitDate; // 입력 필드 먼저 설정
visitDatePicker.setDate(visitDate); // Flatpickr 동기화
}
if (datepickerInstance && data.visitDate) {
console.log(data.visitDate);
console.log(new Date(data.visitDate));
datepickerInstance.setDate(new Date(data.visitDate), { render: true });
}
if (data.managementType) {
f.managementType.value= data.managementType;
}
@@ -150,27 +181,48 @@
visitDatePicker = null;
}
// 1. input 요소가 실제로 존재하는지 확인
// 입력 요소 확인
const input = document.getElementById('visitDate');
if (!input) {
console.warn('#visitDate input not found!');
return;
}
// 2. input에 값이 있으면 flatpickr와 동기화
// 현재 값 가져오기
const currentVal = input.value;
// 3. flatpickr 초기화
visitDatePicker = flatpickr(input, {
dateFormat: 'Y-m-d',
defaultDate: currentVal || null, // 현재 값으로 초기 선택 날짜 설정
enableTime: false,
clickOpens: true,
onChange: function (selectedDates, dateStr, instance) {
console.log('날짜 선택됨:', dateStr);
input.value = dateStr; // 수동으로 input 값 동기화
},
});
// Flatpickr 초기화
try {
visitDatePicker = flatpickr(input, {
dateFormat: 'Y-m-d',
defaultDate: currentVal || null,
enableTime: false,
clickOpens: true,
onReady: function () {
console.log('Flatpickr 초기화 완료');
},
onChange: function (selectedDates, dateStr, instance) {
console.log('날짜 선택됨:', dateStr);
input.value = dateStr; // 입력 필드 동기화
},
onOpen: function () {
console.log('Flatpickr 캘린더 열림');
},
onClose: function () {
console.log('Flatpickr 캘린더 닫힘');
}
});
// 입력 필드 클릭 이벤트 추가 (보조)
input.addEventListener('click', () => {
console.log('visitDate 입력 필드 클릭됨');
if (visitDatePicker) {
visitDatePicker.open(); // 수동으로 캘린더 열기
}
});
} catch (error) {
console.error('Flatpickr 초기화 실패:', error);
}
};
const updateHouseholdVisit = () => {

View File

@@ -125,7 +125,7 @@
tbody.append(
`
<tr data-id="${ct.id}">
<td class="underline"><a href="javascript:goDetail(${ct.seq})">${ct.name || '-'}</a></td>
<td><a href="javascript:goDetail(${ct.seq})">${ct.name || '-'}</a></td>
<td>${ct.phone || '-'}</td>
<td>${ct.regionMainCodeName || '-'}</td>
<td>${ct.householdCount || '-'}</td>

View File

@@ -98,11 +98,15 @@
<tr>
<th> <label for="inUse">사용여부</label></th>
<td>
<div class="component-select">
<select class="form-select" id="inUse" name="inUse">
<option value="true">사용</option>
<option value="false">미사용</option>
</select>
<div class="d-flex">
<div class="component-input">
<div class="component-select">
<select class="select-list" id="inUse" name="inUse">
<option value="true">사용</option>
<option value="false">미사용</option>
</select>
</div>
</div>
</div>
</td>
</tr>
@@ -231,13 +235,17 @@
const previouslySelected = treeWrap.querySelector('button.selected');
if (previouslySelected) {
previouslySelected.classList.remove('selected');
if (previouslySelected.classList.contains('tit')) {
/* if (previouslySelected.classList.contains('tit')) {
previouslySelected.parentNode.classList.add('folding');
}
}*/
}
button.classList.add('selected');
if (button.classList.contains('tit')) {
button.parentNode.classList.remove('folding');
if(button.parentNode.classList.contains('folding')){
button.parentNode.classList.remove('folding');
}else{
button.parentNode.classList.add('folding');
}
}
// 노드 데이터 추출
const data = {

View File

@@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum FileStorageType {
LOCAL("로컬 스토리지"),
S3("AWS S3 스토리지");
S3("AWS S3 스토리지"),
SFTP("SFTP");
private final String desc;
}

View File

@@ -41,7 +41,7 @@ public enum FileUploadType {
AcceptableFileType.PDF,
AcceptableFileType.ZIP)),
NOTICE(
FileStorageType.LOCAL,
FileStorageType.SFTP,
"/notice",
Set.of(
AcceptableFileType.IMAGE,
@@ -55,7 +55,7 @@ public enum FileUploadType {
AcceptableFileType.ZIP)),
RECEIPT(
FileStorageType.LOCAL,
FileStorageType.SFTP,
"/receipt",
Set.of(
AcceptableFileType.IMAGE

View File

@@ -11,18 +11,24 @@ import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class AESEncryptUtil {
@Value("${encrypt.aes.key}")
@Value("${aes.secret-key}")
private String key;
@Value("${encrypt.aes.iv}")
private String iv;
private static final String AES_ALGORITHM = "AES/CBC/PKCS5PADDING";
public static final String ENCRYPT_IV = "0123456789ABCDEF";
public String encrypt(String text)
throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException {
@@ -48,6 +54,42 @@ public class AESEncryptUtil {
return new String(decrypted, StandardCharsets.UTF_8);
}
public byte[] encryptAesCbc(byte[] plainData) {
if (plainData == null || plainData.length == 0) {
throw new IllegalArgumentException("데이터는 null이거나 비어 있을 수 없습니다.");
}
try {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return org.apache.commons.codec.binary.Base64.encodeBase64(cipher.doFinal(plainData));
} catch (Exception e) {
log.error("바이너리 데이터 암호화 실패", e);
throw new RuntimeException("바이너리 데이터 암호화 실패", e);
}
}
public byte[] decryptAesCbc(byte[] cipherData) {
if (cipherData == null || cipherData.length == 0) {
throw new IllegalArgumentException("암호문은 null이거나 비어 있을 수 없습니다.");
}
try {
byte[] encrypted = org.apache.commons.codec.binary.Base64.decodeBase64(cipherData);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(encrypted);
} catch (Exception e) {
log.error("바이너리 데이터 복호화 실패", e);
throw new RuntimeException("바이너리 데이터 복호화 실패", e);
}
}
private String getTransformation() {
return "AES/CBC/PKCS5Padding";
}

View File

@@ -3,9 +3,16 @@ package app.module.core.config.application.util;
import app.module.core.config.adapters.web.security.domain.SocialUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -14,6 +21,7 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Slf4j
public class CommonUtil {
/**
@@ -106,4 +114,41 @@ public class CommonUtil {
flashMessages.add(msg);
session.setAttribute("flashAlertMessages", flashMessages);
}
public static String normalizePath(String path) {
if (path == null || path.trim().isEmpty()) {
log.warn("normalizePath: Input path is null or empty, returning default path");
String defaultPath = System.getProperty("user.home") + File.separator + "Downloads";
return Paths.get(defaultPath).toAbsolutePath().normalize().toString();
}
try {
// Paths.get을 사용하여 경로 정규화
Path normalizedPath = Paths.get(path).toAbsolutePath().normalize();
String result = normalizedPath.toString();
log.debug("Normalized path: {}", result);
return result;
} catch (Exception e) {
log.error("Error normalizing path: {}", path, e);
throw new IllegalArgumentException("Failed to normalize path: " + path, e);
}
}
public static void createDirectories(File directory) {
if (directory == null) {
throw new IllegalArgumentException("Directory cannot be null");
}
try {
if (!directory.exists()) {
boolean created = directory.mkdirs();
log.info("Directory created: {} (Success: {})", directory.getAbsolutePath(), created);
}
if (!directory.canWrite()) {
throw new IOException("No write permission for directory: " + directory.getAbsolutePath());
}
} catch (Exception e) {
log.error("Failed to create directory: {}", directory.getAbsolutePath(), e);
throw new RuntimeException("Failed to create directory", e);
}
}
}

View File

@@ -0,0 +1,84 @@
package app.module.core.config.application.util;
import app.module.core.config.adapters.persistence.entity.UploadFile;
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.nio.file.Paths;
@Slf4j
@Component
@RequiredArgsConstructor
public class SftpFileDeleteUtil {
private final SftpConnector sftpConnector;
@Value("${path.upload.sftp.public}")
private String publicPath;
/**
* SFTP 서버에서 파일을 삭제하는 공통 메서드
* @param deleteFile 삭제할 파일 정보
* @throws JSchException SFTP 연결 오류
* @throws SftpException SFTP 작업 오류
*/
public void deleteRealFile(UploadFile deleteFile) throws JSchException, SftpException {
if (deleteFile == null || deleteFile.getPath() == null || deleteFile.getName() == null) {
log.error("Invalid file information: {}", deleteFile);
throw new IllegalArgumentException("Invalid file information");
}
// 경로 검증 및 생성
String filePath = constructSafeFilePath(deleteFile.getPath(), deleteFile.getName());
log.info("Attempting to delete file from SFTP: {}", filePath);
// SFTP 연결 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.warn("SFTP connection lost, attempting to reconnect");
sftpConnector.connect();
}
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp == null) {
log.error("SFTP channel is not initialized");
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
}
// 파일 삭제
try {
channelSftp.stat(filePath); // 파일 존재 여부 확인
channelSftp.rm(filePath);
log.info("File deleted successfully from SFTP: {}", filePath);
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
log.warn("File does not exist on SFTP: {}", filePath);
} else {
log.error("Failed to delete file from SFTP: {}, error: {}", filePath, e.getMessage(), e);
throw e;
}
}
}
/**
* 경로 조작 방지를 위해 안전한 파일 경로 생성
*/
private String constructSafeFilePath(String subPath, String fileName) {
// 경로 및 파일 이름 정규화
String normalizedSubPath = Paths.get(subPath).normalize().toString().replace("\\", "/");
String normalizedFileName = Paths.get(fileName).getFileName().toString();
String safePath = CommonUtil.removeLastChar(publicPath, "/") + "/" + normalizedSubPath + "/" + normalizedFileName;
// 경로가 publicPath로 시작하는지 검증
if (!safePath.startsWith(publicPath)) {
log.error("Invalid file path detected: {}", safePath);
throw new IllegalArgumentException("Invalid file path: " + safePath);
}
return safePath;
}
}

View File

@@ -0,0 +1,102 @@
package app.module.core.config.application.util;
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@Slf4j
@Component
@RequiredArgsConstructor
public class SftpFileDownloader {
private final SftpConnector sftpConnector;
private final AESEncryptUtil encryptUtil;
@Value("${path.upload.sftp.public}")
private String publicPath;
@Value("${file.download.base-path:/tmp/downloads}")
private String defaultDownloadBasePath;
public void downloadFile(GetFile file) throws JSchException, SftpException, IOException {
// SFTP 연결 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.info("SFTP connection lost, attempting to reconnect");
sftpConnector.connect();
}
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp == null) {
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
}
try {
// 원격 파일 경로 (암호화된 파일명 사용)
String remoteFilePath = CommonUtil.removeLastChar(publicPath, "/") + file.getPath() + "/" +"encrypted_"+ file.getName();
log.info("Remote file path: {}", remoteFilePath);
// 다운로드 경로 정규화
String basePath = CommonUtil.normalizePath(defaultDownloadBasePath);
log.info("Base path: {}", basePath);
String localEncryptedFilePath = basePath + File.separator + "encrypted_" + file.getOriginName();
String localDecryptedFilePath = basePath + File.separator + file.getOriginName();
log.info("Local encrypted file path: {}", localEncryptedFilePath);
log.info("Local decrypted file path: {}", localDecryptedFilePath);
// 로컬 디렉토리 생성
File localDir = new File(localEncryptedFilePath).getParentFile();
CommonUtil.createDirectories(localDir);
// 원격 파일 존재 여부 확인 (디버깅 용)
try {
channelSftp.lstat(remoteFilePath);
log.info("Remote file exists: {}", remoteFilePath);
} catch (SftpException e) {
log.error("Remote file does not exist: {}", remoteFilePath, e);
throw new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "Remote file does not exist: " + remoteFilePath);
}
// 암호화된 파일 다운로드
try (FileOutputStream fos = new FileOutputStream(localEncryptedFilePath)) {
channelSftp.get(remoteFilePath, fos);
log.info("File downloaded to: {}", localEncryptedFilePath);
}
// 파일 복호화
try {
byte[] encryptedContent = Files.readAllBytes(Paths.get(localEncryptedFilePath));
byte[] decryptedContent = encryptUtil.decryptAesCbc(encryptedContent);
Files.write(Paths.get(localDecryptedFilePath), decryptedContent);
log.info("File decrypted and saved to: {}", localDecryptedFilePath);
file.setLocalPath(localDecryptedFilePath);
} catch (Exception e) {
log.error("Failed to decrypt file: {}", file.getOriginName(), e);
throw new IOException("Failed to decrypt file", e);
} finally {
// 암호화된 임시 파일 삭제
Files.deleteIfExists(Paths.get(localEncryptedFilePath));
log.info("Temporary encrypted file deleted: {}", localEncryptedFilePath);
}
} catch (SftpException e) {
log.error("Failed to download file: {} (Error: {})", file.getOriginName(), e.getMessage());
throw e;
} catch (IOException e) {
log.error("IO error during file download or decryption: {}", file.getOriginName(), e);
throw e;
} catch (Exception e) {
log.error("Unexpected error during file download: {}", file.getOriginName(), e);
throw new RuntimeException("Unexpected error during file download", e);
}
}
}

View File

@@ -24,6 +24,7 @@ public class AdminView implements Serializable {
private Boolean accountDisabled;
private Integer loginFailCnt;
private Boolean accountLocked;
private String lastLoginIp;
private LocalDateTime createdAt;
private String createdBy;
private LocalDateTime updatedAt;

View File

@@ -0,0 +1,60 @@
package app.module.core.usecase.file.downloadFile.adapters;
import app.module.core.config.application.util.SftpFileDownloader;
import app.module.core.usecase.file.getFile.ports.GetFilePortIn;
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@Slf4j
@RestController
@RequiredArgsConstructor
class DownloadFileController {
private final GetFilePortIn getFilePortIn;
private final SftpFileDownloader sftpFileDownloader;
@GetMapping(path = "/api/file/download/{fileId}")
ResponseEntity<?> downloadFile(@PathVariable Long fileId) throws JSchException, SftpException, IOException {
GetFile file = getFilePortIn.operate(new GetFileCmd(fileId)).orElseThrow(() -> new IllegalArgumentException("File not found: " + fileId));
// SFTP에서 파일 다운로드
sftpFileDownloader.downloadFile(file);
// 로컬 파일 경로
File downloadedFile = new File(file.getLocalPath());
if (!downloadedFile.exists()) {
throw new IllegalStateException("Downloaded file not found: " + file.getLocalPath());
}
String encodedFileName = URLEncoder.encode(file.getOriginName(), StandardCharsets.UTF_8)
.replace("+", "%20");
// HTTP 헤더 설정
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
headers.add(HttpHeaders.PRAGMA, "no-cache");
headers.add(HttpHeaders.EXPIRES, "0");
return ResponseEntity.ok()
.headers(headers)
.contentLength(downloadedFile.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new FileSystemResource(downloadedFile));
}
}

View File

@@ -9,8 +9,6 @@ import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class GetFile {
private Long id;
private FileUploadType type;
@@ -18,8 +16,10 @@ public class GetFile {
private String name;
private String originName;
private Long fileLength;
private String localPath;
private LocalDateTime createdAt;
private String createdBy;
private LocalDateTime updatedAt;
private String updatedBy;
}

View File

@@ -0,0 +1,71 @@
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SftpConnector {
@Value("${file.upload.sftp.ip}")
private String host;
@Value("${file.upload.sftp.id}")
private String id;
@Value("${file.upload.sftp.password}")
private String password;
@Value("${file.upload.sftp.port}")
private int port;
private Session session;
private ChannelSftp channelSftp;
public void connect() throws JSchException {
if (host == null || id == null || password == null) {
throw new IllegalStateException("SFTP configuration is incomplete: host=" + host + ", id=" + id + ", password=" + (password != null ? "****" : null));
}
try {
JSch jsch = new JSch();
// 세션 설정
session = jsch.getSession(id, host, port);
session.setPassword(password);
// 호스트 키 검증 비활성화 (개발 환경에서만 사용, 프로덕션에서는 적절히 설정)
session.setConfig("StrictHostKeyChecking", "no");
// 연결
session.connect();
// SFTP 채널 열기
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
log.info("SFTP connection established successfully");
}catch (JSchException e){
log.error("Failed to connect to SFTP server", e);
}
}
public void disconnect() {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.disconnect();
log.info("SFTP channel disconnected");
}
if (session != null && session.isConnected()) {
session.disconnect();
log.info("SFTP channel disconnected");
}
}
public boolean isConnected() {
return channelSftp != null && channelSftp.isConnected() && session != null && session.isConnected();
}
// ChannelSftp 객체 반환
public ChannelSftp getChannelSftp() {
return channelSftp;
}
}

View File

@@ -0,0 +1,140 @@
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
import app.module.core.config.application.enums.FileStorageType;
import app.module.core.config.application.util.AESEncryptUtil;
import app.module.core.config.application.util.CommonUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Service
@RequiredArgsConstructor
@Slf4j
public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
@Value("${path.upload.sftp.public}")
private String publicPath;
@Value("${path.upload.sftp.tmpdir}")
private String tmpPath;
private final SftpConnector sftpConnector;
private final AESEncryptUtil aesEncryptUtil; // EncryptUtil 주입
@PostConstruct
public void initialize() throws Exception {
log.info("FileIoService - initialize : path.upload.public is {}", publicPath);
log.info("FileIoService - initialize : path.upload.tmpdir is {}", tmpPath);
try {
Files.createDirectories(Paths.get(tmpPath));
// SFTP 연결 초기화
sftpConnector.connect();
// 원격 디렉토리 생성
createRemoteDirectories(publicPath);
} catch (JSchException | SftpException e) {
throw new IOException("Could not initialize SFTP connection or directories", e);
}
}
private void createRemoteDirectories(String path) throws SftpException {
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp != null) {
String[] folders = path.split("/");
String currentPath = "";
for (String folder : folders) {
if (!folder.isEmpty()) {
currentPath += "/" + folder;
try {
channelSftp.cd(currentPath);
} catch (SftpException e) {
channelSftp.mkdir(currentPath);
channelSftp.cd(currentPath);
}
}
}
}
}
@Override
public FileStorageType getStorageType() {
return FileStorageType.SFTP;
}
@Override
public void operate(MultipartFile multipartFile, String createSubPath, String createFilename) throws IOException {
if (multipartFile == null || multipartFile.isEmpty()) {
throw new RuntimeException("Failed to store empty file.");
}
// 로컬 임시 파일 저장
Path tmpFile = Paths.get(tmpPath, createFilename);
Files.createDirectories(tmpFile.getParent());
try (InputStream inputStream = multipartFile.getInputStream()) {
Files.copy(inputStream, tmpFile, StandardCopyOption.REPLACE_EXISTING);
}
// 파일 내용 암호화
Path encryptedFile = Paths.get(tmpPath, "encrypted_" + createFilename);
try {
// 파일 읽기
byte[] fileContent = Files.readAllBytes(tmpFile);
// 암호화
byte[] encryptedContent = aesEncryptUtil.encryptAesCbc(fileContent);
// 암호화된 내용을 임시 파일로 저장
Files.write(encryptedFile, encryptedContent);
} catch (Exception e) {
log.error("Failed to encrypt file: {}", createFilename, e);
throw new IOException("Failed to encrypt file", e);
}
String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath;
String remoteFilePath = remotePath + "/" + "encrypted_" + createFilename;
try {
// 연결 상태 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.warn("SFTP connection lost, attempting to reconnect");
sftpConnector.connect();
}
createRemoteDirectories(remotePath);
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp == null) {
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
}
// 암호화된 파일 업로드
try (InputStream encryptedInputStream = Files.newInputStream(encryptedFile)) {
channelSftp.put(encryptedInputStream, remoteFilePath);
channelSftp.chmod(0644, remoteFilePath); // 권한 변경 (0777 -> 0644로 보안 강화)
log.info("Encrypted file uploaded to SFTP: {}", remoteFilePath);
}
} catch (SftpException | JSchException e) {
throw new RuntimeException("Failed to upload encrypted file to SFTP", e);
} finally {
// 임시 파일 삭제
Files.deleteIfExists(tmpFile);
Files.deleteIfExists(encryptedFile);
}
}
@PreDestroy
public void cleanup() {
sftpConnector.disconnect();
}
}

View File

@@ -0,0 +1,24 @@
package app.module.core.usecase.file.url.strategy;
import app.module.core.config.application.enums.FileStorageType;
import org.springframework.stereotype.Service;
@Service
public class SftpFileUrlStrategy implements FileUrlStrategy {
@Override
public FileStorageType getStorageType() {
return FileStorageType.SFTP;
}
@Override
public String getInlineURL(String subPath, String filename) {
return String.format("/content-disposition/inline%s/%s", subPath, filename);
}
@Override
public String getAttachmentURL(Long fileId) {
return String.format("/api/file/download/%s", fileId);
}
}

View File

@@ -36,8 +36,6 @@ public class GetHousehold {
private Boolean isPanel;
private String memo;
private String dropReason;
private LocalDate latestRegisterStartDate;
private LocalDate latestRegisterEndDate;
private LocalDateTime createdAt;
private String createdBy;
private LocalDateTime updatedAt;

View File

@@ -9,5 +9,7 @@ import org.apache.ibatis.annotations.Param;
@Mapper
public interface URIMapper {
URITopTier findTopTierByAppType(@Param("appType") AppType appType);
URITopTier findTopTierByAppTypeByRoleId(@Param("appType") AppType appType,@Param("roleId") String roleId);
List<URITopTier> findChildrenByParentId(@Param("parentId") String parentId);
List<URITopTier> findChildrenByParentIdByRoleId(@Param("parentId") String parentId,@Param("roleId") String roleId);
}

View File

@@ -25,12 +25,33 @@ public class URITopTierDao implements URITopTierPortOut {
return recursiveMapping(top);
}
@Override
@Transactional
public URITopTier connectRoleId(AppType appType, String roleId) {
URITopTier top = uriMapper.findTopTierByAppTypeByRoleId(appType,roleId);
if (top == null) {
throw new RuntimeException("There is no top tier item of " + appType);
}
return recursiveMapping(top,roleId);
}
private URITopTier recursiveMapping(URITopTier current) {
List<URITopTier> children = uriMapper.findChildrenByParentId(current.getId());
current.setChildren(children.stream()
.map(this::recursiveMapping)
.map(this::recursiveMapping)
.collect(Collectors.toList()));
return current;
}
private URITopTier recursiveMapping(URITopTier current,String roleId) {
List<URITopTier> children = uriMapper.findChildrenByParentIdByRoleId(current.getId(),roleId);
current.setChildren(children.stream()
.map(uri -> recursiveMapping(uri,roleId))
.collect(Collectors.toList()));
return current;
}
}

View File

@@ -5,4 +5,5 @@ import app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier;
public interface URITopTierPortIn {
URITopTier connect(AppType appType);
URITopTier connectRoleId(AppType appType, String roleId);
}

View File

@@ -6,4 +6,5 @@ import app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier;
public interface URITopTierPortOut {
URITopTier connect(AppType appType);
URITopTier connectRoleId(AppType appType,String roleId);
}

View File

@@ -19,4 +19,10 @@ public class URITopTierService implements URITopTierPortIn {
public URITopTier connect(AppType appType) {
return topTierPortOut.connect(appType);
}
@Override
public URITopTier connectRoleId(AppType appType, String roleId) {
return topTierPortOut.connectRoleId(appType,roleId);
}
}

View File

@@ -18,12 +18,17 @@
a.account_disabled,
a.login_fail_cnt,
a.account_locked,
liu.clientip as last_login_ip,
a.created_at,
a.created_by,
a.updated_at,
a.updated_by
FROM admin a
WHERE id = #{id}
LEFT JOIN ( SELECT clientip,login_id
FROM logged_in_user liu
ORDER BY last_logged_in_at desc
LIMIT 1 ) liu on liu.login_id = a.id
WHERE a.id = #{id}
AND a.is_deleted = false
</select>

View File

@@ -26,18 +26,11 @@
h.is_panel,
h.memo,
h.drop_reason,
dr.start_date as latest_register_start_date,
dr.end_date as latest_register_end_date,
h.created_at,
h.created_by,
h.updated_at,
h.updated_by
FROM household h
LEFT JOIN (
SELECT start_date , end_date ,household_seq
FROM daily_record dr
ORDER BY start_date desc
LIMIT 1 ) dr ON dr.household_seq = h.seq
WHERE h.household_num = #{householdNum}
AND h.is_deleted = false
</select>

View File

@@ -2,32 +2,65 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="app.module.core.usecase.uri.toptier.adapters.persistence.URIMapper">
<select id="findTopTierByAppType" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
SELECT
u.id,
u.app_type,
u.text,
u.uri,
u.show_on_navi,
u.order_no
FROM uri u
WHERE u.app_type = #{appType}
AND u.parent_id IS NULL
AND u.is_deleted = false
</select>
<select id="findTopTierByAppType" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
<select id="findChildrenByParentId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
SELECT
u.id,
u.app_type,
u.text,
u.uri,
u.show_on_navi,
u.order_no
FROM uri u
WHERE u.parent_id = #{parentId}
AND u.is_deleted = false
ORDER BY u.order_no ASC
</select>
<select id="findTopTierByAppTypeByRoleId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
SELECT
id,
app_type,
text,
uri,
show_on_navi,
order_no
FROM uri
WHERE app_type = #{appType}
AND parent_id IS NULL
AND is_deleted = false
u.id,
u.app_type,
u.text,
u.uri,
u.show_on_navi,
u.order_no
FROM uri u
JOIN uri_has_role uhr ON u.id = uhr.uri_id and uhr.is_deleted = false
WHERE u.app_type = #{appType}
AND u.parent_id IS NULL
AND u.is_deleted = false
AND uhr.role_id = #{roleId}
AND u.show_on_navi = true
</select>
<select id="findChildrenByParentId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
<select id="findChildrenByParentIdByRoleId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
SELECT
id,
app_type,
text,
uri,
show_on_navi,
order_no
FROM uri
WHERE parent_id = #{parentId}
AND is_deleted = false
ORDER BY order_no ASC
u.id,
u.app_type,
u.text,
u.uri,
u.show_on_navi,
u.order_no
FROM uri u
JOIN uri_has_role uhr ON u.id = uhr.uri_id and uhr.is_deleted = false
WHERE u.parent_id = #{parentId}
AND u.is_deleted = false
AND uhr.role_id = #{roleId}
AND u.show_on_navi = true
ORDER BY u.order_no ASC
</select>
</mapper>

View File

@@ -831,23 +831,26 @@ COMMENT ON COLUMN operation_log.is_deleted IS '삭제여부';
-- ============================================
-- TABLE : logged_in_user
-- DESC : 로그인 사용자 정보 테이블
-- DESC : 로그인 사용자 이력 테이블
-- ============================================
CREATE SEQUENCE logged_in_user_seq START WITH 1 INCREMENT BY 1 CACHE 1 NO CYCLE;
CREATE TABLE logged_in_user (
id bigint DEFAULT nextval('logged_in_user_seq') NOT NULL, -- 로그 ID (PK)
app_type varchar(255) NOT NULL, -- 앱 타입 (FRONT / ADMIN)
id varchar(255) NOT NULL, -- 로그인 아이디
login_id varchar(255) NOT NULL, -- 로그인 아이디
last_logged_in_at timestamp(6), -- 마지막 로그인 날짜
clientip varchar(255), -- 접속 아이피
CONSTRAINT logged_in_user_pkey PRIMARY KEY (app_type, id),
CONSTRAINT logged_in_user_pkey PRIMARY KEY (id),
CONSTRAINT logged_in_user_app_type_check
CHECK (app_type::text = ANY (ARRAY['FRONT', 'ADMIN']))
);
COMMENT ON TABLE logged_in_user IS '로그인사용자정보테이블';
COMMENT ON TABLE logged_in_user IS '로그인사용자이력테이블';
COMMENT ON COLUMN logged_in_user.id IS '로그 ID';
COMMENT ON COLUMN logged_in_user.app_type IS '앱 타입';
COMMENT ON COLUMN logged_in_user.id IS '로그인 아이디';
COMMENT ON COLUMN logged_in_user.login_id IS '로그인 아이디';
COMMENT ON COLUMN logged_in_user.last_logged_in_at IS '마지막 로그인 날짜';
COMMENT ON COLUMN logged_in_user.clientip IS '접속 아이피';

View File

@@ -153,8 +153,8 @@ CREATE TABLE daily_income (
quantity varchar(10), -- 수량
unit_code varchar(255), -- 단위(매핑코드)
unit_self varchar(100), -- 단위(직접입력)
price integer, -- 현금(원)
estimated_value integer, -- 현물(평가액)
price bigint, -- 현금(원)
estimated_value bigint, -- 현물(평가액)
created_at timestamp(6), -- 생성일
created_by varchar(255), -- 생성자
updated_at timestamp(6), -- 수정일
@@ -211,11 +211,11 @@ CREATE TABLE daily_expense (
expense_kind varchar(100), -- 지출의 종류
expense_kind_mark varchar(10), -- 종류 부호
source_purpose varchar(10), -- 지출원(용도)
quantity varchar(10), -- 수량
quantity varchar(10), -- 수량
unit_code varchar(255), -- 단위(매핑코드)
unit_self varchar(100), -- 단위(직접입력)
price integer, -- 현금(원)
estimated_value integer, -- 현물(평가액)
unit_self varchar(100), -- 단위(직접입력)
price bigint, -- 현금(원)
estimated_value bigint, -- 현물(평가액)
created_at timestamp(6), -- 생성일
created_by varchar(255), -- 생성자
updated_at timestamp(6), -- 수정일
@@ -386,7 +386,7 @@ CREATE TABLE daily_forestry (
quantity varchar(10), -- 수량
unit_code varchar(255), -- 단위(매핑코드)
unit_self varchar(100), -- 단위(직접입력)
estimated_value integer, -- 현물평가
estimated_value bigint, -- 현물평가
created_at timestamp(6), -- 생성일
created_by varchar(255), -- 생성자
updated_at timestamp(6), -- 수정일
@@ -437,7 +437,7 @@ CREATE TABLE daily_farming (
quantity varchar(10), -- 수량
unit_code varchar(255), -- 단위(매핑코드)
unit_self varchar(100), -- 단위(직접입력)
estimated_value integer, -- 현물평가액
estimated_value bigint, -- 현물평가액
created_at timestamp(6), -- 생성일
created_by varchar(255), -- 생성자
updated_at timestamp(6), -- 수정일

View File

@@ -80,5 +80,5 @@ SELECT
a.name AS researcher_name,
a.phone AS researcher_phone
FROM researcher_has_household rhh
JOIN admin a ON rhh.admin_seq = a.seq
JOIN admin a ON rhh.admin_seq = a.seq and a.account_disabled = false
WHERE rhh.is_deleted = false;

View File

@@ -72,7 +72,7 @@ public class FrontSecurityConfig {
.collect(Collectors.toList());
// front - 익명 사용자 접근 허용 URI 등록 (admin 과 달리 공개/비공개 URL 이 존재한다)
FrontPublicAccess.getInstance().setURIs(List.of("/", "/user/register"));
FrontPublicAccess.getInstance().setURIs(List.of("/", "/user/register", "/policy/**"));
http.authorizeHttpRequests(
(auth) ->

View File

@@ -0,0 +1,102 @@
package app.module.front.config.application.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Locale;
@Slf4j
@Component
public class DailyUtil {
/**
* int -> localdate
* @param month 월(yyyyMM)
* @param day 일(d)
* @return LocalDate
*/
public LocalDate getDayToLocalDate(String month, int day) {
SimpleDateFormat beforeSdf = new SimpleDateFormat("yyyyMMdd", Locale.KOREAN);
SimpleDateFormat afterSdf = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREAN);
try {
Date formatDate = beforeSdf.parse(month + String.format("%02d", day));
return LocalDate.parse(afterSdf.format(formatDate));
} catch (Exception e) {
log.warn("[DailyUtil][getDayToLocalDate] month={}, day={}", month, day, e);
}
return null;
}
/**
* 마지막 일 여부
*
* @param searchDate 종료일(yyyy-MM-dd)
* @return true=마지막 일, false=마지막 일 아님
*/
public boolean isLastDay(LocalDate searchDate) {
if (searchDate != null) {
LocalDate lastDate = searchDate.withDayOfMonth(searchDate.lengthOfMonth());
return searchDate == lastDate;
}
return false;
}
/**
* 검색 일의 마지막 일 조회
* @param searchDate 검색
* @return 마지막 일
*/
public int getLastDay(LocalDate searchDate) {
return searchDate.withDayOfMonth(searchDate.lengthOfMonth()).getDayOfMonth();
}
/**
* 자가농업 항목 오픈 여부
* [정책] 자가농업 생산물 중 자가소비량은 7일차 등록일에만 노출 및 선택, 21일 이후는 마지막 날
*
* @param groupNo
* @param searchDate 종료일
* @return true=대상, false=대상 아님
*/
public boolean isFarmingOpen(int groupNo, LocalDate searchDate) {
return groupNo == 4 || groupNo == 8 || groupNo == 12 || isLastDay(searchDate);
}
/**
* 데이터 수정 가능 여부
* [정책] 15일전까지 데이터 수정 가능(등록도 불가)
* @param startDate
* @param endDate
* @return true=수정 가능, false=수정 불가
*/
public boolean isModifiable(LocalDate startDate, LocalDate endDate) {
// TODO : 15일로 변경, 테스트를 위해 30일로 진행중
LocalDate limitStart = LocalDate.now().minusDays(30);
log.debug("isModifiable @@limitStart: {}, startDate: {}, endDate: {}", limitStart, startDate, endDate);
return (limitStart.isBefore(startDate) || limitStart.isEqual(startDate) || limitStart.isEqual(endDate));
}
/**
* 데이터 등록 가능 여부
* @param startDate
* @param endDate
* @return
*/
public boolean isRegisterPossible(LocalDate startDate, LocalDate endDate) {
// TODO : 15일로 변경, 테스트를 위해 60일로 진행중
LocalDate limitStart = LocalDate.now().minusDays(60);
log.debug("isRegisterPossible @@limitStart: {}, startDate: {}, endDate: {}", limitStart, startDate, endDate);
return (limitStart.isBefore(startDate) || limitStart.isEqual(startDate));
}
}

View File

@@ -1,14 +1,19 @@
package app.module.front.usecase.daily.calendar.adapters.persistence;
import app.module.core.config.application.enums.MonthStatus;
import app.module.front.config.application.util.DailyUtil;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.DailyRecordCalendarDto;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.record.adapters.persistence.DailyRecordMapper;
import app.module.front.usecase.daily.record.adapters.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.MonthlyStatusDto;
import app.module.front.usecase.daily.calendar.ports.RecordCalendarPortOut;
import app.module.front.usecase.daily.calendar.ports.application.domain.RecordCalendar;
import app.module.front.usecase.daily.calendar.ports.application.domain.CalendarChildren;
import app.module.front.usecase.daily.calendar.ports.application.domain.RecordCalendarCmd;
import app.module.front.usecase.daily.record.adapters.web.model.DailySort;
import app.module.front.usecase.daily.record.adapters.web.model.DailyTargetStatus;
import app.module.front.usecase.daily.record.ports.application.domain.GetDailyRecordCmd;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
@@ -23,6 +28,8 @@ import java.util.Objects;
@RequiredArgsConstructor
public class RecordCalendarDao implements RecordCalendarPortOut {
private final RecordCalendarMapper recordCalendarMapper;
private final DailyRecordMapper dailyRecordMapper;
private final DailyUtil dailyUtil;
@Override
public List<RecordCalendar> operate(RecordCalendarCmd command) {
@@ -36,12 +43,14 @@ public class RecordCalendarDao implements RecordCalendarPortOut {
monthlyList.add(new CalendarChildren(
"MONTHLY",
"임산물 현황 등록",
null, // TODO
monthlyStatus.isForestNone() ? 0 : 1,
monthlyStatus.isForestNone() ? "/info/monthly" : String.format("/info/monthly/month/%s", command.getSearchMonth())));
monthlyList.add(new CalendarChildren(
"BANK",
"은행 자동이체 내역 등록",
null, // TODO
monthlyStatus.isBankNone() ? 0 : 1,
(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM")).equals(command.getSearchMonth())) ? "/info/bank" : null));
@@ -51,6 +60,11 @@ public class RecordCalendarDao implements RecordCalendarPortOut {
refine.setNo(calendar.getGroupNo());
refine.setStart(calendar.getStartDay());
refine.setEnd(calendar.getEndDay());
refine.setStartDate(dailyUtil.getDayToLocalDate(command.getSearchMonth(), calendar.getStartDay()));
refine.setEndDate(dailyUtil.getDayToLocalDate(command.getSearchMonth(), calendar.getEndDay()));
refine.setRegistrable(dailyUtil.isRegisterPossible(refine.getStartDate(), refine.getEndDate()));
refine.setModifiable(dailyUtil.isModifiable(refine.getStartDate(), refine.getEndDate()));
DailyRecordStatusDto findStatus = statusList.stream()
.filter(f -> Objects.equals(calendar.getDailyId(), f.getDailyId()))
@@ -58,53 +72,62 @@ public class RecordCalendarDao implements RecordCalendarPortOut {
List<CalendarChildren> childList = new ArrayList<>();
if (findStatus == null) {
refine.setChildren(new ArrayList<>());
if (!dailyUtil.isRegisterPossible(refine.getStartDate(), refine.getEndDate())) {
childList.addAll(this.getNoneChildList(dailyUtil.isFarmingOpen(refine.getNo(), refine.getEndDate())));
}
} else {
if (DailyTargetStatus.TARGET.equals(findStatus.getIncomeStatus())
|| DailyTargetStatus.TODAY_NONE.equals(findStatus.getIncomeStatus())) {
childList.add(new CalendarChildren(
"INCOME",
"수입",
DailySort.INCOME.name(),
DailySort.INCOME.getDesc(),
findStatus.getIncomeStatus(),
findStatus.getIncomeCount(),
String.format(pathFormat, "income", command.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getWorkStatus())
|| DailyTargetStatus.TODAY_NONE.equals(findStatus.getWorkStatus())) {
childList.add(new CalendarChildren(
"WORK",
"임업노동 투입 내역",
DailySort.WORK.name(),
DailySort.WORK.getDesc(),
findStatus.getWorkStatus(),
findStatus.getWorkCount(),
String.format(pathFormat, "work", command.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getExpenseStatus())
|| DailyTargetStatus.TODAY_NONE.equals(findStatus.getExpenseStatus())) {
childList.add(new CalendarChildren(
"EXPENSE",
"지출",
DailySort.EXPENSE.name(),
DailySort.EXPENSE.getDesc(),
findStatus.getExpenseStatus(),
findStatus.getExpenseCount(),
String.format(pathFormat, "expense", command.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getPowerStatus())
|| DailyTargetStatus.TODAY_NONE.equals(findStatus.getPowerStatus())) {
childList.add(new CalendarChildren(
"POWER",
"동력 사용시간",
DailySort.POWER.name(),
DailySort.POWER.getDesc(),
findStatus.getPowerStatus(),
findStatus.getPowerCount(),
String.format(pathFormat, "power", command.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getForestryStatus())
|| DailyTargetStatus.TODAY_NONE.equals(findStatus.getForestryStatus())) {
childList.add(new CalendarChildren(
"FORESTRY",
"자가임업 생산물 중 자가소비량",
DailySort.FORESTRY.name(),
DailySort.FORESTRY.getDesc(),
findStatus.getForestryStatus(),
findStatus.getForestryCount(),
String.format(pathFormat, "forestry", command.getSearchMonth(), findStatus.getDayGroupNo())));
}
if (DailyTargetStatus.TARGET.equals(findStatus.getFarmingStatus())
|| DailyTargetStatus.TODAY_NONE.equals(findStatus.getFarmingStatus())) {
childList.add(new CalendarChildren(
"FARMING",
"자가농업 생산물 중 자가소비량",
DailySort.FARMING.name(),
DailySort.FARMING.getDesc(),
findStatus.getFarmingStatus(),
findStatus.getFarmingCount(),
String.format(pathFormat, "farming", command.getSearchMonth(), findStatus.getDayGroupNo())));
}
@@ -118,6 +141,50 @@ public class RecordCalendarDao implements RecordCalendarPortOut {
return refineList;
}
/**
* 미작성 목록 조회
*
* @param farmingOpen
* @return 미작성 목록
*/
private List<CalendarChildren> getNoneChildList(boolean farmingOpen) {
List<CalendarChildren> childList = new ArrayList<>();
for (DailySort type : DailySort.values()) {
if (!DailySort.FARMING.equals(type) || (DailySort.FARMING.equals(type) && farmingOpen)) {
childList.add(new CalendarChildren(type.name(),type.getDesc()));
}
}
return childList;
}
@Override
public boolean getDataNoneCountBySomeDayAfter(RecordCalendarCmd command) {
int dataNoneCount = recordCalendarMapper.getDataNoneCountBySomeDayAfter(command);
return dataNoneCount != 0;
}
@Override
public String getLatestDate(RecordCalendarCmd command) {
String returnValue = null;
DailyRecordStatusDto detail = recordCalendarMapper.getLatestDate(command);
if (detail != null && detail.getStartDate() != null && detail.getEndDate() != null) {
if (detail.getStartDate().getMonth() != detail.getEndDate().getMonth()) {
// 종료일의 달이 변경되면 시작일=종료일 처리
detail.setEndDate(detail.getStartDate());
}
if (detail.getStartDate().equals(detail.getEndDate())) {
returnValue = detail.getStartDate().format(DateTimeFormatter.ofPattern("yyyy년 M월 d일"));
} else {
returnValue = detail.getStartDate().format(DateTimeFormatter.ofPattern("yyyy년 M월 d")) + "~" + detail.getEndDate().format(DateTimeFormatter.ofPattern("d일"));
}
}
return returnValue;
}
/**
* 특정월의 일 그룹 조회
*
@@ -128,14 +195,17 @@ public class RecordCalendarDao implements RecordCalendarPortOut {
List<DailyRecordCalendarDto> calendarList = recordCalendarMapper.getCalendarByDailyRecord(command);
List<DailyRecordCalendarDto> refineList = new ArrayList<>();
for (DailyRecordCalendarDto record : calendarList) {
record.setStartDate(command.getSearchMonth() + String.format("%02d", record.getStartDay()));
for (DailyRecordCalendarDto calendar : calendarList) {
LocalDate startDate = dailyUtil.getDayToLocalDate(command.getSearchMonth(), calendar.getStartDay());
LocalDate endDate = dailyUtil.getDayToLocalDate(command.getSearchMonth(), calendar.getEndDay());
int lastDay = dailyUtil.getLastDay(startDate);
calendar.setStartDate(startDate.toString());
if ((command.getLastDay() == 28 || command.getLastDay() == 30) && record.getStartDay() == command.getLastDay()) {
record.setEndDay(command.getLastDay());
refineList.add(record);
} else if (record.getStartDay() <= command.getLastDay() && record.getEndDay() <= command.getLastDay()) {
refineList.add(record);
if ((lastDay == 28 || lastDay == 30) && calendar.getStartDay() == lastDay) {
calendar.setEndDay(lastDay);
refineList.add(calendar);
} else if (calendar.getStartDay() <= lastDay && calendar.getEndDay() <= lastDay) {
refineList.add(calendar);
}
}
@@ -149,7 +219,7 @@ public class RecordCalendarDao implements RecordCalendarPortOut {
* @return
*/
private List<DailyRecordStatusDto> getDailyRecordStatus(RecordCalendarCmd command) {
List<DailyRecordStatusDto> statusList = recordCalendarMapper.getDailyRecordStatus(command);
List<DailyRecordStatusDto> statusList = dailyRecordMapper.getDailyRecordStatus(new GetDailyRecordCmd(command.getSearchMonth(), null, command.getHouseholdSeq()));
if (statusList == null || statusList.isEmpty()) {
return Collections.emptyList();
}

View File

@@ -1,7 +1,7 @@
package app.module.front.usecase.daily.calendar.adapters.persistence;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.DailyRecordCalendarDto;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.record.adapters.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.MonthlyStatusDto;
import app.module.front.usecase.daily.calendar.ports.application.domain.RecordCalendarCmd;
import org.apache.ibatis.annotations.Mapper;
@@ -18,14 +18,6 @@ public interface RecordCalendarMapper {
*/
List<DailyRecordCalendarDto> getCalendarByDailyRecord(RecordCalendarCmd command);
/**
* 특정일의 일계부 등록 상태 조회
*
* @param command 검색 조건
* @return 일계부 등록 현황 목록
*/
List<DailyRecordStatusDto> getDailyRecordStatus(RecordCalendarCmd command);
/**
* 특정월의 월별 작성 상태 조회
*
@@ -33,4 +25,20 @@ public interface RecordCalendarMapper {
* @return 월별 작성 상태
*/
MonthlyStatusDto getMonthlyStatus(RecordCalendarCmd command);
/**
* 3일전 ~ 15일전 미등록된 데이터 개수 조회
*
* @param command 검색 조건
* @return 미등록 건 수
*/
Integer getDataNoneCountBySomeDayAfter(RecordCalendarCmd command);
/**
* 최신 등록일 데이터 조회
*
* @param command 검색 조건
* @return 최신 등록 데이터
*/
DailyRecordStatusDto getLatestDate(RecordCalendarCmd command);
}

View File

@@ -29,8 +29,7 @@ public class RecordCalendarController {
List<RecordCalendar> calendarList = recordCalendarPortIn.operate(new RecordCalendarCmd(
reqVO.getSearchMonth(),
reqVO.getHouseholdSeq(),
reqVO.getSearchDate().withDayOfMonth(reqVO.getSearchDate().lengthOfMonth()).getDayOfMonth()
reqVO.getHouseholdSeq()
));
return ResponseEntity.status(HttpStatus.OK).body(calendarList);

View File

@@ -1,6 +1,7 @@
package app.module.front.usecase.daily.calendar.adapters.web;
import app.module.front.usecase.daily.calendar.adapters.web.model.RecordCalendarUIReqVO;
import app.module.front.usecase.daily.calendar.ports.RecordCalendarPortIn;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
@@ -13,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
@RequiredArgsConstructor
@RequestMapping(path = "/record/calendar")
public class RecordCalendarUIController {
private final RecordCalendarPortIn recordCalendarPortIn;
@GetMapping(path = "")
public String index(Model model) {
@@ -21,7 +23,7 @@ public class RecordCalendarUIController {
model.addAttribute("reqVO", reqVO);
// TODO : 현재 날짜로부터 3일 이전 날짜에 등록하지 않은 날이 있을 경우
model.addAttribute("dailyDataNone", recordCalendarPortIn.getDataNoneCountBySomeDayAfter());
return "record/calendar";
}

View File

@@ -2,6 +2,8 @@ package app.module.front.usecase.daily.calendar.adapters.web.model;
import app.module.front.usecase.daily.record.adapters.web.model.DailyUIReqVO;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.tika.utils.StringUtils;
import org.slf4j.Logger;
@@ -10,7 +12,8 @@ import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@Data
@Getter
@Setter
@ToString
public class RecordCalendarUIReqVO extends DailyUIReqVO {
private static final Logger LOGGER = LoggerFactory.getLogger(RecordCalendarUIReqVO.class);

View File

@@ -6,5 +6,25 @@ import app.module.front.usecase.daily.calendar.ports.application.domain.RecordCa
import java.util.List;
public interface RecordCalendarPortIn {
/**
* 특정월의 일계부 등록 현황 조회
*
* @param command 검색 조건
* @return 특정월의 일계부 등록 현황
*/
List<RecordCalendar> operate(RecordCalendarCmd command);
/**
* 특정기간의 데이터 미등록 여부 조회
*
* @return true=미등록 데이터 있음, false=없음
*/
boolean getDataNoneCountBySomeDayAfter();
/**
* 일계부 최신 데이터 조회
*
* @return 최신 등록 기간
*/
String getLatestDate();
}

View File

@@ -1,7 +1,5 @@
package app.module.front.usecase.daily.calendar.ports;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.DailyRecordCalendarDto;
import app.module.front.usecase.daily.calendar.adapters.persistence.model.DailyRecordStatusDto;
import app.module.front.usecase.daily.calendar.ports.application.domain.RecordCalendar;
import app.module.front.usecase.daily.calendar.ports.application.domain.RecordCalendarCmd;
@@ -9,4 +7,8 @@ import java.util.List;
public interface RecordCalendarPortOut {
List<RecordCalendar> operate(RecordCalendarCmd command);
boolean getDataNoneCountBySomeDayAfter(RecordCalendarCmd command);
String getLatestDate(RecordCalendarCmd command);
}

Some files were not shown because too many files have changed in this diff Show More