Compare commits

...

44 Commits

Author SHA1 Message Date
ca2c61d8eb 261120_01_ENH: 변경 정보, 관계자 정보 파트 재단이 수정할 수 있도록 수정 2026-11-20 12:26:30 +09:00
82496b6ce4 261103_01_ENH: 공연 상세 관계자 정보 유형별 빈 행 표시 및 단체(인)명 수정 가능하도록 개선 2026-11-03 16:06:36 +09:00
92832afebe 261026_02_ENH: 변경 타입에 clearLabel을 전체 -> 선택 해제로 수정 2026-10-26 17:17:24 +09:00
2667c40086 261026_01_ENH: 공연 상세정보에 관리번호(NCAS), 변경 메모 추가 2026-10-26 16:21:42 +09:00
0708ddd936 260909_01_ENH: 문자 미리보기는 의미가 없어서 제거 2026-09-09 15:06:15 +09:00
3ea6905e00 260826_01_ENH: notihub 수정으로 인한 후속 조치 2026-08-26 12:27:06 +09:00
d84c8b2c34 260819_01_ENH: 자체보고서 업로드 막혀있던 버그 수정 2026-08-19 11:09:09 +09:00
5f7bf5ce1b docs: refresh UI registry contract 2026-08-10 11:32:23 +09:00
a30c155282 docs: adopt AI agent harness 2026-08-07 15:41:59 +09:00
0b125185f5 260806_01_ENH: 문자 템플릿 저장 json에서 form 방식으로 교체 2026-08-06 13:53:00 +09:00
cc905433d3 260728_01_ENH: 연구원 계정에 사업 삭제 기능 부여 2026-07-28 14:57:57 +09:00
cb4054e9e7 260723_01_ENH: 모니터링 배정 다이얼로그 디폴트 페이지 사이즈 변동 적용 되게 수정 2026-07-23 09:15:39 +09:00
6a1a1ba263 260713_01_ENH: 미진행인 모니터링 평가에 대해서도 upload가 가능하도록 수정 및 재단 계정에서도 업로드 가능하게 수정 2026-07-13 11:35:47 +09:00
c6eeb3e62f 260708_03_ENH: pdf 변환에 대한 변환 상태 표기 2026-07-08 16:48:42 +09:00
984d257553 260708_02_ENH: pdf 변환에 대한 공지 및 변환 상태 표기 2026-07-08 16:24:46 +09:00
8fad245959 260708_01_ENH: api 응답 대기시간 300초로 수정 2026-07-08 14:29:52 +09:00
3edbbee103 260707_01_ENH: 모니터링 출발/도착 버튼은 모니터링 일자 이후로 부터 노출되게 수정 및 관리자는 출발 도착 삭제 가능하게 수정 2026-07-07 15:06:19 +09:00
9e12f238d8 260702_04_ENH: KON 조회 compact 조회에서 전체 조회로 수정 2026-07-02 16:08:17 +09:00
788f8d820e 260702_03_ENH: 사용자 페이지 페이지네이션 제거 2026-07-02 15:46:30 +09:00
0de2b6be42 260702_02_ENH: 페이지네이션 제거 2026-07-02 15:34:10 +09:00
07db455633 260702_01_ENH: 사업정보, 모니터링 배정의 datatable의 일부 컬럼 max width 지정 및 truncate 적용 2026-07-02 11:31:14 +09:00
bcb109e826 260701_01_ENH: 배정 화면에서 확정요청 수, 포기인원 수, 확정인원 수 완전 분리 2026-07-01 10:53:55 +09:00
9f214c4a03 260630_02_ENH: 로그아웃 시 alert 안뜨게 수정 2026-06-30 18:04:35 +09:00
0f407e3656 260630_01_ENH: 배정 반려 기능 추가로 인한 후처리 작업 2026-06-30 17:42:56 +09:00
28d6969cde 260629_03_ENH: PDF 미리보기 title 수정 2026-06-29 14:53:06 +09:00
83fd8567de 260629_02_ENH: PDF 미리보기 title 수정 2026-06-29 12:26:08 +09:00
6ce187bcf1 260629_02_ENH: PDF 미리보기 title 제거 2026-06-29 12:17:34 +09:00
1234d16db4 260629_01_ENH: PDF 미리보기 파일명 노출될 수 있도록 수정 및 KON용 code 조회 추가 2026-06-29 11:33:29 +09:00
a09dded4ca 260625_10_ENH: 파일명 수정 2026-06-25 16:05:36 +09:00
5a336ed1b3 260625_09_ENH: 파일명 zip처리 2026-06-25 15:54:59 +09:00
03e9e2c2f1 260625_08_ENH: 서면 평가원 화면에서 모니터링은 1개로 합치고 그에따른 상태값 처리 및 zip 다운로드 적용 2026-06-25 15:49:06 +09:00
f6c9a013b5 260625_07_ENH: table 간격 조정 -> 사업유형, 단체명, 사업명 ... 처리 2026-06-25 14:59:29 +09:00
3bcbfca4e9 260625_06_ENH: table 간격 조정, body width 제한, 일부 label 수정, 지역 수정가능하게 열기, 지자체 양식 다운로드 버튼 제거 2026-06-25 13:56:22 +09:00
0853db0c2a 260625_05_ENH: 연구, 실사 수정사항 적용 5차 2026-06-25 13:30:14 +09:00
63d8653080 260625_04_ENH: 연구, 실사 수정사항 적용 4차 2026-06-25 13:24:57 +09:00
5b3298eaec 260625_03_ENH: 연구, 실사 수정사항 적용 3차 2026-06-25 13:17:37 +09:00
aae4a64b19 260625_01_ENH: 연구, 실사 수정사항 적용 2차 2026-06-25 13:09:30 +09:00
29dd9d628e 260625_01_ENH: 연구, 실사 수정사항 적용 1차 2026-06-25 13:05:37 +09:00
8e3c4302c5 260624_06_ENH: 모니터링에 상태 뱃지 적용 2026-06-24 15:24:17 +09:00
762211990e 260624_05_ENH: 문자발송 팝업 다중 템플릿 적용 2026-06-24 15:11:55 +09:00
f873e2fbd4 260624_04_ENH: 성별 안나오던 내용 수정 2026-06-24 10:43:13 +09:00
c4f8e630ea 260624_03_ENH: label 일괄 관리 및 문자 발송 팝업에 사용가능 변수 추가 2026-06-24 10:39:47 +09:00
438e6258dc 260624_02_ENH: 사용자 상세 정보 가져오기 수정 2026-06-24 09:53:34 +09:00
3d4fa65b0e 260624_01_ENH: 사용자 수정 관련 수정 2026-06-24 09:40:24 +09:00
57 changed files with 2439 additions and 394 deletions

View File

@@ -0,0 +1,13 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-front-common
Source: .agent/consumer-references/change-and-verification.md
-->
# KriFrontCommon Change and Verification
- Pin or constrain the package version according to the consumer repository's dependency policy and commit its lockfile changes.
- Review release notes and the actual affected API before upgrading.
- Run the consumer's focused type-check, test, and build commands after an upgrade.
- Keep `.agent/project.md` near 2-3 KiB as a routing document. Move conditional schemas, endpoint inventories, examples, and issue history to routed `.agent/references/` documents instead of deleting them.
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.

View File

@@ -0,0 +1,15 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-front-common
Source: .agent/consumer-references/package-and-runtime.md
-->
# KriFrontCommon Package and Runtime Contract
- Use the package root for runtime-neutral object, URL, date, string, and shared type utilities.
- Use a focused subpath such as `@kri/common/http`, `@kri/common/browser`, `@kri/common/server`, `@kri/common/security`, `@kri/common/hooks`, `@kri/common/query`, `@kri/common/config`, `@kri/common/jotai`, or `@kri/common/noti-hub` for the corresponding capability.
- Keep browser, server, and runtime-neutral imports on their intended side of the application boundary.
- A consumer that uses React hooks, TanStack Query, or Jotai integrations must provide the compatible optional peer dependency required by its selected entry point.
- Preserve the project's established HTTP client, authentication, error-policy, query-client, storage, and environment conventions when adopting a shared helper.
- Validate external data at runtime; a shared TypeScript type alone does not validate an API response or persisted value.
- Prefer named public exports and retain the consumer project's current module system and bundler conventions.

View File

@@ -0,0 +1,13 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-front-common
Source: .agent/consumer-references/react-compiler.md
-->
# React Compiler and Manual Memoization
- `createKriNextConfig` enables `reactCompiler: true` unless the project overrides it; confirm the effective configuration.
- When enabled, rely on React Compiler instead of adding `useMemo`, `useCallback`, or `React.memo` as a routine performance precaution.
- Use manual memoization only for required reference stability, an Effect or third-party contract, compiler-incompatible code, or a measured performance problem.
- Preserve existing memoization unless approved and verified for removal.
- Use `"use memo"` or `"use no memo"` only for a documented compiler boundary.

View File

@@ -0,0 +1,11 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-ui-registry
Source: .agent/consumer-references/editor-html-compatibility.md
-->
# KriEditor HTML Compatibility
- `enableImageMap` opt-in preserves `map`, nested `area`, and `img.usemap` HTML in WYSIWYG mode; consumers remain responsible for sanitizing URLs and attributes according to their server policy.
- Use `htmlSanitizer` when a consumer must apply a stricter HTML policy than the editor's default DOMPurify profile.
- Use `getWysiwygCompatibility` to keep lossy HTML in HTML mode. The callback must return `compatible: false` when WYSIWYG parsing would remove or materially rewrite content.

View File

@@ -0,0 +1,23 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-ui-registry
Source: .agent/consumer-references/installation-and-adaptation.md
-->
# KriUiRegistry Installation and Adaptation
## Installation and Ownership
- Inspect the registry item and its dependencies before installation. Use the shadcn CLI with the approved registry endpoint under `https://ui-registry.kric.com/r/` instead of copying files from `dist/r` manually.
- `kri-data-table` uses the TanStack Table v8 API. Keep `@tanstack/react-table` within the supported `^8.21.3` range and do not upgrade it to v9 until KriUiRegistry provides an explicitly migrated component contract.
- Respect the consumer project's component aliases, target paths, package manager, styling system, React version, and existing design tokens.
- The shadcn workflow copies component source into the consumer repository. After installation, treat that copy as project-owned code; do not assume registry updates propagate automatically.
- Do not overwrite an existing project component without reviewing the diff and confirming that local behavior and accessibility are preserved.
- Keep package and lockfile changes produced by an installation within the approved scope.
## Adaptation and Verification
- Adapt business data and application behavior outside the shared component when possible. Avoid embedding project-specific API, route, authentication, or environment logic into a reusable component.
- Preserve the installed component's public props, accessibility, keyboard behavior, responsive layout, and loading, empty, error, and disabled states unless the task explicitly changes them.
- If the registry lacks a generally reusable capability, propose it in KriUiRegistry; do not modify that repository unless it is explicitly in scope.
- Run the consumer repository's focused type-check, lint, tests, and build after installation or upgrade.

18
.agent/profile.yml Normal file
View File

@@ -0,0 +1,18 @@
schema_version: 1
project:
id: gwcf-review-front
name: GWCF Monitoring Frontend
type: requested-project
layer: frontend
legacy: false
stack:
- typescript
- react
- nextjs
shared_contracts:
consumes:
- kri-front-common
- kri-ui-registry

18
.agent/project.md Normal file
View File

@@ -0,0 +1,18 @@
# GWCF Monitoring Frontend Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

View File

@@ -0,0 +1,22 @@
## GWCF Monitoring Frontend Repository Rules
### Deliverable and User Workflows
- This Next.js frontend supports GWCF performance records, monitoring assignments, schedules and visits, reviews, users, file preview, and related operational workflows.
- Its product character is similar to KriContact, but its requirements, API, permissions, terminology, and deliverables remain project-specific.
- Preserve selected performance context, assignment state, review state, visit information, filters, file-preview behavior, and user/role boundaries across navigation and mutations.
- Keep personal information, monitoring details, uploaded documents, and exported data out of logs, fixtures, screenshots, and external services.
### Frontend and Local Next.js Guidance
- Use the consumed KRI frontend common and UI registry contracts. Prefer an existing shadcn/ui or registry component before creating a new foundational component.
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
- This repository may use Next.js APIs and conventions newer than model training data. Read the relevant local guide under `node_modules/next/dist/docs/` before changing a Next.js API, routing convention, or file structure, and follow deprecation notices.
- Preserve accessibility, loading, empty, error, unauthorized, confirmation, success, and file-preview states.
- Coordinate request, response, authentication, file, and error changes with the backend without requiring an unsafe simultaneous deployment.
### Harness and Verification
- The previous standalone `AGENTS.md` Next.js guidance has been preserved in this project source. `AGENTS.md` and `CLAUDE.md` are now harness-generated outputs.
- Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
- Use existing npm scripts and focused checks. Do not call production APIs, process customer documents, or submit real monitoring/review data during validation.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

View File

@@ -1,6 +1,6 @@
NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=https://test-gwcf-review.kric.com/api
ENV=prod
ENV=dev
API_BACK_SERVER=http://127.0.0.1:6105/api/v1
NOTI_HUB_SERVER=https://noti-hub.kric.com/api/v1

View File

@@ -4,3 +4,4 @@ NEXT_PUBLIC_API_BASE=http://localhost:6104/api
ENV=local
API_BACK_SERVER=http://localhost:6105/api/v1
NOTI_HUB_SERVER=https://noti-hub.kric.com/api/v1
#NOTI_HUB_SERVER=http://localhost:4011/api/v1

4
.gitattributes vendored Normal file
View File

@@ -0,0 +1,4 @@
/.gitattributes text eol=lf
/.agent/** text eol=lf
/AGENTS.md text eol=lf
/CLAUDE.md text eol=lf

2
.gitignore vendored
View File

@@ -39,3 +39,5 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
.idea

361
AGENTS.md
View File

@@ -1,5 +1,358 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: gwcf-review-front
Schema version: 1
Edit the source fragments or repository .agent files, then recompose.
-->
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
### Attention-Aware Response Style
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## Workflow Skills
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
- Include intended validation in the discussion-phase plan.
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
- Limit formatting to files within the approved scope.
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
- Do not claim that a check passed unless it was executed successfully.
- If a check cannot be run, state the exact reason.
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
- Do not fix unrelated failures without expanding the approved scope.
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
## Artifacts and Session Records
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
- Store durable information in the repository's existing documentation structure.
- Do not place generated reports or temporary analysis files in the repository root.
- Remove task-specific temporary files created by the current task after validation when removal is safe.
## Completion Report
When implementation is complete, report in Korean:
- what changed and why;
- the main affected files or components;
- validation commands actually executed and their results;
- checks not executed and the reason;
- remaining risks, assumptions, or follow-up work;
- database, deployment, dependency, encoding, and compatibility impact when applicable.
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
- Keep the report concise and do not include a full session transcript.
## Requested Project Rules
- Treat the approved requirements, acceptance criteria, and recorded decisions as the primary scope boundary.
- Do not infer a requirement solely from a file name, folder date, or apparently newer document.
- When requirements conflict, report the exact sources and request a decision.
- Preserve original customer, partner, and planning documents as read-only evidence unless document editing is explicitly approved.
- Summarize durable implementation requirements inside the repository rather than relying only on files outside the repository.
- Do not expand the deliverable with speculative features, infrastructure, or architectural changes.
- Record material assumptions and unresolved decisions in the project-specific rules or existing project documentation.
- Define observable acceptance criteria before implementation.
- Treat separately managed Frontend and Backend repositories as independent deliverables with a coordinated contract.
- Protect customer, partner, survey, and field data as sensitive information.
- Keep handoff, operation, configuration, and validation instructions usable by the requesting team.
- Report deviations from the requested scope and obtain approval before proceeding.
## TypeScript
- Treat the repository's current TypeScript version, `tsconfig` files, module system, path aliases, and package manager as authoritative.
- Preserve or strengthen existing strictness. Do not weaken compiler options or hide errors with broad `any`, `@ts-ignore`, or unsafe assertions.
- Prefer narrow domain types, discriminated unions, and explicit boundary types over duplicated or overly generic shapes.
- Validate untrusted runtime input even when a compile-time type exists.
- Keep imports, exports, aliases, and generated-code boundaries consistent with the repository.
- Do not introduce a JavaScript-to-TypeScript conversion outside the approved scope.
- Run the repository's focused type-check, lint, test, and build commands as applicable.
## React
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable.
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
- Treat any planned Next.js migration as a separate policy and task; the current React application remains authoritative until that migration slice is approved.
## Next.js
- Treat the repository's current Next.js and React versions, routing model, rendering model, and package manager as authoritative.
- Preserve server and client component boundaries. Add `use client` only when browser APIs, state, effects, or client-only libraries require it.
- Keep secrets, privileged data access, and server-only modules out of client bundles.
- Preserve established route, layout, middleware, authentication, authorization, caching, revalidation, and error-handling conventions.
- Validate request parameters, payloads, headers, cookies, and external responses at runtime.
- Do not create new frontend TypeScript type or interface names ending in `Dto` or `DTO`. Use domain- or purpose-specific names such as `User`, `UserInput`, `UserRequest`, or `UserResponse`; do not rename existing types solely to enforce this rule outside the approved scope.
- Use the approved KRI frontend and UI contracts when the project profile includes them; do not copy shared implementations into an application.
- Avoid incidental routing-model or rendering-strategy migrations.
- Run the repository's focused lint, type-check, test, and production build commands as applicable.
## KriFrontCommon Consumer Contract
- Consume the published `@kri/common` package only through entry points declared by its `package.json` `exports` map.
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
- Prefer a public shared helper or an approved backward-compatible library addition over copying or forking shared behavior locally.
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Package entry points, runtime boundaries, HTTP, authentication, state, storage, environment, or optional peer integrations | `.agent-harness/references/kri-front-common/package-and-runtime.md` |
| React rendering performance, memoization, or React Compiler behavior | `.agent-harness/references/kri-front-common/react-compiler.md` |
| Package upgrade, dependency changes, lockfile, or verification | `.agent-harness/references/kri-front-common/change-and-verification.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
## Noti-hub SMS Types
- `MessageType.SMS = 21`, `LMS = 22`, `MMS = 23`; `ChannelType.SMS = 2` is unchanged. `SMS_TYPE_ARRAY` and `SmsType` include all three.
- `LMS_MMS = 22` remains a deprecated source-compatibility alias for LMS only. It does not represent MMS. Enum reverse lookup for 22 returns LMS. Use numeric bulk-list paths; the server no longer accepts LMS_MMS in paths. Numeric 21/22/23 bulk-list requests all return the entire SMS channel, not type-filtered lists.
- Requests retain their existing URLs/body shapes. The server chooses the actual type per recipient after substitution: attachment -> MMS; otherwise title or UTF-8 body >= 90 bytes -> LMS; otherwise SMS.
- Refresh templates from the save response (`tmplatTy`); display actual delivery types from `sendTy`, not the template or result code. A bulk can contain multiple SMS types. LMS/MMS share result codes; use existing server result labels.
- SMS, LMS, MMS and KKO use cancellation code 9998. Verify with `npm run typecheck`, `npm run build`, and `node --test tests/noti-hub-sms.test.mjs`.
## Noti-hub Reservation Cancellation
- Import cancellation types, constants, and helpers from `@kri/common/noti-hub` only. They are runtime-neutral and require no optional peers.
- Individual current cancellation state is determined by resultCode via isReserveCanceledResult; bulk current state is cancellationStatus (NONE/PARTIAL/ALL). These describe current cancellation state, not cancellation eligibility. cancelDt and cancelUser are request history, not current state.
- SendResultInfo, SendInfo, and BulkSendInfo expose optional cancelable. Use isSendCancelable(item), which returns true only for cancelable === true, for cancellation eligibility; missing values from older responses are treated as false. Never infer eligibility from cancelDt, result labels, or result codes.
- cancelable reflects query-time state and may change before cancellation. Determine the final outcome from SendCancelResponse counts.
- sendIdx is the single-cancel identifier, not cmid. It is absent from the latest abbreviated report (/api/v1/report/last/send/...). Request sendIdx must be a positive integer; bulkSendKey is required and at most 32 characters.
- EMAIL_RESERVE_CANCELED_RESULT_CODE is 108 for EMAIL. SMS_KKO_RESERVE_CANCELED_RESULT_CODE is 9998 for SMS, LMS, MMS, and KKO. Unknown message types are not recognized as canceled.
- Display the server's resultViewLabel/resultLabel ("예약 취소"). There is no separate result-code list API.
- HTTP 200 can contain notCancelableCount. parseSendCancelResponse validates nonnegative integer counts and targetCount = canceledCount + alreadyCanceledCount + notCancelableCount, throwing TypeError on invalid data. Bulk targetCount counts currently registered detail rows; response canceledCount counts only cancellations made by that request.
- Existing response fields are unchanged; all added fields on existing types are optional. Verify with npm run typecheck and npm run build.
## HTTP Streaming
- `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body).
- Streaming shares ordinary authentication, URL, body and HTTP-error policy. Read body incrementally; no automatic JSON/NDJSON/SSE parsing or reconnect is performed.
- Streaming options accept an external AbortSignal. Caller cancellation raises AbortError without an HTTP error notification. Cancel the body when it will not be consumed.
- timeoutMs covers connection/headers (and an HTTP error body); idleTimeoutMs covers inactivity after successful headers and resets on consumed chunks. Both default to the client's defaultTimeoutMs (60 seconds by default), and 0 disables that timer for streaming only.
- Mid-stream transport/time-out errors reach the body reader. HTTP error statuses use existing HttpError handlers before a stream is returned. A 204 response has body=null.
- See HTTP_STREAMING.md for examples and node --test tests/http-stream.test.mjs for focused validation after npm run build.
## KriUiRegistry Consumer Contract
When implementing or changing frontend UI, use this order:
1. Reuse an existing shared component in the project when it already meets the requirement.
2. Prefer an approved component from KriUiRegistry.
3. Otherwise, prefer a suitable shadcn/ui component.
4. Create a custom component only when the preceding options cannot meet the requirement safely.
### KriAutoComplete Search Scroll
- `kri-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior.
- When enabled, a search value change (including clearing it) resets the option list scroll to the top on the next animation frame in both `filter` and `inputOnly` modes. Async result updates alone do not trigger another reset.
### KriAutoComplete Option Tooltip
- `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior.
- When enabled, hovering an option shows its full `label` in a right-side tooltip. `singleLine` stays on one line until the available viewport width; `wrap` wraps at 28rem. The item depends on the shadcn `tooltip` component and provides its own `TooltipProvider`.
### KriAutoComplete Search Match
- `kri-auto-complete` exposes `searchMatch?: 'fuzzy' | 'contains'` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `fuzzy` (cmdk's default subsequence scoring), preserving existing behavior.
- `contains` keeps only options whose label or value contains the search text as a case-insensitive substring, in the original option order. It applies only when `searchMode` is `filter`.
### KriEditor SMS Preview
- `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract.
- Attachment presence (`smsHasAttachment`) takes priority and reports MMS. Otherwise a title or UTF-8 preview size >= `smsMaxBytes` (default 90) reports LMS; the remainder reports SMS. LMS/MMS share `lmsMaxBytes` (default 2000).
- UTF-8 byte counting includes `smsPreviewSuffix` and its separating newline, without storing the suffix in the body.
- This is a preview. Use the template-save response for saved `tmplatTy` and delivery-result `sendTy` for actual per-recipient type after server substitution. Registry updates require updating installed consumer copies.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Installing, upgrading, adapting, or verifying a registry component | `.agent-harness/references/kri-ui-registry/installation-and-adaptation.md` |
| KriEditor HTML, image-map, sanitizer, or WYSIWYG compatibility | `.agent-harness/references/kri-ui-registry/editor-html-compatibility.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriUiRegistry's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
# GWCF Monitoring Frontend Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

View File

@@ -11,20 +11,26 @@ import {DataTableColumn} from "@/components/data-table/DataTable.type";
import {SmsSendDialog} from "@/components/dialog/SmsSendDialog";
import {AssignMonitoringDialog} from "@/components/dialog/AssignMonitoringDialog";
import {useCodesQuery} from "@/query/code";
import {usePerformanceListQuery} from "@/query/performance";
import {usePerformanceDetailQuery, usePerformanceListQuery} from "@/query/performance";
import {
useMonitoringApplyUserCountsQuery,
useMonitoringApplyUsersQuery,
useSaveMonitoringAssignMutation,
} from "@/query/assign";
import {filterPerformance, getCodeLabel} from "@/lib/gwcf/view";
import {MONITORING_ASSIGN_TYPE} from "@/lib/gwcf/performance-status";
import {
isAssignConfirmed,
isAssignRejected, isAssignRequested,
MONITORING_ASSIGN_TYPE
} from "@/lib/gwcf/performance-status";
import {PerformanceAssign, PerformanceFull} from "@/types/gwcf";
import {useDialog} from "@/hooks/useDialog";
import {useMounted} from "@/hooks/useMounted";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {SMS_TEMPLATE_IDS} from "@/query/notification";
import {buildPerformanceSmsParams} from "@/lib/gwcf/notification";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/gwcf/field-labels";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
const AssignPage = () => {
const mounted = useMounted();
@@ -41,11 +47,18 @@ const AssignPage = () => {
monitoringDate: "",
keyword: "",
});
const debouncedFilters = useDebouncedValue(filters);
const [selected, setSelected] = useState<PerformanceFull | null>(null);
const smsAddParam = useMemo(() => selected ? buildPerformanceSmsParams(selected) : {}, [selected]);
const [assignSaveTargetIds, setAssignSaveTargetIds] = useState<string[]>([]);
const filtersInitializedRef = useRef(false);
type SmsMode = "assignConfirm" | "normal";
const [smsMode, setSmsMode] = useState<SmsMode>("assignConfirm");
const [smsTargetIds, setSmsTargetIds] = useState<string[]>([]);
const [smsTemplateIdx, setSmsTemplateIdx] = useState<number[]>([]);
const [smsDialogTitle, setSmsDialogTitle] = useState<string>("");
const [newSmsTemplateIdx, setNewSmsTemplateIdx] = useState<number|undefined>(undefined);
const smsAddParam = useMemo(() => selected ? buildPerformanceSmsParams(selected) : {}, [selected]);
const refreshAssignList = () => {
void refetchPerformanceList();
@@ -54,9 +67,17 @@ const AssignPage = () => {
const updateFilters = (updater: (prev: typeof filters) => typeof filters) => {
setFilters(updater);
refreshAssignList();
};
useEffect(() => {
if (!filtersInitializedRef.current) {
filtersInitializedRef.current = true;
return;
}
refreshAssignList();
}, [debouncedFilters, refetchApplyCounts, refetchPerformanceList]);
useEffect(() => {
hideDialog("assignMonitoringDialog");
hideDialog("assignSmsSendDialog");
@@ -82,13 +103,13 @@ const AssignPage = () => {
const filteredData = useMemo(() => {
return data
.filter((item) => filterPerformance(item, filters))
.filter((item) => filterPerformance(item, debouncedFilters))
.sort((a, b) => {
const aDate = a.performanceMonitoringSchedule?.monitoringDate ?? "";
const bDate = b.performanceMonitoringSchedule?.monitoringDate ?? "";
return bDate.localeCompare(aDate);
});
}, [data, filters]);
}, [data, debouncedFilters]);
const openAssign = (performance: PerformanceFull) => {
suppressAssignCloseRef.current = false;
@@ -114,29 +135,76 @@ const AssignPage = () => {
return (performance.performanceAssignList ?? []).filter((assign) => assign.assignType === MONITORING_ASSIGN_TYPE);
};
const smsBeforeSendProps =
smsMode === "assignConfirm"
? {
isBeforeSendPending: saveAssignMutation.isPending,
onBeforeDefaultTemplateSend: async () => {
if (!selected) throw new Error("공연 정보가 없습니다.");
const monitoringAssigns = await saveAssignMutation.mutateAsync({
performanceId: selected.id,
userIds: assignSaveTargetIds,
});
applySavedAssignsToSelected(selected.id, monitoringAssigns);
},
onSent: refreshAssignList,
}
: {};
const columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
{accessorKey: "id", header: "연번", cell: ({row}) => row.original.id, enableSorting: true},
{accessorKey: "performanceName", header: "사업명", enableSorting: true},
{id: "area", header: "지역", cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
{accessorKey: "performanceDtInfo", header: "사업 일정"},
{accessorKey: "performanceTimeInfo", header: "운영 시간"},
{id: "monitoringDate", header: "모니터링 일정", cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate ?? "", enableSorting: true},
{id: "monitoringTime", header: "모니터링 시간", cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""},
{id: "applyCount", header: "신청자 수", cell: ({row}) => applyCountMap.get(String(row.original.id)) ?? 0, enableSorting: true},
{id: "requestCount", header: "확정요청 수", cell: ({row}) => getMonitoringAssigns(row.original).length},
{id: "confirmedCount", header: "확정인원 수", cell: ({row}) => getMonitoringAssigns(row.original).filter((assign) => assign.assignConfirm).length},
{accessorKey: "id", header: PERFORMANCE_FIELD_LABELS.id, cell: ({row}) => row.original.id},
{
accessorKey: "performanceName",
header: PERFORMANCE_FIELD_LABELS.performanceName,
cell: ({row}) => (
<div className="max-w-[400px] truncate" title={row.original.performanceName}>
{row.original.performanceName}
</div>
),
},
{id: "area", header: PERFORMANCE_FIELD_LABELS.performanceArea, cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
{
accessorKey: "performanceDtInfo",
header: PERFORMANCE_FIELD_LABELS.performanceDtInfo,
cell: ({row}) => (
<div className="max-w-[250px] truncate" title={row.original.performanceDtInfo}>
{row.original.performanceDtInfo}
</div>
),
enableSorting: false
},
{
accessorKey: "performanceTimeInfo",
header: PERFORMANCE_FIELD_LABELS.performanceTimeInfo,
cell: ({row}) => (
<div className="max-w-[250px] truncate" title={row.original.performanceTimeInfo}>
{row.original.performanceTimeInfo}
</div>
),
enableSorting: false
},
{id: "monitoringDate", header: PERFORMANCE_FIELD_LABELS.monitoringDate, accessorFn:(row) => row.performanceMonitoringSchedule?.monitoringDate ?? "", cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate ?? ""},
{id: "monitoringTime", header: PERFORMANCE_FIELD_LABELS.monitoringTimeInfo, cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""},
{id: "applyCount", header: "신청자 수", accessorFn:((row) => applyCountMap.get(String(row.id)) ?? 0), cell: ({row}) => applyCountMap.get(String(row.original.id)) ?? 0},
{id: "requestedCount", header: "확정요청 수", accessorFn:((row) => getMonitoringAssigns(row).filter(isAssignRequested).length), cell: ({row}) => getMonitoringAssigns(row.original).filter(isAssignRequested).length},
{id: "rejectedCount", header: "포기인원 수", accessorFn:((row) => getMonitoringAssigns(row).filter(isAssignRejected).length), cell: ({row}) => getMonitoringAssigns(row.original).filter(isAssignRejected).length},
{id: "confirmedCount", header: "확정인원 수", accessorFn:((row) => getMonitoringAssigns(row).filter(isAssignConfirmed).length), cell: ({row}) => getMonitoringAssigns(row.original).filter(isAssignConfirmed).length},
], [applyCountMap, codes]);
const {data: detailData} = usePerformanceDetailQuery(selected?.id ?? 0, Boolean(selected?.id && assignOpen));
if(!mounted) return <LoadingOverlay force={true} />
return (
<div className="space-y-4">
<PagePanel>
<div className="grid gap-2 md:grid-cols-[160px_160px_180px_1fr_auto]">
<MultiFilterSelect value={filters.businessType} onChange={(value) => updateFilters((prev) => ({...prev, businessType: value}))} options={codes.business_type} placeholder="사업 유형" />
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder="지역" />
<MultiFilterSelect value={filters.businessType} onChange={(value) => updateFilters((prev) => ({...prev, businessType: value}))} options={codes.business_type} placeholder={PERFORMANCE_FIELD_LABELS.businessType} />
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder={PERFORMANCE_FIELD_LABELS.performanceArea} />
<Input type="date" value={filters.monitoringDate} onChange={(event) => updateFilters((prev) => ({...prev, monitoringDate: event.target.value}))} />
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder="연번 or 사업명" />
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder={`${PERFORMANCE_FIELD_LABELS.id} or ${PERFORMANCE_FIELD_LABELS.performanceName}`} />
<Button type="button" variant="outline" onClick={refreshAssignList}>
<Search className="h-4 w-4" />
검색
@@ -161,7 +229,7 @@ const AssignPage = () => {
hideDialog("assignMonitoringDialog");
refreshAssignList();
}}
selected={selected}
selected={detailData ?? selected}
codes={codes}
applyUsers={applyUsers}
isSavingAssign={saveAssignMutation.isPending}
@@ -171,10 +239,29 @@ const AssignPage = () => {
{onSuccess: (monitoringAssigns) => applySavedAssignsToSelected(performanceId, monitoringAssigns)}
)
}
onOpenSms={(assignUserIds, smsUserIds) => {
onOpenAssignSms={(assignUserIds, smsUserIds) => {
suppressAssignCloseRef.current = true;
setAssignSaveTargetIds(assignUserIds);
setSmsTargetIds(smsUserIds);
setSmsMode("assignConfirm");
setSmsTemplateIdx([SMS_TEMPLATE_IDS.ASSIGN_CONFIRM])
setSmsDialogTitle("확정 문자 발송")
setNewSmsTemplateIdx(undefined);
showDialog("assignSmsSendDialog", false);
}}
onOpenNormalSms={(smsUserIds) => {
suppressAssignCloseRef.current = true;
setSmsTargetIds(smsUserIds);
setSmsMode("normal");
setSmsTemplateIdx([SMS_TEMPLATE_IDS.INFORM_ASSIGN, SMS_TEMPLATE_IDS.REMIND_ASSIGN])
setSmsDialogTitle("문자 발송")
setNewSmsTemplateIdx(SMS_TEMPLATE_IDS.CUSTOM);
showDialog("assignSmsSendDialog", false);
}}
/>
@@ -194,21 +281,13 @@ const AssignPage = () => {
suppressAssignCloseRef.current = false;
}, 0);
}}
title="확정 문자 발송"
templateIdx={SMS_TEMPLATE_IDS.ASSIGN_CONFIRM}
newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM}
title={smsDialogTitle}
templateIdx={smsTemplateIdx}
newMessageTemplateIdx={newSmsTemplateIdx}
selectedUsers={smsTargetUsers}
addParams={smsAddParam}
isBeforeSendPending={saveAssignMutation.isPending}
onBeforeDefaultTemplateSend={async () => {
if (!selected) throw new Error("공연 정보가 없습니다.");
const monitoringAssigns = await saveAssignMutation.mutateAsync({
performanceId: selected.id,
userIds: assignSaveTargetIds,
});
applySavedAssignsToSelected(selected.id, monitoringAssigns);
}}
onSent={refreshAssignList}
denyParamKeys={["userCmpn", "userTeam", "userRole", "id"]}
{...smsBeforeSendProps}
/>
</div>
);

View File

@@ -17,18 +17,27 @@ import {useMounted} from "@/hooks/useMounted";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {toLocalDateString} from "@/lib/gwcf/date";
import {
getMonitoringDisplayRow,
getMonitoringDisplayRow, getMonitoringDisplayStatus, isAssignConfirmed,
} from "@/lib/gwcf/performance-status";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/gwcf/field-labels";
import {getCodeLabel} from "@/lib/gwcf/view";
import {StatusPill} from "@/components/gwcf/StatusPill";
const today = toLocalDateString();
const todayTime = new Date(`${today}T00:00:00`).getTime();
const toDateTime = (date?: string) => {
if (!date) return Number.POSITIVE_INFINITY;
const time = new Date(`${date}T00:00:00`).getTime();
const toDateTime = (date?: string | null) => {
const normalizedDate = date?.trim();
if (!normalizedDate) return Number.POSITIVE_INFINITY;
const time = new Date(`${normalizedDate}T00:00:00`).getTime();
return Number.isNaN(time) ? Number.POSITIVE_INFINITY : time;
};
const canSaveMonitoringVisit = (date?: string | null) => {
const time = toDateTime(date);
return Number.isFinite(time) && todayTime >= time;
};
const compareMonitoringSchedule = (a: PerformanceFull, b: PerformanceFull) => {
const aTime = toDateTime(a.performanceMonitoringSchedule?.monitoringDate);
const bTime = toDateTime(b.performanceMonitoringSchedule?.monitoringDate);
@@ -75,7 +84,6 @@ const MonitoringPage = () => {
const userId = auth.user?.userId;
const [selectedId, setSelectedId] = useState<number | null>(null);
const [detailId, setDetailId] = useState<number | null>(null);
const [visitMode, setVisitMode] = useState<"departure" | "arrival">("departure");
const refreshMonitoringList = () => {
@@ -85,7 +93,7 @@ const MonitoringPage = () => {
const assignedItems = useMemo(() => {
if (!userId) return [];
return data.filter((item) =>
item.performanceAssignList?.some((assign) => assign.assignUser === userId && assign.assignConfirm)
item.performanceAssignList?.some((assign) => assign.assignUser === userId && isAssignConfirmed(assign))
);
}, [data, userId]);
@@ -97,11 +105,6 @@ const MonitoringPage = () => {
return sortedItems.find((item) => item.id === selectedId) ?? sortedItems[0] ?? null;
}, [selectedId, sortedItems]);
const detailSelected = useMemo(() => {
if (!detailId) return null;
return sortedItems.find((item) => item.id === detailId) ?? null;
}, [detailId, sortedItems]);
const selectedMonitoringRow = useMemo(() => {
if (!selected || !userId) return undefined;
return ([0, 1] as const)
@@ -110,32 +113,50 @@ const MonitoringPage = () => {
}, [selected, userId]);
const hasDeparture = Boolean(selectedMonitoringRow?.slot.timeline.departure || selectedMonitoringRow?.slot.visit?.length);
const hasArrival = Boolean(selectedMonitoringRow?.slot.timeline.arrival);
const canSaveVisit = canSaveMonitoringVisit(selected?.performanceMonitoringSchedule?.monitoringDate);
const columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
{
accessorKey: "performanceName",
header: "사업명",
cell: ({row}) => (
header: PERFORMANCE_FIELD_LABELS.performanceName,
cell: ({row}) => {
if (!row.original || !userId) return undefined;
const prow = ([0, 1] as const)
.map((index) => getMonitoringDisplayRow(row.original, index))
.find((item) => item.userId === userId);
const latestVisit = prow?.slot.visit?.[0];
const status = prow
? getMonitoringDisplayStatus(
prow,
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
getCodeLabel(codes, "review_status", prow?.review?.reviewStatus)
)
: {label: "미배치", variant: "danger" as const};
return (
<div className="max-w-[180px] whitespace-normal py-2 text-sm font-semibold leading-5">
{row.original.performanceName}
{row.original.performanceName}<br/>
<StatusPill variant={status.variant}>{status.label}</StatusPill>
</div>
),
)
},
},
{
id: "monitoringDate",
header: "일정",
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate?.slice(5) || "-",
header: PERFORMANCE_FIELD_LABELS.monitoringDate,
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate?.slice(5) ?? "",
},
{
id: "monitoringTime",
header: "시간",
header: PERFORMANCE_FIELD_LABELS.monitoringTimeInfo,
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringTimeInfo || "-",
},
], []);
], [codes]);
const visitOpen = isDialogOpen("monitoringVisitDialog");
const detailOpen = isDialogOpen("monitoringDetailDialog");
const {data: detailData} = usePerformanceDetailQuery(detailId ?? 0, Boolean(detailId && detailOpen));
const {data: detailData} = usePerformanceDetailQuery(selectedId ?? 0, Boolean(selectedId && detailOpen));
const openVisit = (mode: "departure" | "arrival") => {
setVisitMode(mode);
@@ -239,14 +260,14 @@ const MonitoringPage = () => {
{selected && (
<section className="rounded-md border">
<div className="border-b bg-muted px-3 py-2 text-center font-semibold">
{selected.performanceMonitoringSchedule?.monitoringDate} {selected.performanceMonitoringSchedule?.monitoringTimeInfo}
{[selected.performanceMonitoringSchedule?.monitoringDate, selected.performanceMonitoringSchedule?.monitoringTimeInfo].filter(Boolean).join(" ")}
</div>
<div className="grid grid-cols-[80px_1fr] border-b">
<div className="bg-muted px-3 py-2 text-sm font-semibold">사업명</div>
<div className="bg-muted px-3 py-2 text-sm font-semibold">{PERFORMANCE_FIELD_LABELS.performanceName}</div>
<div className="px-3 py-2 text-sm">{selected.performanceName}</div>
</div>
<div className="grid grid-cols-[80px_1fr]">
<div className="bg-muted px-3 py-2 text-sm font-semibold">장소</div>
<div className="bg-muted px-3 py-2 text-sm font-semibold">{PERFORMANCE_FIELD_LABELS.monitoringAddress}</div>
<div className="px-3 py-2 text-sm">{selected.performanceMonitoringSchedule?.monitoringAddress}</div>
</div>
</section>
@@ -255,9 +276,9 @@ const MonitoringPage = () => {
{selected && (
<div>
{!hasDeparture ? (
<Button type="button" className="w-full" onClick={() => openVisit("departure")}>출발</Button>
<Button type="button" className="w-full" disabled={!canSaveVisit} onClick={() => openVisit("departure")}>출발</Button>
) : (
<Button type="button" className="w-full" disabled={hasArrival} onClick={() => openVisit("arrival")}>도착</Button>
<Button type="button" className="w-full" disabled={!canSaveVisit || hasArrival} onClick={() => openVisit("arrival")}>도착</Button>
)}
</div>
)}
@@ -270,7 +291,7 @@ const MonitoringPage = () => {
getRowId={(row) => String(row.id)}
selectMode="click-event"
onRowClick={(item) => {
setDetailId(item.id);
setSelectedId(item.id);
showDialog("monitoringDetailDialog");
}}
highlightRowIds={selected ? [String(selected.id)] : []}
@@ -307,10 +328,9 @@ const MonitoringPage = () => {
}
hideDialog("monitoringDetailDialog");
setDetailId(null);
refreshMonitoringList();
}}
performance={detailData ?? detailSelected}
performance={detailData ?? selected}
codes={codes}
userId={userId}
/>

View File

@@ -1,6 +1,6 @@
"use client";
import {useCallback, useMemo, useRef, useState} from "react";
import {useCallback, useEffect, useMemo, useRef, useState} from "react";
import {Search, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
@@ -14,6 +14,7 @@ import {DataTable} from "@/components/data-table/DataTable";
import {DataTableColumn} from "@/components/data-table/DataTable.type";
import {useCodesQuery} from "@/query/code";
import {
useDeletePerformanceMutation,
useDownloadAssignExcelTemplateMutation,
useDownloadPerformanceExcelTemplateMutation,
useExportPerformanceMutation,
@@ -23,8 +24,16 @@ import {
useUploadPerformanceExcelMutation,
} from "@/query/performance";
import {useUploadWrittenAssignExcelMutation} from "@/query/assign";
import {useDownloadReviewOriginalMutation, useDownloadReviewPdfMutation} from "@/query/review";
import {filterPerformance, getCodeLabel, isInternalRole, isWrittenReviewerRole} from "@/lib/gwcf/view";
import {useDownloadReviewOriginalByPerformanceMutation, useDownloadReviewOriginalMutation, useDownloadReviewPdfMutation} from "@/query/review";
import {
filterPerformance,
getCodeLabel,
includesText,
isFoundationRole,
isInternalRole,
isResearcherRole,
isWrittenReviewerRole
} from "@/lib/gwcf/view";
import {
getMonitoringDisplayRow,
getMonitoringDisplayStatus,
@@ -45,6 +54,7 @@ import {Code, PerformanceFull, PerformanceReview} from "@/types/gwcf";
import {useDialog} from "@/hooks/useDialog";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {useMounted} from "@/hooks/useMounted";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {
downloadBlob,
downloadExcelBuffer, getReviewOriginalDownloadName,
@@ -52,6 +62,7 @@ import {
openWrittenReviewWindow,
} from "@/lib/gwcf/file";
import ExcelDownloadButton from "@/components/common/ExcelDownloadButton";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/gwcf/field-labels";
type PerformanceFilters = {
businessType: string[];
@@ -59,6 +70,7 @@ type PerformanceFilters = {
area: string[];
startMonth: string[];
monitoringDate: string;
monitoringAdd: string[];
localReviewStatus: string[];
monitoring1Status: string[];
monitoring2Status: string[];
@@ -66,13 +78,44 @@ type PerformanceFilters = {
keyword: string;
};
const monthOptions: Code[] = Array.from({length: 12}, (_, index) => ({
const monthOptions: Code[] = [
{
codeGroup: "month",
codeValue: 0,
codeGroupLabel: PERFORMANCE_FIELD_LABELS.performanceStartMonth,
codeLabel: `미정`,
memo: "",
},
...Array.from({length: 12}, (_, index) => ({
codeGroup: "month",
codeValue: index + 1,
codeGroupLabel: "사업 수행 월",
codeGroupLabel: PERFORMANCE_FIELD_LABELS.performanceStartMonth,
codeLabel: `${index + 1}월`,
memo: "",
}));
}))
];
const monitoringAddOptions: Code[] = [
{
codeGroup: "monitoring_add",
codeValue: 0,
codeGroupLabel: PERFORMANCE_FIELD_LABELS.monitoringAdd,
codeLabel: "추가 X",
memo: "",
},
{
codeGroup: "monitoring_add",
codeValue: 1,
codeGroupLabel: PERFORMANCE_FIELD_LABELS.monitoringAdd,
codeLabel: "추가 O",
memo: "",
},
];
const getPerformanceGroupKey = (performanceId: number) => {
const id = String(performanceId);
return id.length > 2 ? id.slice(0, -2) : id;
};
const PerformancePage = () => {
const mounted = useMounted();
@@ -80,12 +123,15 @@ const PerformancePage = () => {
const userRole = auth.user?.userRole;
const userId = auth.user?.userId;
const canEdit = isInternalRole(userRole);
const canEditNoticeAndStaff = isFoundationRole(userRole);
const canDelete = isResearcherRole(userRole);
const isWrittenReviewer = isWrittenReviewerRole(userRole);
const {isDialogOpen, showDialog, hideDialog} = useDialog();
const {data: codes} = useCodesQuery();
const {data = [], refetch: refetchPerformanceList} = usePerformanceListQuery();
const updateMutation = useUpdatePerformanceMutation();
const deleteMutation = useDeletePerformanceMutation();
const performanceUploadMutation = useUploadPerformanceExcelMutation();
const writtenAssignUploadMutation = useUploadWrittenAssignExcelMutation();
const performanceTemplateMutation = useDownloadPerformanceExcelTemplateMutation();
@@ -93,6 +139,7 @@ const PerformancePage = () => {
const exportMutation = useExportPerformanceMutation();
const reviewPdfMutation = useDownloadReviewPdfMutation();
const reviewOriginalMutation = useDownloadReviewOriginalMutation();
const reviewOriginalByPerformanceMutation = useDownloadReviewOriginalByPerformanceMutation();
const [filters, setFilters] = useState<PerformanceFilters>({
businessType: [],
@@ -100,14 +147,17 @@ const PerformancePage = () => {
area: [],
startMonth: [],
monitoringDate: "",
monitoringAdd: [],
localReviewStatus: [],
monitoring1Status: [],
monitoring2Status: [],
writtenReviewStatus: [],
keyword: "",
});
const debouncedFilters = useDebouncedValue(filters);
const [selectedId, setSelectedId] = useState<number | null>(null);
const lastSelectedRef = useRef<number | null>(null);
const filtersInitializedRef = useRef(false);
const detailOpen = isDialogOpen("performanceDetailDialog");
const performanceRegisterOpen = isDialogOpen("performanceExcelRegisterDialog");
@@ -120,9 +170,17 @@ const PerformancePage = () => {
const updateFilters = (updater: (prev: PerformanceFilters) => PerformanceFilters) => {
setFilters(updater);
refreshPerformanceList();
};
useEffect(() => {
if (!filtersInitializedRef.current) {
filtersInitializedRef.current = true;
return;
}
void refetchPerformanceList();
}, [debouncedFilters, refetchPerformanceList]);
const handlePerformanceDetailOpenChange = (open: boolean) => {
if (open) {
showDialog("performanceDetailDialog");
@@ -181,40 +239,45 @@ const PerformancePage = () => {
const monitoring2Row = getMonitoringDisplayRow(item, 1);
const monitoring2LatestVisit = monitoring2Row.slot.visit?.[0];
const baseFilters = {
businessType: debouncedFilters.businessType,
genre: debouncedFilters.genre,
area: debouncedFilters.area,
monitoringDate: debouncedFilters.monitoringDate,
};
return (
filterPerformance(item, {
businessType: filters.businessType,
genre: filters.genre,
area: filters.area,
monitoringDate: filters.monitoringDate,
keyword: filters.keyword,
}) &&
matchesStatus(filters.startMonth, String(item.performanceStartMonth)) &&
matchesStatus(filters.localReviewStatus, getReviewStatusFilterValue(
(
filterPerformance(item, {...baseFilters, keyword: debouncedFilters.keyword}) ||
(filterPerformance(item, baseFilters) && includesText(item.performanceDetail["NCAS"], debouncedFilters.keyword.trim()))
) &&
matchesStatus(debouncedFilters.startMonth, String(item.performanceStartMonth)) &&
matchesStatus(debouncedFilters.monitoringAdd, item.id % 100 === 1 ? "0" : "1") &&
matchesStatus(debouncedFilters.localReviewStatus, getReviewStatusFilterValue(
localReview,
getCodeLabel(codes, "review_status", localReview?.reviewStatus),
{isWrittenReviewer, alwaysAssigned: true}
)) &&
matchesStatus(filters.monitoring1Status, getMonitoringStatusFilterValue(
matchesStatus(debouncedFilters.monitoring1Status, getMonitoringStatusFilterValue(
monitoring1Row,
getCodeLabel(codes, "monitoring_visit_status", monitoring1LatestVisit?.monitoringVisitStatus),
getCodeLabel(codes, "review_status", monitoring1Row.review?.reviewStatus),
isWrittenReviewer
)) &&
matchesStatus(filters.monitoring2Status, getMonitoringStatusFilterValue(
matchesStatus(debouncedFilters.monitoring2Status, getMonitoringStatusFilterValue(
monitoring2Row,
getCodeLabel(codes, "monitoring_visit_status", monitoring2LatestVisit?.monitoringVisitStatus),
getCodeLabel(codes, "review_status", monitoring2Row.review?.reviewStatus),
isWrittenReviewer
)) &&
matchesStatus(filters.writtenReviewStatus, getReviewStatusFilterValue(
matchesStatus(debouncedFilters.writtenReviewStatus, getReviewStatusFilterValue(
writtenReviewRow?.review,
getCodeLabel(codes, "review_status", writtenReviewRow?.review?.reviewStatus),
{isWrittenReviewer, allowInProgress: true, assigned: Boolean(writtenReviewRow?.assign)}
))
);
});
}, [codes, data, filters, getVisibleWrittenReviewRow, isWrittenReviewer]);
}, [codes, data, debouncedFilters, getVisibleWrittenReviewRow, isWrittenReviewer]);
const openDetail = (performance: PerformanceFull) => {
if (isWrittenReviewer) return;
@@ -223,6 +286,14 @@ const PerformancePage = () => {
showDialog("performanceDetailDialog");
};
const deletePerformance = async (performanceId: number) => {
if (!performanceId) return;
await deleteMutation.mutateAsync(performanceId);
alert("삭제되었습니다.");
window.location.replace("/performance");
};
const downloadReviewPdf = async (performanceId: number, review?: PerformanceReview) => {
if (!review || !isReviewComplete(review)) return;
if (!review.regUser) return;
@@ -237,6 +308,16 @@ const PerformancePage = () => {
downloadBlob(buffer, getReviewOriginalDownloadName(performanceId, review.reviewType, review.uploadFileName));
};
const downloadMonitoringReviews = async (performanceId: number) => {
const reviewType = 1;
try {
const buffer = await reviewOriginalByPerformanceMutation.mutateAsync({performanceId, reviewType});
downloadBlob(buffer, `모니터링-${performanceId}-${reviewType}.zip`, "application/zip");
} catch {
alert("다운로드할 모니터링 파일을 찾을 수 없습니다.");
}
};
const openWrittenReviewLink = (performanceId: number, userId?: string, complete = false) => {
openWrittenReviewWindow(performanceId, userId, complete);
};
@@ -268,7 +349,7 @@ const PerformancePage = () => {
: undefined;
return (
<div className="flex min-w-24 justify-center text-xs">
<div className="flex justify-center text-xs">
<StatusPill
variant={display.variant}
onClick={onClick}
@@ -298,7 +379,7 @@ const PerformancePage = () => {
const visitUser = getMonitoringRecordedUser(latestVisit);
return (
<div className="flex min-w-24 justify-center text-xs">
<div className="flex justify-center text-xs">
<StatusPill
variant={display.variant}
onClick={isReviewComplete(row.review) ? () => downloadReviewOriginal(performance.id, row.review) : undefined}
@@ -317,26 +398,137 @@ const PerformancePage = () => {
);
};
const renderWrittenReviewerMonitoringStatus = (performance: PerformanceFull) => {
const groupKey = getPerformanceGroupKey(performance.id);
const monitoringRows = data
.filter((item) => getPerformanceGroupKey(item.id) === groupKey)
.flatMap((item) => ([0, 1] as const).map((index) => getMonitoringDisplayRow(item, index)));
const completeCount = monitoringRows.filter((item) => isReviewComplete(item.review)).length;
const totalCount = monitoringRows.length;
const display = completeCount === 0
? {label: "미완료", variant: "pending" as const}
: completeCount === totalCount
? {label: "완료", variant: "done" as const}
: {label: "일부 완료", variant: "inprogress" as const};
const onClick = completeCount > 0 ? () => downloadMonitoringReviews(performance.id) : undefined;
return (
<div className="flex justify-center text-xs">
<StatusPill
variant={display.variant}
onClick={onClick}
tooltip={(
<div className="space-y-1">
<div>완료: {completeCount}</div>
<div>전체: {totalCount}</div>
</div>
)}
>
{display.label}
</StatusPill>
</div>
);
};
const columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
{accessorKey: "id", header: "연번", cell: ({row}) => row.original.id, enableSorting: true},
{id: "businessType", header: "사업 유형", cell: ({row}) => getCodeLabel(codes, "business_type", row.original.businessType)},
{id: "genre", header: "분야(장르)", cell: ({row}) => getCodeLabel(codes, "genre", row.original.performanceGenre)},
{id: "area", header: "지역", cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
{accessorKey: "artistName", header: "단체(인)명", enableSorting: true},
{accessorKey: "performanceName", header: "사업명", enableSorting: true},
{id: "startMonth", header: "사업 수행 월", cell: ({row}) => `${row.original.performanceStartMonth}월`, enableSorting: true},
{accessorKey: "performanceDtInfo", header: "사업 일정"},
{accessorKey: "performanceTimeInfo", header: "운영 시간"},
...(!isWrittenReviewer ? [{
{accessorKey: "no", header: PERFORMANCE_FIELD_LABELS.no,
accessorFn: (row) => row.performanceDetail["performanceNo"] ?? "",
cell: ({row}) => row.original.performanceDetail["performanceNo"] ?? "",
},
{accessorKey: "id", header: PERFORMANCE_FIELD_LABELS.id, cell: ({row}) => row.original.id},
{id: "ncas", header: PERFORMANCE_FIELD_LABELS.NCAS,
accessorFn: (row) => row.performanceDetail["NCAS"] ?? "",
cell: ({row}) => row.original.performanceDetail["NCAS"] ?? "",
},
...(!isWrittenReviewer ? [
{accessorKey: "monitoringAdd", header: PERFORMANCE_FIELD_LABELS.monitoringAdd,
accessorFn: (row) => row.id % 100 !== 1? "추가" : "",
cell: ({row}) => row.original.id % 100 !== 1? "추가" : "",
enableSorting: false
},
]: []) as DataTableColumn<PerformanceFull>[],
{
id: "businessType",
header: PERFORMANCE_FIELD_LABELS.businessType,
cell: ({row}) => {
const value = getCodeLabel(codes, "business_type", row.original.businessType);
return (
<div className="max-w-[130px] truncate" title={value}>
{value}
</div>
);
},
size: 130,
maxSize: 130,
},
{id: "genre", header: PERFORMANCE_FIELD_LABELS.performanceGenre, cell: ({row}) => getCodeLabel(codes, "genre", row.original.performanceGenre)},
{id: "area", header: PERFORMANCE_FIELD_LABELS.performanceArea, cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
{
accessorKey: "artistName",
header: PERFORMANCE_FIELD_LABELS.artistName,
cell: ({row}) => (
<div className="max-w-[120px] truncate" title={row.original.artistName}>
{row.original.artistName}
</div>
),
size: 120,
maxSize: 120,
},
{
accessorKey: "performanceName",
header: PERFORMANCE_FIELD_LABELS.performanceName,
cell: ({row}) => (
<div className="max-w-[300px] truncate" title={row.original.performanceName}>
{row.original.performanceName}
</div>
),
},
{id: "startMonth", header: PERFORMANCE_FIELD_LABELS.performanceStartMonth,
accessorFn: (row) => row.performanceStartMonth ?? 0,
cell: ({row}) => row.original.performanceStartMonth === 0? "미정":`${row.original.performanceStartMonth}월`},
{
accessorKey: "performanceDtInfo",
header: PERFORMANCE_FIELD_LABELS.performanceDtInfo,
cell: ({row}) => (
<div className="max-w-[65px] truncate" title={row.original.performanceDtInfo}>
{row.original.performanceDtInfo}
</div>
),
enableSorting: false
},
{
accessorKey: "performanceTimeInfo",
header: PERFORMANCE_FIELD_LABELS.performanceTimeInfo,
cell: ({row}) => (
<div className="max-w-[65px] truncate" title={row.original.performanceTimeInfo}>
{row.original.performanceTimeInfo}
</div>
),
enableSorting: false
},
...(!isWrittenReviewer ? [
{
id: "monitoringDate",
header: "모니터링 일정",
header: PERFORMANCE_FIELD_LABELS.monitoringDate,
accessorFn: (row) => row.performanceMonitoringSchedule?.monitoringDate ?? "",
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate ?? "",
enableSorting: true,
} satisfies DataTableColumn<PerformanceFull>] : []),
},
{
id: "timeTreeCheckDt",
header: PERFORMANCE_FIELD_LABELS.timeTreeCheckDt,
accessorFn: (row) => row.performanceDetail["timeTreeCheckDt"] ?? "",
cell: ({row}) => row.original.performanceDetail["timeTreeCheckDt"] ?? "",
}
]: []) as DataTableColumn<PerformanceFull>[],
{
id: "localReview",
header: "지자체 평가",
header: "자체 보고서",
cell: ({row}) => {
if(row.original.id % 100 !== 1){
return "-";
}
const found = getReviewByType(row.original, LOCAL_GOVERNMENT_REVIEW_TYPE);
return renderReviewStatus({
performance: row.original,
@@ -346,13 +538,22 @@ const PerformancePage = () => {
noTooltip: isWrittenReviewer,
});
},
size:40,
},
{id: "monitoring1", header: "모니터링 1", cell: ({row}) => renderMonitoringStatus(row.original, 0)},
{id: "monitoring2", header: "모니터링 2", cell: ({row}) => renderMonitoringStatus(row.original, 1)},
...(!isWrittenReviewer ? [
{id: "monitoring1", header: "모니터링 1", cell: ({row}) => renderMonitoringStatus(row.original, 0), size:40,},
{id: "monitoring2", header: "모니터링 2", cell: ({row}) => renderMonitoringStatus(row.original, 1), size:40,},
] : [
{id: "monitoring", header: "모니터링", cell: ({row}) => renderWrittenReviewerMonitoringStatus(row.original), size:40,}
]) as DataTableColumn<PerformanceFull>[],
{
id: "writtenReview",
header: "서면 평가",
cell: ({row}) => {
if(row.original.id % 100 !== 1){
return "-";
}
const found = getVisibleWrittenReviewRow(row.original);
return renderReviewStatus({
performance: row.original,
@@ -362,8 +563,9 @@ const PerformancePage = () => {
alwaysAssigned: Boolean(found?.assign),
});
},
size:40,
},
], [codes, getVisibleWrittenReviewRow, isWrittenReviewer]);
], [codes, data, getVisibleWrittenReviewRow, isWrittenReviewer]);
const downloadPerformanceTemplate = async () => {
const buffer = await performanceTemplateMutation.mutateAsync();
@@ -394,21 +596,24 @@ const PerformancePage = () => {
<PagePanel>
<div className="space-y-2">
<div className={isWrittenReviewer ? "grid gap-2 md:grid-cols-[280px_170px_140px_140px_1fr_auto]" : "grid gap-2 md:grid-cols-[280px_170px_140px_140px_140px_1fr_auto]"}>
<MultiFilterSelect value={filters.businessType} onChange={(value) => updateFilters((prev) => ({...prev, businessType: value}))} options={codes.business_type} placeholder="사업 유형" />
<MultiFilterSelect value={filters.genre} onChange={(value) => updateFilters((prev) => ({...prev, genre: value}))} options={codes.genre} placeholder="분야(장르)" />
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder="지역" />
<MultiFilterSelect value={filters.startMonth} onChange={(value) => updateFilters((prev) => ({...prev, startMonth: value}))} options={monthOptions} placeholder="사업 수행 월" />
<MultiFilterSelect value={filters.businessType} onChange={(value) => updateFilters((prev) => ({...prev, businessType: value}))} options={codes.business_type} placeholder={PERFORMANCE_FIELD_LABELS.businessType} />
<MultiFilterSelect value={filters.genre} onChange={(value) => updateFilters((prev) => ({...prev, genre: value}))} options={codes.genre} placeholder={PERFORMANCE_FIELD_LABELS.performanceGenre} />
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder={PERFORMANCE_FIELD_LABELS.performanceArea} />
<MultiFilterSelect value={filters.startMonth} onChange={(value) => updateFilters((prev) => ({...prev, startMonth: value}))} options={monthOptions} placeholder={PERFORMANCE_FIELD_LABELS.performanceStartMonth} />
{!isWrittenReviewer && (
<DatePicker value={filters.monitoringDate} onChange={(value) => updateFilters((prev) => ({...prev, monitoringDate: value}))} placeholder="모니터링 일정" />
<DatePicker value={filters.monitoringDate} onChange={(value) => updateFilters((prev) => ({...prev, monitoringDate: value}))} placeholder={PERFORMANCE_FIELD_LABELS.monitoringDate} />
)}
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder="연번 or 사업명" />
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder={`${PERFORMANCE_FIELD_LABELS.id}, ${PERFORMANCE_FIELD_LABELS.NCAS} or ${PERFORMANCE_FIELD_LABELS.performanceName}`} />
<Button type="button" variant="outline" onClick={refreshPerformanceList}>
<Search className="h-4 w-4" />
검색
</Button>
</div>
<div className="grid gap-2 md:grid-cols-[183px_183px_183px_183px]">
<MultiFilterSelect value={filters.localReviewStatus} onChange={(value) => updateFilters((prev) => ({...prev, localReviewStatus: value}))} options={localReviewStatusOptions} placeholder="지자체 평가 상태" />
<div className="grid gap-2 md:grid-cols-[183px_183px_183px_183px_183px]">
{!isWrittenReviewer && (
<MultiFilterSelect value={filters.monitoringAdd} onChange={(value) => updateFilters((prev) => ({...prev, monitoringAdd: value}))} options={monitoringAddOptions} placeholder={PERFORMANCE_FIELD_LABELS.monitoringAdd} />
)}
<MultiFilterSelect value={filters.localReviewStatus} onChange={(value) => updateFilters((prev) => ({...prev, localReviewStatus: value}))} options={localReviewStatusOptions} placeholder="자체 보고서 상태" />
<MultiFilterSelect value={filters.monitoring1Status} onChange={(value) => updateFilters((prev) => ({...prev, monitoring1Status: value}))} options={monitoringStatusOptions} placeholder="모니터링1 상태" />
<MultiFilterSelect value={filters.monitoring2Status} onChange={(value) => updateFilters((prev) => ({...prev, monitoring2Status: value}))} options={monitoringStatusOptions} placeholder="모니터링2 상태" />
<MultiFilterSelect value={filters.writtenReviewStatus} onChange={(value) => updateFilters((prev) => ({...prev, writtenReviewStatus: value}))} options={writtenReviewStatusOptions} placeholder="서면평가 상태" />
@@ -441,6 +646,8 @@ const PerformancePage = () => {
selectMode={isWrittenReviewer ? "none" : "click-event"}
onRowClick={isWrittenReviewer ? undefined : openDetail}
defaultPageSize={10}
headerFontClass="content-text-base"
cellFontClass="content-text-sm"
/>
</PagePanel>
@@ -451,7 +658,10 @@ const PerformancePage = () => {
performance={detailData ?? data.find((item) => item.id === selectedId) ?? null}
codes={codes}
canEdit={canEdit}
canEditNoticeAndStaff={canEditNoticeAndStaff}
canDelete={canDelete}
onSave={(draft) => updateMutation.mutate(draft)}
onDelete={deletePerformance}
/>
)}
@@ -459,6 +669,7 @@ const PerformancePage = () => {
open={performanceRegisterOpen}
onOpenChange={handlePerformanceRegisterOpenChange}
title="사업 등록"
notice={`${PERFORMANCE_FIELD_LABELS.NCAS} 열이 추가되었습니다. 새 양식을 다운로드해 사용해 주세요.`}
onDownloadTemplate={downloadPerformanceTemplate}
onUpload={(file) => performanceUploadMutation.mutateAsync(file)}
isUploading={performanceUploadMutation.isPending}

View File

@@ -29,6 +29,8 @@ import {useMounted} from "@/hooks/useMounted";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {downloadExcelBuffer} from "@/lib/gwcf/file";
import ExcelDownloadButton from "@/components/common/ExcelDownloadButton";
import {USER_FIELD_LABELS} from "@/lib/gwcf/field-labels";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
type UserTab = "monitoring" | "written";
type UserFilters = {area: string[]; gender: string[]; genre: string[]; keyword: string};
@@ -59,6 +61,8 @@ const UserPage = () => {
const [, forceDraftRender] = useState(0);
const draftRef = useRef<UserFull | null>(null);
const [filters, setFilters] = useState<UserFilters>({area: [], gender: [], genre: [], keyword: ""});
const debouncedFilters = useDebouncedValue(filters);
const filtersInitializedRef = useRef(false);
const userRole = tabRole[tab];
const {data = [], refetch: refetchUsers} = useUsersQuery(userRole);
@@ -77,9 +81,17 @@ const UserPage = () => {
const updateFilters = (updater: (prev: UserFilters) => UserFilters) => {
setFilters(updater);
refreshUserList();
};
useEffect(() => {
if (!filtersInitializedRef.current) {
filtersInitializedRef.current = true;
return;
}
refreshUserList();
}, [debouncedFilters, refetchAssignCounts, refetchUsers]);
useEffect(() => {
setSelectedIds([]);
setEditingId(null);
@@ -88,7 +100,7 @@ const UserPage = () => {
setFilters({area: [], gender: [], genre: [], keyword: ""});
}, [tab]);
const filteredData = useMemo(() => data.filter((user) => filterUser(user, filters)), [data, filters]);
const filteredData = useMemo(() => data.filter((user) => filterUser(user, debouncedFilters)), [data, debouncedFilters]);
const smsTargetUsers = useMemo(
() => data.filter((user) => selectedIds.includes(user.userId)),
[data, selectedIds]
@@ -146,11 +158,11 @@ const UserPage = () => {
downloadExcelBuffer(buffer, tab === "monitoring" ? "모니터링 요원.xlsx" : "서면 평가위원.xlsx");
};
const renderEditableCell = (user: UserFull, key: string, fallbackKeys: string[], type: "text" | "select" = "text", options: Code[] = []) => {
const renderEditableCell = (user: UserFull, key: string, type: "text" | "select" = "text", options: Code[] = []) => {
const draft = draftRef.current;
const isEditing = editingId === user.userId && draft;
const source = isEditing ? draft.userDetail : user.userDetail;
const value = getDetailValue(source, [key, ...fallbackKeys]);
const value = getDetailValue(source, key);
if (!isEditing) return type === "select" ? (getOptionLabel(options, value) || "-") : (value || "-");
@@ -171,30 +183,30 @@ const UserPage = () => {
const columns = useMemo<DataTableColumn<UserFull>[]>(() => {
const commonColumns: DataTableColumn<UserFull>[] = [
{accessorKey: "userId", header: "ID", enableSorting: true},
{accessorKey: "userId", header: USER_FIELD_LABELS.userId},
{id: "password", header: "PW", cell: () => "****"},
];
const monitoringColumns: DataTableColumn<UserFull>[] = [
{id: "participationCount", header: "참여 횟수", cell: ({row}) => assignCountMap.get(row.original.userId) ?? 0, enableSorting: true},
{id: "area", header: "지역", cell: ({row}) => renderEditableCell(row.original, "area", ["userArea", "region"], "select", codes.area)},
{id: "gender", header: "성별", cell: ({row}) => renderEditableCell(row.original, "gender", ["userGender"], "select", codes.gender)},
{id: "age", header: "연령", cell: ({row}) => renderEditableCell(row.original, "age", ["userAge"])},
{id: "tel", header: "연락처", cell: ({row}) => renderEditableCell(row.original, "tel", ["phone", "userTel"])},
{id: "email", header: "이메일", cell: ({row}) => renderEditableCell(row.original, "email", ["userEmail"])},
{id: "hasCar", header: "자차 여부", cell: ({row}) => renderEditableCell(row.original, "userHasCar", ["has_car", "hasCar"], "select", codes.has_car)},
{id: "participationCount", header: "참여 횟수", accessorFn: (row) => assignCountMap.get(row.userId) ?? 0, cell: ({row}) => assignCountMap.get(row.original.userId) ?? 0},
{id: "userArea", header: USER_FIELD_LABELS.userArea, cell: ({row}) => renderEditableCell(row.original, "userArea", "select", codes.area)},
{id: "userGender", header: USER_FIELD_LABELS.gender, cell: ({row}) => renderEditableCell(row.original, "userGender", "select", codes.gender)},
{id: "userAge", header: USER_FIELD_LABELS.userAge, cell: ({row}) => renderEditableCell(row.original, "userAge")},
{id: "userTel", header: USER_FIELD_LABELS.userTel, cell: ({row}) => renderEditableCell(row.original, "userTel")},
{id: "userEmail", header: USER_FIELD_LABELS.userEmail, cell: ({row}) => renderEditableCell(row.original, "userEmail")},
{id: "userHasCar", header: USER_FIELD_LABELS.userHasCar, cell: ({row}) => renderEditableCell(row.original, "userHasCar", "select", codes.has_car)},
];
const writtenColumns: DataTableColumn<UserFull>[] = [
{id: "genre", header: "장르", cell: ({row}) => renderEditableCell(row.original, "userGenre", ["genre", "reviewGenre"], "select", codes.genre)},
{id: "tel", header: "연락처", cell: ({row}) => renderEditableCell(row.original, "tel", ["phone", "userTel"])},
{id: "email", header: "이메일", cell: ({row}) => renderEditableCell(row.original, "email", ["userEmail"])},
{id: "userGenre", header: USER_FIELD_LABELS.userGenre, cell: ({row}) => renderEditableCell(row.original, "userGenre", "select", codes.genre)},
{id: "userTel", header: USER_FIELD_LABELS.userTel, cell: ({row}) => renderEditableCell(row.original, "userTel")},
{id: "userEmail", header: USER_FIELD_LABELS.userEmail, cell: ({row}) => renderEditableCell(row.original, "userEmail")},
];
const actionColumns: DataTableColumn<UserFull>[] = [
{
id: "memo",
header: "메모",
header: USER_FIELD_LABELS.memo,
cell: ({row}) => {
const draft = draftRef.current;
return editingId === row.original.userId && draft ? (
@@ -278,7 +290,8 @@ const UserPage = () => {
getRowId={(row) => row.userId}
selectMode={tab === "monitoring" ? "multi" : "none"}
onRowSelectionChange={(rows) => setSelectedIds(rows.map((row) => row.userId))}
defaultPageSize={10}
defaultPageSize={1000}
showPagination={false}
/>
</PagePanel>
@@ -310,10 +323,11 @@ const UserPage = () => {
hideDialog("userSmsSendDialog");
refreshUserList();
}}
templateIdx={SMS_TEMPLATE_IDS.ACCOUNT_MONITORING}
templateIdx={[SMS_TEMPLATE_IDS.ACCOUNT_MONITORING]}
newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM}
selectedUsers={smsTargetUsers}
onSent={refreshUserList}
denyParamKeys={["userCmpn", "userTeam", "userRole"]}
/>
</div>
);

View File

@@ -1,3 +1,6 @@
import {headers} from "next/headers";
import {getFileNameFromContentDisposition} from "@/lib/gwcf/file";
type FilePreviewPageProps = {
searchParams: Promise<{
src?: string;
@@ -17,14 +20,56 @@ const parseImages = (images?: string) => {
}
};
const isAllowedSrc = (src: string) => src.startsWith("/api/review/pdf/") || src.startsWith("/api/file/");
const isAllowedSrc = (src: string) =>
src.startsWith("/api/review/pdf/") ||
src.startsWith("/api/review/template/pdf/") ||
src.startsWith("/api/file/");
const getAbsoluteSrc = async (src: string) => {
const headersList = await headers();
const host = headersList.get("x-forwarded-host") ?? headersList.get("host");
if (!host) return undefined;
const protocol = headersList.get("x-forwarded-proto") ?? "http";
return new URL(src, `${protocol}://${host}`).toString();
};
const getPdfTitleFromSrc = async (src: string) => {
if (!isAllowedSrc(src)) return undefined;
try {
const headersList = await headers();
const absoluteSrc = await getAbsoluteSrc(src);
if (!absoluteSrc) return undefined;
const response = await fetch(absoluteSrc, {
headers: {
cookie: headersList.get("cookie") ?? "",
},
cache: "no-store",
});
const fileName = getFileNameFromContentDisposition(response.headers.get("content-disposition"));
await response.body?.cancel().catch(() => undefined);
return fileName;
} catch {
return undefined;
}
};
const getTitle = async (paramTitle: string, src: string, type: "image" | "pdf") => {
const defaultTitle = "파일 미리보기";
if(paramTitle) return paramTitle;
if(type === "pdf") return await getPdfTitleFromSrc(src) ?? defaultTitle;
return defaultTitle;
}
export default async function FilePreviewPage({ searchParams }: FilePreviewPageProps) {
const params = await searchParams;
const title = params.title ?? "파일 미리보기";
const images = parseImages(params.images);
const src = params.src ?? "";
const type = params.type ?? (images.length > 0 ? "image" : "pdf");
const src = params.src ?? "";
const title = await getTitle(params.title ?? "", src, type) ;
return (
<main className="flex min-h-screen flex-col bg-background text-foreground">

View File

@@ -57,6 +57,12 @@ export const POST = async (
);
return NextResponse.json(result, { status: 200 });
}
if (action === "reject" && second && third && slug.length === 3) {
const result = await backApi.post<string>(
`/assign/reject/${encodeURIComponent(second)}/${encodeURIComponent(third)}`
);
return NextResponse.json(result, { status: 200 });
}
if(action === "written" && second === "excel-template"){
const result = await backApi.post<ArrayBuffer>(

View File

@@ -2,7 +2,7 @@ import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {errorToResponse} from "@/lib/http-util";
import {createBackApi} from "@/lib/server-api";
import {PerformanceCompact} from "@/types/gwcf";
import {Code, PerformanceCompact, PerformanceFull} from "@/types/gwcf";
const ALLOWED_ORIGIN = "https://kon.kric.com";
@@ -66,6 +66,11 @@ export const POST = async (
const [action] = slug;
const backApi = await createBackApi();
if(action === "code" && slug.length === 2) {
const result = await backApi.get<Code[]>(`/code/${encodeURIComponent(slug[1])}`)
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "assign-confirm" && slug.length === 3) {
const result = await backApi.post<string>(
`/assign/confirm/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`
@@ -73,8 +78,20 @@ export const POST = async (
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "assign-reject" && slug.length === 3) {
const result = await backApi.post<string>(
`/assign/reject/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`
);
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "performance" && slug.length === 2) {
const result = await backApi.get<PerformanceFull>(`/performance/${encodeURIComponent(slug[1])}`)
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "performance-list") {
const result = await backApi.get<PerformanceCompact[]>(`/performance/list/compact`)
const result = await backApi.get<PerformanceFull[]>(`/performance/list`)
return withCors(NextResponse.json(result, { status: 200 }));
}

View File

@@ -98,3 +98,26 @@ export const POST = async (
return errorToResponse(error);
}
};
export const DELETE = async (
req: NextRequest,
context: RouteContext
) => {
try {
void req;
const {slug = []} = await context.params;
const [action, subAction, performanceId, userId] = slug;
const backApi = await createBackApi();
if (action === "visit" && subAction === "reset" && performanceId && userId && slug.length === 4) {
await backApi.del<void>(
`/monitoring/visit/reset/${encodeURIComponent(performanceId)}/${encodeURIComponent(userId)}`
);
return NextResponse.json(null, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -4,6 +4,7 @@ import {errorToResponse} from "@/lib/http-util";
import {createNotiHubApi} from "@/lib/server-api";
import {
BulkSendResponse,
CreateTemplateRequest,
SaveTemplateRequest,
SendSmsBulkRequest,
Template,
@@ -15,14 +16,31 @@ export const GET = async (
) => {
try {
const {slug = []} = await context.params;
const [action, templateIdx] = slug;
const [action, second, third, fourth] = slug;
if (action !== "template" || !templateIdx) {
if (action !== "template") {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const notiHubApi = await createNotiHubApi();
const template = await notiHubApi.get<Template>(`/template/${encodeURIComponent(templateIdx)}`);
let path: string;
if (second === "list") {
if (slug.length !== 4 || !third || !fourth) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
path = `/template/list/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`;
} else {
if (slug.length !== 2 || !second) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
path = `/template/${encodeURIComponent(second)}`;
}
if (!path) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const template = await notiHubApi.get<Template | Template[]>(path);
return NextResponse.json(template, { status: 200 });
} catch (error: unknown) {
@@ -30,6 +48,35 @@ export const GET = async (
}
};
export const PUT = async (
req: NextRequest,
context: RouteContext
) => {
try {
const {slug = []} = await context.params;
if (slug.length !== 1 || slug[0] !== "template") {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const formData = await req.formData();
const templatePart = formData.get("template");
const body = templatePart instanceof Blob
? JSON.parse(await templatePart.text()) as CreateTemplateRequest
: null;
if (!body || !body.itrntPrjctCd || body.tmplatTy == null || !body.tmplatNm || !body.tmplatBody || !body.sendTel || !body.sendNm) {
return NextResponse.json({ message: "Template request body is invalid." }, { status: 400 });
}
const notiHubApi = await createNotiHubApi();
const backendForm = new FormData();
backendForm.append("template", new Blob([JSON.stringify(body)], {type: "application/json"}));
const created = await notiHubApi.putForm<Template>("/template", backendForm);
return NextResponse.json(created, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PATCH = async (
req: NextRequest,
context: RouteContext
@@ -42,7 +89,11 @@ export const PATCH = async (
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const body = await req.json().catch(() => null) as SaveTemplateRequest | null;
const formData = await req.formData();
const templatePart = formData.get("template");
const body = templatePart instanceof Blob
? JSON.parse(await templatePart.text()) as SaveTemplateRequest
: null;
if (!body || !body.tmplatIdx) {
return NextResponse.json({ message: "Template request body is invalid." }, { status: 400 });
}
@@ -52,12 +103,19 @@ export const PATCH = async (
const next: Template = {
...current,
tmplatNm: body.tmplatNm,
tmplatPurpose: body.tmplatPurpose ?? current.tmplatPurpose ?? 0,
tmplatTitle: body.tmplatTitle,
tmplatBody: body.tmplatBody,
sendTel: body.sendTel,
};
await notiHubApi.patch<void>("/template", next);
const backendForm = new FormData();
backendForm.append(
"template",
new Blob([JSON.stringify(next)], {type: "application/json"})
);
await notiHubApi.patchForm<void>("/template", backendForm);
return NextResponse.json(next, { status: 200 });
} catch (error: unknown) {

View File

@@ -10,6 +10,17 @@ import {CookieKeys} from "@/store/cookie/cookie-keys";
const reviewFileName = (prefix: string, performanceId: string, reviewType: string) =>
`${prefix}-${performanceId}-${reviewType}`;
const replaceContentDispositionType = (
contentDisposition: string | null,
disposition: "inline" | "attachment",
fallbackFileName: string
) => {
const fileNamePart = contentDisposition?.split(";").slice(1).join(";");
return fileNamePart
? `${disposition};${fileNamePart}`
: `${disposition}; filename="${fallbackFileName}"`;
};
export const GET = async (
req: NextRequest,
context: RouteContext
@@ -19,10 +30,10 @@ export const GET = async (
const [action, second, third, fourth] = slug;
const backApi = await createBackApi();
if (action === "template" && second === "download" && third && slug.length === 3) {
if (action === "template" && second === "download" && third && fourth && slug.length === 4) {
const cookieStore = await cookies();
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
const response = await fetch(`${serverEnv.API_BACK_SERVER.replace(/\/+$/, "")}/review/template/download/${encodeURIComponent(third)}`, {
const response = await fetch(`${serverEnv.API_BACK_SERVER.replace(/\/+$/, "")}/review/template/download/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`, {
headers: accessToken ? {authorization: `Bearer ${accessToken}`} : undefined,
cache: "no-store",
});
@@ -43,12 +54,54 @@ export const GET = async (
});
}
if (action === "template" && second === "pdf" && third && fourth && slug.length === 4) {
const cookieStore = await cookies();
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
const response = await fetch(`${serverEnv.API_BACK_SERVER.replace(/\/+$/, "")}/review/template/pdf/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`, {
headers: accessToken ? {authorization: `Bearer ${accessToken}`} : undefined,
cache: "no-store",
});
if (!response.ok) {
return new NextResponse(await response.text().catch(() => ""), {status: response.status});
}
const result = await response.arrayBuffer();
const disposition = req.nextUrl.searchParams.get("disposition") === "inline" ? "inline" : "attachment";
return new NextResponse(result, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": replaceContentDispositionType(
response.headers.get("content-disposition"),
disposition,
`review-template-${third}-${fourth}.pdf`
),
},
});
}
if (action === "download" && second && third && fourth && slug.length === 4) {
const result = await backApi.get<ArrayBuffer>(
`/review/download/${encodeURIComponent(second)}/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`,
{ expectBinary: true }
);
return new NextResponse(result, {
status: 200,
headers: {
"Content-Type": "application/zip",
"Content-Disposition": `attachment; filename="${reviewFileName("review-original", second, third)}.zip"`,
},
});
}
if (action === "download" && second && third && slug.length === 3) {
const result = await backApi.get<ArrayBuffer>(
`/review/download/${encodeURIComponent(second)}/${encodeURIComponent(third)}`,
{ expectBinary: true }
);
return new NextResponse(result, {
status: 200,
headers: {
@@ -115,10 +168,12 @@ export const POST = async (
const backendForm = new FormData();
backendForm.append("file", file, file.name);
const paramUserId = req.nextUrl.searchParams.get("paramUserId") ?? undefined;
const result = await backApi.postForm<PerformanceReview>(
`/review/${encodeURIComponent(action)}/${encodeURIComponent(second)}`,
backendForm
backendForm,
{ query: paramUserId ? { paramUserId } : undefined }
);
return NextResponse.json(result, { status: 200 });
}

View File

@@ -1,17 +1,18 @@
"use client";
import {useIsFetching} from "@tanstack/react-query";
import {useIsFetching, useIsMutating} from "@tanstack/react-query";
import {useLoading} from "@/hooks/useLoading";
import {useEffect} from "react";
const ReactQueryLoadingSync = () => {
const fetching = useIsFetching();
const mutating = useIsMutating();
const { showLoading, hideLoading } = useLoading();
useEffect(() => {
if (fetching > 0) showLoading();
if (fetching > 0 || mutating > 0) showLoading();
else hideLoading();
}, [fetching, showLoading, hideLoading]);
}, [fetching, mutating, showLoading, hideLoading]);
return null;
};

View File

@@ -48,7 +48,9 @@ export function DataTable<TData>({
defaultPageSize = 10,
pageSizeOptions = [5, 10, 25, 50],
showPagination = true,
paginationItemsToDisplay = 5
paginationItemsToDisplay = 5,
headerFontClass = 'content-text-lg',
cellFontClass = 'content-text-base',
}: Readonly<DataTableProps<TData>>) {
// Pagination state
const [pagination, setPagination] = useState<PaginationState>({
@@ -90,6 +92,14 @@ export function DataTable<TData>({
}
}, [rowSelection, selectMode])
useEffect(() => {
setPagination(prev => ({
...prev,
pageIndex: 0,
pageSize: Math.max(1, defaultPageSize),
}))
}, [defaultPageSize])
// selectMode에 따라 select column 추가
const enhancedColumns: DataTableColumn<TData, any>[] = [
...(isNotSelection
@@ -200,7 +210,8 @@ export function DataTable<TData>({
<TableHead
key={header.id}
className={cn(
'content-text-lg font-semibold text-gray-900',
'font-semibold text-gray-900',
headerFontClass,
column.id === 'actions' && 'w-[140px] text-center'
)}
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
@@ -209,7 +220,7 @@ export function DataTable<TData>({
<Button
type='button'
variant='ghost'
className='px-0 font-semibold content-text-lg flex items-center gap-1'
className={cn('px-0 font-semibold flex items-center gap-1', headerFontClass)}
onClick={column.getToggleSortingHandler()}
>
<span>{headerContent}</span>
@@ -240,8 +251,8 @@ export function DataTable<TData>({
onPointerCancel={drag.onPointerCancel}
onClick={drag.wrapClick(() => handleRowClick(row))}
className={cn(
'content-text-base',
'[&>td]:py-3 [&>td]:px-3',
cellFontClass,
'[&>td]:py-2 [&>td]:px-2',
selectMode !== 'none' && 'cursor-pointer',
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
shouldHighlight && 'bg-emerald-50',

View File

@@ -38,4 +38,6 @@ export interface DataTableProps<TData> {
pageSizeOptions?: number[];
showPagination?: boolean;
paginationItemsToDisplay?: number;
headerFontClass?: string;
cellFontClass?: string;
}

View File

@@ -11,7 +11,13 @@ import {StatusPill} from "@/components/gwcf/StatusPill";
import {Code, MonitoringApplyUser, PerformanceFull} from "@/types/gwcf";
import {CodeGroup} from "@/query/code";
import {getCodeLabel, getDetailValue} from "@/lib/gwcf/view";
import {getAssignStatusDisplay, MONITORING_ASSIGN_TYPE} from "@/lib/gwcf/performance-status";
import {
getAssignStatusDisplay,
isAssignConfirmed, isAssignRejected, isAssignRequested,
isNotAssignRejected,
MONITORING_ASSIGN_TYPE
} from "@/lib/gwcf/performance-status";
import {PERFORMANCE_FIELD_LABELS, USER_FIELD_LABELS} from "@/lib/gwcf/field-labels";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
@@ -23,7 +29,8 @@ export function AssignMonitoringDialog({
applyUsers,
isSavingAssign,
onSaveAssign,
onOpenSms,
onOpenAssignSms,
onOpenNormalSms,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -32,7 +39,8 @@ export function AssignMonitoringDialog({
applyUsers: MonitoringApplyUser[];
isSavingAssign?: boolean;
onSaveAssign: (performanceId: number, userIds: string[]) => void;
onOpenSms: (assignUserIds: string[], smsUserIds: string[]) => void;
onOpenAssignSms: (assignUserIds: string[], smsUserIds: string[]) => void;
onOpenNormalSms: (smsUserIds: string[]) => void;
}>) {
const monitoringAssigns = useMemo(
() => (selected?.performanceAssignList ?? []).filter((item) => item.assignType === MONITORING_ASSIGN_TYPE),
@@ -46,13 +54,13 @@ export function AssignMonitoringDialog({
return;
}
setCheckedIds(monitoringAssigns.map((item) => item.assignUser));
setCheckedIds(monitoringAssigns.filter(isNotAssignRejected).map((item) => item.assignUser));
}, [monitoringAssigns, open, selected?.id]);
const confirmRequestCount = monitoringAssigns.length;
const confirmedCount = monitoringAssigns.filter((item) => item.assignConfirm).length;
const smsTargetIds = checkedIds.filter(
(userId) => !monitoringAssigns.some((assign) => assign.assignUser === userId && assign.assignConfirm)
const confirmRequestCount = monitoringAssigns.filter(isAssignRequested).length;
const confirmedCount = monitoringAssigns.filter(isAssignConfirmed).length;
const assignSmsTargetIds = checkedIds.filter(
(userId) => !monitoringAssigns.some((assign) => assign.assignUser === userId && isAssignConfirmed(assign))
);
const updateChecked = (applyUser: MonitoringApplyUser, checked: boolean) => {
@@ -66,15 +74,19 @@ export function AssignMonitoringDialog({
return;
}
if(isAssignRejected(currentAssign)) {
if (!confirm("이미 포기한 사용자 입니다. 정말로 다시 배정하시겠습니까?")) return;
}
const next = Array.from(new Set([...checkedIds, applyUser.userId]));
setCheckedIds(next);
return;
}
if (currentAssign?.assignConfirm) {
if (!confirm("이미 승인된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
} else if (currentAssign) {
if (!confirm("이미 문자 발송된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
if (isAssignConfirmed(currentAssign)) {
if (!confirm("이미 승인된 상태입니다. 정말로 취소하시겠습니까?")) return;
} else if (isNotAssignRejected(currentAssign) && currentAssign) {
if (!confirm("이미 문자 발송된 상태입니다. 정말로 취소하시겠습니까?")) return;
}
const next = checkedIds.filter((userId) => userId !== applyUser.userId);
@@ -107,7 +119,7 @@ export function AssignMonitoringDialog({
},
{
id: "user",
header: "신청자",
header: USER_FIELD_LABELS.userName,
cell: ({row}) => (
<div>
<div className="font-semibold">{row.original.user?.userName || row.original.userId}</div>
@@ -117,14 +129,14 @@ export function AssignMonitoringDialog({
},
{
id: "area",
header: "지역",
header: USER_FIELD_LABELS.userArea,
cell: ({row}) =>
getCodeLabel(codes, "area", getDetailValue(row.original.user?.userDetail, ["area", "userArea", "region"])) || "-",
getCodeLabel(codes, "area", getDetailValue(row.original.user?.userDetail, "userArea")) || "-",
},
{
id: "tel",
header: "연락처",
cell: ({row}) => getDetailValue(row.original.user?.userDetail, ["tel", "phone", "userTel"], "-"),
header: USER_FIELD_LABELS.userTel,
cell: ({row}) => getDetailValue(row.original.user?.userDetail, "userTel", "-"),
},
{
id: "status",
@@ -133,7 +145,7 @@ export function AssignMonitoringDialog({
const assigned = monitoringAssigns.find((item) => item.assignUser === row.original.userId);
if (!assigned) return null;
const display = getAssignStatusDisplay(assigned.assignConfirm);
const display = getAssignStatusDisplay(assigned.assignStatus);
return <StatusPill variant={display.variant}>{display.label}</StatusPill>;
},
},
@@ -152,23 +164,23 @@ export function AssignMonitoringDialog({
<table className="w-full border-collapse text-sm">
<tbody>
{[
["연번", selected?.id],
["사업유형", getCodeLabel(codes, "business_type", selected?.businessType)],
["분야(장르)", getCodeLabel(codes, "genre", selected?.performanceGenre)],
["지역", getCodeLabel(codes, "area", selected?.performanceArea)],
["단체(팀)명", selected?.artistName],
["사업명", selected?.performanceName],
["사업 일정", selected?.performanceDtInfo],
["운영 시간", selected?.performanceTimeInfo],
["모니터링 일정", selected?.performanceMonitoringSchedule?.monitoringDate],
["모니터링 시간", selected?.performanceMonitoringSchedule?.monitoringTimeInfo],
["방문 장소", selected?.performanceMonitoringSchedule?.monitoringAddress],
["예매 예약", getCodeLabel(codes, "ticket_reservation_status", selected?.ticketReservationStatus)],
["예매 비고", selected?.ticketReservationMemo],
[PERFORMANCE_FIELD_LABELS.id, selected?.id],
[PERFORMANCE_FIELD_LABELS.businessType, getCodeLabel(codes, "business_type", selected?.businessType)],
[PERFORMANCE_FIELD_LABELS.performanceGenre, getCodeLabel(codes, "genre", selected?.performanceGenre)],
[PERFORMANCE_FIELD_LABELS.performanceArea, getCodeLabel(codes, "area", selected?.performanceArea)],
[PERFORMANCE_FIELD_LABELS.artistName, selected?.artistName],
[PERFORMANCE_FIELD_LABELS.performanceName, selected?.performanceName],
[PERFORMANCE_FIELD_LABELS.performanceDtInfo, selected?.performanceDtInfo],
[PERFORMANCE_FIELD_LABELS.performanceTimeInfo, selected?.performanceTimeInfo],
[PERFORMANCE_FIELD_LABELS.monitoringDate, selected?.performanceMonitoringSchedule?.monitoringDate ?? ""],
[PERFORMANCE_FIELD_LABELS.monitoringTimeInfo, selected?.performanceMonitoringSchedule?.monitoringTimeInfo],
[PERFORMANCE_FIELD_LABELS.monitoringAddress, selected?.performanceMonitoringSchedule?.monitoringAddress],
[PERFORMANCE_FIELD_LABELS.ticketReservationStatus, getCodeLabel(codes, "ticket_reservation_status", selected?.ticketReservationStatus)],
[PERFORMANCE_FIELD_LABELS.ticketReservationMemo, selected?.ticketReservationMemo],
].map(([label, value]) => (
<tr key={String(label)}>
<th className="w-32 border bg-muted p-2 text-left">{label}</th>
<td className="border p-2">{value || "-"}</td>
<td className="border p-2">{value || (label === PERFORMANCE_FIELD_LABELS.monitoringDate ? "" : "-")}</td>
</tr>
))}
</tbody>
@@ -190,16 +202,18 @@ export function AssignMonitoringDialog({
<div className="font-semibold">{confirmedCount}</div>
</div>
</div>
<div className="max-h-[50vh] overflow-auto [&_[data-slot=table-container]]:overflow-visible [&_th]:sticky [&_th]:top-0 [&_th]:z-10 [&_th]:bg-background [&_th]:shadow-[inset_0_1px_0_var(--border),inset_0_-1px_0_var(--border)]">
<DataTable
columns={columns}
data={applyUsers}
getRowId={(row) => row.userId}
defaultPageSize={applyUsers.length || 10}
pageSizeOptions={[applyUsers.length || 10]}
defaultPageSize={applyUsers.length}
pageSizeOptions={[applyUsers.length]}
showPagination={false}
selectMode="click-event"
onRowClick={toggleApplyUser}
/>
</div>
</section>
</div>
@@ -208,10 +222,14 @@ export function AssignMonitoringDialog({
<Save className="h-4 w-4" />
저장
</Button>
<Button type="button" variant="outline" disabled={smsTargetIds.length === 0 || isSavingAssign} onClick={() => onOpenSms(checkedIds, smsTargetIds)}>
<Button type="button" variant="outline" disabled={assignSmsTargetIds.length === 0 || isSavingAssign} onClick={() => onOpenAssignSms(checkedIds, assignSmsTargetIds)}>
<Send className="h-4 w-4" />
확정 문자 발송
</Button>
<Button type="button" variant="outline" disabled={checkedIds.length === 0} onClick={() => onOpenNormalSms(checkedIds)}>
<Send className="h-4 w-4" />
문자 발송
</Button>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>

View File

@@ -17,6 +17,7 @@ export function ExcelRegisterDialog({
open,
onOpenChange,
title,
notice,
onDownloadTemplate,
onUpload,
isUploading,
@@ -24,6 +25,7 @@ export function ExcelRegisterDialog({
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
notice?: string;
onDownloadTemplate: () => void;
onUpload: (file: File) => Promise<ExcelUploadResult>;
isUploading?: boolean;
@@ -56,6 +58,7 @@ export function ExcelRegisterDialog({
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="space-y-3">
{notice && <p className="text-xs text-red-500">* {notice}</p>}
<Button type="button" variant="outline" className="w-full" onClick={onDownloadTemplate}>
<Download className="h-4 w-4" />
양식 다운로드

View File

@@ -5,7 +5,7 @@ import {Download, ImageIcon, ScanSearch, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {StatusPill} from "@/components/gwcf/StatusPill";
import {Code, PerformanceFull} from "@/types/gwcf";
import {Code, PDF_CONVERT_STATUS, PdfConvertStatus, PerformanceFull} from "@/types/gwcf";
import {CodeGroup} from "@/query/code";
import {getCodeLabel} from "@/lib/gwcf/view";
import {
@@ -24,13 +24,15 @@ import {
buildEvidenceImageSrc,
buildImagePreviewUrl,
buildReviewPdfPreviewUrl,
buildReviewTemplatePdfPreviewUrl,
downloadBlob,
downloadFromUrl,
getEvidenceZipDownloadName,
getReviewOriginalDownloadName,
getReviewPdfDownloadName,
getReviewOriginalDownloadName, getReviewPdfDisabled,
getReviewPdfDownloadName, getReviewPdfStatusLabel,
openPreviewWindow,
} from "@/lib/gwcf/file";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/gwcf/field-labels";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
@@ -38,25 +40,27 @@ function MobileDetailRow({label, children}: {label: string; children: ReactNode}
return (
<div className="space-y-1 border-b px-3 py-2 last:border-b-0">
<div className="text-xs font-semibold text-muted-foreground">{label}</div>
<div className="break-words text-sm">{children || "-"}</div>
<div className="break-words text-sm">{children ?? "-"}</div>
</div>
);
}
function ActionButton({
children,
className,
icon = "download",
disabled = false,
onClick,
}: Readonly<{
children: ReactNode;
className?: string;
icon?: "download" | "upload" | "image" | "preview";
disabled?: boolean;
onClick?: () => void;
}>) {
const Icon = icon === "upload" ? Upload : icon === "image" ? ImageIcon : icon === "preview" ? ScanSearch : Download;
return (
<Button type="button" size="sm" variant="outline" disabled={disabled} onClick={onClick} className="min-h-10 flex-1">
<Button type="button" size="sm" variant="outline" disabled={disabled} onClick={onClick} className={className? className : "min-h-10 flex-1"}>
<Icon className="h-4 w-4" />
{children}
</Button>
@@ -69,6 +73,7 @@ function MonitoringReviewActions({
reviewType,
userId,
uploadFileName,
pdfConvert,
pdfFileName,
}: Readonly<{
canUpload: boolean;
@@ -76,6 +81,7 @@ function MonitoringReviewActions({
reviewType: number;
userId?: string;
uploadFileName?: string;
pdfConvert?: PdfConvertStatus;
pdfFileName?: string;
}>) {
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -112,12 +118,15 @@ function MonitoringReviewActions({
};
return (
<div>
<div className="grid grid-cols-2 gap-2">
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
<ActionButton icon="upload" disabled={!canUpload || uploadMutation.isPending} onClick={() => fileInputRef.current?.click()}>파일 업로드</ActionButton>
<ActionButton disabled={!userId || !uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</ActionButton>
<ActionButton disabled={!userId || !pdfFileName || pdfMutation.isPending} onClick={downloadPdf}>PDF</ActionButton>
<ActionButton icon="preview" disabled={!userId || !pdfFileName} onClick={previewPdf}>미리보기</ActionButton>
<ActionButton disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert) || pdfMutation.isPending} onClick={downloadPdf}>{getReviewPdfStatusLabel(pdfConvert)}</ActionButton>
<ActionButton icon="preview" disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert)} onClick={previewPdf}>미리보기</ActionButton>
</div>
<span className="text-xs text-red-500">* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.</span>
</div>
);
}
@@ -189,7 +198,27 @@ export function MonitoringPerformanceDetailDialog({
)
: {label: "미배치", variant: "danger" as const};
const downloadTemplate = () => downloadFromUrl("/api/review/template/download/1");
const reviewType = row?.reviewType ?? 1;
const templateClassification = Number(String(performance?.id ?? 0).charAt(0));
const buildTemplateDownloadUrl = (classification: number) => `/api/review/template/download/${reviewType}/${classification}`;
const downloadTemplate = () => downloadFromUrl(buildTemplateDownloadUrl(templateClassification));
const previewTemplateFile = async (classification: number, title: string) => {
const previewWindow = window.open("about:blank", "_blank");
if (previewWindow) previewWindow.opener = null;
const previewUrl = buildReviewTemplatePdfPreviewUrl(reviewType, classification, title);
if (previewWindow) {
previewWindow.location.href = previewUrl;
return;
}
openPreviewWindow(previewUrl);
};
const previewTemplate = () => void previewTemplateFile(templateClassification, "모니터링 현장 점검표.pdf");
const previewEduFile = () => void previewTemplateFile(99, "도민 모니터링단 매뉴얼.pdf");
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -202,33 +231,32 @@ export function MonitoringPerformanceDetailDialog({
{performance ? (
<>
<section className="overflow-hidden rounded-md border">
<MobileDetailRow label="연번">{performance.id}</MobileDetailRow>
<MobileDetailRow label="사업유형">{getCodeLabel(codes, "business_type", performance.businessType)}</MobileDetailRow>
<MobileDetailRow label="분야(장르)">{getCodeLabel(codes, "genre", performance.performanceGenre)}</MobileDetailRow>
<MobileDetailRow label="지역">{getCodeLabel(codes, "area", performance.performanceArea)}</MobileDetailRow>
<MobileDetailRow label="단체(인)명">{performance.artistName}</MobileDetailRow>
<MobileDetailRow label="사업명">{performance.performanceName}</MobileDetailRow>
<MobileDetailRow label="사업 수행 월">{performance.performanceStartMonth}월</MobileDetailRow>
<MobileDetailRow label="사업 일정">{performance.performanceDtInfo}</MobileDetailRow>
<MobileDetailRow label="운영 시간">{performance.performanceTimeInfo}</MobileDetailRow>
<MobileDetailRow label="예매 예약">{getCodeLabel(codes, "ticket_reservation_status", performance.ticketReservationStatus)}</MobileDetailRow>
<MobileDetailRow label="예매 비고">{performance.ticketReservationMemo}</MobileDetailRow>
<MobileDetailRow label="모니터링 일정">{performance.performanceMonitoringSchedule?.monitoringDate}</MobileDetailRow>
<MobileDetailRow label="모니터링 시간">{performance.performanceMonitoringSchedule?.monitoringTimeInfo}</MobileDetailRow>
<MobileDetailRow label="방문 장소">{performance.performanceMonitoringSchedule?.monitoringAddress}</MobileDetailRow>
<MobileDetailRow label="메모">{performance.performanceMemo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.id}>{performance.id}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.businessType}>{getCodeLabel(codes, "business_type", performance.businessType)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceGenre}>{getCodeLabel(codes, "genre", performance.performanceGenre)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceArea}>{getCodeLabel(codes, "area", performance.performanceArea)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.artistName}>{performance.artistName}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceName}>{performance.performanceName}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceStartMonth}>{performance.performanceStartMonth}월</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceDtInfo}>{performance.performanceDtInfo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceTimeInfo}>{performance.performanceTimeInfo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationStatus}>{getCodeLabel(codes, "ticket_reservation_status", performance.ticketReservationStatus)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationMemo}>{performance.ticketReservationMemo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.monitoringDate}>{performance.performanceMonitoringSchedule?.monitoringDate ?? ""}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.monitoringTimeInfo}>{performance.performanceMonitoringSchedule?.monitoringTimeInfo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAddress}>{performance.performanceMonitoringSchedule?.monitoringAddress}</MobileDetailRow>
{/*<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceMemo}>{performance.performanceMemo}</MobileDetailRow>*/}
</section>
<section className="space-y-3 rounded-md border p-3">
<div className="flex items-center justify-between gap-2">
<div className="font-semibold">나의 진행 상태</div>
<div className="flex items-center gap-2">
<Button type="button" size="sm" variant="outline" onClick={downloadTemplate}>
<Download className="h-4 w-4" />
양식
</Button>
<div className="flex items-start justify-between gap-3">
<div className="shrink-0 font-semibold leading-6">나의 진행 상태</div>
<StatusPill variant={status.variant}>{status.label}</StatusPill>
</div>
<div className="flex items-center justify-end gap-2">
<ActionButton icon="preview" onClick={previewEduFile} className="h-8 min-h-0 shrink-0 px-2 text-xs">교육자료</ActionButton>
<ActionButton icon="preview" onClick={previewTemplate} className="h-8 min-h-0 shrink-0 px-2 text-xs">양식</ActionButton>
<ActionButton icon="download" onClick={downloadTemplate} className="h-8 min-h-0 shrink-0 px-2 text-xs">양식 다운로드</ActionButton>
</div>
{row ? (
<MonitoringReviewActions
@@ -238,6 +266,7 @@ export function MonitoringPerformanceDetailDialog({
userId={row.review?.regUser || row.userId}
uploadFileName={row.review?.uploadFileName}
pdfFileName={row.review?.pdfFileName}
pdfConvert={row.review?.pdfConvert}
/>
) : (
<div className="rounded-md bg-muted p-3 text-sm text-muted-foreground">나의 모니터링 배정 정보를 찾을 수 없습니다.</div>

View File

@@ -15,7 +15,7 @@ function DetailRow({label, children}: {label: string; children: ReactNode}) {
return (
<div className="grid grid-cols-[130px_1fr] border-b last:border-b-0">
<div className="bg-muted px-3 py-2 text-sm font-semibold">{label}</div>
<div className="min-h-9 px-3 py-2 text-sm">{children || "-"}</div>
<div className="min-h-9 px-3 py-2 text-sm">{children ?? "-"}</div>
</div>
);
}
@@ -51,7 +51,7 @@ export function MonitoringVisitDialog({
<div className="rounded-md border">
<DetailRow label="현재 시간">{nowText}</DetailRow>
<DetailRow label="모니터링 일정">
{performance?.performanceMonitoringSchedule?.monitoringDate} {performance?.performanceMonitoringSchedule?.monitoringTimeInfo}
{[performance?.performanceMonitoringSchedule?.monitoringDate, performance?.performanceMonitoringSchedule?.monitoringTimeInfo].filter(Boolean).join(" ")}
</DetailRow>
<DetailRow label="사업명">{performance?.performanceName}</DetailRow>
<DetailRow label="장소">{performance?.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>

View File

@@ -1,14 +1,22 @@
"use client";
import {ReactNode, useEffect, useMemo, useRef, useState} from "react";
import {Download, ImageIcon, ScanSearch, Upload} from "lucide-react";
import {Download, ImageIcon, ScanSearch, Upload, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {DatePicker} from "@/components/common/DatePicker";
import {FilterSelect} from "@/components/gwcf/FilterSelect";
import {StatusPill} from "@/components/gwcf/StatusPill";
import {Code, PerformanceCompact, PerformanceFull, PerformanceMonitoringSchedule, PerformanceStaff, UserFull} from "@/types/gwcf";
import {
Code,
PdfConvertStatus,
PerformanceCompact,
PerformanceFull,
PerformanceMonitoringSchedule,
PerformanceStaff,
UserFull
} from "@/types/gwcf";
import {CodeGroup} from "@/query/code";
import {getCodeLabel, getDetailValue, ROLE} from "@/lib/gwcf/view";
import {
@@ -27,7 +35,7 @@ import {
useReviewFileQuery,
useUploadReviewFileMutation,
} from "@/query/review";
import {useDownloadEvidenceZipMutation, useMonitoringEvidenceQuery} from "@/query/monitoring";
import {useDownloadEvidenceZipMutation, useMonitoringEvidenceQuery, useResetMonitoringVisitMutation} from "@/query/monitoring";
import {useUsersQuery} from "@/query/user";
import {useLoading} from "@/hooks/useLoading";
import {
@@ -37,19 +45,88 @@ import {
downloadBlob,
downloadFromUrl,
getEvidenceZipDownloadName,
getReviewOriginalDownloadName,
getReviewPdfDownloadName,
getReviewOriginalDownloadName, getReviewPdfDisabled,
getReviewPdfDownloadName, getReviewPdfStatusLabel,
openPreviewWindow,
openWrittenReviewWindow,
} from "@/lib/gwcf/file";
import {PERFORMANCE_FIELD_LABELS, USER_FIELD_LABELS} from "@/lib/gwcf/field-labels";
import {useAuth} from "@/hooks/useAuth";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
type PerformanceDetail = PerformanceCompact["performanceDetail"];
type MonitoringVisitResetStatus = "departure" | "arrival";
const DETAIL_TEXT_MAX_LENGTH = 2048;
const ARTIST_NAME_MAX_LENGTH = 128;
type StaffTextField = "staffName" | "staffTel1" | "staffTel2" | "staffEmail";
// DB 컬럼 길이와 맞춘다.
const STAFF_FIELD_MAX_LENGTH: Record<StaffTextField, number> = {
staffName: 32,
staffTel1: 32,
staffTel2: 32,
staffEmail: 128,
};
const STAFF_TEXT_FIELDS: StaffTextField[] = ["staffName", "staffTel1", "staffTel2", "staffEmail"];
type StaffRow = {
key: string;
// null이면 유형 코드가 없어 입력할 수 없는 빈 행이다.
staffType: number | null;
staff: PerformanceStaff | null;
index: number | null;
};
const isBlankStaff = (staff: PerformanceStaff) => STAFF_TEXT_FIELDS.every((field) => (staff[field] ?? "").trim() === "");
// 관계자 유형 코드마다 행을 만들고, 데이터가 없는 유형은 빈 행으로 채운다.
// 빈 행과 새로 입력한 관계자는 같은 key를 사용해 입력 중 포커스가 유지되게 한다.
const buildStaffRows = (staffList: PerformanceStaff[], staffCodes: Code[]): StaffRow[] => {
const toRow = (staff: PerformanceStaff, index: number): StaffRow => ({
key: staff.id > 0 ? `staff-${staff.id}` : `new-${staff.staffType}`,
staffType: staff.staffType,
staff,
index,
});
const rows: StaffRow[] = [];
const usedIndexes = new Set<number>();
staffCodes.forEach((code) => {
const matched = staffList
.map((staff, index) => ({staff, index}))
.filter(({staff}) => staff.staffType === code.codeValue);
if (matched.length === 0) {
rows.push({key: `new-${code.codeValue}`, staffType: code.codeValue, staff: null, index: null});
return;
}
matched.forEach(({staff, index}) => {
usedIndexes.add(index);
rows.push(toRow(staff, index));
});
});
staffList.forEach((staff, index) => {
if (!usedIndexes.has(index)) rows.push(toRow(staff, index));
});
if (rows.length === 0) {
rows.push({key: "empty", staffType: null, staff: null, index: null});
}
return rows;
};
// UpdateNoticeDt는 한국시간 ISO 문자열이므로 시간대 변환 없이 표시만 정리한다.
const formatUpdateNoticeDt = (value?: string) => (value ?? "").replace("T", " ").replace(/\.\d+/, "");
function DetailRow({label, children}: {label: string; children: ReactNode}) {
return (
<div className="grid grid-cols-[130px_1fr] border-b last:border-b-0">
<div className="bg-muted px-3 py-2 text-sm font-semibold">{label}</div>
<div className="min-h-9 px-3 py-2 text-sm">{children || "-"}</div>
<div className="min-h-9 px-3 py-2 text-sm">{children ?? "-"}</div>
</div>
);
}
@@ -86,22 +163,22 @@ function AssignedUserInfo({
type: "monitoring" | "written";
}>) {
const detail = user?.userDetail;
const tel = getDetailValue(detail, ["tel", "phone", "userTel"], "-");
const email = getDetailValue(detail, ["email", "userEmail"], "-");
const tel = getDetailValue(detail, "userTel", "-");
const email = getDetailValue(detail, "userEmail", "-");
const metaValue = type === "monitoring"
? getCodeLabel(codes, "area", getDetailValue(detail, ["area", "userArea", "region"]))
: getCodeLabel(codes, "genre", getDetailValue(detail, ["userGenre", "genre", "reviewGenre"]));
const metaLabel = type === "monitoring" ? "지역" : "장르";
const hasCar = getCodeLabel(codes, "has_car", getDetailValue(detail, ["userHasCar", "has_car", "hasCar"])) || "-";
? getCodeLabel(codes, "area", getDetailValue(detail, "userArea"))
: getCodeLabel(codes, "genre", getDetailValue(detail, "userGenre"));
const metaLabel = type === "monitoring" ? USER_FIELD_LABELS.userArea : USER_FIELD_LABELS.userGenre;
const hasCar = getCodeLabel(codes, "has_car", getDetailValue(detail, "userHasCar")) || "-";
return (
<div className="rounded-md border bg-muted/30 p-2 text-sm">
<div className="grid gap-1 text-xs text-muted-foreground sm:grid-cols-2">
<span>ID: {userId || "-"}</span>
<span>{metaLabel}: {metaValue || "-"}</span>
<span>연락처: {tel}</span>
<span>이메일: {email}</span>
{type === "monitoring" && <span>자차유무: {hasCar}</span>}
<span>{USER_FIELD_LABELS.userTel}: {tel}</span>
<span>{USER_FIELD_LABELS.userEmail}: {email}</span>
{type === "monitoring" && <span>{USER_FIELD_LABELS.userHasCar}: {hasCar}</span>}
</div>
</div>
);
@@ -113,6 +190,7 @@ function ReviewFileActions({
userId,
uploadFileName,
pdfFileName,
pdfConvert,
canUpload,
canEdit,
}: Readonly<{
@@ -121,6 +199,7 @@ function ReviewFileActions({
userId?: string;
uploadFileName?: string;
pdfFileName?: string;
pdfConvert?: PdfConvertStatus
canUpload: boolean;
canEdit: boolean;
}>) {
@@ -133,7 +212,9 @@ function ReviewFileActions({
const upload = async (file?: File) => {
try {
if (!file) return;
await withLoadingAsync(() => uploadMutation.mutateAsync({performanceId, reviewType, file}));
await withLoadingAsync(() =>
uploadMutation.mutateAsync({performanceId, reviewType, file, paramUserId: userId})
);
alert("파일 업로드가 완료되었습니다.");
} finally {
if (fileInputRef.current) fileInputRef.current.value = "";
@@ -166,15 +247,16 @@ function ReviewFileActions({
return (
<div className="flex flex-wrap gap-1">
{canEdit && (
{canEdit && userId && (
<>
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
<FileActionButton icon="upload" disabled={uploadMutation.isPending || !canUpload} onClick={() => fileInputRef.current?.click()}>파일 업로드</FileActionButton>
</>
)}
<FileActionButton icon="download" disabled={!userId || !uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</FileActionButton>
<FileActionButton icon="download" disabled={!userId || !pdfFileName || pdfMutation.isPending} onClick={downloadPdf}>PDF</FileActionButton>
<FileActionButton icon="preview" disabled={!userId || !pdfFileName} onClick={previewPdf}>미리보기</FileActionButton>
<FileActionButton icon="download" disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert) || pdfMutation.isPending} onClick={downloadPdf}>{getReviewPdfStatusLabel(pdfConvert)}</FileActionButton>
<FileActionButton icon="preview" disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert)} onClick={previewPdf}>미리보기</FileActionButton>
<span className="text-xs text-red-500">* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.</span>
</div>
);
}
@@ -216,29 +298,37 @@ function EvidenceZipButton({performanceId, userId}: {performanceId: number; user
function LocalGovernmentReviewRow({
performance,
codes,
loginUserId,
}: {
performance: PerformanceFull | PerformanceCompact;
codes: CodeMap;
loginUserId: string | undefined;
}) {
const reviewType = LOCAL_GOVERNMENT_REVIEW_TYPE;
const fallbackReviewRow = getReviewByType(performance as PerformanceFull, reviewType);
const userId = fallbackReviewRow?.review.regUser || fallbackReviewRow?.userId;
const {data: fetchedReview} = useReviewFileQuery(performance.id, reviewType, userId, performance.id > 0 && Boolean(userId));
if(performance.id % 100 !== 1){
return null;
}
const review = fetchedReview ?? fallbackReviewRow?.review;
const label = getCodeLabel(codes, "review_status", review?.reviewStatus);
const display = getReviewStatusDisplay(label, review, true);
return (
<div className="space-y-2 border-b p-3">
<div className="font-semibold">지자체</div>
<div className="font-semibold">자체 보고서</div>
<div className="flex flex-wrap items-center gap-2">
<StatusPill variant={display.variant}>{display.label}</StatusPill>
<ReviewFileActions
performanceId={performance.id}
reviewType={reviewType}
userId={review?.regUser || userId}
userId={review?.regUser || userId || loginUserId}
uploadFileName={review?.uploadFileName}
pdfFileName={review?.pdfFileName}
pdfConvert={review?.pdfConvert}
canUpload={true}
canEdit={true}
/>
@@ -263,11 +353,25 @@ function MonitoringStatusRow({
const row = getMonitoringDisplayRow(performance as PerformanceFull, index);
const user = row.userId ? userMap.get(row.userId) : undefined;
const latestVisit = row.slot.visit?.[0];
const resetMutation = useResetMonitoringVisitMutation();
const display = getMonitoringDisplayStatus(
row,
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
getCodeLabel(codes, "review_status", row.review?.reviewStatus)
);
const resetStatus: MonitoringVisitResetStatus | null =
display.variant === "departed" ? "departure" : display.variant === "arrived" ? "arrival" : null;
const resetUserId = row.evidenceUserId || row.userId;
const canResetMonitoringVisit = canEdit && Boolean(resetStatus && resetUserId);
const resetMonitoringVisit = () => {
if (!resetStatus || !resetUserId) return;
if (!confirm("방문 정보를 정말 삭제하시겠습니까?")) return;
resetMutation.mutate({
performanceId: performance.id,
userId: resetUserId,
});
};
return (
<div className="space-y-2 border-b p-3">
@@ -275,15 +379,36 @@ function MonitoringStatusRow({
<div className="grid gap-1 text-sm">
<AssignedUserInfo userId={row.userId} user={user} codes={codes} type="monitoring" />
<div className="flex flex-wrap items-center gap-2 mb-2">
<StatusPill variant={display.variant}>{display.label}</StatusPill>
<StatusPill variant={display.variant}>
<span className="inline-flex items-center gap-1">
{display.label}
{canResetMonitoringVisit && (
<button
type="button"
aria-label={`${display.label} 상태 취소`}
className="inline-flex h-4 w-4 items-center justify-center rounded-full text-red-600 hover:bg-red-50 hover:text-red-700 disabled:pointer-events-none disabled:opacity-50 cursor-pointer"
disabled={resetMutation.isPending}
onClick={(event) => {
event.stopPropagation();
resetMonitoringVisit();
}}
>
<X className="h-3 w-3" />
</button>
)}
</span>
</StatusPill>
<ReviewFileActions
performanceId={performance.id}
reviewType={row.reviewType}
userId={row.review?.regUser || row.userId}
uploadFileName={row.review?.uploadFileName}
pdfFileName={row.review?.pdfFileName}
canUpload={canEdit && isReviewComplete(row.review)}
canEdit={canEdit}
pdfConvert={row.review?.pdfConvert}
//canUpload={canEdit && isReviewComplete(row.review)}
//canEdit={canEdit}
canUpload={true}
canEdit={true}
/>
</div>
{row.slot.visit?.length ? (
@@ -318,6 +443,10 @@ function WrittenReviewRows({
userMap: Map<string, UserFull>;
canEdit: boolean;
}>) {
if(performance.id % 100 !== 1){
return null;
}
const rows = getWrittenReviewRows(performance as PerformanceFull);
if(rows.length === 0){
@@ -365,17 +494,27 @@ export function PerformanceDetailDialog({
performance,
codes,
canEdit,
canEditNoticeAndStaff = false,
canDelete,
onSave,
onDelete,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
performance: PerformanceFull | PerformanceCompact | null;
codes: CodeMap;
canEdit: boolean;
// 기본 정보는 표시만 하고 변경 정보, 관계자 정보만 수정할 수 있는 권한
canEditNoticeAndStaff?: boolean;
canDelete: boolean;
onSave?: (performance: PerformanceCompact) => void;
onDelete?: (performanceId: number) => void;
}>) {
const {auth} = useAuth();
const [draft, setDraft] = useState<PerformanceCompact | null>(null);
const [isEditing, setIsEditing] = useState(false);
const canModify = canEdit || canEditNoticeAndStaff;
const isEditingBasic = isEditing && canEdit;
const {data: monitoringUsers = []} = useUsersQuery(ROLE.MONITORING, open);
const {data: writtenUsers = []} = useUsersQuery(ROLE.WRITTEN_REVIEWER, open);
const monitoringUserMap = useMemo(
@@ -387,6 +526,8 @@ export function PerformanceDetailDialog({
[writtenUsers]
);
const userId = auth.user?.userId;
useEffect(() => {
if (!performance) {
setDraft(null);
@@ -418,6 +559,16 @@ export function PerformanceDetailDialog({
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
};
const updateDetail = <K extends keyof PerformanceDetail>(key: K, value: PerformanceDetail[K]) => {
setDraft((prev) => prev ? {
...prev,
performanceDetail: {
...prev.performanceDetail,
[key]: value,
},
} : prev);
};
const updateSchedule = <K extends keyof PerformanceMonitoringSchedule>(key: K, value: PerformanceMonitoringSchedule[K]) => {
setDraft((prev) => prev ? {
...prev,
@@ -437,6 +588,39 @@ export function PerformanceDetailDialog({
});
};
const updateStaffRow = (row: StaffRow, key: StaffTextField, value: string) => {
if (row.index !== null) {
updateStaff(row.index, key, value);
return;
}
const staffType = row.staffType;
if (staffType === null) return;
setDraft((prev) => {
if (!prev) return prev;
// id는 서버에서 새로 발급하므로 0으로 보낸다.
const newStaff: PerformanceStaff = {
id: 0,
performanceId: prev.id,
staffType,
staffName: "",
staffTel1: "",
staffTel2: "",
staffEmail: "",
[key]: value,
};
return {...prev, performanceStaff: [...(prev.performanceStaff ?? []), newStaff]};
});
};
const renderStaffCell = (row: StaffRow, field: StaffTextField) => {
const value = row.staff?.[field] ?? "";
if (!isEditing || row.staffType === null) return value;
return <Input maxLength={STAFF_FIELD_MAX_LENGTH[field]} value={value} onChange={(event) => updateStaffRow(row, field, event.target.value)} />;
};
const staffRows = draft ? buildStaffRows(draft.performanceStaff ?? [], codes.staff_type ?? []) : [];
const resetDraft = () => {
if (!performance) return;
setDraft({
@@ -460,12 +644,60 @@ export function PerformanceDetailDialog({
const save = () => {
if (!draft) return;
onSave?.(draft);
const detail = draft.performanceDetail ?? {};
const ncas = detail["NCAS"] ?? "";
const updateNoticeTarget = detail["UpdateNoticeTarget"] ?? "";
const updateNoticeMemo = detail["UpdateNoticeMemo"] ?? "";
if (!/^\d*$/.test(ncas)) {
alert(`${PERFORMANCE_FIELD_LABELS.NCAS}는 숫자만 입력할 수 있습니다.`);
return;
}
if (ncas.length > DETAIL_TEXT_MAX_LENGTH || updateNoticeMemo.length > DETAIL_TEXT_MAX_LENGTH) {
alert(`${PERFORMANCE_FIELD_LABELS.NCAS}와 ${PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo}은 최대 2,048자까지 입력할 수 있습니다.`);
return;
}
if (updateNoticeTarget !== "" && updateNoticeMemo.trim() === "") {
alert(`${PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget}을 선택한 경우 ${PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo}을 입력해 주세요.`);
return;
}
// 기본 정보를 수정할 수 없는 권한은 기존 값을 고칠 수 없으므로 검사하지 않는다.
if (canEdit && (draft.artistName ?? "").trim() === "") {
alert(`${PERFORMANCE_FIELD_LABELS.artistName}을 입력해 주세요.`);
return;
}
// 모든 칸이 공란인 관계자는 저장하지 않는다.
const performanceStaff = (draft.performanceStaff ?? []).filter((staff) => !isBlankStaff(staff));
if (performanceStaff.some((staff) => (staff.staffName ?? "").trim() === "")) {
alert("관계자 이름을 입력해 주세요.");
return;
}
const performanceDetail: PerformanceDetail = {
...detail,
NCAS: ncas,
UpdateNoticeTarget: updateNoticeTarget,
UpdateNoticeMemo: updateNoticeMemo,
};
// 변경 일시는 서버에서 생성하므로 요청에서 제외한다.
delete performanceDetail["UpdateNoticeDt"];
onSave?.({...draft, performanceDetail, performanceStaff});
setIsEditing(false);
};
const downloadTemplate = (reviewType: number) => {
downloadFromUrl(`/api/review/template/download/${reviewType}`);
const deletePerformance = () => {
if(!draft) return;
if(confirm("삭제 되면 복구할 수 없습니다. 삭제를 진행 하시겠습니까?")){
onDelete?.(draft.id);
}
}
const downloadTemplate = (reviewType: number, classification: number) => {
downloadFromUrl(`/api/review/template/download/${reviewType}/${classification}`);
};
return (
@@ -480,25 +712,64 @@ export function PerformanceDetailDialog({
<div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
<div className="space-y-4">
<section className="rounded-md border">
<DetailRow label="연번">{draft.id}</DetailRow>
<DetailRow label="사업유형">{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
<DetailRow label="분야(장르)">{getCodeLabel(codes, "genre", draft.performanceGenre)}</DetailRow>
<DetailRow label="지역">{getCodeLabel(codes, "area", draft.performanceArea)}</DetailRow>
<DetailRow label="단체(인)명">{draft.artistName}</DetailRow>
<DetailRow label="사업명">{isEditing ? <Input value={draft.performanceName} onChange={(event) => updateDraft("performanceName", event.target.value)} /> : draft.performanceName}</DetailRow>
<DetailRow label="사업 수행 월">{isEditing ? <Input type="number" value={draft.performanceStartMonth} onChange={(event) => updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`}</DetailRow>
<DetailRow label="사업 일정">{isEditing ? <Input value={draft.performanceDtInfo} onChange={(event) => updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo}</DetailRow>
<DetailRow label="운영 시간">{isEditing ? <Input value={draft.performanceTimeInfo} onChange={(event) => updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo}</DetailRow>
<DetailRow label="예매 예약">
{isEditing ? (
<FilterSelect value={String(draft.ticketReservationStatus ?? "")} onChange={(value) => updateDraft("ticketReservationStatus", Number(value))} options={codes.ticket_reservation_status ?? []} placeholder="예매 예약" />
<DetailRow label={PERFORMANCE_FIELD_LABELS.no}>{draft.performanceDetail["performanceNo"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.id}>{draft.id}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.NCAS}>{isEditingBasic ? <Input inputMode="numeric" maxLength={DETAIL_TEXT_MAX_LENGTH} value={draft.performanceDetail["NCAS"] ?? ""} onChange={(event) => updateDetail("NCAS", event.target.value.replace(/\D/g, ""))} /> : draft.performanceDetail["NCAS"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAdd}>{draft.id % 100 !== 1? "추가" : ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.businessType}>{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceGenre}>{getCodeLabel(codes, "genre", draft.performanceGenre)}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceArea}>
{isEditingBasic ? (
<FilterSelect value={String(draft.performanceArea ?? "")} onChange={(value) => updateDraft("performanceArea", Number(value))} options={codes.area ?? []} placeholder={PERFORMANCE_FIELD_LABELS.performanceArea} />
) : getCodeLabel(codes, "area", draft.performanceArea)}
</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceAreaDetail}>{isEditingBasic ? <Input value={draft.performanceDetail["performanceAreaDetail"] ?? ""} onChange={(event) => updateDetail("performanceAreaDetail", event.target.value)} /> : draft.performanceDetail["performanceAreaDetail"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.artistName}>{isEditingBasic ? <Input maxLength={ARTIST_NAME_MAX_LENGTH} value={draft.artistName ?? ""} onChange={(event) => updateDraft("artistName", event.target.value)} /> : draft.artistName}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceName}>{isEditingBasic ? <Input value={draft.performanceName} onChange={(event) => updateDraft("performanceName", event.target.value)} /> : draft.performanceName}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceStartMonth}>{isEditingBasic ? <Input type="number" value={draft.performanceStartMonth} onChange={(event) => updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceDtInfo}>{isEditingBasic ? <Input value={draft.performanceDtInfo} onChange={(event) => updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceTimeInfo}>{isEditingBasic ? <Input value={draft.performanceTimeInfo} onChange={(event) => updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationStatus}>
{isEditingBasic ? (
<FilterSelect value={String(draft.ticketReservationStatus ?? "")} onChange={(value) => updateDraft("ticketReservationStatus", Number(value))} options={codes.ticket_reservation_status ?? []} placeholder={PERFORMANCE_FIELD_LABELS.ticketReservationStatus} />
) : getCodeLabel(codes, "ticket_reservation_status", draft.ticketReservationStatus)}
</DetailRow>
<DetailRow label="예매 비고">{isEditing ? <Input value={draft.ticketReservationMemo} onChange={(event) => updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo}</DetailRow>
<DetailRow label="모니터링 일정">{isEditing ? <DatePicker value={draft.performanceMonitoringSchedule?.monitoringDate ?? ""} onChange={(value) => updateSchedule("monitoringDate", value)} /> : draft.performanceMonitoringSchedule?.monitoringDate}</DetailRow>
<DetailRow label="모니터링 시간">{isEditing ? <Input value={draft.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""} onChange={(event) => updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringTimeInfo}</DetailRow>
<DetailRow label="방문 장소">{isEditing ? <Input value={draft.performanceMonitoringSchedule?.monitoringAddress ?? ""} onChange={(event) => updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>
<DetailRow label="메모">{isEditing ? <Input value={draft.performanceMemo} onChange={(event) => updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationMemo}>{isEditingBasic ? <Input value={draft.ticketReservationMemo} onChange={(event) => updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringDate}>{isEditingBasic ? <DatePicker value={draft.performanceMonitoringSchedule?.monitoringDate ?? ""} onChange={(value) => updateSchedule("monitoringDate", value)} /> : draft.performanceMonitoringSchedule?.monitoringDate ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringTimeInfo}>{isEditingBasic ? <Input value={draft.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""} onChange={(event) => updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringTimeInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.needMonitoring}>{isEditingBasic ? <Input value={draft.performanceDetail["needMonitoring"] ?? ""} onChange={(event) => updateDetail("needMonitoring", event.target.value)} /> : draft.performanceDetail["needMonitoring"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.needWrittenReview}>{isEditingBasic ? <Input value={draft.performanceDetail["needWrittenReview"] ?? ""} onChange={(event) => updateDetail("needWrittenReview", event.target.value)} /> : draft.performanceDetail["needWrittenReview"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.checkDeliver}>{isEditingBasic ? <Input value={draft.performanceDetail["checkDeliver"] ?? ""} onChange={(event) => updateDetail("checkDeliver", event.target.value)} /> : draft.performanceDetail["checkDeliver"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.timeTreeCheckDt}>{isEditingBasic ? <DatePicker value={draft.performanceDetail["timeTreeCheckDt"] ?? ""} onChange={(value) => updateDetail("timeTreeCheckDt", value)} /> : draft.performanceDetail["timeTreeCheckDt"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAddress}>{isEditingBasic ? <Input value={draft.performanceMonitoringSchedule?.monitoringAddress ?? ""} onChange={(event) => updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceMemo}>{isEditingBasic ? <Input value={draft.performanceMemo} onChange={(event) => updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.checkReport}>{isEditingBasic ? <Input value={draft.performanceDetail["checkReport"] ?? ""} onChange={(event) => updateDetail("checkReport", event.target.value)} /> : draft.performanceDetail["checkReport"] ?? ""}</DetailRow>
</section>
<section className="rounded-md border">
<div className="border-b bg-muted px-3 py-2 font-semibold">변경 정보</div>
<div className="overflow-auto">
<table className="w-full min-w-[620px] border-collapse text-sm">
<thead>
<tr className="bg-muted">
<th className="w-[180px] border p-2">{PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget}</th>
<th className="border p-2">{PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo}</th>
<th className="w-[170px] border p-2">{PERFORMANCE_FIELD_LABELS.UpdateNoticeDt}</th>
</tr>
</thead>
<tbody>
<tr>
<td className="border p-2">
{isEditing ? (
<FilterSelect value={draft.performanceDetail["UpdateNoticeTarget"] ?? ""} onChange={(value) => updateDetail("UpdateNoticeTarget", value)} options={codes.update_notice_target ?? []} placeholder={PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget} clearLabel="선택 해제" />
) : getCodeLabel(codes, "update_notice_target", draft.performanceDetail["UpdateNoticeTarget"])}
</td>
<td className="border p-2">{isEditing ? <Input maxLength={DETAIL_TEXT_MAX_LENGTH} value={draft.performanceDetail["UpdateNoticeMemo"] ?? ""} onChange={(event) => updateDetail("UpdateNoticeMemo", event.target.value)} /> : draft.performanceDetail["UpdateNoticeMemo"] ?? ""}</td>
<td className="border p-2 text-center">{formatUpdateNoticeDt(draft.performanceDetail["UpdateNoticeDt"])}</td>
</tr>
</tbody>
</table>
</div>
</section>
<section className="rounded-md border">
@@ -515,13 +786,12 @@ export function PerformanceDetailDialog({
</tr>
</thead>
<tbody>
{draft.performanceStaff?.map((staff, index) => (
<tr key={staff.id}>
<td className="border p-2">{getCodeLabel(codes, "staff_type", staff.staffType)}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffName} onChange={(event) => updateStaff(index, "staffName", event.target.value)} /> : staff.staffName}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffTel1} onChange={(event) => updateStaff(index, "staffTel1", event.target.value)} /> : staff.staffTel1}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffTel2} onChange={(event) => updateStaff(index, "staffTel2", event.target.value)} /> : staff.staffTel2}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffEmail} onChange={(event) => updateStaff(index, "staffEmail", event.target.value)} /> : staff.staffEmail}</td>
{staffRows.map((row) => (
<tr key={row.key}>
<td className="h-9 border p-2">{getCodeLabel(codes, "staff_type", row.staffType)}</td>
{STAFF_TEXT_FIELDS.map((field) => (
<td key={field} className="border p-2">{renderStaffCell(row, field)}</td>
))}
</tr>
))}
</tbody>
@@ -534,17 +804,13 @@ export function PerformanceDetailDialog({
<div className="flex flex-wrap items-center justify-between gap-2 border-b bg-muted px-3 py-2">
<div className="font-semibold">평가 및 모니터링 현황</div>
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" onClick={() => downloadTemplate(1)}>
<Button type="button" size="sm" variant="outline" onClick={() => downloadTemplate(1, Number(String(performance?.id ?? 0).charAt(0)))}>
<Download className="h-4 w-4" />
모니터링 양식
</Button>
<Button type="button" size="sm" variant="outline" onClick={() => downloadTemplate(3)}>
<Download className="h-4 w-4" />
지자체 양식
</Button>
</div>
</div>
<LocalGovernmentReviewRow performance={performance ?? draft} codes={codes} />
<LocalGovernmentReviewRow performance={performance ?? draft} codes={codes} loginUserId={userId} />
<MonitoringStatusRow performance={performance ?? draft} index={0} codes={codes} userMap={monitoringUserMap} canEdit={canEdit} />
<MonitoringStatusRow performance={performance ?? draft} index={1} codes={codes} userMap={monitoringUserMap} canEdit={canEdit} />
<WrittenReviewRows performance={performance ?? draft} codes={codes} userMap={writtenUserMap} canEdit={canEdit} />
@@ -554,8 +820,9 @@ export function PerformanceDetailDialog({
</div>
<DialogFooter className="shrink-0 border-t pt-4">
{canEdit && draft && !isEditing && <Button type="button" onClick={() => setIsEditing(true)}>수정</Button>}
{canEdit && draft && isEditing && (
{canDelete && draft && <Button type="button" variant="destructive" onClick={deletePerformance}>삭제</Button>}
{canModify && draft && !isEditing && <Button type="button" onClick={() => setIsEditing(true)}>수정</Button>}
{canModify && draft && isEditing && (
<>
<Button type="button" onClick={save}>저장</Button>
<Button type="button" variant="outline" onClick={() => { resetDraft(); setIsEditing(false); }}>취소</Button>

View File

@@ -1,11 +1,13 @@
"use client";
import {useEffect, useMemo, useState} from "react";
import {Edit, RotateCcw, Save, Send} from "lucide-react";
import {useEffect, useMemo, useRef, useState} from "react";
import {Edit, RotateCcw, Save, Send, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
@@ -14,6 +16,7 @@ import {
import {
NOTIFICATION_REQUEST_SERVICE,
useNotificationTemplateQuery,
useNotificationTemplatesQuery,
useSaveNotificationTemplateMutation,
useSendSmsBulkMutation,
} from "@/query/notification";
@@ -21,17 +24,23 @@ import {SaveTemplateRequest, Template} from "@/types/notification";
import {UserCompact} from "@/types/gwcf";
import {getDetailValue} from "@/lib/gwcf/view";
import {useAuth} from "@/hooks/useAuth";
import {buildUserMsgParam} from "@/lib/gwcf/notification";
import { buildUserMsgParam, isPhoneVerificationSupported} from "@/lib/gwcf/notification";
import {getSmsParamLabel} from "@/lib/gwcf/field-labels";
import {TMPLAT_PURPOSE} from "@/types/notification";
type TemplateDraft = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
type TemplateDraft = Pick<Template, "tmplatIdx" | "tmplatTy" | "tmplatPurpose" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
const EMPTY_DENY_PARAM_KEYS: string[] = [];
const toText = (value: string | null | undefined) => value ?? "";
const toDraft = (template: Template, emptyBody = false): TemplateDraft => ({
const toDraft = (template: Template, isNewMessage = false): TemplateDraft => ({
tmplatIdx: template.tmplatIdx,
tmplatTy: template.tmplatTy,
tmplatPurpose: isPhoneVerificationSupported(template) ? template.tmplatPurpose ?? TMPLAT_PURPOSE.NORMAL : TMPLAT_PURPOSE.NORMAL,
tmplatNm: toText(template.tmplatNm),
tmplatTitle: toText(template.tmplatTitle),
tmplatBody: emptyBody ? "" : toText(template.tmplatBody),
tmplatTitle: isNewMessage ? "" : toText(template.tmplatTitle),
tmplatBody: isNewMessage ? "" : toText(template.tmplatBody),
sendTel: toText(template.sendTel),
});
@@ -43,6 +52,7 @@ export function SmsSendDialog({
newMessageTemplateIdx,
selectedUsers,
addParams = {},
denyParamKeys = EMPTY_DENY_PARAM_KEYS,
onBeforeDefaultTemplateSend,
isBeforeSendPending = false,
onSent,
@@ -50,66 +60,113 @@ export function SmsSendDialog({
open: boolean;
onOpenChange: (open: boolean) => void;
title?: string;
templateIdx: number;
templateIdx: number[];
newMessageTemplateIdx?: number;
selectedUsers: UserCompact[];
addParams?: Record<string, string>;
denyParamKeys?: string[];
onBeforeDefaultTemplateSend?: () => Promise<void>;
isBeforeSendPending?: boolean;
onSent?: () => void;
}>) {
const {auth} = useAuth();
const [activeTemplateIdx, setActiveTemplateIdx] = useState(templateIdx);
const templateIdxKey = templateIdx.join(",");
const templateIdxList = useMemo(
() => Array.from(new Set(templateIdx.filter((idx) => idx > 0))),
[templateIdxKey]
);
const defaultTemplateIdx = templateIdxList[0] ?? 0;
const [activeTemplateIdx, setActiveTemplateIdx] = useState(defaultTemplateIdx);
const [isNewMessage, setIsNewMessage] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [draft, setDraft] = useState<TemplateDraft | null>(null);
const bodyTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const templateQuery = useNotificationTemplateQuery(activeTemplateIdx, open);
const templatesQuery = useNotificationTemplatesQuery(templateIdxList, open);
const newMessageTemplateQuery = useNotificationTemplateQuery(newMessageTemplateIdx ?? 0, Boolean(open && isNewMessage && newMessageTemplateIdx));
const saveTemplateMutation = useSaveNotificationTemplateMutation();
const sendSmsMutation = useSendSmsBulkMutation();
const activeTemplate = isNewMessage
? newMessageTemplateQuery.data
: templatesQuery.data.find((template) => template.tmplatIdx === activeTemplateIdx);
const isBusy = templateQuery.isLoading || saveTemplateMutation.isPending || sendSmsMutation.isPending || isBeforeSendPending;
const isBusy = templatesQuery.isLoading || newMessageTemplateQuery.isLoading || saveTemplateMutation.isPending || sendSmsMutation.isPending || isBeforeSendPending;
const canEdit = isNewMessage || isEditing;
const denyParamKeySet = useMemo(() => new Set(denyParamKeys), [denyParamKeys]);
const destinations = useMemo(() => {
return selectedUsers
.map((user) => ({
sid: user.userId,
destTel: getDetailValue(user.userDetail, ["userTel"]),
destNm: user.userName || user.userId,
msgParam: {
.map((user) => {
const msgParam = Object.fromEntries(
Object.entries({
...buildUserMsgParam(user),
...addParams,
},
}))
}).filter(([key]) => !denyParamKeySet.has(key))
);
return {
sid: user.userId,
destTel: getDetailValue(user.userDetail, "userTel"),
destNm: user.userName || user.userId,
msgParam,
};
})
.filter((item) => item.destTel);
}, [selectedUsers, addParams]);
}, [selectedUsers, addParams, denyParamKeySet]);
const msgParamKeys = useMemo(() => {
return Array.from(
new Set(destinations.flatMap((destination) => Object.keys(destination.msgParam)))
);
}, [destinations]);
useEffect(() => {
if (!open) return;
setActiveTemplateIdx(templateIdx);
setActiveTemplateIdx(defaultTemplateIdx);
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
}, [open, templateIdx]);
}, [defaultTemplateIdx, open]);
useEffect(() => {
if (!open || !templateQuery.data) return;
if (!open || !activeTemplate) return;
setDraft(toDraft(templateQuery.data, isNewMessage));
setDraft(toDraft(activeTemplate, isNewMessage));
setIsEditing(false);
}, [isNewMessage, open, templateQuery.data]);
}, [activeTemplate, isNewMessage, open]);
const updateDraft = <K extends keyof TemplateDraft>(key: K, value: TemplateDraft[K]) => {
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
};
const insertMsgParam = (key: string) => {
if (!draft || !canEdit || isBusy) return;
const token = `#{${key}}`;
const textarea = bodyTextareaRef.current;
const body = draft.tmplatBody;
const selectionStart = textarea?.selectionStart ?? body.length;
const selectionEnd = textarea?.selectionEnd ?? selectionStart;
const nextBody = `${body.slice(0, selectionStart)}${token}${body.slice(selectionEnd)}`;
const nextCursor = selectionStart + token.length;
updateDraft("tmplatBody", nextBody);
requestAnimationFrame(() => {
textarea?.focus();
textarea?.setSelectionRange(nextCursor, nextCursor);
});
};
const saveTemplate = async () => {
if (!draft) return null;
const payload: SaveTemplateRequest = {
tmplatIdx: draft.tmplatIdx,
tmplatPurpose: draft.tmplatPurpose,
tmplatNm: draft.tmplatNm,
tmplatTitle: draft.tmplatTitle,
tmplatBody: draft.tmplatBody,
@@ -122,6 +179,20 @@ export function SmsSendDialog({
return saved;
};
const cancelEdit = () => {
if (activeTemplate) {
setDraft(toDraft(activeTemplate, isNewMessage));
}
setIsEditing(false);
};
const changeTemplate = (value: string) => {
setActiveTemplateIdx(Number(value));
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
};
const switchToNewMessage = () => {
if (!newMessageTemplateIdx) return;
@@ -132,12 +203,14 @@ export function SmsSendDialog({
};
const restoreTemplate = () => {
setActiveTemplateIdx(templateIdx);
setActiveTemplateIdx(defaultTemplateIdx);
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
};
const isSmsOrLms = draft ? isPhoneVerificationSupported(draft) : false;
const send = async () => {
if (!draft) return;
@@ -181,14 +254,11 @@ export function SmsSendDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
<DialogHeader>
<DialogContent showCloseButton={false} className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
<DialogHeader className="flex-row flex-wrap items-center justify-between gap-3 space-y-0">
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 p-3">
<div className="text-sm text-muted-foreground">
<div className="flex flex-wrap items-center gap-2">
<div className="text-sm text-muted-foreground whitespace-nowrap">
선택 인원: <span className="font-semibold text-foreground">{selectedUsers.length}</span>명
{destinations.length !== selectedUsers.length && (
<span className="ml-2 text-destructive">발송 가능 {destinations.length}명</span>
@@ -206,9 +276,17 @@ export function SmsSendDialog({
</Button>
)
)}
<DialogClose asChild>
<Button type="button" size="icon" variant="ghost" className="h-8 w-8 shrink-0">
<X className="h-4 w-4" />
<span className="sr-only">닫기</span>
</Button>
</DialogClose>
</div>
</DialogHeader>
{templateQuery.isLoading && (
<div className="min-h-0 flex-1 space-y-4 pr-1">
{(templatesQuery.isLoading || newMessageTemplateQuery.isLoading) && (
<div className="rounded-md border p-4 text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</div>
)}
@@ -217,7 +295,28 @@ export function SmsSendDialog({
<div className="grid gap-3 md:grid-cols-2">
<label className="space-y-1 text-sm">
<span className="font-medium">템플릿명</span>
<Input value={draft.tmplatNm} disabled />
<Select
value={String(activeTemplateIdx)}
onValueChange={changeTemplate}
disabled={isBusy || isEditing || isNewMessage || templateIdxList.length <= 1}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="템플릿 선택" />
</SelectTrigger>
<SelectContent>
{isNewMessage && draft && (
<SelectItem value={String(draft.tmplatIdx)}>
{toText(draft.tmplatNm) || `${draft.tmplatIdx}`}
</SelectItem>
)}
{templatesQuery.data.map((template) => (
<SelectItem key={template.tmplatIdx} value={String(template.tmplatIdx)}>
{toText(template.tmplatNm) || `${template.tmplatIdx}`}
{template.tmplatPurpose === TMPLAT_PURPOSE.PHONE_VERIFICATION && " (인증)"}
</SelectItem>
))}
</SelectContent>
</Select>
</label>
<label className="space-y-1 text-sm">
<span className="font-medium">발신번호</span>
@@ -228,15 +327,55 @@ export function SmsSendDialog({
<span className="font-medium">제목</span>
<Input value={draft.tmplatTitle} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("tmplatTitle", event.target.value)} />
</label>
{isSmsOrLms && (
<label className="space-y-1 text-sm">
<span className="font-medium">템플릿 용도</span>
<Select
value={String(draft.tmplatPurpose)}
onValueChange={(value) => updateDraft("tmplatPurpose", Number(value))}
disabled={!canEdit || isBusy}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={String(TMPLAT_PURPOSE.NORMAL)}>일반</SelectItem>
<SelectItem value={String(TMPLAT_PURPOSE.PHONE_VERIFICATION)}>휴대전화번호 인증</SelectItem>
</SelectContent>
</Select>
</label>
)}
<label className="space-y-1 text-sm">
<span className="font-medium">내용</span>
<textarea
ref={bodyTextareaRef}
value={draft.tmplatBody}
disabled={!canEdit || isBusy}
onChange={(event) => updateDraft("tmplatBody", event.target.value)}
className="min-h-56 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70"
className="min-h-80 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70"
/>
</label>
{msgParamKeys.length > 0 && (
<div className="space-y-1 text-sm">
<div className="font-medium text-muted-foreground">사용 가능 변수값</div>
<div className="max-h-36 overflow-y-auto rounded-md border bg-muted/20 p-2">
<div className="flex flex-wrap gap-1.5">
{msgParamKeys.map((key) => (
<Button
key={key}
type="button"
className="h-auto flex-col items-start gap-0 rounded bg-muted px-2 py-1 text-center text-xs text-foreground hover:bg-muted/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={!canEdit || isBusy}
onClick={() => insertMsgParam(key)}
>
<span className="text-center">{getSmsParamLabel(key)}</span>
<code className="font-mono text-muted-foreground">{`#{${key}}`}</code>
</Button>
))}
</div>
</div>
</div>
)}
</div>
)}
</div>
@@ -249,10 +388,16 @@ export function SmsSendDialog({
</Button>
)}
{!isNewMessage && draft && isEditing && (
<>
<Button type="button" variant="outline" onClick={saveTemplate} disabled={isBusy}>
<Save className="h-4 w-4" />
저장
</Button>
<Button type="button" variant="outline" onClick={cancelEdit} disabled={isBusy}>
<RotateCcw className="h-4 w-4" />
취소
</Button>
</>
)}
<Button type="button" disabled={!draft || isBusy || isEditing || selectedUsers.length === 0} onClick={send}>
<Send className="h-4 w-4" />

View File

@@ -10,6 +10,7 @@ export function FilterSelect({
placeholder,
className,
useClear = true,
clearLabel = "전체",
}: {
value: string;
onChange: (value: string) => void;
@@ -17,6 +18,7 @@ export function FilterSelect({
placeholder: string;
className?: string;
useClear?: boolean;
clearLabel?: string;
}) {
return (
<KriSingleSelect
@@ -27,7 +29,7 @@ export function FilterSelect({
getValue={(item) => String(item.codeValue)}
getLabel={(item) => item.codeLabel}
useClear={useClear}
clearLabel="전체"
clearLabel={clearLabel}
widthClassName={className}
spanClassName="text-sm"
badgeClassName="text-sm"

View File

@@ -48,9 +48,9 @@ const MainLayout = ({ children }: MainLayoutProps) => {
/>
{/* 본문 */}
<div className="flex flex-1 min-h-0">
<div className="flex min-h-0 min-w-0 flex-1">
{/* 메인 콘텐츠만 가변 높이 적용 */}
<main className="flex-1 p-4">
<main className="min-w-0 max-w-full flex-1 overflow-x-hidden p-4">
{children}
</main>
</div>

View File

@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
export function useDebouncedValue<T>(value: T, delayMs = 1200) {
export function useDebouncedValue<T>(value: T, delayMs = 500) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {

View File

@@ -0,0 +1,56 @@
export const USER_FIELD_LABELS = {
userId: "ID",
userName: "이름",
userCmpn: "소속",
userTeam: "팀",
userRole: "권한",
memo: "메모",
userArea: "지역",
gender: "성별",
userGender: "성별",
userAge: "연령",
userTel: "연락처",
userEmail: "이메일",
userHasCar: "자차 여부",
userGenre: "장르",
} as const;
export const PERFORMANCE_FIELD_LABELS = {
no: "No.",
id: "연번",
NCAS: "관리번호",
monitoringAdd: "분류",
businessType: "사업유형",
performanceGenre: "분야(장르)",
performanceArea: "지역",
performanceAreaDetail: "지역 세부",
artistName: "단체(인)명",
performanceName: "사업명",
performanceStartMonth: "사업 수행 월",
performanceDtInfo: "사업 일정",
performanceTimeInfo: "운영 시간",
ticketReservationStatus: "티켓 예약",
ticketReservationMemo: "티켓 비고",
performanceMemo: "메모",
monitoringDate: "모니터링 일정",
monitoringTimeInfo: "모니터링 시간",
needMonitoring: "모니터링 필요여부",
needWrittenReview: "서면평가 필요여부",
checkDeliver: "교부여부",
timeTreeCheckDt: "타임트리 확인일시",
monitoringAddress: "방문 장소",
checkReport: "보고서 확인여부",
UpdateNoticeTarget: "변경 사항",
UpdateNoticeMemo: "변경 내용",
UpdateNoticeDt: "변경 일시",
performanceId: "사업 ID",
monitoringPaymentDate: "요원 비용지급일",
} as const;
export const SMS_PARAM_LABELS = {
...USER_FIELD_LABELS,
...PERFORMANCE_FIELD_LABELS,
} as const;
export const getSmsParamLabel = (key: string) =>
SMS_PARAM_LABELS[key as keyof typeof SMS_PARAM_LABELS] ?? key;

View File

@@ -1,11 +1,47 @@
import {downloadFile} from "@/lib/utils";
import {buildWrittenReviewLink} from "@/config/gwcf.config";
import {PDF_CONVERT_STATUS, PdfConvertStatus} from "@/types/gwcf";
const REVIEW_TIMESTAMP_PREFIX = /^\d{4}-\d{2}-\d{2}_\d{6}_/;
export const removeTimestampPrefix = (fileName?: string) =>
fileName?.replace(REVIEW_TIMESTAMP_PREFIX, "");
const trimDispositionValue = (value: string) => value.trim().replace(/^"|"$/g, "");
const decodeDispositionValue = (value: string) => {
const trimmed = trimDispositionValue(value);
const encodedValue = trimmed.includes("''") ? trimmed.split("''").slice(1).join("''") : trimmed;
try {
return decodeURIComponent(encodedValue);
} catch {
return encodedValue;
}
};
const getDispositionParams = (contentDisposition: string) =>
contentDisposition
.split(";")
.slice(1)
.map((part) => part.trim())
.reduce<Record<string, string>>((params, part) => {
const separatorIndex = part.indexOf("=");
if (separatorIndex < 0) return params;
const key = part.slice(0, separatorIndex).trim().toLowerCase();
const value = part.slice(separatorIndex + 1).trim();
if (key && value) params[key] = value;
return params;
}, {});
export const getFileNameFromContentDisposition = (contentDisposition?: string | null) => {
if (!contentDisposition) return undefined;
const params = getDispositionParams(contentDisposition);
const fileName = params["filename*"] || params.filename;
return fileName ? decodeDispositionValue(fileName) : undefined;
};
export const downloadBlob = (
buffer: ArrayBuffer,
fileName: string,
@@ -39,6 +75,27 @@ export const getReviewPdfDownloadName = (
pdfFileName?: string
) => removeTimestampPrefix(pdfFileName) || `review-pdf-${performanceId}-${reviewType}.pdf`;
export const getReviewPdfDisabled = (
userId: string | undefined,
pdfFileName?: string,
pdfConvert?: PdfConvertStatus
) => !userId || !pdfFileName || pdfConvert !== PDF_CONVERT_STATUS.COMPLETED;
export const getReviewPdfStatusLabel = (
pdfConvert?: PdfConvertStatus
) => {
switch (pdfConvert) {
case PDF_CONVERT_STATUS.COMPLETED:
return "PDF";
case PDF_CONVERT_STATUS.FAILED:
case PDF_CONVERT_STATUS.NOT_TARGET:
return "변환 실패";
case PDF_CONVERT_STATUS.IN_PROGRESS:
default:
return "변환 중";
}
}
export const getEvidenceZipDownloadName = (performanceId: number, userId: string) =>
`도착 증빙_${performanceId}_${userId}.zip`;
@@ -49,7 +106,16 @@ export const buildReviewPdfPreviewUrl = (
title?: string
) => {
const src = `/api/review/pdf/${performanceId}/${reviewType}/${encodeURIComponent(userId)}?disposition=inline`;
return `/file-preview?type=pdf&src=${encodeURIComponent(src)}&title=${encodeURIComponent(title || getReviewPdfDownloadName(performanceId, reviewType))}`;
return `/file-preview?type=pdf&src=${encodeURIComponent(src)}${title ? `&title=${encodeURIComponent(title)}` : ""}`;
};
export const buildReviewTemplatePdfPreviewUrl = (
reviewType: number,
classification: number,
title?: string
) => {
const src = `/api/review/template/pdf/${reviewType}/${classification}?disposition=inline`;
return `/file-preview?type=pdf&src=${encodeURIComponent(src)}${title ? `&title=${encodeURIComponent(title)}` : ""}`;
};
export const buildEvidenceImageSrc = (

View File

@@ -1,4 +1,18 @@
import {PerformanceFull, UserCompact} from "@/types/gwcf";
import {TMPLAT_PURPOSE, Template} from "@/types/notification";
export const PHONE_VERIFICATION_PREVIEW = "인증번호는 [######] 입니다.";
export const isPhoneVerificationSupported = (template: Pick<Template, "tmplatTy">) =>
template.tmplatTy === 10 || template.tmplatTy === 20;
export const buildTemplatePreviewBody = (template: Pick<Template, "tmplatBody" | "tmplatPurpose">) =>
template.tmplatPurpose === TMPLAT_PURPOSE.PHONE_VERIFICATION
? `${template.tmplatBody}\n${PHONE_VERIFICATION_PREVIEW}`
: template.tmplatBody;
export const getSmsByteLength = (value: string) =>
Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 0x7f ? 2 : 1), 0);
export const toNotificationParamValue = (value: unknown) => value == null ? "" : String(value);

View File

@@ -1,5 +1,6 @@
import {Code, PerformanceAssign, PerformanceFull, PerformanceMonitoringVisit, PerformanceReview, UserCompact} from "@/types/gwcf";
import type {StatusPillVariant} from "@/components/gwcf/StatusPill";
import {ASSIGN_STATUS, AssignStatus} from "@/types/gwcf";
export const LOCAL_GOVERNMENT_REVIEW_TYPE = 3;
export const MONITORING_ASSIGN_TYPE = 1;
@@ -49,6 +50,22 @@ export const STATUS_FILTER = {
DONE: "-1007",
} as const;
export const isAssignRequested = (assign?: Pick<PerformanceAssign, "assignStatus">) => {
return assign?.assignStatus === ASSIGN_STATUS.REQUESTED;
};
export const isAssignConfirmed = (assign?: Pick<PerformanceAssign, "assignStatus">) => {
return assign?.assignStatus === ASSIGN_STATUS.CONFIRMED;
};
export const isAssignRejected = (assign?: Pick<PerformanceAssign, "assignStatus">) => {
return assign?.assignStatus === ASSIGN_STATUS.REJECTED;
};
export const isNotAssignRejected = (assign?: Pick<PerformanceAssign, "assignStatus">) => {
return assign?.assignStatus !== ASSIGN_STATUS.REJECTED;
};
export const makeStatusOption = (value: string, label: string): Code => ({
codeGroup: "status_filter",
codeValue: Number(value),
@@ -94,7 +111,7 @@ const getMonitoringTimeline = (visits: PerformanceMonitoringVisit[]): Monitoring
export const getMonitoringSlots = (performance: Partial<PerformanceFull>): [MonitoringSlot, MonitoringSlot] => {
const confirmedAssigns = (performance.performanceAssignList ?? [])
.filter((assign) => assign.assignType === MONITORING_ASSIGN_TYPE && assign.assignConfirm)
.filter((assign) => assign.assignType === MONITORING_ASSIGN_TYPE && isAssignConfirmed(assign))
.sort((a, b) => a.assignOrder - b.assignOrder || a.id - b.id);
const visits = performance.performanceMonitoringVisitMap ?? {};
@@ -125,7 +142,6 @@ export const getReviewRows = (performance: Partial<PerformanceFull>) => {
export const getMonitoringReviewByIndex = (
performance: Partial<PerformanceFull>,
index: 0 | 1,
slot?: MonitoringSlot
) => {
const assignedUserId = slot?.assign?.assignUser;
@@ -140,10 +156,11 @@ export const getMonitoringReviewByIndex = (
export const getMonitoringDisplayRow = (
performance: Partial<PerformanceFull>,
index: 0 | 1
index: 0 | 1,
isWrittenReviewer: boolean = false
): MonitoringDisplayRow => {
const slot = getMonitoringSlots(performance)[index];
const reviewRow = getMonitoringReviewByIndex(performance, index, slot);
const reviewRow = getMonitoringReviewByIndex(performance, slot);
const visit = slot.visit?.[0];
return {
@@ -310,8 +327,8 @@ export const getMonitoringDisplayStatus = (
return getMonitoringStatusDisplay(visitLabel, row.slot);
};
export const getAssignStatusDisplay = (confirmed: boolean): StatusDisplay => {
return confirmed
? {label: "확정", variant: "done"}
: {label: "요청", variant: "inprogress"};
export const getAssignStatusDisplay = (status: AssignStatus): StatusDisplay => {
if (status === ASSIGN_STATUS.CONFIRMED) return {label: "확정", variant: "done"};
if (status === ASSIGN_STATUS.REJECTED) return {label: "포기", variant: "danger"};
return {label: "요청", variant: "inprogress"};
};

View File

@@ -16,6 +16,7 @@ export const getRoleGroup = (role?: number | null) => {
return Math.floor(role / 1000) * 1000;
};
export const isResearcherRole = (role?: number | null) => !role ? false : role <= ROLE.RESEARCHER;
export const isInternalRole = (role?: number | null) => getRoleGroup(role) === 1000;
export const isExternalRole = (role?: number | null) => getRoleGroup(role) === 2000;
export const isMonitoringRole = (role?: number | null) => getRoleGroup(role) === 9000;
@@ -35,14 +36,12 @@ export const getCodeLabel = (
export const getDetailValue = (
detail: Record<string, string> | undefined,
keys: string[],
key: string,
fallback = ""
) => {
if (!detail) return fallback;
for (const key of keys) {
const value = detail[key];
if (value !== undefined && value !== "") return value;
}
return fallback;
};
@@ -92,9 +91,9 @@ export const filterUser = (
}
) => {
const detail = user.userDetail ?? {};
const area = getDetailValue(detail, ["area", "userArea", "region"]);
const gender = getDetailValue(detail, ["gender", "userGender"]);
const genre = getDetailValue(detail, ["genre", "performanceGenre", "reviewGenre"]);
const area = getDetailValue(detail, "userArea");
const gender = getDetailValue(detail, "userGender");
const genre = getDetailValue(detail, "userGenre");
const keyword = filters.keyword?.trim() ?? "";
const matches = (filter: string | string[] | undefined, value: string) => {
if (!filter || filter.length === 0) return true;
@@ -112,8 +111,8 @@ export const filterUser = (
includesText(user.userTeam, keyword) ||
includesText(user.userCmpn, keyword) ||
includesText(user.memo, keyword) ||
includesText(getDetailValue(detail, ["tel", "phone", "userTel"]), keyword) ||
includesText(getDetailValue(detail, ["email", "userEmail"]), keyword)
includesText(getDetailValue(detail, "userTel"), keyword) ||
includesText(getDetailValue(detail, "userEmail"), keyword)
)
);
};

View File

@@ -119,7 +119,7 @@ const getErrorMessage = (data: unknown) => {
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
const {
getToken,
defaultTimeoutMs = 60_000,
defaultTimeoutMs = 300_000,
defaultHeaders = { "content-type": "application/json" },
setErrorMessage,
} = opts;
@@ -305,7 +305,10 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
const putForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", form });
return { request, get, post, put, patch, del, postForm, putForm };
const patchForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PATCH", form });
return { request, get, post, put, patch, del, postForm, putForm, patchForm };
};
export const nextApi = createHttpClient(clientEnv.API_BASE);

View File

@@ -91,19 +91,6 @@ export function useAssignCancelMutation() {
});
}
export function useKonAssignConfirmMutation() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
nextApi.post<string>(`/assign/confirm/${performanceId}/${encodeURIComponent(userId)}`),
onSuccess: (_res, {performanceId, userId}) => {
qc.invalidateQueries({ queryKey: qk.assignConfirm(performanceId, userId) });
qc.invalidateQueries({ queryKey: ["performance", "list"] });
},
});
}
export function useUploadWrittenAssignExcelMutation() {
const qc = useQueryClient();

View File

@@ -27,7 +27,7 @@ export const useLogoutMutation = () => {
const userId = auth.user?.userId ?? "";
try {
if (userId){
await nextApi.post(`/logout/${userId}`, null, { autoLogoutOnAuthError: false });
await nextApi.post(`/logout/${userId}`, null, { autoLogoutOnAuthError: false, suppressAlert: true });
}
} catch (e) {
console.error(e);

View File

@@ -17,6 +17,7 @@ export const CODE_GROUPS = [
"review_type",
"staff_type",
"ticket_reservation_status",
"update_notice_target",
"user_role",
] as const;

View File

@@ -56,3 +56,17 @@ export function useDownloadEvidenceZipMutation() {
),
});
}
export function useResetMonitoringVisitMutation() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
nextApi.del<void>(`/monitoring/visit/reset/${performanceId}/${encodeURIComponent(userId)}`),
onSuccess: (_res, {performanceId, userId}) => {
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
qc.invalidateQueries({ queryKey: qk.performanceList() });
qc.invalidateQueries({ queryKey: qk.monitoringEvidence(performanceId, userId) });
},
});
}

View File

@@ -1,13 +1,15 @@
"use client";
import {useMutation, useQuery} from "@tanstack/react-query";
import {useMutation, useQueries, useQuery} from "@tanstack/react-query";
import {nextApi} from "@/lib/http-client";
import {BulkSendResponse, SaveTemplateRequest, SendSmsBulkRequest, Template} from "@/types/notification";
import {BulkSendResponse, CreateTemplateRequest, SaveTemplateRequest, SendSmsBulkRequest, Template, TemplateListItem} from "@/types/notification";
export const SMS_TEMPLATE_IDS = {
ACCOUNT_MONITORING: 45,
ASSIGN_CONFIRM: 46,
CUSTOM: 47,
INFORM_ASSIGN: 48,
REMIND_ASSIGN: 49,
} as const;
export const NOTIFICATION_REQUEST_SERVICE = "gwcf-review";
@@ -20,10 +22,54 @@ export function useNotificationTemplateQuery(templateIdx: number, enabled = true
});
}
export function useNotificationTemplatesQuery(templateIdxList: number[], enabled = true) {
return useQueries({
queries: templateIdxList.map((templateIdx) => ({
queryKey: ["notification", "template", templateIdx],
queryFn: () => nextApi.get<Template>(`/notification/template/${templateIdx}`),
enabled: enabled && templateIdx > 0,
})),
combine: (results) => ({
data: results.flatMap((result) => result.data ? [result.data] : []),
isLoading: results.some((result) => result.isLoading),
isError: results.some((result) => result.isError),
}),
});
}
export function useNotificationTemplateListQuery(chnnlTy: number, itrntPrjctCd: string, enabled = true) {
return useQuery({
queryKey: ["notification", "template-list", chnnlTy, itrntPrjctCd],
queryFn: () => nextApi.get<TemplateListItem[]>(`/notification/template/list/${encodeURIComponent(chnnlTy)}/${encodeURIComponent(itrntPrjctCd)}`),
enabled: enabled && Boolean(itrntPrjctCd),
});
}
export function useCreateNotificationTemplateMutation() {
return useMutation({
mutationFn: (data: CreateTemplateRequest) => {
const formData = new FormData();
formData.append(
"template",
new Blob([JSON.stringify(data)], {type: "application/json"})
);
return nextApi.putForm<Template>("/notification/template", formData);
},
});
}
export function useSaveNotificationTemplateMutation() {
return useMutation({
mutationFn: (data: SaveTemplateRequest) =>
nextApi.patch<Template>("/notification/template", data),
mutationFn: (data: SaveTemplateRequest) => {
const formData = new FormData();
formData.append(
"template",
new Blob([JSON.stringify(data)], {type: "application/json"})
);
return nextApi.patchForm<Template>("/notification/template", formData);
},
});
}

View File

@@ -19,10 +19,24 @@ export function useUploadReviewFileMutation() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({performanceId, reviewType, file}: {performanceId: number; reviewType: number; file: File}) => {
mutationFn: ({
performanceId,
reviewType,
file,
paramUserId,
}: {
performanceId: number;
reviewType: number;
file: File;
paramUserId?: string;
}) => {
const formData = new FormData();
formData.append("file", file, file.name);
return nextApi.postForm<PerformanceReview>(`/review/${performanceId}/${reviewType}`, formData);
return nextApi.postForm<PerformanceReview>(
`/review/${performanceId}/${reviewType}`,
formData,
{query: paramUserId ? {paramUserId} : undefined}
);
},
onSuccess: (_res, {performanceId, reviewType}) => {
qc.invalidateQueries({ queryKey: ["review", performanceId, reviewType] });
@@ -39,6 +53,13 @@ export function useDownloadReviewOriginalMutation() {
});
}
export function useDownloadReviewOriginalByPerformanceMutation() {
return useMutation({
mutationFn: ({performanceId, reviewType}: {performanceId: number; reviewType: number}) =>
nextApi.get<ArrayBuffer>(`/review/download/${performanceId}/${reviewType}`, {expectBinary: true}),
});
}
export function useDownloadReviewPdfMutation() {
return useMutation({
mutationFn: ({performanceId, reviewType, userId}: {performanceId: number; reviewType: number; userId: string}) =>

View File

@@ -26,13 +26,21 @@ export type Code = {
memo: string;
};
export const ASSIGN_STATUS = {
REQUESTED: 0,
CONFIRMED: 1,
REJECTED: 9,
} as const;
export type AssignStatus = typeof ASSIGN_STATUS[keyof typeof ASSIGN_STATUS];
export type PerformanceAssign = {
id: number;
performanceId: number;
assignType: number;
assignOrder: number;
assignUser: string;
assignConfirm: boolean;
assignStatus: AssignStatus;
};
export type MonitoringApplyUser = {
@@ -91,7 +99,7 @@ export type PerformanceFull = PerformanceBase & {
export type PerformanceMonitoringSchedule = {
id: number;
performanceId: number;
monitoringDate: string;
monitoringDate: string | null;
monitoringTimeInfo: string;
monitoringAddress: string;
};
@@ -109,6 +117,15 @@ export type PerformanceMonitoringVisit = {
gpsRaw: Record<string, unknown>;
};
export const PDF_CONVERT_STATUS = {
IN_PROGRESS: 0,
COMPLETED: 1,
NOT_TARGET: 8,
FAILED: 9,
} as const;
export type PdfConvertStatus = typeof PDF_CONVERT_STATUS[keyof typeof PDF_CONVERT_STATUS];
export type PerformanceReview = {
performanceId: number;
reviewType: number;
@@ -116,7 +133,7 @@ export type PerformanceReview = {
reviewDt: string;
reviewStatus: number;
uploadFileName: string;
pdfConvert: boolean;
pdfConvert: PdfConvertStatus;
pdfFileName: string;
};

View File

@@ -1,6 +1,7 @@
export type Template = {
itrntPrjctCd: string;
tmplatTy: number;
tmplatPurpose: number;
tmplatNm: string;
tmplatTitle: string;
tmplatBody: string;
@@ -15,6 +16,18 @@ export type Template = {
tmplatIdx: number;
};
export const TMPLAT_PURPOSE = {
NORMAL: 0,
PHONE_VERIFICATION: 1,
} as const;
export type TemplatePurpose = (typeof TMPLAT_PURPOSE)[keyof typeof TMPLAT_PURPOSE];
export type CreateTemplateRequest = Pick<
Template,
"itrntPrjctCd" | "tmplatTy" | "tmplatPurpose" | "tmplatNm" | "tmplatBody" | "sendTel" | "sendNm"
>;
export type SmsDestination = {
sid?: string;
destTel: string;
@@ -22,7 +35,9 @@ export type SmsDestination = {
msgParam?: Record<string, string>;
};
export type SaveTemplateRequest = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
export type SaveTemplateRequest = Pick<Template, "tmplatIdx" | "tmplatPurpose" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
export type TemplateListItem = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatPurpose">;
export type SendSmsBulkRequest = {
templateIdx: number;