Compare commits
127 Commits
39ab7996d9
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 904bbd6509 | |||
| 88b36bf27d | |||
| 359969c13f | |||
| 02a830f3ee | |||
| 27e41c783b | |||
| db1f12f9aa | |||
| f955dbaeea | |||
| 623615a287 | |||
| e64a48417b | |||
| 606b6e30d0 | |||
| 4daf2daf9c | |||
| 2d00f7e490 | |||
| d9c76d6d9c | |||
| 88233f3a39 | |||
| d595ea8b8c | |||
| 986f9bf9a9 | |||
| dd4fc8f230 | |||
| 7f9cbe4f09 | |||
| d91fc8f5a8 | |||
| 491b5a5e9f | |||
| 72c8cdca37 | |||
| ff9968db2e | |||
| bfde326316 | |||
| 5a82fe6396 | |||
| 475204b12b | |||
| d17b7316e7 | |||
| 273caf267d | |||
| 50a0cb1ef5 | |||
| 07e70d1f44 | |||
| e67d57c51a | |||
| 98546a83fd | |||
| 55c988ce20 | |||
| 61ac9420c9 | |||
| 362aca6dbf | |||
| 4fd52bf8fc | |||
| 27b4902a7c | |||
| 5a2f30c8b0 | |||
| 47973ed82d | |||
| 19a5d8b606 | |||
| 6c0722f2e5 | |||
| 3b552f38cf | |||
| 3c27a1fa46 | |||
| 2adbba779a | |||
| c2c2eed3b4 | |||
| fd4ddb5797 | |||
| 38ce40c360 | |||
| 17ad56939c | |||
| f65dacdec1 | |||
| 061ef782bc | |||
| bbaedfc325 | |||
| b087d9527e | |||
| 191c0017a8 | |||
| d2e214696d | |||
| 8f0de91e93 | |||
| 361c065ec9 | |||
| eb44c57d39 | |||
| d4db99337a | |||
| d2e826702e | |||
| 3d58ffc1b4 | |||
| 4e51530922 | |||
| 044579c27f | |||
| bb641464e2 | |||
| ae8f2e6fc5 | |||
| 831f1fac6b | |||
| 81dd5165f3 | |||
| 59c9238632 | |||
| dce71d6448 | |||
| 3ce503da18 | |||
| c13d5e3d79 | |||
| ea81777a24 | |||
| 45d7622961 | |||
| 264707ac56 | |||
| f76415f236 | |||
| f12c374a84 | |||
| b6dc4e9d6c | |||
| d088661719 | |||
| cf208b7f38 | |||
| 746f709e92 | |||
| c4639d6ca2 | |||
| b86ab58767 | |||
| 825cf5f35f | |||
| 11f7ec1719 | |||
| 35bcc1615c | |||
| e8ddcdb88d | |||
| be86e2a618 | |||
| c92c984def | |||
| 03a291c0f9 | |||
| 057f610704 | |||
| 8802f9d22a | |||
| c5e2a3a6db | |||
| ff7791b76d | |||
| 96d9b3baf8 | |||
| afcb15bc98 | |||
| 3181535e16 | |||
| 10a4bc9ab3 | |||
| c4d1a6c998 | |||
| 1e5d27afe2 | |||
| 38672c262d | |||
| 2464f6b443 | |||
| 2ad807b3f9 | |||
| b543d66186 | |||
| effe279be9 | |||
| c2f6da0dd5 | |||
| 73228a2573 | |||
| cb7b000b08 | |||
| 5e7199087d | |||
| 642b0a559f | |||
| 3337119459 | |||
| 47acc5b4b3 | |||
| 5c9ed53b3b | |||
| 7bfb1ca987 | |||
| 0fbec01f73 | |||
| b6ed23fa88 | |||
| 050c4ccc6e | |||
| b36893610f | |||
| 4b3100b09c | |||
| a48ec34114 | |||
| fbb61780ff | |||
| d8292b8158 | |||
| c324617879 | |||
| bbc035c778 | |||
| a603f6ad6f | |||
| de73dbd8db | |||
| be67eed7e4 | |||
| d674db2232 | |||
| 8cd0f5bd53 | |||
| e9bb02820c |
@@ -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.
|
||||||
@@ -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.
|
||||||
13
.agent-harness/references/kri-front-common/react-compiler.md
Normal file
13
.agent-harness/references/kri-front-common/react-compiler.md
Normal 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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -1,28 +1,18 @@
|
|||||||
## KriContact Front Repository Rules
|
# KriContact Front Project Instruction Router
|
||||||
|
|
||||||
### Product Purpose and Current Phase
|
## Required Project References
|
||||||
|
|
||||||
- This is the launched Next.js frontend for KRI contact operations. Preserve first-release behavior while planning and delivering approved follow-up features.
|
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
|
||||||
- The primary workflows include project and contact-list management, interviewer and list assignment, call/contact and event history, survey/contact/interview/message progress, SMS and email templates, result codes, users, companies, and roles.
|
|
||||||
- Prefer product-purpose clarity, workflow consistency, and backward compatibility over broad technical cleanup.
|
|
||||||
|
|
||||||
### Domain and Integration Boundaries
|
| Task scope | Required reference |
|
||||||
|
|---|---|
|
||||||
|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
|
||||||
|
|
||||||
- Preserve the selected project context and company, project, role, and user access boundaries across navigation, queries, dialogs, and mutations.
|
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
|
||||||
- Treat list headers/items, assignment state, contact history, call state, progress metrics, result codes, templates, uploaded files, and exported files as coordinated API contracts with contact-server.
|
|
||||||
- Keep server-only credentials and privileged integration logic out of client bundles. Preserve the established Next.js API proxy and server/client boundaries.
|
|
||||||
- Minimize exposure of names, telephone numbers, contact history, and uploaded list data in UI state, logs, errors, screenshots, and test fixtures.
|
|
||||||
- Do not send real SMS or email, initiate real calls, or invoke production integrations during development or validation.
|
|
||||||
|
|
||||||
### Frontend Implementation
|
## Harness Workflow
|
||||||
|
|
||||||
- Use the consumed KRI frontend common and UI registry contracts instead of copying shared utilities, components, or conventions locally.
|
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
|
||||||
- Prefer an existing shadcn/ui or approved registry component before creating a new foundational UI component. Compose or extend it locally only for project-specific behavior.
|
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
|
||||||
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`; use domain- or purpose-specific names.
|
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
|
||||||
- Preserve accessibility and loading, empty, error, disabled, confirmation, and success states for operational workflows.
|
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.
|
||||||
- Coordinate request, response, validation, authentication, and error-shape changes with contact-server without requiring an unsafe simultaneous deployment.
|
|
||||||
|
|
||||||
### Harness and Verification
|
|
||||||
|
|
||||||
- `AGENTS.md` and `CLAUDE.md` are generated. Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
|
|
||||||
- Use the repository's existing package manager and focused lint, type-check, test, or build commands. Validation must not call real business integrations.
|
|
||||||
|
|||||||
28
.agent/references/repository-rules.md
Normal file
28
.agent/references/repository-rules.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
## KriContact Front Repository Rules
|
||||||
|
|
||||||
|
### Product Purpose and Current Phase
|
||||||
|
|
||||||
|
- This is the launched Next.js frontend for KRI contact operations. Preserve first-release behavior while planning and delivering approved follow-up features.
|
||||||
|
- The primary workflows include project and contact-list management, interviewer and list assignment, call/contact and event history, survey/contact/interview/message progress, SMS and email templates, result codes, users, companies, and roles.
|
||||||
|
- Prefer product-purpose clarity, workflow consistency, and backward compatibility over broad technical cleanup.
|
||||||
|
|
||||||
|
### Domain and Integration Boundaries
|
||||||
|
|
||||||
|
- Preserve the selected project context and company, project, role, and user access boundaries across navigation, queries, dialogs, and mutations.
|
||||||
|
- Treat list headers/items, assignment state, contact history, call state, progress metrics, result codes, templates, uploaded files, and exported files as coordinated API contracts with contact-server.
|
||||||
|
- Keep server-only credentials and privileged integration logic out of client bundles. Preserve the established Next.js API proxy and server/client boundaries.
|
||||||
|
- Minimize exposure of names, telephone numbers, contact history, and uploaded list data in UI state, logs, errors, screenshots, and test fixtures.
|
||||||
|
- Do not send real SMS or email, initiate real calls, or invoke production integrations during development or validation.
|
||||||
|
|
||||||
|
### Frontend Implementation
|
||||||
|
|
||||||
|
- Use the consumed KRI frontend common and UI registry contracts instead of copying shared utilities, components, or conventions locally.
|
||||||
|
- Prefer an existing shadcn/ui or approved registry component before creating a new foundational UI component. Compose or extend it locally only for project-specific behavior.
|
||||||
|
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`; use domain- or purpose-specific names.
|
||||||
|
- Preserve accessibility and loading, empty, error, disabled, confirmation, and success states for operational workflows.
|
||||||
|
- Coordinate request, response, validation, authentication, and error-shape changes with contact-server without requiring an unsafe simultaneous deployment.
|
||||||
|
|
||||||
|
### Harness and Verification
|
||||||
|
|
||||||
|
- `AGENTS.md` and `CLAUDE.md` are generated. Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
|
||||||
|
- Use the repository's existing package manager and focused lint, type-check, test, or build commands. Validation must not call real business integrations.
|
||||||
41
.agents/skills/attention-aware-communication/SKILL.md
Normal file
41
.agents/skills/attention-aware-communication/SKILL.md
Normal 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.
|
||||||
37
.agents/skills/karpathy-guidelines/SKILL.md
Normal file
37
.agents/skills/karpathy-guidelines/SKILL.md
Normal 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.
|
||||||
29
.agents/skills/project-reference-loader/SKILL.md
Normal file
29
.agents/skills/project-reference-loader/SKILL.md
Normal 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.
|
||||||
38
.agents/skills/verification-before-completion/SKILL.md
Normal file
38
.agents/skills/verification-before-completion/SKILL.md
Normal 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.
|
||||||
41
.claude/skills/attention-aware-communication/SKILL.md
Normal file
41
.claude/skills/attention-aware-communication/SKILL.md
Normal 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.
|
||||||
37
.claude/skills/karpathy-guidelines/SKILL.md
Normal file
37
.claude/skills/karpathy-guidelines/SKILL.md
Normal 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.
|
||||||
29
.claude/skills/project-reference-loader/SKILL.md
Normal file
29
.claude/skills/project-reference-loader/SKILL.md
Normal 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.
|
||||||
38
.claude/skills/verification-before-completion/SKILL.md
Normal file
38
.claude/skills/verification-before-completion/SKILL.md
Normal 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.
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
NEXT_PUBLIC_ENV=dev
|
NEXT_PUBLIC_ENV=dev
|
||||||
NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api
|
NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api
|
||||||
|
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
|
||||||
|
|
||||||
ENV=dev
|
ENV=dev
|
||||||
CONTACT_SERVER=http://127.0.0.1:4001
|
CONTACT_SERVER=http://127.0.0.1:4001
|
||||||
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
||||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
|
||||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
AUTH_COOKIE_DOMAIN=kric.com
|
||||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
NEXT_PUBLIC_ENV=local
|
NEXT_PUBLIC_ENV=local
|
||||||
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
||||||
|
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
|
||||||
|
|
||||||
ENV=local
|
ENV=local
|
||||||
CONTACT_SERVER=http://localhost:4001
|
CONTACT_SERVER=http://localhost:4001
|
||||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
|
||||||
#API_NOTIHUB_SERVER=http://localhost:4011/api/v1
|
|
||||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
AUTH_COOKIE_DOMAIN=
|
||||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
NEXT_PUBLIC_ENV=prod
|
NEXT_PUBLIC_ENV=prod
|
||||||
NEXT_PUBLIC_API_BASE=https://contact.kric.com/api
|
NEXT_PUBLIC_API_BASE=https://contact.kric.com/api
|
||||||
|
NEXT_PUBLIC_KART_URL=https://kart.kric.com
|
||||||
|
|
||||||
ENV=prod
|
ENV=prod
|
||||||
CONTACT_SERVER=http://127.0.0.1:4001
|
CONTACT_SERVER=http://127.0.0.1:4001
|
||||||
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
||||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
|
||||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
AUTH_COOKIE_DOMAIN=kric.com
|
||||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
|
||||||
|
|||||||
152
AGENTS.md
152
AGENTS.md
@@ -35,6 +35,13 @@ Later and more specific instructions may override earlier general instructions o
|
|||||||
- Lead with the result or decision, then provide only the detail needed to verify it.
|
- Lead with the result or decision, then provide only the detail needed to verify it.
|
||||||
- Do not create or retain a full session transcript.
|
- 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
|
## Work Authorization
|
||||||
|
|
||||||
- The default workflow is discussion first and explicit execution approval second.
|
- The default workflow is discussion first and explicit execution approval second.
|
||||||
@@ -152,6 +159,13 @@ Preferred human-facing tools:
|
|||||||
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
|
- 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.
|
- 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
|
## Validation
|
||||||
|
|
||||||
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
|
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
|
||||||
@@ -215,6 +229,7 @@ When implementation is complete, report in Korean:
|
|||||||
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
|
||||||
@@ -234,80 +249,109 @@ When implementation is complete, report in Korean:
|
|||||||
|
|
||||||
## KriFrontCommon Consumer Contract
|
## KriFrontCommon Consumer Contract
|
||||||
|
|
||||||
### Package Usage
|
- Consume the published `@kri/common` package only through entry points declared by its `package.json` `exports` map.
|
||||||
|
|
||||||
- Consume this contract through the published `@kri/common` package and only through entry points declared in its `package.json` `exports` map.
|
|
||||||
- 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.
|
|
||||||
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
|
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
|
||||||
- Do not copy or fork a shared utility locally merely to avoid using an available public entry point. Propose a backward-compatible library addition when the shared contract is genuinely missing.
|
- Prefer a public shared helper or an approved backward-compatible library addition over copying or forking shared behavior locally.
|
||||||
|
|
||||||
### Runtime and Optional Integrations
|
|
||||||
|
|
||||||
- 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.
|
|
||||||
|
|
||||||
### Change Safety
|
|
||||||
|
|
||||||
- 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.
|
|
||||||
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
||||||
|
|
||||||
## KriUiRegistry Consumer Contract
|
### Required Shared References
|
||||||
|
|
||||||
### UI Component Selection
|
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:
|
When implementing or changing frontend UI, use this order:
|
||||||
|
|
||||||
1. Reuse an existing shared component in the project when it already meets the requirement.
|
1. Reuse an existing shared component in the project when it already meets the requirement.
|
||||||
2. Prefer an approved component from KriUiRegistry.
|
2. Prefer an approved component from KriUiRegistry.
|
||||||
3. Otherwise, prefer a suitable shadcn/ui component.
|
3. Otherwise, prefer a suitable shadcn/ui component.
|
||||||
4. Create a new custom component only when the preceding options cannot meet the requirement without an unsafe or misleading adaptation.
|
4. Create a custom component only when the preceding options cannot meet the requirement safely.
|
||||||
|
|
||||||
### Installation and Ownership
|
### KriAutoComplete Search Scroll
|
||||||
|
|
||||||
- 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-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior.
|
||||||
- `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.
|
- 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.
|
||||||
- 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
|
### KriAutoComplete Option Tooltip
|
||||||
|
|
||||||
- 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.
|
- `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior.
|
||||||
- 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.
|
- 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`.
|
||||||
- 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.
|
|
||||||
|
|
||||||
## KriContact Front Repository Rules
|
### KriAutoComplete Search Match
|
||||||
|
|
||||||
### Product Purpose and Current Phase
|
- `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`.
|
||||||
|
|
||||||
- This is the launched Next.js frontend for KRI contact operations. Preserve first-release behavior while planning and delivering approved follow-up features.
|
### KriEditor SMS Preview
|
||||||
- The primary workflows include project and contact-list management, interviewer and list assignment, call/contact and event history, survey/contact/interview/message progress, SMS and email templates, result codes, users, companies, and roles.
|
|
||||||
- Prefer product-purpose clarity, workflow consistency, and backward compatibility over broad technical cleanup.
|
|
||||||
|
|
||||||
### Domain and Integration Boundaries
|
- `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.
|
||||||
|
|
||||||
- Preserve the selected project context and company, project, role, and user access boundaries across navigation, queries, dialogs, and mutations.
|
### Required Shared References
|
||||||
- Treat list headers/items, assignment state, contact history, call state, progress metrics, result codes, templates, uploaded files, and exported files as coordinated API contracts with contact-server.
|
|
||||||
- Keep server-only credentials and privileged integration logic out of client bundles. Preserve the established Next.js API proxy and server/client boundaries.
|
|
||||||
- Minimize exposure of names, telephone numbers, contact history, and uploaded list data in UI state, logs, errors, screenshots, and test fixtures.
|
|
||||||
- Do not send real SMS or email, initiate real calls, or invoke production integrations during development or validation.
|
|
||||||
|
|
||||||
### Frontend Implementation
|
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
||||||
|
|
||||||
- Use the consumed KRI frontend common and UI registry contracts instead of copying shared utilities, components, or conventions locally.
|
| Task scope | Required reference |
|
||||||
- Prefer an existing shadcn/ui or approved registry component before creating a new foundational UI component. Compose or extend it locally only for project-specific behavior.
|
|---|---|
|
||||||
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`; use domain- or purpose-specific names.
|
| Installing, upgrading, adapting, or verifying a registry component | `.agent-harness/references/kri-ui-registry/installation-and-adaptation.md` |
|
||||||
- Preserve accessibility and loading, empty, error, disabled, confirmation, and success states for operational workflows.
|
| KriEditor HTML, image-map, sanitizer, or WYSIWYG compatibility | `.agent-harness/references/kri-ui-registry/editor-html-compatibility.md` |
|
||||||
- Coordinate request, response, validation, authentication, and error-shape changes with contact-server without requiring an unsafe simultaneous deployment.
|
|
||||||
|
|
||||||
### Harness and Verification
|
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.
|
||||||
|
|
||||||
- `AGENTS.md` and `CLAUDE.md` are generated. Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
|
# KriContact Front Project Instruction Router
|
||||||
- Use the repository's existing package manager and focused lint, type-check, test, or build commands. Validation must not call real business integrations.
|
|
||||||
|
## 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.
|
||||||
|
|||||||
1285
package-lock.json
generated
1285
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@
|
|||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@kri/common": "^0.18.0",
|
"@kri/common": "^0.20.0",
|
||||||
"@radix-ui/react-checkbox": "^1.3.3",
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
@@ -42,13 +42,14 @@
|
|||||||
"@tiptap/starter-kit": "^3.12.0",
|
"@tiptap/starter-kit": "^3.12.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"cmdk": "^1.1.1",
|
"cmdk": "^1.1.1",
|
||||||
|
"cn": "0.5.2",
|
||||||
"date-fns": "^4.4.0",
|
"date-fns": "^4.4.0",
|
||||||
"dompurify": "^3.4.10",
|
"dompurify": "^3.4.10",
|
||||||
"echarts": "^6.1.0",
|
"echarts": "^6.1.0",
|
||||||
"echarts-for-react": "^3.0.6",
|
"echarts-for-react": "^3.0.6",
|
||||||
"jotai": "^2.15.1",
|
"jotai": "^2.15.1",
|
||||||
"lucide-react": "^0.553.0",
|
"lucide-react": "^0.553.0",
|
||||||
"next": "^16.0.7",
|
"next": "^16.4.6",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"prettier": "^3.9.6",
|
"prettier": "^3.9.6",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
@@ -61,13 +62,13 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@types/node": "^20",
|
"@types/node": "^24.19.2",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"babel-plugin-react-compiler": "1.0.0",
|
"babel-plugin-react-compiler": "1.0.0",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "^16.0.7",
|
"eslint-config-next": "^16.4.6",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { useAtom } from 'jotai'
|
||||||
|
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
|
||||||
import { useMounted } from '@kri/common/hooks'
|
import { useMounted } from '@kri/common/hooks'
|
||||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
@@ -13,7 +15,10 @@ import { AssignTargetList, useAssignTargetRows } from '@/components/assign/Assig
|
|||||||
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
||||||
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
||||||
import { useListHeaderQuery } from '@/query/list'
|
import { useListHeaderQuery } from '@/query/list'
|
||||||
import { useResetListAssignMutation, useUpsertListAssignMutation } from '@/query/assign'
|
import { ListJobPageQueryContext, useSubmitListJob } from '@/query/list-job'
|
||||||
|
import { ListJobGatePanel } from '@/components/list/ListJobGate'
|
||||||
|
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
|
||||||
|
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
|
||||||
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
|
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
|
||||||
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
||||||
import type { ResultCode } from '@/types/project'
|
import type { ResultCode } from '@/types/project'
|
||||||
@@ -55,8 +60,13 @@ const ListAssignPage = () => {
|
|||||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||||
const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx)
|
const assignMutation = useSubmitListJob(prjctIdx)
|
||||||
const resetListAssignMutation = useResetListAssignMutation(prjctIdx)
|
const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled, {
|
||||||
|
hasSelection: !!selectedAssignId,
|
||||||
|
isSubmitting: assignMutation.isPending,
|
||||||
|
})
|
||||||
|
const { gate: assignGate, dataRevision } = pageMonitor
|
||||||
|
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
|
||||||
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType })
|
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType })
|
||||||
|
|
||||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||||
@@ -122,7 +132,15 @@ const ListAssignPage = () => {
|
|||||||
|
|
||||||
const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0
|
const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (enabled && openRequest && !openRequest.opened && openRequest.jobType === 'LIST_ASSIGN'
|
||||||
|
&& openRequest.userId === auth.user?.userId && openRequest.prjctIdx === prjctIdx) {
|
||||||
|
setOpenRequest({ ...openRequest, opened: true })
|
||||||
|
}
|
||||||
|
}, [enabled, openRequest, auth.user?.userId, prjctIdx, setOpenRequest])
|
||||||
|
|
||||||
const handleAssign = async () => {
|
const handleAssign = async () => {
|
||||||
|
if (assignGate.submitBlocked || assignMutation.isPending) return
|
||||||
if (!selectedAssignId) {
|
if (!selectedAssignId) {
|
||||||
alert('배정할 대상을 선택해주세요.')
|
alert('배정할 대상을 선택해주세요.')
|
||||||
return
|
return
|
||||||
@@ -131,33 +149,38 @@ const ListAssignPage = () => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
await upsertListAssignMutation.mutateAsync({
|
await assignMutation.mutateAsync({
|
||||||
assignId: selectedAssignId,
|
jobType: 'LIST_ASSIGN',
|
||||||
request: {
|
path: `mutations/assign/${encodeURIComponent(selectedAssignId)}`,
|
||||||
|
body: {
|
||||||
assignType: effectiveAssignType,
|
assignType: effectiveAssignType,
|
||||||
transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
|
transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
|
||||||
listFilter: currentListFilter,
|
listFilter: currentListFilter,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
alert('배정되었습니다.')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleResetAssign = async () => {
|
const handleResetAssign = async () => {
|
||||||
|
if (assignGate.submitBlocked || assignMutation.isPending) return
|
||||||
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
|
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
|
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
|
||||||
|
|
||||||
await resetListAssignMutation.mutateAsync({
|
await assignMutation.mutateAsync({
|
||||||
|
jobType: 'LIST_ASSIGN',
|
||||||
|
path: 'mutations/assign-reset',
|
||||||
|
body: {
|
||||||
assignType: effectiveAssignType,
|
assignType: effectiveAssignType,
|
||||||
listFilter: currentListFilter,
|
listFilter: currentListFilter,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
alert('배정이 초기화 되었습니다.')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />
|
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<ListJobPageQueryContext.Provider value="LIST_ASSIGN">
|
||||||
<div className="flex gap-4 text-sm">
|
<div className="flex gap-4 text-sm">
|
||||||
<div className="w-72 shrink-0 space-y-2">
|
<div className="w-72 shrink-0 space-y-2">
|
||||||
<Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
|
<Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
|
||||||
@@ -180,8 +203,11 @@ const ListAssignPage = () => {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1 space-y-2">
|
||||||
|
<ListJobGatePanel gate={assignGate} />
|
||||||
|
<ListJobRefreshNotice monitor={pageMonitor} />
|
||||||
<ListSearchTable
|
<ListSearchTable
|
||||||
|
dataRevision={dataRevision}
|
||||||
prjctIdx={prjctIdx}
|
prjctIdx={prjctIdx}
|
||||||
enabled={enabled}
|
enabled={enabled}
|
||||||
userRole={userRole}
|
userRole={userRole}
|
||||||
@@ -219,10 +245,10 @@ const ListAssignPage = () => {
|
|||||||
예약 이관
|
예약 이관
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
<Button type="button" onClick={handleAssign}>
|
<Button type="button" onClick={handleAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
|
||||||
배정
|
배정
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" variant="outline" onClick={handleResetAssign}>
|
<Button type="button" variant="outline" onClick={handleResetAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
|
||||||
배정 초기화
|
배정 초기화
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
@@ -230,6 +256,7 @@ const ListAssignPage = () => {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</ListJobPageQueryContext.Provider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
|
||||||
import AppMainLayout from "@/components/app-shell/AppMainLayout";
|
import AppMainLayout from "@/components/app-shell/AppMainLayout";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
@@ -31,8 +32,8 @@ export default async function MainLayoutWrapper({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppMainLayout initialFontSize={initialFontSize}>
|
<AuthSessionGate><AppMainLayout initialFontSize={initialFontSize}>
|
||||||
{children}
|
{children}
|
||||||
</AppMainLayout>
|
</AppMainLayout></AuthSessionGate>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { Suspense, useEffect, useMemo, useState } from "react";
|
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { ArrowLeft, RefreshCw } from "lucide-react";
|
import { ArrowLeft, RefreshCw } from "lucide-react";
|
||||||
import { useMounted } from "@kri/common/hooks";
|
import { useMounted } from "@kri/common/hooks";
|
||||||
@@ -37,6 +37,7 @@ const ListContactPageContent = () => {
|
|||||||
const userRole = auth?.user?.userRole ?? 0;
|
const userRole = auth?.user?.userRole ?? 0;
|
||||||
const ctiCallPhase = useCtiCallPhase();
|
const ctiCallPhase = useCtiCallPhase();
|
||||||
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
|
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
|
||||||
|
const hasObservedCall = useRef(false);
|
||||||
|
|
||||||
const queriesEnabled = mounted && prjctIdx > 0;
|
const queriesEnabled = mounted && prjctIdx > 0;
|
||||||
const enabled = queriesEnabled && !!sid;
|
const enabled = queriesEnabled && !!sid;
|
||||||
@@ -74,10 +75,12 @@ const ListContactPageContent = () => {
|
|||||||
const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true;
|
const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true;
|
||||||
|
|
||||||
if (!shouldBlockNavigation) {
|
if (!shouldBlockNavigation) {
|
||||||
if (hasGuardEntry) window.history.back();
|
if (hasGuardEntry && hasObservedCall.current) window.history.back();
|
||||||
|
hasObservedCall.current = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
hasObservedCall.current = true;
|
||||||
let isRestoringHistory = false;
|
let isRestoringHistory = false;
|
||||||
|
|
||||||
if (!hasGuardEntry) {
|
if (!hasGuardEntry) {
|
||||||
@@ -174,12 +177,13 @@ const ListContactPageContent = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 text-sm">
|
<div className="space-y-6 text-sm">
|
||||||
<div className="flex items-center gap-3 w-1/2 pr-5">
|
{/* lg 미만은 아래 패널이 1열이므로 전체 폭을 쓰고, 한 줄에 들어가도록 글자/간격을 줄인다. */}
|
||||||
|
<div className="flex w-full items-center gap-2 lg:w-1/2 lg:gap-3 lg:pr-5">
|
||||||
<Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로">
|
<Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로">
|
||||||
<ArrowLeft className="h-4 w-4" />
|
<ArrowLeft className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<h1 className="text-2xl font-bold tracking-tight">컨택 진행</h1>
|
<h1 className="text-xl font-bold tracking-tight max-lg:whitespace-nowrap lg:text-2xl">컨택 진행</h1>
|
||||||
<span className="text-2xl font-bold tracking-tight">SID: {sid}</span>
|
<span className="text-xl font-bold tracking-tight max-lg:min-w-0 max-lg:truncate lg:text-2xl">SID: {sid}</span>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { useAtom } from 'jotai'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
|
||||||
import type { PaginationState } from '@tanstack/react-table'
|
import type { PaginationState } from '@tanstack/react-table'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||||
import { useMounted } from "@kri/common/hooks";
|
import { useMounted } from "@kri/common/hooks";
|
||||||
@@ -10,26 +14,29 @@ import { useDialog } from '@/hooks/useDialog'
|
|||||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||||
import { useStorage } from '@/hooks/useStorage'
|
import { useStorage } from '@/hooks/useStorage'
|
||||||
import { StorageKeys } from '@/store/storage/storage-keys'
|
import { StorageKeys } from '@/store/storage/storage-keys'
|
||||||
import { ListManageActions } from '@/components/list/ListManageActions'
|
import { ListManageActions, type ListManageActionKey } from '@/components/list/ListManageActions'
|
||||||
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
||||||
import {
|
import {
|
||||||
useDownloadListEventHistoryMutation,
|
|
||||||
useDownloadListExcelTemplateMutation,
|
useDownloadListExcelTemplateMutation,
|
||||||
useDownloadListItemFileMutation,
|
|
||||||
useDownloadListMutation,
|
|
||||||
useDownloadListUpdateHistoryMutation,
|
|
||||||
useDownloadUploadHistoryFileMutation,
|
useDownloadUploadHistoryFileMutation,
|
||||||
useListHeaderQuery,
|
useListHeaderQuery,
|
||||||
useListUploadHistoryQuery,
|
useListUploadHistoryQuery,
|
||||||
useResetListMutation,
|
|
||||||
useUpdateListHeaderMutation,
|
useUpdateListHeaderMutation,
|
||||||
useUploadListExcelMutation,
|
|
||||||
} from '@/query/list'
|
} from '@/query/list'
|
||||||
|
import { ListJobPageQueryContext, useMyActiveListJobs, useSubmitListJob } from '@/query/list-job'
|
||||||
|
import { ListJobGatePanel } from '@/components/list/ListJobGate'
|
||||||
|
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
|
||||||
|
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
|
||||||
|
import { useTrackedListJobs } from '@/store/list-job-tracker'
|
||||||
|
import { isListPageActionBlocked } from '@/utils/listJobAvailability'
|
||||||
|
import type { ListJobType } from '@/types/list-job'
|
||||||
|
import { LIST_DOWNLOAD_JOB_TYPE, LIST_JOB_VIEW, MESSAGE_JOB_TYPE } from '@/const/listJobConst'
|
||||||
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
||||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||||
import {
|
import {
|
||||||
createEmptyListFilter,
|
createEmptyListFilter,
|
||||||
ListEventHistoryBase,
|
ListEventHistoryBase,
|
||||||
|
ListEventHistoryOrder,
|
||||||
type LastListVisit,
|
type LastListVisit,
|
||||||
type ListDownloadMode,
|
type ListDownloadMode,
|
||||||
type ListDownloadPayload,
|
type ListDownloadPayload,
|
||||||
@@ -37,8 +44,8 @@ import {
|
|||||||
type ListFilterTarget,
|
type ListFilterTarget,
|
||||||
type listHeader,
|
type listHeader,
|
||||||
type ListSearchUiState,
|
type ListSearchUiState,
|
||||||
ListResetMode,
|
type ListResetRequest,
|
||||||
type ListResetScope,
|
type ListResetSelection,
|
||||||
type ListUploadRequest,
|
type ListUploadRequest,
|
||||||
} from '@/types/list'
|
} from '@/types/list'
|
||||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||||
@@ -48,7 +55,7 @@ import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog'
|
|||||||
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
|
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
|
||||||
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
||||||
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
|
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
|
||||||
import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from '@kri/common/browser'
|
import { downloadFile } from '@kri/common/browser'
|
||||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
||||||
import { isInternalManager, isManager } from "@/utils/userRole";
|
import { isInternalManager, isManager } from "@/utils/userRole";
|
||||||
import { applyListAccessFilter } from "@/utils/listAccess";
|
import { applyListAccessFilter } from "@/utils/listAccess";
|
||||||
@@ -77,10 +84,12 @@ const createEmptySearchUiState = (): ListSearchUiState => ({
|
|||||||
|
|
||||||
const ListManagePage = () => {
|
const ListManagePage = () => {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
const mounted = useMounted()
|
const mounted = useMounted()
|
||||||
const { auth } = useAuth()
|
const { auth } = useAuth()
|
||||||
const { showDialog } = useDialog()
|
const { showDialog } = useDialog()
|
||||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
|
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
|
||||||
|
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
|
||||||
|
|
||||||
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
|
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
|
||||||
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
|
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
|
||||||
@@ -92,6 +101,7 @@ const ListManagePage = () => {
|
|||||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
|
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
|
||||||
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null)
|
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null)
|
||||||
const [restoreResolved, setRestoreResolved] = useState(false)
|
const [restoreResolved, setRestoreResolved] = useState(false)
|
||||||
|
const previousPrjctIdxRef = useRef(0)
|
||||||
|
|
||||||
const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage(
|
const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage(
|
||||||
StorageKeys.LastListVisit,
|
StorageKeys.LastListVisit,
|
||||||
@@ -106,19 +116,56 @@ const ListManagePage = () => {
|
|||||||
const canManageList = isManager(userRole);
|
const canManageList = isManager(userRole);
|
||||||
// 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨.
|
// 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨.
|
||||||
const isInternal = isInternalManager(userRole);
|
const isInternal = isInternalManager(userRole);
|
||||||
|
const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled, { hasSelection: selectedRows.length > 0 })
|
||||||
|
const { gate: pageGate, dataRevision } = pageMonitor
|
||||||
|
const trackedJobs = useTrackedListJobs()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!mounted || !restoreResolved || !enabled || !openRequest || openRequest.opened
|
||||||
|
|| openRequest.userId !== userId || openRequest.prjctIdx !== prjctIdx) return
|
||||||
|
const view = LIST_JOB_VIEW[openRequest.jobType]
|
||||||
|
if (view.path !== '/list/manage' || !view.dialogId) return
|
||||||
|
if (!canManageList || (!isInternal && (openRequest.jobType === 'LIST_UPLOAD' || openRequest.jobType === 'LIST_RESET'))) {
|
||||||
|
toast.error('해당 작업 화면을 열 권한이 없습니다.')
|
||||||
|
setOpenRequest(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (view.downloadMode) setDownloadMode(view.downloadMode)
|
||||||
|
if (view.messageMode) setMessageSendMode(view.messageMode)
|
||||||
|
showDialog(view.dialogId)
|
||||||
|
setOpenRequest({ ...openRequest, opened: true })
|
||||||
|
}, [mounted, restoreResolved, enabled, openRequest, userId, prjctIdx, canManageList, isInternal, setOpenRequest, showDialog])
|
||||||
|
|
||||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||||
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
|
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
|
||||||
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
|
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
|
||||||
const uploadListExcelMutation = useUploadListExcelMutation(prjctIdx)
|
const submitJob = useSubmitListJob(prjctIdx)
|
||||||
|
// 전역 ListJobWatcher가 갱신하는 동일 쿼리를 구독하고 별도 폴링은 만들지 않는다.
|
||||||
|
const myActiveJobsQuery = useMyActiveListJobs(prjctIdx, false)
|
||||||
|
const myActiveJobTypes = new Set<string>((myActiveJobsQuery.data ?? []).map((job) => job.jobType))
|
||||||
|
const inspectableJobTypes = new Set([
|
||||||
|
...trackedJobs.filter(job => job.userId === userId && job.prjctIdx === prjctIdx).map(job => job.jobType),
|
||||||
|
...myActiveJobTypes,
|
||||||
|
...(pageGate.availability?.blockers.filter(blocker => blocker.mine && blocker.jobKey).map(blocker => blocker.jobType) ?? []),
|
||||||
|
])
|
||||||
|
const isActionDisabled = (jobType: ListJobType) => !inspectableJobTypes.has(jobType) && isListPageActionBlocked(
|
||||||
|
pageGate.status === 'unsupported' ? undefined : pageGate.availability,
|
||||||
|
jobType,
|
||||||
|
pageGate.status === 'checking' || pageGate.status === 'error',
|
||||||
|
)
|
||||||
|
const actionJobTypes: Record<ListManageActionKey, ListJobType> = {
|
||||||
|
reset: 'LIST_RESET', upload: 'LIST_UPLOAD', ...LIST_DOWNLOAD_JOB_TYPE, ...MESSAGE_JOB_TYPE,
|
||||||
|
}
|
||||||
|
const disabledActions = new Set((Object.keys(actionJobTypes) as ListManageActionKey[]).filter(action => isActionDisabled(actionJobTypes[action])))
|
||||||
|
const runningActions = new Set<ListManageActionKey>([
|
||||||
|
...(myActiveJobTypes.has('LIST_RESET') ? ['reset' as const] : []),
|
||||||
|
...(myActiveJobTypes.has('LIST_UPLOAD') ? ['upload' as const] : []),
|
||||||
|
...(Object.keys(LIST_DOWNLOAD_JOB_TYPE) as ListDownloadMode[]).filter((mode) => myActiveJobTypes.has(LIST_DOWNLOAD_JOB_TYPE[mode])),
|
||||||
|
...(Object.keys(MESSAGE_JOB_TYPE) as MessageSendMode[]).filter((mode) => myActiveJobTypes.has(MESSAGE_JOB_TYPE[mode])),
|
||||||
|
])
|
||||||
const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx)
|
const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx)
|
||||||
const resetListMutation = useResetListMutation(prjctIdx)
|
|
||||||
const downloadListMutation = useDownloadListMutation(prjctIdx)
|
|
||||||
const downloadListUpdateHistoryMutation = useDownloadListUpdateHistoryMutation(prjctIdx)
|
|
||||||
const downloadListEventHistoryMutation = useDownloadListEventHistoryMutation(prjctIdx)
|
|
||||||
const downloadListItemFileMutation = useDownloadListItemFileMutation(prjctIdx)
|
|
||||||
const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
|
const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
|
||||||
|
|
||||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||||
@@ -136,9 +183,34 @@ const ListManagePage = () => {
|
|||||||
removeLastListVisit()
|
removeLastListVisit()
|
||||||
}
|
}
|
||||||
setRestoreResolved(true)
|
setRestoreResolved(true)
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [mounted, isSelectedProjectHydrated, restoreResolved])
|
}, [mounted, isSelectedProjectHydrated, restoreResolved])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!mounted || !isSelectedProjectHydrated || prjctIdx <= 0) return
|
||||||
|
|
||||||
|
const previousPrjctIdx = previousPrjctIdxRef.current
|
||||||
|
previousPrjctIdxRef.current = prjctIdx
|
||||||
|
if (previousPrjctIdx === 0 || previousPrjctIdx === prjctIdx) return
|
||||||
|
|
||||||
|
setSelectedRows([])
|
||||||
|
setCurrentListFilter(createEmptyListFilter())
|
||||||
|
setFilterSummary([])
|
||||||
|
setSearchUiState(createEmptySearchUiState())
|
||||||
|
setPagination({ pageIndex: 0, pageSize: 25 })
|
||||||
|
setRestoredVisit(null)
|
||||||
|
}, [isSelectedProjectHydrated, mounted, prjctIdx])
|
||||||
|
|
||||||
|
// 브라우저 뒤로가기(popstate)는 Next.js가 이 페이지를 재마운트하지 않고 재사용할 수 있어
|
||||||
|
// refetchOnMount만으로는 최신 데이터를 보장 못한다. popstate는 브라우저 네이티브 이벤트라
|
||||||
|
// 재마운트 여부와 무관하게 항상 발생하므로, 여기서 명시적으로 무효화한다.
|
||||||
|
useEffect(() => {
|
||||||
|
const handlePopState = () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['list', 'search-filter'] })
|
||||||
|
}
|
||||||
|
window.addEventListener('popstate', handlePopState)
|
||||||
|
return () => window.removeEventListener('popstate', handlePopState)
|
||||||
|
}, [queryClient])
|
||||||
|
|
||||||
const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined
|
const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined
|
||||||
|
|
||||||
const selectedSidSet = useMemo(
|
const selectedSidSet = useMemo(
|
||||||
@@ -192,28 +264,16 @@ const ListManagePage = () => {
|
|||||||
showDialog('messageSendDialog')
|
showDialog('messageSendDialog')
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleResetConfirm = async (payload: { target: ListFilterTarget; scope: ListResetScope }) => {
|
const handleResetConfirm = async (payload: { target: ListFilterTarget; selection: ListResetSelection }) => {
|
||||||
const listFilter = buildTargetFilter(payload.target)
|
const body: ListResetRequest = {
|
||||||
const resetCount = await resetListMutation.mutateAsync({
|
...payload.selection,
|
||||||
resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL,
|
listFilter: buildTargetFilter(payload.target),
|
||||||
listFilter,
|
}
|
||||||
})
|
await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body })
|
||||||
alert(`${resetCount}건 삭제 되었습니다.`)
|
|
||||||
refreshList()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
|
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
|
||||||
const res = await uploadListExcelMutation.mutateAsync({ file, request })
|
await submitJob.mutateAsync({ jobType: 'LIST_UPLOAD', path: 'upload', file, body: request })
|
||||||
|
|
||||||
if (res.hasErrorFile && res.errorFileBase64) {
|
|
||||||
alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다.");
|
|
||||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE);
|
|
||||||
}
|
|
||||||
else{
|
|
||||||
alert(`${res.successCount}개의 리스트를 업로드했습니다.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
refreshList()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleDownloadTemplate = async () => {
|
const handleDownloadTemplate = async () => {
|
||||||
@@ -232,43 +292,47 @@ const ListManagePage = () => {
|
|||||||
|
|
||||||
const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
|
const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
|
||||||
const listFilter = buildTargetFilter(payload.target)
|
const listFilter = buildTargetFilter(payload.target)
|
||||||
|
const jobType = LIST_DOWNLOAD_JOB_TYPE[payload.mode]
|
||||||
|
|
||||||
if (payload.mode === 'list') {
|
if (payload.mode === 'list') {
|
||||||
const buffer = await downloadListMutation.mutateAsync(listFilter)
|
await submitJob.mutateAsync({ jobType, path: `downloads/list?includeResult=${payload.includeResult}`, body: listFilter })
|
||||||
downloadArrayBuffer(buffer, `${prjctName} list.xlsx`)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.mode === 'list-change-history') {
|
if (payload.mode === 'list-change-history') {
|
||||||
const buffer = await downloadListUpdateHistoryMutation.mutateAsync(listFilter)
|
await submitJob.mutateAsync({ jobType, path: 'downloads/update-history', body: listFilter })
|
||||||
downloadArrayBuffer(buffer, `${prjctName} update-history.xlsx`)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.mode === 'upload-file') {
|
if (payload.mode === 'upload-file') {
|
||||||
const buffer = await downloadListItemFileMutation.mutateAsync(listFilter)
|
await submitJob.mutateAsync({ jobType, path: 'downloads/item-files', body: listFilter })
|
||||||
downloadArrayBuffer(buffer, `${prjctName} upload-files.zip`, 'application/zip')
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const buffer = await downloadListEventHistoryMutation.mutateAsync({
|
await submitJob.mutateAsync({ jobType, path: `downloads/event-history?includeResult=${payload.includeResult}`, body: {
|
||||||
listFilter,
|
listFilter,
|
||||||
resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY],
|
resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY],
|
||||||
searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL,
|
searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL,
|
||||||
|
historyOrder: payload.historyOrder ?? ListEventHistoryOrder.DESC,
|
||||||
dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo),
|
dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo),
|
||||||
})
|
} })
|
||||||
downloadArrayBuffer(buffer, `${prjctName} contact-history.xlsx`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
|
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<ListJobPageQueryContext.Provider value="LIST_RESET">
|
||||||
<div className="space-y-6 text-sm">
|
<div className="space-y-6 text-sm">
|
||||||
|
<ListJobGatePanel gate={pageGate} showCurrentJob={false} />
|
||||||
|
<ListJobRefreshNotice monitor={pageMonitor} clearsSelection={selectedRows.length > 0} />
|
||||||
{canManageList && (
|
{canManageList && (
|
||||||
<ListManageActions
|
<ListManageActions
|
||||||
showAdminActions={isInternal}
|
showAdminActions={isInternal}
|
||||||
|
runningActions={runningActions}
|
||||||
|
disabledActions={disabledActions}
|
||||||
|
headerManageDisabled={pageGate.submitBlocked}
|
||||||
onReset={() => showDialog('listResetDialog')}
|
onReset={() => showDialog('listResetDialog')}
|
||||||
onHeaderManage={() => showDialog('listHeaderManageDialog')}
|
onHeaderManage={() => { if (!pageGate.submitBlocked) showDialog('listHeaderManageDialog') }}
|
||||||
onUpload={() => showDialog('listUploadDialog')}
|
onUpload={() => showDialog('listUploadDialog')}
|
||||||
onDownload={openDownloadDialog}
|
onDownload={openDownloadDialog}
|
||||||
onMessageSend={openMessageDialog}
|
onMessageSend={openMessageDialog}
|
||||||
@@ -277,6 +341,7 @@ const ListManagePage = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<ListSearchTable
|
<ListSearchTable
|
||||||
|
key={prjctIdx}
|
||||||
prjctIdx={prjctIdx}
|
prjctIdx={prjctIdx}
|
||||||
enabled={enabled}
|
enabled={enabled}
|
||||||
userRole={userRole}
|
userRole={userRole}
|
||||||
@@ -287,6 +352,8 @@ const ListManagePage = () => {
|
|||||||
listHeaders={headerManageRows}
|
listHeaders={headerManageRows}
|
||||||
fieldInterviewEnabled={selectedProject?.ff !== false}
|
fieldInterviewEnabled={selectedProject?.ff !== false}
|
||||||
enableBatchEdit={canManageList}
|
enableBatchEdit={canManageList}
|
||||||
|
batchEditDisabled={isActionDisabled('LIST_UPDATE')}
|
||||||
|
dataRevision={dataRevision}
|
||||||
selectMode={canManageList ? 'multi' : 'click-event'}
|
selectMode={canManageList ? 'multi' : 'click-event'}
|
||||||
refreshKey={listRefreshKey}
|
refreshKey={listRefreshKey}
|
||||||
onCurrentFilterChange={setCurrentListFilter}
|
onCurrentFilterChange={setCurrentListFilter}
|
||||||
@@ -303,16 +370,21 @@ const ListManagePage = () => {
|
|||||||
initialSearchState={restoredForThisProject}
|
initialSearchState={restoredForThisProject}
|
||||||
onSearchStateChange={setSearchUiState}
|
onSearchStateChange={setSearchUiState}
|
||||||
focusRowId={restoredForThisProject?.sid}
|
focusRowId={restoredForThisProject?.sid}
|
||||||
|
collapsibleFiltersOnMobile
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{isInternal && (
|
{isInternal && (
|
||||||
<>
|
<>
|
||||||
<ListResetDialog
|
<ListResetDialog
|
||||||
|
key={prjctIdx}
|
||||||
|
prjctIdx={prjctIdx}
|
||||||
|
surveys={projectInfoQuery.data?.surveys}
|
||||||
selectedSids={selectedSidSet}
|
selectedSids={selectedSidSet}
|
||||||
filterSummary={filterSummary}
|
filterSummary={filterSummary}
|
||||||
onConfirm={handleResetConfirm}
|
onConfirm={handleResetConfirm}
|
||||||
/>
|
/>
|
||||||
<ListUploadDialog
|
<ListUploadDialog
|
||||||
|
prjctIdx={prjctIdx}
|
||||||
onUpload={handleUploadConfirm}
|
onUpload={handleUploadConfirm}
|
||||||
onDownloadTemplate={handleDownloadTemplate}
|
onDownloadTemplate={handleDownloadTemplate}
|
||||||
uploadHistory={uploadHistoryQuery.data ?? []}
|
uploadHistory={uploadHistoryQuery.data ?? []}
|
||||||
@@ -322,13 +394,14 @@ const ListManagePage = () => {
|
|||||||
}}
|
}}
|
||||||
headerRows={headerManageRows}
|
headerRows={headerManageRows}
|
||||||
/>
|
/>
|
||||||
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} />
|
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} saveDisabled={pageGate.submitBlocked} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{canManageList && (
|
{canManageList && (
|
||||||
<>
|
<>
|
||||||
<ListDownloadDialog
|
<ListDownloadDialog
|
||||||
|
prjctIdx={prjctIdx}
|
||||||
mode={downloadMode}
|
mode={downloadMode}
|
||||||
selectedSids={selectedSidSet}
|
selectedSids={selectedSidSet}
|
||||||
filterSummary={filterSummary}
|
filterSummary={filterSummary}
|
||||||
@@ -346,6 +419,7 @@ const ListManagePage = () => {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</ListJobPageQueryContext.Provider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { MessageType, type TemplateEmail } from "@kri/common/noti-hub";
|
import { MessageType, TemplatePurpose, type TemplateEmail } from "@kri/common/noti-hub";
|
||||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||||
|
import type { TemplateWithPurpose } from "@/types/message";
|
||||||
|
|
||||||
const EmailTemplatePage = () => {
|
const EmailTemplatePage = () => {
|
||||||
|
|
||||||
const defaultEmailTemplate : TemplateEmail = {
|
const defaultEmailTemplate : TemplateWithPurpose & TemplateEmail = {
|
||||||
tmplatIdx: undefined,
|
tmplatIdx: undefined,
|
||||||
itrntPrjctCd: '',
|
itrntPrjctCd: '',
|
||||||
tmplatTy: MessageType.EMAIL,
|
tmplatTy: MessageType.EMAIL,
|
||||||
|
tmplatPurpose: TemplatePurpose.NORMAL,
|
||||||
tmplatNm: '',
|
tmplatNm: '',
|
||||||
tmplatTitle: '',
|
tmplatTitle: '',
|
||||||
tmplatBody: '',
|
tmplatBody: '',
|
||||||
|
|||||||
13
src/app/(pages)/(main)/message/template/kko/page.tsx
Normal file
13
src/app/(pages)/(main)/message/template/kko/page.tsx
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import KkoMessageTemplate from "@/components/message-template/KkoMessageTemplate";
|
||||||
|
|
||||||
|
const KkoTemplatePage = () => {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 text-sm">
|
||||||
|
<KkoMessageTemplate />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default KkoTemplatePage;
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { MessageType, type TemplateSms } from "@kri/common/noti-hub";
|
import { MessageType, TemplatePurpose, type TemplateSms } from "@kri/common/noti-hub";
|
||||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||||
|
import type { TemplateWithPurpose } from "@/types/message";
|
||||||
|
|
||||||
const SmsTemplatePage = () => {
|
const SmsTemplatePage = () => {
|
||||||
|
|
||||||
const defaultSmsTemplate : TemplateSms = {
|
const defaultSmsTemplate : TemplateWithPurpose & TemplateSms = {
|
||||||
tmplatIdx: undefined,
|
tmplatIdx: undefined,
|
||||||
itrntPrjctCd: '',
|
itrntPrjctCd: '',
|
||||||
tmplatTy: MessageType.SMS,
|
tmplatTy: MessageType.SMS,
|
||||||
|
tmplatPurpose: TemplatePurpose.NORMAL,
|
||||||
tmplatNm: '',
|
tmplatNm: '',
|
||||||
tmplatTitle: undefined,
|
tmplatTitle: undefined,
|
||||||
tmplatBody: '',
|
tmplatBody: '',
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
'use client'
|
'use client'
|
||||||
import {useMemo, useState} from "react";
|
import {useMemo, useState} from "react";
|
||||||
|
import {ChevronDown} from "lucide-react";
|
||||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||||
|
import {Badge} from "@/components/ui/badge";
|
||||||
import {Button} from "@/components/ui/button";
|
import {Button} from "@/components/ui/button";
|
||||||
|
import {cn} from "@/lib/utils";
|
||||||
import {DataTable} from "@/components/data-table/DataTable";
|
import {DataTable} from "@/components/data-table/DataTable";
|
||||||
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
|
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
|
||||||
import {
|
import {
|
||||||
@@ -23,11 +26,11 @@ import { useMounted } from "@kri/common/hooks";
|
|||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||||
import {useRouter} from "next/navigation";
|
import {useRouter} from "next/navigation";
|
||||||
|
import type {Route} from "next";
|
||||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||||
import {useGroupCodeListQuery} from "@/query/intranet";
|
import {useGroupCodeListQuery} from "@/query/intranet";
|
||||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||||
import {isInternalManager, isManager} from "@/utils/userRole";
|
import {isInternalManager, isManager} from "@/utils/userRole";
|
||||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
|
||||||
|
|
||||||
const MainPage = () => {
|
const MainPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -99,6 +102,9 @@ const MainPage = () => {
|
|||||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||||
|
// 모바일(md 미만)에서만 필터 영역을 접고 펼친다. md 이상에서는 항상 노출된다.
|
||||||
|
const [filtersOpen, setFiltersOpen] = useState(false);
|
||||||
|
const hasActiveFilters = searchStatus.length > 0 || searchDept.length > 0 || searchFw.length > 0;
|
||||||
|
|
||||||
const userId = auth.user?.userId ?? "";
|
const userId = auth.user?.userId ?? "";
|
||||||
const userRole = auth.user?.userRole;
|
const userRole = auth.user?.userRole;
|
||||||
@@ -123,7 +129,7 @@ const MainPage = () => {
|
|||||||
showDialog('projectCreateDialog');
|
showDialog('projectCreateDialog');
|
||||||
}
|
}
|
||||||
|
|
||||||
const navigateWithProject = (projectInfo: ProjectInfo, path: string) => {
|
const navigateWithProject = (projectInfo: ProjectInfo, path: Route) => {
|
||||||
setSelectedProject({
|
setSelectedProject({
|
||||||
prjctIdx: projectInfo.prjctIdx,
|
prjctIdx: projectInfo.prjctIdx,
|
||||||
prjctCd: projectInfo.prjctCd,
|
prjctCd: projectInfo.prjctCd,
|
||||||
@@ -154,11 +160,12 @@ const MainPage = () => {
|
|||||||
<div className="space-y-6 text-sm">
|
<div className="space-y-6 text-sm">
|
||||||
<AppPageTitle titleText={"프로젝트"}/>
|
<AppPageTitle titleText={"프로젝트"}/>
|
||||||
|
|
||||||
<div className="flex gap-2 items-center">
|
<div className="flex flex-col gap-2 md:flex-row md:flex-wrap md:items-center">
|
||||||
<div className="flex flex-1 items-center gap-2">
|
<div className="flex flex-col gap-2 md:flex-1 md:flex-row md:flex-wrap md:items-center">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
placeholder="프로젝트 코드 Or 프로젝트 명"
|
placeholder="프로젝트 코드 Or 프로젝트 명"
|
||||||
className="w-120 h-9 bg-white"
|
className="h-9 flex-1 bg-white md:w-120 md:flex-none"
|
||||||
value={searchText}
|
value={searchText}
|
||||||
onChange={(e) => setSearchText(e.target.value)}
|
onChange={(e) => setSearchText(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
@@ -167,6 +174,34 @@ const MainPage = () => {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
<Button
|
||||||
|
className="md:hidden"
|
||||||
|
onClick={handleSearchClick}
|
||||||
|
>
|
||||||
|
검색
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-between md:hidden"
|
||||||
|
aria-expanded={filtersOpen}
|
||||||
|
aria-controls="project-search-filters"
|
||||||
|
onClick={() => setFiltersOpen((prev) => !prev)}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
필터
|
||||||
|
{hasActiveFilters ? <Badge>적용 중</Badge> : null}
|
||||||
|
</span>
|
||||||
|
<ChevronDown className={cn("h-4 w-4 transition-transform", filtersOpen && "rotate-180")} />
|
||||||
|
</Button>
|
||||||
|
<div
|
||||||
|
id="project-search-filters"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-2 md:flex-row md:flex-wrap md:items-center",
|
||||||
|
!filtersOpen && "hidden md:flex",
|
||||||
|
)}
|
||||||
|
>
|
||||||
{
|
{
|
||||||
isManager(userRole) &&
|
isManager(userRole) &&
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
@@ -176,7 +211,7 @@ const MainPage = () => {
|
|||||||
getValue={(item) => item.value}
|
getValue={(item) => item.value}
|
||||||
getLabel={(item) => item.label}
|
getLabel={(item) => item.label}
|
||||||
placeholder="진행 상태"
|
placeholder="진행 상태"
|
||||||
widthClassName="w-60"
|
widthClassName="w-full md:w-60"
|
||||||
heightClassName="h-9"
|
heightClassName="h-9"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
@@ -187,7 +222,7 @@ const MainPage = () => {
|
|||||||
getValue={(item) => item.value}
|
getValue={(item) => item.value}
|
||||||
getLabel={(item) => item.label}
|
getLabel={(item) => item.label}
|
||||||
placeholder="담당 그룹"
|
placeholder="담당 그룹"
|
||||||
widthClassName="w-60"
|
widthClassName="w-full md:w-60"
|
||||||
heightClassName="h-9"
|
heightClassName="h-9"
|
||||||
/>
|
/>
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
@@ -197,10 +232,12 @@ const MainPage = () => {
|
|||||||
getValue={(item) => item.value}
|
getValue={(item) => item.value}
|
||||||
getLabel={(item) => item.label}
|
getLabel={(item) => item.label}
|
||||||
placeholder="담당 실사"
|
placeholder="담당 실사"
|
||||||
widthClassName="w-60"
|
widthClassName="w-full md:w-60"
|
||||||
heightClassName="h-9"
|
heightClassName="h-9"
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
<Button
|
<Button
|
||||||
|
className="hidden md:inline-flex"
|
||||||
onClick={handleSearchClick}
|
onClick={handleSearchClick}
|
||||||
>
|
>
|
||||||
검색
|
검색
|
||||||
@@ -208,6 +245,7 @@ const MainPage = () => {
|
|||||||
</div>
|
</div>
|
||||||
{isInternal && (
|
{isInternal && (
|
||||||
<Button
|
<Button
|
||||||
|
className="w-full md:w-auto"
|
||||||
onClick={handleCreateClick}
|
onClick={handleCreateClick}
|
||||||
>
|
>
|
||||||
프로젝트 등록
|
프로젝트 등록
|
||||||
|
|||||||
@@ -11,12 +11,14 @@ import { clientEnv } from "@/lib/env.client";
|
|||||||
import { MessageType } from "@kri/common/noti-hub";
|
import { MessageType } from "@kri/common/noti-hub";
|
||||||
import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
|
import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
|
||||||
|
|
||||||
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS_MMS, MessageType.EMAIL] as const;
|
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS, MessageType.MMS, MessageType.EMAIL, MessageType.KKO] as const;
|
||||||
|
|
||||||
const SEND_TYPE_LABEL: Record<number, string> = {
|
const SEND_TYPE_LABEL: Record<number, string> = {
|
||||||
[MessageType.SMS]: "단문",
|
[MessageType.SMS]: "단문",
|
||||||
[MessageType.LMS_MMS]: "장문",
|
[MessageType.LMS]: "장문",
|
||||||
|
[MessageType.MMS]: "첨부 문자",
|
||||||
[MessageType.EMAIL]: "메일",
|
[MessageType.EMAIL]: "메일",
|
||||||
|
[MessageType.KKO]: "알림톡",
|
||||||
};
|
};
|
||||||
|
|
||||||
type SummaryRow = {
|
type SummaryRow = {
|
||||||
@@ -27,6 +29,7 @@ type SummaryRow = {
|
|||||||
successCount: number;
|
successCount: number;
|
||||||
failCount: number;
|
failCount: number;
|
||||||
standByCount: number;
|
standByCount: number;
|
||||||
|
canceledCount: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
|
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
|
||||||
@@ -43,6 +46,7 @@ const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
|
|||||||
successCount: sum(matched, "successCount"),
|
successCount: sum(matched, "successCount"),
|
||||||
failCount: sum(matched, "failCount"),
|
failCount: sum(matched, "failCount"),
|
||||||
standByCount: sum(matched, "standByCount"),
|
standByCount: sum(matched, "standByCount"),
|
||||||
|
canceledCount: sum(matched, "canceledCount"),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -79,6 +83,7 @@ const MessageProgressPage = () => {
|
|||||||
successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
|
successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
|
||||||
failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
|
failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
|
||||||
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
|
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
|
||||||
|
canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0),
|
||||||
}),
|
}),
|
||||||
[rows],
|
[rows],
|
||||||
);
|
);
|
||||||
@@ -102,6 +107,7 @@ const MessageProgressPage = () => {
|
|||||||
<th className="h-10 px-3 text-center font-semibold border-b">성공</th>
|
<th className="h-10 px-3 text-center font-semibold border-b">성공</th>
|
||||||
<th className="h-10 px-3 text-center font-semibold border-b">실패</th>
|
<th className="h-10 px-3 text-center font-semibold border-b">실패</th>
|
||||||
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
|
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
|
||||||
|
<th className="h-10 px-3 text-center font-semibold border-b">취소</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -114,6 +120,7 @@ const MessageProgressPage = () => {
|
|||||||
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
|
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
|
||||||
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
|
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
|
||||||
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
|
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
|
||||||
|
<td className="h-10 px-3 text-center">{caseUnit(row.canceledCount)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
<tr className="bg-gray-50 font-semibold">
|
<tr className="bg-gray-50 font-semibold">
|
||||||
@@ -123,6 +130,7 @@ const MessageProgressPage = () => {
|
|||||||
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
|
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
|
||||||
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
|
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
|
||||||
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
|
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
|
||||||
|
<td className="h-10 px-3 text-center">{caseUnit(total.canceledCount)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -1,19 +1,18 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
|
||||||
import { useMounted } from "@kri/common/hooks";
|
import { useMounted } from "@kri/common/hooks";
|
||||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||||
import { useProjectInfoQuery, useSurveyRedirectUrlQuery } from "@/query/project";
|
import { useProjectInfoQuery } from "@/query/project";
|
||||||
|
import { clientEnv } from "@/lib/env.client";
|
||||||
import { SurveyType } from "@/types/project";
|
import { SurveyType } from "@/types/project";
|
||||||
import { SURVEY_TYPE_LABEL } from "@/const/projectConst";
|
import { SURVEY_TYPE_LABEL } from "@/const/projectConst";
|
||||||
|
|
||||||
const SurveyProgressPage = () => {
|
const SurveyProgressPage = () => {
|
||||||
const mounted = useMounted();
|
const mounted = useMounted();
|
||||||
const { selectedProject } = useSelectedProject();
|
const { selectedProject } = useSelectedProject();
|
||||||
const openedForRef = useRef<string | null>(null);
|
|
||||||
|
|
||||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||||
const enabled = mounted && prjctIdx > 0;
|
const enabled = mounted && prjctIdx > 0;
|
||||||
@@ -21,35 +20,7 @@ const SurveyProgressPage = () => {
|
|||||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||||
const surveys = projectInfoQuery.data?.surveys ?? [];
|
const surveys = projectInfoQuery.data?.surveys ?? [];
|
||||||
|
|
||||||
const [activeSurveyIdx, setActiveSurveyIdx] = useState<number | null>(null);
|
const isLoading = !mounted || projectInfoQuery.isLoading;
|
||||||
const [openedUrl, setOpenedUrl] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const selectedSurvey = surveys.find((s) => s.prjctSurveyIdx === activeSurveyIdx) ?? null;
|
|
||||||
const surveyTy = selectedSurvey?.surveyTy ?? SurveyType.NONE;
|
|
||||||
|
|
||||||
const isKonKiwi = surveyTy === SurveyType.KON || surveyTy === SurveyType.KIWI;
|
|
||||||
const isKiwi = surveyTy === SurveyType.KIWI ? 1 : 0;
|
|
||||||
const pkey = selectedSurvey?.surveyPrjctCd ?? "";
|
|
||||||
|
|
||||||
const redirectUrlEnabled = enabled && !!selectedSurvey && isKonKiwi && !!pkey;
|
|
||||||
const redirectUrlQuery = useSurveyRedirectUrlQuery(isKiwi, pkey, redirectUrlEnabled);
|
|
||||||
|
|
||||||
const targetUrl = !selectedSurvey
|
|
||||||
? null
|
|
||||||
: isKonKiwi
|
|
||||||
? (redirectUrlQuery.data ?? null)
|
|
||||||
: surveyTy === SurveyType.EXTERNAL
|
|
||||||
? (selectedSurvey.surveyDashboardUrl || null)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!targetUrl || openedForRef.current === targetUrl) return;
|
|
||||||
openedForRef.current = targetUrl;
|
|
||||||
window.open(targetUrl, "_blank");
|
|
||||||
setOpenedUrl(targetUrl);
|
|
||||||
}, [targetUrl]);
|
|
||||||
|
|
||||||
const isLoading = !mounted || projectInfoQuery.isLoading || (redirectUrlEnabled && redirectUrlQuery.isLoading);
|
|
||||||
|
|
||||||
if (isLoading) return <LoadingOverlayAdapter force />;
|
if (isLoading) return <LoadingOverlayAdapter force />;
|
||||||
|
|
||||||
@@ -62,7 +33,14 @@ const SurveyProgressPage = () => {
|
|||||||
) : (
|
) : (
|
||||||
<div className="max-w-[600px] space-y-2">
|
<div className="max-w-[600px] space-y-2">
|
||||||
{surveys.map((survey) => {
|
{surveys.map((survey) => {
|
||||||
const hasReport = survey.surveyTy !== SurveyType.NONE;
|
const isKonKiwi = survey.surveyTy === SurveyType.KON || survey.surveyTy === SurveyType.KIWI;
|
||||||
|
let targetUrl: string | null = null;
|
||||||
|
if (isKonKiwi && survey.surveyPrjctCd) {
|
||||||
|
const projectType = survey.surveyTy === SurveyType.KIWI ? 1 : 0;
|
||||||
|
targetUrl = `${clientEnv.KART_URL}/Report/Current?projectType=${projectType}&pkey=${encodeURIComponent(survey.surveyPrjctCd)}`;
|
||||||
|
} else if (survey.surveyTy === SurveyType.EXTERNAL) {
|
||||||
|
targetUrl = survey.surveyDashboardUrl || null;
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={survey.prjctSurveyIdx ?? survey.surveyOrder}
|
key={survey.prjctSurveyIdx ?? survey.surveyOrder}
|
||||||
@@ -72,28 +50,21 @@ const SurveyProgressPage = () => {
|
|||||||
<p className="font-semibold">{survey.surveyName}</p>
|
<p className="font-semibold">{survey.surveyName}</p>
|
||||||
<p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p>
|
<p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
{targetUrl ? (
|
||||||
type="button"
|
<Button asChild>
|
||||||
disabled={!hasReport}
|
<a href={targetUrl} target="_blank" rel="noopener noreferrer">
|
||||||
onClick={() => setActiveSurveyIdx(survey.prjctSurveyIdx ?? null)}
|
|
||||||
>
|
|
||||||
바로가기
|
바로가기
|
||||||
|
</a>
|
||||||
</Button>
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button type="button" disabled>바로가기</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{openedUrl ? (
|
|
||||||
<p>
|
|
||||||
새 창에서 열립니다. 열리지 않았다면{" "}
|
|
||||||
<a href={openedUrl} target="_blank" rel="noreferrer" className="text-blue-600 underline">
|
|
||||||
여기
|
|
||||||
</a>
|
|
||||||
를 클릭해 주세요.
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {useDialog} from '@/hooks/useDialog'
|
|||||||
import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
|
import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
|
||||||
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
||||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||||
import { X } from 'lucide-react'
|
import { X, Copy, Check } from 'lucide-react'
|
||||||
import {
|
import {
|
||||||
ProjectInfo, ProjectSurvey, ProjectUpdateRequest, ResultCode,
|
ProjectInfo, ProjectSurvey, ProjectUpdateRequest, ResultCode,
|
||||||
ProjectStatus, ResultCodeType, SurveyType
|
ProjectStatus, ResultCodeType, SurveyType
|
||||||
@@ -123,7 +123,6 @@ const createSurveyDraft = (surveyOrder: number): SurveyDraft => ({
|
|||||||
surveyPrjctCd: '',
|
surveyPrjctCd: '',
|
||||||
surveyUrl: '',
|
surveyUrl: '',
|
||||||
surveyFullUrl: null,
|
surveyFullUrl: null,
|
||||||
surveyShortUrl: null,
|
|
||||||
surveyDashboardUrl: '',
|
surveyDashboardUrl: '',
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -168,7 +167,6 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
|
|||||||
surveyPrjctCd: '',
|
surveyPrjctCd: '',
|
||||||
surveyUrl: '',
|
surveyUrl: '',
|
||||||
surveyFullUrl: null,
|
surveyFullUrl: null,
|
||||||
surveyShortUrl: null,
|
|
||||||
surveyDashboardUrl: '',
|
surveyDashboardUrl: '',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -178,14 +176,57 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
|
|||||||
surveyPrjctCd: value,
|
surveyPrjctCd: value,
|
||||||
surveyUrl: buildKonKiwiSurveyUrl(survey.surveyTy),
|
surveyUrl: buildKonKiwiSurveyUrl(survey.surveyTy),
|
||||||
surveyFullUrl: null,
|
surveyFullUrl: null,
|
||||||
surveyShortUrl: null,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// KON/KIWI는 호스트 placeholder까지 고정하고 '?' 이후 쿼리스트링만 편집 가능하게 한다.
|
||||||
|
const konKiwiPlaceholderPrefix = survey.surveyTy === SurveyType.KIWI ? 'https://[$KIWI-URL]' : 'https://[$KON-URL]'
|
||||||
|
// 저장 후 surveyUrl의 placeholder가 실제(단축) 호스트로 치환되므로 현재 base를 그대로 접두어로 쓴다.
|
||||||
|
const konKiwiUrlBase = survey.surveyUrl?.trim()
|
||||||
|
? survey.surveyUrl.split('?')[0]
|
||||||
|
: konKiwiPlaceholderPrefix
|
||||||
|
const konKiwiQuery = (() => {
|
||||||
|
const url = survey.surveyUrl ?? ''
|
||||||
|
const idx = url.indexOf('?')
|
||||||
|
return idx >= 0 ? url.slice(idx + 1) : ''
|
||||||
|
})()
|
||||||
|
|
||||||
|
const handleKonKiwiQueryChange = (nextQuery: string) => {
|
||||||
|
// 파라미터만 수정: surveyUrl base(단축/placeholder)는 유지하고 뒤 파라미터만 교체한다.
|
||||||
|
const patch: Partial<ProjectSurvey> = {
|
||||||
|
surveyUrl: `${konKiwiUrlBase}?${nextQuery}`,
|
||||||
|
}
|
||||||
|
// surveyFullUrl은 base(psidx 등)는 고정하고, 동일한 파라미터 꼬리만 함께 교체한다.
|
||||||
|
// 파라미터 꼬리를 갖지 않는 값(순수 단축 URL 등)은 건드리지 않는다.
|
||||||
|
const fullUrl = survey.surveyFullUrl
|
||||||
|
if (fullUrl && konKiwiQuery && fullUrl.endsWith(konKiwiQuery)) {
|
||||||
|
patch.surveyFullUrl = fullUrl.slice(0, fullUrl.length - konKiwiQuery.length) + nextQuery
|
||||||
|
}
|
||||||
|
onChange(survey.uiKey, patch)
|
||||||
|
}
|
||||||
|
|
||||||
|
const [copiedField, setCopiedField] = useState<'url' | 'fullUrl' | null>(null)
|
||||||
|
const copyToClipboard = async (value: string | null | undefined, field: 'url' | 'fullUrl') => {
|
||||||
|
const text = value?.trim() ?? ''
|
||||||
|
if (!text) return
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text)
|
||||||
|
setCopiedField(field)
|
||||||
|
setTimeout(() => setCopiedField((prev) => (prev === field ? null : prev)), 1500)
|
||||||
|
} catch {
|
||||||
|
// 클립보드 접근 실패 시 무시
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-3 rounded-lg border p-4">
|
<div className="space-y-3 rounded-lg border p-4">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<p className="text-base font-semibold">설문 {index + 1}</p>
|
<p className="text-base font-semibold">설문 {index + 1}</p>
|
||||||
|
<span className="text-sm font-semibold ">
|
||||||
|
(설문 번호: {survey.prjctSurveyIdx ?? '미발급'})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<Button type="button" variant="ghost" size="icon-sm" onClick={() => onRemove(survey.uiKey)} aria-label="설문 삭제">
|
<Button type="button" variant="ghost" size="icon-sm" onClick={() => onRemove(survey.uiKey)} aria-label="설문 삭제">
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -238,23 +279,60 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
|
|||||||
heightClassName="h-9"
|
heightClassName="h-9"
|
||||||
widthClassName="w-full"
|
widthClassName="w-full"
|
||||||
/>
|
/>
|
||||||
|
{kartProjectListQuery.isError && (
|
||||||
|
<div role="alert" className="flex items-center gap-2 text-destructive">
|
||||||
|
<span>프로젝트 목록을 불러오지 못했습니다.</span>
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => void kartProjectListQuery.refetch()}>
|
||||||
|
다시 시도
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<Label className="text-base">설문 URL</Label>
|
<Label className="text-base">설문 URL</Label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isKonKiwi ? (
|
||||||
|
<div className="flex flex-1 items-center">
|
||||||
|
<span className="inline-flex h-9 items-center whitespace-nowrap rounded-l-md border border-r-0 bg-gray-100 px-3 text-sm text-muted-foreground">
|
||||||
|
{konKiwiUrlBase}?
|
||||||
|
</span>
|
||||||
|
<Input
|
||||||
|
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
|
||||||
|
value={konKiwiQuery}
|
||||||
|
onChange={(e) => handleKonKiwiQueryChange(e.target.value)}
|
||||||
|
placeholder="sid=[$SID]"
|
||||||
|
className="h-9 rounded-l-none"
|
||||||
|
aria-invalid={invalidField === 'surveyUrl'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
<Input
|
<Input
|
||||||
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
|
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
|
||||||
value={survey.surveyUrl || ''}
|
value={survey.surveyUrl || ''}
|
||||||
onChange={(e) => onChange(survey.uiKey, {
|
onChange={(e) => onChange(survey.uiKey, {
|
||||||
surveyUrl: e.target.value,
|
surveyUrl: e.target.value,
|
||||||
surveyFullUrl: null,
|
surveyFullUrl: null,
|
||||||
surveyShortUrl: null,
|
|
||||||
})}
|
})}
|
||||||
placeholder="https://"
|
placeholder="https://"
|
||||||
className="h-9"
|
className="h-9 flex-1"
|
||||||
aria-invalid={invalidField === 'surveyUrl'}
|
aria-invalid={invalidField === 'surveyUrl'}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => copyToClipboard(survey.surveyUrl, 'url')}
|
||||||
|
disabled={!survey.surveyUrl?.trim()}
|
||||||
|
aria-label="설문 URL 복사"
|
||||||
|
className="h-9 w-9 shrink-0 p-0"
|
||||||
|
>
|
||||||
|
{copiedField === 'url' ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{survey.surveyTy === SurveyType.EXTERNAL && (
|
{survey.surveyTy === SurveyType.EXTERNAL && (
|
||||||
@@ -374,7 +452,7 @@ const ProjectInfoPage = () => {
|
|||||||
|
|
||||||
const updateMutation = useUpdateProjectMutation(prjctIdx);
|
const updateMutation = useUpdateProjectMutation(prjctIdx);
|
||||||
const deleteMutation = useDeleteProjectMutation(prjctIdx);
|
const deleteMutation = useDeleteProjectMutation(prjctIdx);
|
||||||
const uploadScenarioMutation = useUploadScenarioImageMutation(prjctIdx, projectInfo.prjctCd);
|
const uploadScenarioMutation = useUploadScenarioImageMutation(projectInfo.prjctCd);
|
||||||
|
|
||||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
||||||
const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
|
const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
|
||||||
@@ -710,7 +788,9 @@ const ProjectInfoPage = () => {
|
|||||||
|
|
||||||
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h3 className="text-xl font-semibold">설문 연동</h3>
|
<div className="flex items-center gap-4">
|
||||||
|
<h3 className="shrink-0 text-xl font-semibold">설문 연동</h3>
|
||||||
|
</div>
|
||||||
<Button type="button" variant="outline" onClick={handleAddSurvey}>
|
<Button type="button" variant="outline" onClick={handleAddSurvey}>
|
||||||
설문 추가
|
설문 추가
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -9,17 +9,25 @@ import {useRouter} from "next/navigation";
|
|||||||
import {apiError} from "@kri/common/http";
|
import {apiError} from "@kri/common/http";
|
||||||
import {NONE_HTTP_ERROR} from "@kri/common/http";
|
import {NONE_HTTP_ERROR} from "@kri/common/http";
|
||||||
import {useLoginMutation} from "@/query/auth";
|
import {useLoginMutation} from "@/query/auth";
|
||||||
|
import {useInternalInfoQuery} from "@/query/internal";
|
||||||
|
import {cn} from "@/lib/utils";
|
||||||
|
|
||||||
const LoginPage = () => {
|
const LoginPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const loginMutation = useLoginMutation();
|
const loginMutation = useLoginMutation();
|
||||||
|
const internalInfoQuery = useInternalInfoQuery(true);
|
||||||
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const [userId, setUserId] = useState<string>("");
|
const [userId, setUserId] = useState<string>("");
|
||||||
const [userPw, setUserPw] = useState<string>("");
|
const [userPw, setUserPw] = useState<string>("");
|
||||||
|
|
||||||
|
const clientIp = internalInfoQuery.data?.clientIp || "";
|
||||||
|
const clientId = internalInfoQuery.data?.clientId || "";
|
||||||
|
const isCallSeat = clientIp.startsWith("10.10.15");
|
||||||
|
const isCallSeatAndUnable = isCallSeat && clientId === "";
|
||||||
|
|
||||||
const passwordInputRef = useRef<HTMLInputElement | null>(null);
|
const passwordInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
const tryLogin = async () => {
|
const tryLogin = async () => {
|
||||||
@@ -107,7 +115,12 @@ const LoginPage = () => {
|
|||||||
ref={passwordInputRef}
|
ref={passwordInputRef}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<p className="text-base">
|
||||||
|
IP: {clientIp}
|
||||||
|
</p>
|
||||||
|
<p className={cn("text-base", isCallSeatAndUnable && "font-bold text-red-500")}>
|
||||||
|
{isCallSeatAndUnable? "전화걸기 이용 불가(관리자에게 문의해 주세요)" : `자리번호: ${clientId}`}
|
||||||
|
</p>
|
||||||
{error && (
|
{error && (
|
||||||
<p className="text-sm text-red-500">
|
<p className="text-sm text-red-500">
|
||||||
{error}
|
{error}
|
||||||
@@ -116,7 +129,7 @@ const LoginPage = () => {
|
|||||||
|
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="w-full mt-6 h-11"
|
className="w-full mt-3 h-11"
|
||||||
disabled={loginMutation.isPending}
|
disabled={loginMutation.isPending}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -14,10 +14,8 @@ const toRedirectSlug = (slug: string): RedirectSlug | null => {
|
|||||||
|
|
||||||
const redirectPage = async ({
|
const redirectPage = async ({
|
||||||
params,
|
params,
|
||||||
searchParams,
|
|
||||||
}: redirectPageProps) => {
|
}: redirectPageProps) => {
|
||||||
const { slug } = await params;
|
const { slug } = await params;
|
||||||
const sp = searchParams ? await searchParams : undefined;
|
|
||||||
const redirectSlug = toRedirectSlug(slug);
|
const redirectSlug = toRedirectSlug(slug);
|
||||||
|
|
||||||
if (!redirectSlug) notFound();
|
if (!redirectSlug) notFound();
|
||||||
|
|||||||
@@ -64,37 +64,6 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return new NextResponse(null, { status: 204 });
|
return new NextResponse(null, { status: 204 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (action === "list" && slug.length === 3) {
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
if (!body) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ message: "요청 바디가 없습니다." },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await contactApi.put<number>(`/assign/list/${slug[1]}/${slug[2]}`, body);
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
|
||||||
} catch (error: unknown) {
|
|
||||||
return errorToResponse(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
|
||||||
try {
|
|
||||||
const { slug = [] } = await context.params;
|
|
||||||
const [action] = slug;
|
|
||||||
const contactApi = await createContactApi();
|
|
||||||
|
|
||||||
if (action === "list" && slug[1] === "reset" && slug.length === 3) {
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
const result = await contactApi.del<number>(`/assign/list/reset/${slug[2]}`, { json: body });
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
|
|||||||
22
src/app/api/auth/[[...slug]]/route.ts
Normal file
22
src/app/api/auth/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { errorToResponse } from "@kri/common/http";
|
||||||
|
import { createContactApi } from "@/lib/http-server";
|
||||||
|
import {isLoginUser} from "@/lib/auth-user";
|
||||||
|
|
||||||
|
export async function GET(_request: Request, context: { params: Promise<{ slug?: string[] }> }) {
|
||||||
|
const { slug = [] } = await context.params;
|
||||||
|
if (slug.length !== 1 || slug[0] !== "my-info")
|
||||||
|
return NextResponse.json({ message: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||||
|
try {
|
||||||
|
const api = await createContactApi();
|
||||||
|
const user = await api.get<unknown>("/auth/my-info", { cache: "no-store" });
|
||||||
|
if (!isLoginUser(user)) {
|
||||||
|
return NextResponse.json({ message: "Invalid user response" }, { status: 502, headers: { "Cache-Control": "no-store" } });
|
||||||
|
}
|
||||||
|
return NextResponse.json({ userId: user.userId, userName: user.userName, userCmpn: user.userCmpn, userTeam: user.userTeam, userRole: user.userRole }, { headers: { "Cache-Control": "no-store" } });
|
||||||
|
} catch (error) {
|
||||||
|
const response = errorToResponse(error);
|
||||||
|
response.headers.set("Cache-Control", "no-store");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import {NextRequest, NextResponse} from "next/server";
|
import {NextRequest, NextResponse} from "next/server";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createKartApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {KonKiwiProjectInfo} from "@/types/project";
|
import {KonKiwiProjectInfo} from "@/types/project";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
|
|
||||||
@@ -9,32 +9,19 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
const kartApi = await createKartApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if(action === "project-list" && slug.length === 4){
|
if(action === "project-list" && slug.length === 3){
|
||||||
const keyword = (searchParams.get("keyword") ?? "").trim();
|
const keyword = (searchParams.get("keyword") ?? "").trim();
|
||||||
const result = await kartApi.get<KonKiwiProjectInfo[]>(
|
const [, intranetCode, projectType] = slug;
|
||||||
`/project/list/${slug[1]}/${slug[2]}/${slug[3]}`,
|
if (!intranetCode.trim() || intranetCode.length > 32 || !["0", "1"].includes(projectType)) {
|
||||||
{ query: keyword ? { keyword } : {} }
|
return NextResponse.json({ message: "프로젝트 정보를 확인해 주세요." }, { status: 400 });
|
||||||
);
|
|
||||||
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
}
|
}
|
||||||
|
const result = await contactApi.get<KonKiwiProjectInfo[]>(`/kart/project/list`, {
|
||||||
if(action === "survey-redirect-url" && slug.length === 3){
|
query: { intranetCode, projectType, ...(keyword ? { keyword } : {}) },
|
||||||
const [, isKiwi, pkey] = slug;
|
|
||||||
|
|
||||||
const skey = await kartApi.get<string>(`/encrypt/pkey`, {
|
|
||||||
headers: { pkey, iskiwi: isKiwi },
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const shortUrl = await kartApi.post<string>(
|
return NextResponse.json(result, { status: 200 });
|
||||||
`/uri/short`,
|
|
||||||
{ realURI: "/Report/Current", mode: "U" },
|
|
||||||
{ headers: { skey } },
|
|
||||||
);
|
|
||||||
|
|
||||||
return NextResponse.json(shortUrl, { status: 200 });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
|
|||||||
@@ -2,25 +2,7 @@ import {NextRequest, NextResponse} from "next/server";
|
|||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createContactApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import type {ListCallHist, ListCallHistSession} from "@/types/list";
|
import type {ListCallHist} from "@/types/list";
|
||||||
|
|
||||||
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
|
||||||
try {
|
|
||||||
const { slug = [] } = await context.params;
|
|
||||||
const [action, agentSessionId] = slug;
|
|
||||||
if (action !== "session" || !agentSessionId) {
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const contactApi = await createContactApi();
|
|
||||||
const result = await contactApi.get<ListCallHistSession>(
|
|
||||||
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
|
|
||||||
);
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
} catch (error: unknown) {
|
|
||||||
return errorToResponse(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
@@ -45,21 +27,3 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PATCH = async (_req: NextRequest, context: RouteContext) => {
|
|
||||||
try {
|
|
||||||
const { slug = [] } = await context.params;
|
|
||||||
const [action, agentSessionId] = slug;
|
|
||||||
if (action !== "hangup" || !agentSessionId) {
|
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const contactApi = await createContactApi();
|
|
||||||
const result = await contactApi.patch<boolean>(
|
|
||||||
`/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`,
|
|
||||||
);
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
} catch (error: unknown) {
|
|
||||||
return errorToResponse(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import {createContactApi} from "@/lib/http-server";
|
|||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import type {ListEventHistory, ListUpdateHistory} from "@/types/list";
|
import type {ListEventHistory, ListUpdateHistory} from "@/types/list";
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
@@ -30,7 +30,7 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
export const DELETE = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
|
|||||||
59
src/app/api/list-jobs/[[...slug]]/route.ts
Normal file
59
src/app/api/list-jobs/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { cookies } from 'next/headers'
|
||||||
|
import { errorToResponse } from '@kri/common/http'
|
||||||
|
import { createContactApi } from '@/lib/http-server'
|
||||||
|
import { serverEnv } from '@/lib/env.server'
|
||||||
|
import { CookieKeys } from '@/store/cookie/cookie-keys'
|
||||||
|
import type { RouteContext } from '@/types/common'
|
||||||
|
|
||||||
|
const project = '[1-9][0-9]*'
|
||||||
|
const key = '[a-f0-9]{32}'
|
||||||
|
const getPath = new RegExp(`^${project}/(?:availability|upload-reset-active|my-active|${key}(?:/(?:sid-failures|range-failures|validation-errors|source-file|files/[0-9]+|message-report/(?:batches|preparation-failures)))?)$`)
|
||||||
|
const postPath = new RegExp(`^${project}/(?:upload|reset|${key}/cancel|mutations/(?:update|assign-reset|assign/[^/]+)|downloads/(?:list|event-history|update-history|item-files)|messages/(?:email|sms|kko))$`)
|
||||||
|
|
||||||
|
// The shared HTTP client decodes binary bodies. Forward file bodies as streams instead.
|
||||||
|
async function forwardFile(req: NextRequest, path: string) {
|
||||||
|
const token = (await cookies()).get(CookieKeys.AuthToken)?.value
|
||||||
|
if (!token) return NextResponse.json({ message: '로그인이 필요합니다.' }, { status: 401 })
|
||||||
|
const headers = new Headers({ Authorization: `Bearer ${token}` })
|
||||||
|
if (req.method === 'POST') {
|
||||||
|
const type = req.headers.get('content-type')
|
||||||
|
if (!type?.startsWith('multipart/form-data;')) return NextResponse.json({ message: '파일 요청 형식이 올바르지 않습니다.' }, { status: 400 })
|
||||||
|
headers.set('Content-Type', type)
|
||||||
|
}
|
||||||
|
const options: RequestInit & { duplex?: 'half' } = {
|
||||||
|
method: req.method, headers, cache: 'no-store', redirect: 'error',
|
||||||
|
signal: AbortSignal.any([req.signal, AbortSignal.timeout(300_000)]),
|
||||||
|
...(req.method === 'POST' ? { body: req.body, duplex: 'half' as const } : {}),
|
||||||
|
}
|
||||||
|
const upstream = await fetch(`${serverEnv.API_CONTACT_SERVER.replace(/\/$/, '')}/list/jobs/${path}`, options)
|
||||||
|
const responseHeaders = new Headers({ 'Cache-Control': 'no-store' })
|
||||||
|
for (const name of ['Content-Type', 'Content-Disposition', 'Content-Length']) {
|
||||||
|
const value = upstream.headers.get(name)
|
||||||
|
if (value) responseHeaders.set(name, value)
|
||||||
|
}
|
||||||
|
return new NextResponse(upstream.body, { status: upstream.status, headers: responseHeaders })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function proxy(req: NextRequest, context: RouteContext) {
|
||||||
|
try {
|
||||||
|
const { slug = [] } = await context.params
|
||||||
|
const path = slug.map(encodeURIComponent).join('/')
|
||||||
|
if (!(req.method === 'GET' ? getPath : postPath).test(path)) return NextResponse.json({ message: '지원하지 않는 작업 경로입니다.' }, { status: 404 })
|
||||||
|
if (/\/(source-file|files\/[0-9]+|upload)$/.test(path)) return await forwardFile(req, path)
|
||||||
|
const query = new URLSearchParams()
|
||||||
|
for (const name of ['offset', 'limit', 'includeResult', 'jobType']) {
|
||||||
|
const value = req.nextUrl.searchParams.get(name)
|
||||||
|
if (value !== null) query.set(name, value)
|
||||||
|
}
|
||||||
|
const url = `/list/jobs/${path}${query.size ? `?${query}` : ''}`
|
||||||
|
const api = await createContactApi()
|
||||||
|
const value = req.method === 'GET'
|
||||||
|
? await api.get(url, { cache: 'no-store' })
|
||||||
|
: await api.post(url, await req.json().catch(() => undefined))
|
||||||
|
return NextResponse.json(value, { headers: { 'Cache-Control': 'no-store' } })
|
||||||
|
} catch (error: unknown) { return errorToResponse(error) }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET = proxy
|
||||||
|
export const POST = proxy
|
||||||
@@ -9,7 +9,7 @@ const excelHeaders = {
|
|||||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
};
|
};
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
@@ -100,42 +100,6 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return new NextResponse(null, { status: 204 });
|
return new NextResponse(null, { status: 204 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (action === "excel-upload") {
|
|
||||||
const form = await req.formData();
|
|
||||||
const result = await contactApi.postForm(`/list/excel/upload/${slug[1]}`, form);
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "excel-download") {
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
const result = await contactApi.post<ArrayBuffer>(`/list/excel/download/${slug[1]}`, body, { expectBinary: true });
|
|
||||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "excel-download-update") {
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
const result = await contactApi.post<ArrayBuffer>(`/list/excel/download/update/${slug[1]}`, body, {
|
|
||||||
expectBinary: true,
|
|
||||||
});
|
|
||||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "event-history-download") {
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
const result = await contactApi.post<ArrayBuffer>(`/list-hist/excel/download/event/${slug[1]}`, body, {
|
|
||||||
expectBinary: true,
|
|
||||||
});
|
|
||||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "item-file-download") {
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
const result = await contactApi.post<ArrayBuffer>(`/list/item-file/download/${slug[1]}`, body, {
|
|
||||||
expectBinary: true,
|
|
||||||
});
|
|
||||||
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/zip" } });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "upload-history-file") {
|
if (action === "upload-history-file") {
|
||||||
const result = await contactApi.post<ArrayBuffer>(
|
const result = await contactApi.post<ArrayBuffer>(
|
||||||
`/list/excel/upload-history/file/${slug[1]}/${slug[2]}`,
|
`/list/excel/upload-history/file/${slug[1]}/${slug[2]}`,
|
||||||
@@ -173,15 +137,3 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
|
||||||
try {
|
|
||||||
const { slug = [] } = await context.params;
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
const contactApi = await createContactApi();
|
|
||||||
const result = await contactApi.del<number>(`/list/${slug[0]}`, { json: body });
|
|
||||||
return NextResponse.json(result, { status: 200 });
|
|
||||||
} catch (error: unknown) {
|
|
||||||
return errorToResponse(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import type { LoginRequest, LoginUser } from "@kri/common";
|
import type { LoginRequest, LoginUser } from "@kri/common";
|
||||||
import {serverEnv} from "@/lib/env.server";
|
import {setAuthCookie} from "@/lib/auth-cookie";
|
||||||
import {createContactApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
|
||||||
|
|
||||||
//?ㅼ젣 Backend
|
//?ㅼ젣 Backend
|
||||||
type LoginResponse = {
|
type LoginResponse = {
|
||||||
@@ -19,13 +18,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
const result = await contactApi.post<LoginResponse>("/auth/login", body);
|
const result = await contactApi.post<LoginResponse>("/auth/login", body);
|
||||||
|
|
||||||
const res = NextResponse.json(result.user, { status: 200 });
|
const res = NextResponse.json(result.user, { status: 200 });
|
||||||
res.cookies.set(CookieKeys.AuthToken, result.accessToken, {
|
setAuthCookie(res, result.accessToken);
|
||||||
httpOnly: true,
|
|
||||||
secure: serverEnv.ENV === "prod",
|
|
||||||
sameSite: "lax",
|
|
||||||
path: "/",
|
|
||||||
maxAge: 24 * 60 * 60, // 24?쒓컙
|
|
||||||
});
|
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
} catch (error : unknown) {
|
} catch (error : unknown) {
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import {serverEnv} from "@/lib/env.server";
|
import {setAuthCookie} from "@/lib/auth-cookie";
|
||||||
import {createContactApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
_req: NextRequest,
|
||||||
context: RouteContext
|
context: RouteContext
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
@@ -22,13 +21,7 @@ export async function POST(
|
|||||||
await contactApi.post<boolean>(url);
|
await contactApi.post<boolean>(url);
|
||||||
const res = NextResponse.json({ ok: true });
|
const res = NextResponse.json({ ok: true });
|
||||||
|
|
||||||
res.cookies.set(CookieKeys.AuthToken, "", {
|
setAuthCookie(res, "");
|
||||||
httpOnly: true,
|
|
||||||
secure: serverEnv.ENV === "prod",
|
|
||||||
sameSite: "lax",
|
|
||||||
path: "/",
|
|
||||||
maxAge: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
|
|||||||
@@ -1,20 +1,19 @@
|
|||||||
import {NextRequest, NextResponse} from "next/server";
|
import {NextRequest, NextResponse} from "next/server";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createNotihubApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import type {FileResponse, PageRequest, PageResponse} from "@kri/common";
|
import type {FileResponse, PageRequest, PageResponse} from "@kri/common";
|
||||||
import type {BulkSendInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
|
import type {BulkSendInfo, SendResultInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
|
||||||
import type {SendResultInfo} from "@/types/message";
|
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action, sendTy, reqstSvc, prjctCd] = slug;
|
const [action, sendTy, reqstSvc, prjctCd] = slug;
|
||||||
const notihubApi = await createNotihubApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
|
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
|
||||||
const result = await notihubApi.get<BulkSendInfo[]>(
|
const result = await contactApi.get<BulkSendInfo[]>(
|
||||||
`/report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
|
`/message-report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, {status: 200});
|
return NextResponse.json(result, {status: 200});
|
||||||
}
|
}
|
||||||
@@ -23,8 +22,8 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
const [, sid, prjctCdParam, reqstSvcParam] = slug;
|
const [, sid, prjctCdParam, reqstSvcParam] = slug;
|
||||||
const channelTy = req.nextUrl.searchParams.get("channelTy");
|
const channelTy = req.nextUrl.searchParams.get("channelTy");
|
||||||
const query = channelTy ? `?channelTy=${channelTy}` : "";
|
const query = channelTy ? `?channelTy=${channelTy}` : "";
|
||||||
const result = await notihubApi.get<SendResultInfo[]>(
|
const result = await contactApi.get<SendResultInfo[]>(
|
||||||
`/report/send-result/${encodeURIComponent(sid)}/${prjctCdParam}/${reqstSvcParam}${query}`,
|
`/message-report/send-result/${encodeURIComponent(sid)}/${prjctCdParam}/${reqstSvcParam}${query}`,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, {status: 200});
|
return NextResponse.json(result, {status: 200});
|
||||||
}
|
}
|
||||||
@@ -39,7 +38,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
|||||||
try {
|
try {
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action, bulkSendKey] = slug;
|
const [action, bulkSendKey] = slug;
|
||||||
const notihubApi = await createNotihubApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if (action === "bulk-detail" && bulkSendKey) {
|
if (action === "bulk-detail" && bulkSendKey) {
|
||||||
const body: PageRequest | null = await req.json().catch(() => null);
|
const body: PageRequest | null = await req.json().catch(() => null);
|
||||||
@@ -47,16 +46,16 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.post<PageResponse<SendResultInfo>>(
|
const result = await contactApi.post<PageResponse<SendResultInfo>>(
|
||||||
`/report/bulk-detail/${bulkSendKey}`,
|
`/message-report/bulk-detail/${bulkSendKey}`,
|
||||||
body,
|
body,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, {status: 200});
|
return NextResponse.json(result, {status: 200});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (action === "bulk-detail-excel" && bulkSendKey) {
|
if (action === "bulk-detail-excel" && bulkSendKey) {
|
||||||
const result = await notihubApi.post<FileResponse>(
|
const result = await contactApi.post<FileResponse>(
|
||||||
`/report/bulk-detail/excel/${bulkSendKey}`,
|
`/message-report/bulk-detail-excel/${bulkSendKey}`,
|
||||||
undefined,
|
undefined,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, {status: 200});
|
return NextResponse.json(result, {status: 200});
|
||||||
@@ -68,8 +67,8 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.post<SendResultSummaryResponse[]>(
|
const result = await contactApi.post<SendResultSummaryResponse[]>(
|
||||||
`/report/send-result-summary`,
|
`/message-report/send-result-summary`,
|
||||||
body,
|
body,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, {status: 200});
|
return NextResponse.json(result, {status: 200});
|
||||||
|
|||||||
65
src/app/api/message-send/[[...slug]]/route.ts
Normal file
65
src/app/api/message-send/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import {NextRequest, NextResponse} from "next/server";
|
||||||
|
import {RouteContext} from "@/types/common";
|
||||||
|
import {createContactApi} from "@/lib/http-server";
|
||||||
|
import {errorToResponse} from "@kri/common/http";
|
||||||
|
import type {SendCancelResponse} from "@kri/common/noti-hub";
|
||||||
|
import type {MessageSendChannel, SendSingleResponse} from "@/types/message";
|
||||||
|
|
||||||
|
const isChannel = (value: string): value is MessageSendChannel =>
|
||||||
|
value === "sms" || value === "email" || value === "kko";
|
||||||
|
|
||||||
|
const BULK_SEND_KEY_MAX_LENGTH = 32;
|
||||||
|
|
||||||
|
const readCancelBody = (body: unknown, target: string): Record<string, number | string> | null => {
|
||||||
|
if (!body || typeof body !== "object") return null;
|
||||||
|
if (target === "single") {
|
||||||
|
const sendIdx = (body as {sendIdx?: unknown}).sendIdx;
|
||||||
|
return typeof sendIdx === "number" && Number.isSafeInteger(sendIdx) && sendIdx > 0 ? {sendIdx} : null;
|
||||||
|
}
|
||||||
|
if (target === "bulk") {
|
||||||
|
const bulkSendKey = (body as {bulkSendKey?: unknown}).bulkSendKey;
|
||||||
|
return typeof bulkSendKey === "string" && bulkSendKey.trim() !== "" && bulkSendKey.length <= BULK_SEND_KEY_MAX_LENGTH
|
||||||
|
? {bulkSendKey}
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||||
|
try {
|
||||||
|
const {slug = []} = await context.params;
|
||||||
|
const [channel, action, prjctIdx] = slug;
|
||||||
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
|
// 예약 취소 (POST /message-send/cancel/{single|bulk}). 채널 구분 없이 공통 API를 사용한다.
|
||||||
|
if (channel === "cancel") {
|
||||||
|
if (action !== "single" && action !== "bulk") {
|
||||||
|
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||||
|
}
|
||||||
|
const cancelBody = readCancelBody(await req.json().catch(() => null), action);
|
||||||
|
if (!cancelBody) {
|
||||||
|
return NextResponse.json({message: "취소 요청 값이 올바르지 않습니다."}, {status: 400});
|
||||||
|
}
|
||||||
|
const result = await contactApi.post<SendCancelResponse>(`/message-send/cancel/${action}`, cancelBody);
|
||||||
|
return NextResponse.json(result, {status: 200});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isChannel(channel) || !prjctIdx) {
|
||||||
|
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
if (!body) {
|
||||||
|
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action === "single") {
|
||||||
|
const result = await contactApi.post<SendSingleResponse>(`/message-send/${channel}/single/${prjctIdx}`, body);
|
||||||
|
return NextResponse.json(result, {status: 200});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return errorToResponse(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,15 +1,45 @@
|
|||||||
import {NextRequest, NextResponse} from "next/server";
|
import {NextRequest, NextResponse} from "next/server";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createNotihubApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import type { Template, TemplateSummary } from "@kri/common/noti-hub";
|
import type { KkoSenderProfile } from "@/types/message";
|
||||||
|
import type { KkoTemplateDetail, KkoTemplateListResponse, Template, TemplateSummary } from "@kri/common/noti-hub";
|
||||||
|
|
||||||
|
// 외부 알림톡 템플릿 목록·상세 조회. JSON 본문을 contact-back에 그대로 전달한다.
|
||||||
|
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||||
|
try{
|
||||||
|
const {slug = []} = await context.params;
|
||||||
|
const [channel, action] = slug;
|
||||||
|
if (channel !== "kko" || slug.length !== 2 || (action !== "list" && action !== "detail")) {
|
||||||
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
if (!body || typeof body !== "object") {
|
||||||
|
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const contactApi = await createContactApi();
|
||||||
|
const result = action === "list"
|
||||||
|
? await contactApi.post<KkoTemplateListResponse>(`/message-template/kko/list`, body)
|
||||||
|
: await contactApi.post<KkoTemplateDetail>(`/message-template/kko/detail`, body);
|
||||||
|
return NextResponse.json(result, { status: 200 });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return errorToResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||||
try{
|
try{
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
const notihubApi = await createNotihubApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
|
if (slug.length === 2 && action === "kko" && slug[1] === "profiles") {
|
||||||
|
const result = await contactApi.get<KkoSenderProfile[]>(`/message-template/kko/profiles`);
|
||||||
|
return NextResponse.json(result, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
if(slug.length === 2 && slug[1] === "attachment"){
|
if(slug.length === 2 && slug[1] === "attachment"){
|
||||||
const fileName = searchParams.get("fileName");
|
const fileName = searchParams.get("fileName");
|
||||||
@@ -17,23 +47,23 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return NextResponse.json({ message: "fileName은 필수입니다." }, { status: 400 });
|
return NextResponse.json({ message: "fileName은 필수입니다." }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.get<ArrayBuffer>(
|
const result = await contactApi.get<ArrayBuffer>(
|
||||||
`/template/${slug[0]}/attachment?fileName=${encodeURIComponent(fileName)}`,
|
`/message-template/${slug[0]}/attachment?fileName=${encodeURIComponent(fileName)}`,
|
||||||
{ expectBinary: true },
|
{ expectBinary: true },
|
||||||
);
|
);
|
||||||
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/octet-stream" } });
|
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/octet-stream" } });
|
||||||
}
|
}
|
||||||
|
|
||||||
if(slug.length === 1){
|
if(slug.length === 1){
|
||||||
const result = await notihubApi.get<Template>(
|
const result = await contactApi.get<Template>(
|
||||||
`/template/${slug[0]}`,
|
`/message-template/${slug[0]}`,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if(action === "list" && slug.length === 3){
|
if(action === "list" && slug.length === 3){
|
||||||
const result = await notihubApi.get<TemplateSummary[]>(
|
const result = await contactApi.get<TemplateSummary[]>(
|
||||||
`/template/list/${slug[1]}/${slug[2]}`,
|
`/message-template/list/${slug[1]}/${slug[2]}`,
|
||||||
);
|
);
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
@@ -46,10 +76,9 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
|
|
||||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||||
try{
|
try{
|
||||||
const { searchParams } = new URL(req.url);
|
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
const notihubApi = await createNotihubApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if(action === "body-image" && slug.length === 2){
|
if(action === "body-image" && slug.length === 2){
|
||||||
const itrntPrjctCd = slug[1];
|
const itrntPrjctCd = slug[1];
|
||||||
@@ -64,8 +93,8 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.putForm<string>(
|
const result = await contactApi.putForm<string>(
|
||||||
`/template/body-image/${itrntPrjctCd}`,
|
`/message-template/body-image/${itrntPrjctCd}`,
|
||||||
formData
|
formData
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -81,7 +110,7 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.putForm<Template>(`/template`, formData);
|
const result = await contactApi.putForm<Template>(`/message-template`, formData);
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,10 +122,9 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
|||||||
|
|
||||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||||
try{
|
try{
|
||||||
const { searchParams } = new URL(req.url);
|
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
const notihubApi = await createNotihubApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if(!action){
|
if(!action){
|
||||||
const formData = await req.formData().catch(() => null);
|
const formData = await req.formData().catch(() => null);
|
||||||
@@ -107,7 +135,7 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.request<Template>(`/template`, { method: "PATCH", form: formData });
|
const result = await contactApi.request<Template>(`/message-template`, { method: "PATCH", form: formData });
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,3 +144,20 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
|||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 템플릿 삭제. 성공 응답은 빈 body이므로 JSON으로 파싱하지 않는다.
|
||||||
|
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||||
|
try{
|
||||||
|
const {slug = []} = await context.params;
|
||||||
|
const [tmplatIdx] = slug;
|
||||||
|
if (slug.length !== 1 || !/^[1-9]\d*$/.test(tmplatIdx)) {
|
||||||
|
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const contactApi = await createContactApi();
|
||||||
|
await contactApi.del(`/message-template/${tmplatIdx}`, { expectText: true });
|
||||||
|
return new NextResponse(null, { status: 204 });
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return errorToResponse(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
import {NextRequest, NextResponse} from "next/server";
|
|
||||||
import {RouteContext} from "@/types/common";
|
|
||||||
import {createContactApi} from "@/lib/http-server";
|
|
||||||
import {errorToResponse} from "@kri/common/http";
|
|
||||||
import type {MessageBulkSendResponse} from "@/types/message";
|
|
||||||
|
|
||||||
const isChannel = (value: string): value is "sms" | "email" => value === "sms" || value === "email";
|
|
||||||
|
|
||||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
|
||||||
try {
|
|
||||||
const {slug = []} = await context.params;
|
|
||||||
const [channel, action, prjctIdx] = slug;
|
|
||||||
const contactApi = await createContactApi();
|
|
||||||
|
|
||||||
if (!isChannel(channel) || !prjctIdx) {
|
|
||||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await req.json().catch(() => null);
|
|
||||||
if (!body) {
|
|
||||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "single") {
|
|
||||||
await contactApi.post(`/message/${channel}/single/${prjctIdx}`, body);
|
|
||||||
return new NextResponse(null, {status: 204});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (action === "bulk") {
|
|
||||||
const result = await contactApi.post<MessageBulkSendResponse>(`/message/${channel}/bulk/${prjctIdx}`, body);
|
|
||||||
return NextResponse.json(result, {status: 200});
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
|
||||||
} catch (error: unknown) {
|
|
||||||
return errorToResponse(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import {NextRequest, NextResponse} from "next/server";
|
import {NextRequest, NextResponse} from "next/server";
|
||||||
import {createContactApi, createIntranetApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import type {PageResponse} from "@kri/common";
|
import type {PageResponse} from "@kri/common";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
@@ -172,10 +172,9 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
export const DELETE = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
|
||||||
const contactApi = await createContactApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if(slug.length === 1){
|
if(slug.length === 1){
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
export const PUT = async (req: NextRequest) => {
|
||||||
try {
|
try {
|
||||||
const body = await req.json().catch(() => null);
|
const body = await req.json().catch(() => null);
|
||||||
if (!body) {
|
if (!body) {
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
import {NextRequest, NextResponse} from "next/server";
|
import {NextRequest, NextResponse} from "next/server";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createContactApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
|
import {ResultCode} from "@/types/project";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { searchParams } = new URL(req.url);
|
|
||||||
const {slug = []} = await context.params;
|
const {slug = []} = await context.params;
|
||||||
const [action] = slug;
|
|
||||||
const contactApi = await createContactApi();
|
const contactApi = await createContactApi();
|
||||||
|
|
||||||
if(slug.length === 1){
|
if(slug.length === 1){
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import {RoleInfo} from "@/types/role";
|
|||||||
import {errorToResponse} from "@kri/common/http";
|
import {errorToResponse} from "@kri/common/http";
|
||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
|
|
||||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
export const DELETE = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
const [userId] = slug ?? [];
|
const [userId] = slug ?? [];
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
|||||||
import {Geist, Geist_Mono} from "next/font/google";
|
import {Geist, Geist_Mono} from "next/font/google";
|
||||||
import { AppProvider } from "@/components/providers/AppProvider";
|
import { AppProvider } from "@/components/providers/AppProvider";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import {Toaster} from "sonner";
|
import {Toaster} from "@/components/ui/sonner";
|
||||||
|
|
||||||
const geistSans = Geist({
|
const geistSans = Geist({
|
||||||
variable: "--font-geist-sans",
|
variable: "--font-geist-sans",
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { CalendarClock, LogOut, ZoomIn, ZoomOut } from "lucide-react";
|
import { CalendarClock, LogOut, UserRound, ZoomIn, ZoomOut } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { KriHeader } from "@/components/layout/KriHeader";
|
import { KriHeader } from "@/components/layout/KriHeader";
|
||||||
import type { TopMenuItem } from "@/config/menu.types";
|
import type { TopMenuItem } from "@/config/menu.types";
|
||||||
import type { LoginUser } from "@kri/common";
|
import type { LoginUser } from "@kri/common";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useInternalInfoQuery } from "@/query/internal";
|
||||||
|
import { useCtiConnectionStatus } from "@/hooks/useCtiConnectionStatus";
|
||||||
|
|
||||||
interface AppHeaderProps {
|
interface AppHeaderProps {
|
||||||
isMain: boolean;
|
isMain: boolean;
|
||||||
@@ -40,16 +51,24 @@ export function AppHeader({
|
|||||||
increaseFontSize,
|
increaseFontSize,
|
||||||
onOpenReserveSearch,
|
onOpenReserveSearch,
|
||||||
}: AppHeaderProps) {
|
}: AppHeaderProps) {
|
||||||
|
const internalInfoQuery = useInternalInfoQuery(!!userInfo);
|
||||||
|
const seatNo = internalInfoQuery.data?.clientId ?? "";
|
||||||
|
const ctiConnectionStatus = useCtiConnectionStatus();
|
||||||
|
const isCtiConnected = ctiConnectionStatus === "open";
|
||||||
|
|
||||||
|
const showProjectTitle = isViewProjectTitle && !!projectName;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<KriHeader
|
<KriHeader
|
||||||
logo={
|
logo={
|
||||||
<div className="flex h-10 w-20 items-center justify-center">
|
<div className="flex h-10 w-16 items-center justify-center sm:w-20">
|
||||||
<Image
|
<Image
|
||||||
src="/kri_logo.png"
|
src="/kri_logo.png"
|
||||||
alt="KRI 로고"
|
alt="KRI 로고"
|
||||||
width={120}
|
width={120}
|
||||||
height={40}
|
height={40}
|
||||||
className="object-contain"
|
className="h-full w-full object-contain"
|
||||||
priority
|
priority
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -62,33 +81,75 @@ export function AppHeader({
|
|||||||
onToggleMenu={onToggleMenu}
|
onToggleMenu={onToggleMenu}
|
||||||
onNavigate={(path) => {if(!isContactPage) onNavigate(path)}}
|
onNavigate={(path) => {if(!isContactPage) onNavigate(path)}}
|
||||||
className="border-gray-200 bg-white"
|
className="border-gray-200 bg-white"
|
||||||
innerClassName="h-16 px-4"
|
// 모바일(sm 미만)은 헤더 폭이 좁아 로고와 우측 버튼이 겹치지 않도록 간격을 줄인다.
|
||||||
|
innerClassName="h-16 gap-2 px-2 sm:gap-4 sm:px-4"
|
||||||
center={
|
center={
|
||||||
isViewProjectTitle && projectName ? (
|
showProjectTitle ? (
|
||||||
<h1 className="ml-3 text-2xl font-bold">{projectName}</h1>
|
<h1 className="ml-3 hidden truncate text-2xl font-bold lg:block" title={projectName}>{projectName}</h1>
|
||||||
) : null
|
) : null
|
||||||
}
|
}
|
||||||
right={
|
right={
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-1 border-r pr-4">
|
<div className="flex items-center gap-1 border-r pr-2 sm:pr-4">
|
||||||
<Button variant="ghost" size="icon" onClick={decreaseFontSize} title="폰트 작게">
|
<Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={decreaseFontSize} title="폰트 작게">
|
||||||
<ZoomOut className="h-4 w-4" />
|
<ZoomOut className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<span className="min-w-[3rem] text-center text-xs text-gray-500">{fontSize}px</span>
|
<span className="min-w-6 text-center text-xs text-gray-500" title={`글자 크기 ${fontSize}px`}>{fontSize}</span>
|
||||||
<Button variant="ghost" size="icon" onClick={increaseFontSize} title="폰트 크게">
|
<Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={increaseFontSize} title="폰트 크게">
|
||||||
<ZoomIn className="h-4 w-4" />
|
<ZoomIn className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="ghost" size="icon-lg" onClick={onOpenReserveSearch} title="예약 내역 조회">
|
<Button variant="ghost" size="icon-lg" className="size-8 sm:size-10" onClick={onOpenReserveSearch} title="예약 내역 조회">
|
||||||
<CalendarClock className="size-6" />
|
<CalendarClock className="size-6" />
|
||||||
</Button>
|
</Button>
|
||||||
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span>
|
<span className="hidden items-center gap-1.5 text-sm text-gray-600 sm:inline-flex">
|
||||||
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
|
{userInfo?.userName || ""}
|
||||||
|
{seatNo ? (
|
||||||
|
<span className="inline-flex items-center gap-1">
|
||||||
|
{`(${seatNo})`}
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-block h-2 w-2 rounded-full",
|
||||||
|
isCtiConnected ? "bg-green-500" : "bg-red-500",
|
||||||
|
)}
|
||||||
|
title={isCtiConnected ? "CTI 연결됨" : "CTI 연결 안됨"}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
<Button variant="ghost" size="sm" className="hidden gap-2 sm:inline-flex" onClick={() => onNavigate("/logout")}>
|
||||||
<LogOut className="h-4 w-4" />
|
<LogOut className="h-4 w-4" />
|
||||||
<span className="hidden sm:inline">로그아웃</span>
|
<span>로그아웃</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
{/* 모바일(sm 미만)은 헤더 폭이 좁아 이름과 로그아웃을 사용자 메뉴로 묶는다. CTI는 모바일에서 사용하지 않아 표시하지 않는다. */}
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="size-8 sm:hidden" title="사용자 메뉴" aria-label="사용자 메뉴">
|
||||||
|
<UserRound className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
{userInfo?.userName ? (
|
||||||
|
<>
|
||||||
|
<DropdownMenuLabel>{`${userInfo.userName} 님`}</DropdownMenuLabel>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
<DropdownMenuItem onSelect={() => onNavigate("/logout")}>
|
||||||
|
<LogOut className="h-4 w-4" />
|
||||||
|
로그아웃
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
{/* 모바일(lg 미만)은 헤더 공간이 좁아 프로젝트명을 헤더 아래 한 줄로 내려 표시한다. */}
|
||||||
|
{showProjectTitle ? (
|
||||||
|
<div className="border-b border-gray-200 bg-white px-4 py-2 lg:hidden">
|
||||||
|
<h1 className="truncate text-center text-lg font-bold" title={projectName}>{projectName}</h1>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { ReactNode, useEffect, useMemo, useState } from "react";
|
import { ReactNode, useEffect, useMemo, useState } from "react";
|
||||||
import { usePathname, useRouter } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
|
import type { Route } from "next";
|
||||||
import { useMounted } from "@kri/common/hooks";
|
import { useMounted } from "@kri/common/hooks";
|
||||||
import { getCurrentPositionMeta } from "@kri/common/browser";
|
import { getCurrentPositionMeta } from "@kri/common/browser";
|
||||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||||
@@ -16,6 +17,7 @@ import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data"
|
|||||||
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { FONT_SIZE } from "@/const/commonConst";
|
import { FONT_SIZE } from "@/const/commonConst";
|
||||||
|
import { ListJobWatcher } from "@/components/list/ListJobWatcher";
|
||||||
|
|
||||||
type AppMainLayoutProps = {
|
type AppMainLayoutProps = {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -141,7 +143,8 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
});
|
});
|
||||||
|
|
||||||
const movePage = (path: string) => {
|
const movePage = (path: string) => {
|
||||||
router.push(path);
|
// 메뉴 설정(menu.data.ts)의 경로라 typedRoutes가 정적으로 검사할 수 없다.
|
||||||
|
router.push(path as Route);
|
||||||
};
|
};
|
||||||
|
|
||||||
const decreaseFontSize = () => {
|
const decreaseFontSize = () => {
|
||||||
@@ -152,6 +155,11 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
|
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 모바일(lg 미만)에서는 사이드바가 본문을 덮는 오버레이라 메뉴를 접힌 상태로 시작한다.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!window.matchMedia("(min-width: 64rem)").matches) setMenuOpen(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
|
||||||
@@ -193,7 +201,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
bodyClassName={cn(!isMain && isContactPage && "min-h-0")}
|
bodyClassName={cn(!isMain && isContactPage && "min-h-0")}
|
||||||
mainClassName={cn("p-4", "min-h-0")}
|
mainClassName={cn("p-4", "min-h-0")}
|
||||||
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
||||||
sidebarOpen={!isMain && isContactPage && menuOpen}
|
sidebarOpen={!isMain && !isContactPage && menuOpen}
|
||||||
onSidebarOpenChange={setMenuOpen}
|
onSidebarOpenChange={setMenuOpen}
|
||||||
header={
|
header={
|
||||||
<AppHeader
|
<AppHeader
|
||||||
@@ -228,6 +236,7 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
{mounted && auth.user && <ListJobWatcher userId={auth.user.userId} prjctIdx={selectedProject?.prjctIdx ?? 0} />}
|
||||||
<ReserveSearchDialog />
|
<ReserveSearchDialog />
|
||||||
</KriMainLayout>
|
</KriMainLayout>
|
||||||
);
|
);
|
||||||
|
|||||||
19
src/components/app-shell/AuthSessionGate.tsx
Normal file
19
src/components/app-shell/AuthSessionGate.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useAuthSession } from "@/hooks/useAuthSession";
|
||||||
|
|
||||||
|
export function AuthSessionGate({ children }: { children: ReactNode }) {
|
||||||
|
const session = useAuthSession();
|
||||||
|
const user = session.data;
|
||||||
|
const checking = session.isPending || session.isFetching;
|
||||||
|
const identity = user && JSON.stringify([user.userId, user.userRole, user.userTeam, user.userCmpn]);
|
||||||
|
|
||||||
|
return <>
|
||||||
|
{session.isError && !checking && <div role="alert" className="p-8 text-center text-sm">
|
||||||
|
<p>로그인 정보를 확인하지 못했습니다.</p>
|
||||||
|
<button type="button" onClick={() => { void session.refetch(); }}>다시 시도</button>
|
||||||
|
</div>}
|
||||||
|
{user && <div key={identity} hidden={session.isError}>{children}</div>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -124,6 +124,12 @@ export function AssignTargetList({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
<div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||||
|
{summary ? (
|
||||||
|
<div className="shrink-0 border-b border-gray-200 bg-gray-50 px-3 py-1 text-lg font-semibold text-gray-700">
|
||||||
|
전체 {summary.totalCount}건 · 미배정 {summary.unassignedCount}건
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{canFilterByCmpn ? (
|
{canFilterByCmpn ? (
|
||||||
<div className="shrink-0 border-b border-gray-200 p-2">
|
<div className="shrink-0 border-b border-gray-200 p-2">
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
@@ -139,12 +145,6 @@ export function AssignTargetList({
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{summary ? (
|
|
||||||
<div className="shrink-0 border-b border-gray-200 bg-gray-50 px-3 py-1 text-lg font-semibold text-gray-700">
|
|
||||||
전체 {summary.totalCount}건 · 미배정 {summary.unassignedCount}건
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
<table className="w-full table-fixed">
|
<table className="w-full table-fixed">
|
||||||
<colgroup>
|
<colgroup>
|
||||||
|
|||||||
@@ -3,14 +3,15 @@
|
|||||||
import * as React from 'react'
|
import * as React from 'react'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { MultiSelect } from '@/components/common/multi-select'
|
import { MultiSelect } from '@/components/common/multi-select'
|
||||||
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
import type { MultiSelectOption, MultiSelectRef, MultiSelectSearchMatch } from '@/components/common/multi-select'
|
||||||
|
|
||||||
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select'
|
export type { MultiSelectOption, MultiSelectRef, MultiSelectSearchMatch } from '@/components/common/multi-select'
|
||||||
|
|
||||||
export interface KriAutoCompleteBaseProps<T> {
|
export interface KriAutoCompleteBaseProps<T> {
|
||||||
items: T[]
|
items: T[]
|
||||||
searchable?: boolean
|
searchable?: boolean
|
||||||
searchMode?: 'filter' | 'inputOnly'
|
searchMode?: 'filter' | 'inputOnly'
|
||||||
|
searchMatch?: MultiSelectSearchMatch
|
||||||
defaultSearchValue?: string
|
defaultSearchValue?: string
|
||||||
onSearchValueChange?: (value: string) => void
|
onSearchValueChange?: (value: string) => void
|
||||||
placeholder?: string
|
placeholder?: string
|
||||||
@@ -58,6 +59,7 @@ export function KriMultiSelect<T = unknown>({
|
|||||||
onChange,
|
onChange,
|
||||||
searchable = true,
|
searchable = true,
|
||||||
searchMode = 'filter',
|
searchMode = 'filter',
|
||||||
|
searchMatch = 'contains',
|
||||||
defaultSearchValue = '',
|
defaultSearchValue = '',
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
maxCount = 1,
|
maxCount = 1,
|
||||||
@@ -100,6 +102,7 @@ export function KriMultiSelect<T = unknown>({
|
|||||||
badgeLabelClassName={badgeLabelClassName}
|
badgeLabelClassName={badgeLabelClassName}
|
||||||
searchable={searchable}
|
searchable={searchable}
|
||||||
searchMode={searchMode}
|
searchMode={searchMode}
|
||||||
|
searchMatch={searchMatch}
|
||||||
defaultSearchValue={defaultSearchValue}
|
defaultSearchValue={defaultSearchValue}
|
||||||
onSearchValueChange={onSearchValueChange}
|
onSearchValueChange={onSearchValueChange}
|
||||||
maxCount={maxCount}
|
maxCount={maxCount}
|
||||||
@@ -135,6 +138,7 @@ function KriSingleSelectInner<T>(
|
|||||||
onChange,
|
onChange,
|
||||||
searchable = true,
|
searchable = true,
|
||||||
searchMode = 'filter',
|
searchMode = 'filter',
|
||||||
|
searchMatch = 'contains',
|
||||||
defaultSearchValue = '',
|
defaultSearchValue = '',
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
placeholder = '옵션을 선택하세요',
|
placeholder = '옵션을 선택하세요',
|
||||||
@@ -216,6 +220,7 @@ function KriSingleSelectInner<T>(
|
|||||||
badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'}
|
badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'}
|
||||||
searchable={searchable}
|
searchable={searchable}
|
||||||
searchMode={searchMode}
|
searchMode={searchMode}
|
||||||
|
searchMatch={searchMatch}
|
||||||
defaultSearchValue={defaultSearchValue}
|
defaultSearchValue={defaultSearchValue}
|
||||||
onSearchValueChange={onSearchValueChange}
|
onSearchValueChange={onSearchValueChange}
|
||||||
preventDeselect={preventDeselect}
|
preventDeselect={preventDeselect}
|
||||||
|
|||||||
247
src/components/common/KriColorPalette.tsx
Normal file
247
src/components/common/KriColorPalette.tsx
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, type CSSProperties, type KeyboardEvent } from 'react'
|
||||||
|
import { Check } from 'lucide-react'
|
||||||
|
import { Slider as SliderPrimitive } from 'radix-ui'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { ColorPicker, ColorPickerArea, ColorPickerHueSlider } from '@/components/common/color-palette/color-picker'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { formatHexColor, isLightHexColor, normalizeHexColor, parseHexColor } from '@/components/common/color-palette/color'
|
||||||
|
|
||||||
|
export const KRI_COLOR_PALETTE_DEFAULT_COLORS = [
|
||||||
|
'#111827', '#4B5563', '#9CA3AF', '#E5E7EB', '#EF4444', '#F97316', '#F59E0B', '#EAB308',
|
||||||
|
'#84CC16', '#22C55E', '#14B8A6', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
const CUSTOM_PICKER_FALLBACK = '#3B82F6'
|
||||||
|
const CHECKERBOARD = 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 8px 8px'
|
||||||
|
|
||||||
|
export type KriColorPaletteProps = {
|
||||||
|
/** `#RRGGBB` 또는 `#RRGGBBAA` 형식의 색상. 지정되지 않았으면 null */
|
||||||
|
value: string | null
|
||||||
|
onChange: (value: string | null) => void
|
||||||
|
colors?: readonly string[]
|
||||||
|
/** 색상 영역·색조 슬라이더·HEX 입력 노출 여부 */
|
||||||
|
allowCustom?: boolean
|
||||||
|
/**
|
||||||
|
* 투명도 슬라이더 노출 및 `#RRGGBBAA` 입력 허용 여부.
|
||||||
|
* false여도 전달받은 값의 투명도는 표시·보존하며, 사용자가 색을 바꾸면 불투명(`#RRGGBB`)으로 바뀐다.
|
||||||
|
*/
|
||||||
|
allowAlpha?: boolean
|
||||||
|
allowClear?: boolean
|
||||||
|
disabled?: boolean
|
||||||
|
placeholder?: string
|
||||||
|
className?: string
|
||||||
|
'aria-label'?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const swatchStyle = (color: string): CSSProperties => ({
|
||||||
|
background: `linear-gradient(${color}, ${color}), ${CHECKERBOARD}`,
|
||||||
|
})
|
||||||
|
|
||||||
|
export function KriColorPalette({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
colors = KRI_COLOR_PALETTE_DEFAULT_COLORS,
|
||||||
|
allowCustom = true,
|
||||||
|
allowAlpha = false,
|
||||||
|
allowClear = true,
|
||||||
|
disabled = false,
|
||||||
|
placeholder = '색상 없음',
|
||||||
|
className,
|
||||||
|
'aria-label': ariaLabel = '색상 선택',
|
||||||
|
}: KriColorPaletteProps) {
|
||||||
|
const normalizedValue = normalizeHexColor(value)
|
||||||
|
const parsedValue = parseHexColor(normalizedValue)
|
||||||
|
const currentAlpha = parsedValue?.alpha ?? 255
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
// 프리셋·HEX 입력·제거로 값이 바뀌면 색상 영역을 새 값으로 다시 초기화한다.
|
||||||
|
const [pickerKey, setPickerKey] = useState(0)
|
||||||
|
const [hexDraft, setHexDraft] = useState(normalizedValue ?? '')
|
||||||
|
const [hexDraftSource, setHexDraftSource] = useState(normalizedValue)
|
||||||
|
const [hexInvalid, setHexInvalid] = useState(false)
|
||||||
|
|
||||||
|
if (hexDraftSource !== normalizedValue) {
|
||||||
|
setHexDraftSource(normalizedValue)
|
||||||
|
setHexDraft(normalizedValue ?? '')
|
||||||
|
setHexInvalid(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const withAlpha = (rgb: string) => formatHexColor(rgb, allowAlpha ? currentAlpha : 255)
|
||||||
|
|
||||||
|
const selectDiscrete = (next: string | null) => {
|
||||||
|
onChange(next)
|
||||||
|
setPickerKey((key) => key + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePickerChange = (next: string) => {
|
||||||
|
const parsed = parseHexColor(next)
|
||||||
|
if (!parsed) return
|
||||||
|
const nextValue = withAlpha(parsed.rgb)
|
||||||
|
if (nextValue === normalizedValue) return
|
||||||
|
onChange(nextValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAlphaChange = (values: number[]) => {
|
||||||
|
const percent = values[0] ?? 100
|
||||||
|
const nextValue = formatHexColor(parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK, (percent / 100) * 255)
|
||||||
|
if (nextValue === normalizedValue) return
|
||||||
|
onChange(nextValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
const commitHexDraft = () => {
|
||||||
|
if (hexDraft.trim() === '') {
|
||||||
|
setHexDraft(normalizedValue ?? '')
|
||||||
|
setHexInvalid(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 전달받은 값을 그대로 두고 포커스만 이동한 경우(투명도 포함 값 포함)는 변경으로 보지 않는다.
|
||||||
|
if (normalizeHexColor(hexDraft) === normalizedValue) {
|
||||||
|
setHexDraft(normalizedValue ?? '')
|
||||||
|
setHexInvalid(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const parsed = parseHexColor(hexDraft)
|
||||||
|
if (!parsed || (!allowAlpha && parsed.alpha !== 255)) {
|
||||||
|
setHexInvalid(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const nextValue = formatHexColor(parsed.rgb, parsed.alpha)
|
||||||
|
setHexInvalid(false)
|
||||||
|
setHexDraft(nextValue)
|
||||||
|
if (nextValue !== normalizedValue) selectDiscrete(nextValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleHexKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (event.key !== 'Enter') return
|
||||||
|
event.preventDefault()
|
||||||
|
commitHexDraft()
|
||||||
|
}
|
||||||
|
|
||||||
|
const hexFormatLabel = allowAlpha ? '#RRGGBB 또는 #RRGGBBAA' : '#RRGGBB'
|
||||||
|
const alphaPercent = Math.round((currentAlpha / 255) * 100)
|
||||||
|
|
||||||
|
// disabled이면 트리거 상태와 무관하게 팝오버가 열리지 않도록 한다(이미 열린 상태에서 disabled로 바뀐 경우 포함).
|
||||||
|
const resolvedOpen = open && !disabled
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Popover open={resolvedOpen} onOpenChange={(nextOpen) => setOpen(nextOpen && !disabled)}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={`${ariaLabel}: ${normalizedValue ?? placeholder}`}
|
||||||
|
className={cn('w-full justify-start gap-2 px-2 font-normal', className)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className={cn('size-4 shrink-0 rounded-sm border', !normalizedValue && 'bg-[linear-gradient(to_bottom_right,transparent_calc(50%-1px),var(--destructive)_calc(50%-1px)_calc(50%+1px),transparent_calc(50%+1px))]')}
|
||||||
|
style={normalizedValue ? swatchStyle(normalizedValue) : undefined}
|
||||||
|
/>
|
||||||
|
<span className={cn('truncate font-mono text-xs', !normalizedValue && 'text-muted-foreground font-sans')}>
|
||||||
|
{normalizedValue ?? placeholder}
|
||||||
|
</span>
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent align="start" className="w-64 space-y-3 p-3">
|
||||||
|
<div className="grid grid-cols-8 gap-1.5" role="group" aria-label="기본 색상">
|
||||||
|
{colors.map((color) => {
|
||||||
|
const parsedColor = parseHexColor(color)
|
||||||
|
if (!parsedColor) return null
|
||||||
|
const selected = parsedColor.rgb === parsedValue?.rgb
|
||||||
|
const checkColorClass = isLightHexColor(parsedColor.rgb) ? 'text-black' : 'text-white'
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={parsedColor.rgb}
|
||||||
|
type="button"
|
||||||
|
className="focus-visible:ring-ring flex size-6 items-center justify-center rounded-sm border focus-visible:ring-2 focus-visible:outline-none"
|
||||||
|
style={{ backgroundColor: parsedColor.rgb }}
|
||||||
|
aria-label={`색상 ${parsedColor.rgb}`}
|
||||||
|
aria-pressed={selected}
|
||||||
|
title={parsedColor.rgb}
|
||||||
|
onClick={() => selectDiscrete(withAlpha(parsedColor.rgb))}
|
||||||
|
>
|
||||||
|
{selected ? <Check className={cn('size-3.5', checkColorClass)} /> : null}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{allowCustom ? (
|
||||||
|
<div className="space-y-3 border-t pt-3">
|
||||||
|
<ColorPicker
|
||||||
|
key={pickerKey}
|
||||||
|
inline
|
||||||
|
defaultValue={parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK}
|
||||||
|
onValueChange={handlePickerChange}
|
||||||
|
className="flex flex-col gap-3"
|
||||||
|
>
|
||||||
|
<ColorPickerArea className="h-32" />
|
||||||
|
<ColorPickerHueSlider aria-label="색조" />
|
||||||
|
</ColorPicker>
|
||||||
|
{allowAlpha ? (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<SliderPrimitive.Root
|
||||||
|
className="relative flex w-full touch-none items-center select-none"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
step={1}
|
||||||
|
value={[alphaPercent]}
|
||||||
|
onValueChange={handleAlphaChange}
|
||||||
|
aria-label="투명도"
|
||||||
|
>
|
||||||
|
<SliderPrimitive.Track
|
||||||
|
className="relative h-3 w-full grow overflow-hidden rounded-full"
|
||||||
|
style={{ background: CHECKERBOARD }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="absolute inset-0 rounded-full"
|
||||||
|
style={{ background: `linear-gradient(to right, transparent, ${parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK})` }}
|
||||||
|
/>
|
||||||
|
</SliderPrimitive.Track>
|
||||||
|
<SliderPrimitive.Thumb className="border-primary/50 bg-background focus-visible:ring-ring block size-4 rounded-full border shadow focus-visible:ring-1 focus-visible:outline-none" />
|
||||||
|
</SliderPrimitive.Root>
|
||||||
|
<span className="text-muted-foreground w-10 shrink-0 text-right font-mono text-xs">{alphaPercent}%</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Input
|
||||||
|
value={hexDraft}
|
||||||
|
onChange={(event) => {
|
||||||
|
setHexDraft(event.target.value)
|
||||||
|
setHexInvalid(false)
|
||||||
|
}}
|
||||||
|
onBlur={commitHexDraft}
|
||||||
|
onKeyDown={handleHexKeyDown}
|
||||||
|
placeholder={allowAlpha ? '#RRGGBBAA' : '#RRGGBB'}
|
||||||
|
maxLength={allowAlpha ? 9 : 7}
|
||||||
|
aria-label="HEX 색상 코드"
|
||||||
|
aria-invalid={hexInvalid}
|
||||||
|
className="h-8 font-mono text-sm"
|
||||||
|
/>
|
||||||
|
{hexInvalid ? <p className="text-destructive text-xs">{hexFormatLabel} 형식으로 입력해 주세요.</p> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{allowClear ? (
|
||||||
|
<div className="flex justify-end border-t pt-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
disabled={!normalizedValue}
|
||||||
|
onClick={() => selectDiscrete(null)}
|
||||||
|
>
|
||||||
|
색상 제거
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
)
|
||||||
|
}
|
||||||
1687
src/components/common/color-palette/color-picker.tsx
Normal file
1687
src/components/common/color-palette/color-picker.tsx
Normal file
File diff suppressed because it is too large
Load Diff
42
src/components/common/color-palette/color.ts
Normal file
42
src/components/common/color-palette/color.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
export type ParsedHexColor = {
|
||||||
|
/** `#RRGGBB` (대문자) */
|
||||||
|
rgb: string
|
||||||
|
/** 0~255. 투명도가 없는 값은 255 */
|
||||||
|
alpha: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEX_COLOR_PATTERN = /^#?([0-9A-F]{6})([0-9A-F]{2})?$/
|
||||||
|
|
||||||
|
/** `#RRGGBB` 또는 `#RRGGBBAA`(대소문자 무관, `#` 생략 가능)를 해석한다. 형식이 다르면 null. */
|
||||||
|
export const parseHexColor = (value: string | null | undefined): ParsedHexColor | null => {
|
||||||
|
if (!value) return null
|
||||||
|
const match = HEX_COLOR_PATTERN.exec(value.trim().toUpperCase())
|
||||||
|
if (!match) return null
|
||||||
|
return {
|
||||||
|
rgb: `#${match[1]}`,
|
||||||
|
alpha: match[2] ? Number.parseInt(match[2], 16) : 255,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 투명도가 255이면 `#RRGGBB`, 아니면 `#RRGGBBAA`로 만든다. */
|
||||||
|
export const formatHexColor = (rgb: string, alpha = 255): string => {
|
||||||
|
const clamped = Math.max(0, Math.min(255, Math.round(alpha)))
|
||||||
|
if (clamped === 255) return rgb.toUpperCase()
|
||||||
|
return `${rgb.toUpperCase()}${clamped.toString(16).padStart(2, '0').toUpperCase()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 정규화된 hex 문자열. 형식이 다르면 null. */
|
||||||
|
export const normalizeHexColor = (value: string | null | undefined): string | null => {
|
||||||
|
const parsed = parseHexColor(value)
|
||||||
|
return parsed ? formatHexColor(parsed.rgb, parsed.alpha) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 흰 배경 위에 그렸을 때 밝은 색인지 판단한다(투명도 반영). 글자색 대비 결정에 쓴다. */
|
||||||
|
export const isLightHexColor = (value: string): boolean => {
|
||||||
|
const parsed = parseHexColor(value)
|
||||||
|
if (!parsed) return true
|
||||||
|
const ratio = parsed.alpha / 255
|
||||||
|
const channel = (offset: number) => Number.parseInt(parsed.rgb.slice(offset, offset + 2), 16) * ratio + 255 * (1 - ratio)
|
||||||
|
const luminance = (channel(1) * 299 + channel(3) * 587 + channel(5) * 114) / 1000
|
||||||
|
return luminance > 150
|
||||||
|
}
|
||||||
8
src/components/common/color-palette/use-ref-with-init.ts
Normal file
8
src/components/common/color-palette/use-ref-with-init.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
function useRefWithInit<T>(init: () => T): React.RefObject<T> {
|
||||||
|
const [ref] = React.useState(() => ({ current: init() }));
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useRefWithInit };
|
||||||
14
src/components/common/color-palette/use-value-as-ref.ts
Normal file
14
src/components/common/color-palette/use-value-as-ref.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { useLayoutEffect } from "radix-ui/internal";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
function useValueAsRef<T>(value: T) {
|
||||||
|
const ref = React.useRef<T>(value);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
ref.current = value;
|
||||||
|
});
|
||||||
|
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useValueAsRef };
|
||||||
154
src/components/common/color-palette/visually-hidden-input.tsx
Normal file
154
src/components/common/color-palette/visually-hidden-input.tsx
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
type InputValue = string[] | string;
|
||||||
|
|
||||||
|
interface VisuallyHiddenInputProps<T = InputValue> extends Omit<
|
||||||
|
React.InputHTMLAttributes<HTMLInputElement>,
|
||||||
|
"value" | "checked" | "onReset"
|
||||||
|
> {
|
||||||
|
value?: T;
|
||||||
|
checked?: boolean;
|
||||||
|
control: HTMLElement | null;
|
||||||
|
bubbles?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function VisuallyHiddenInput<T = InputValue>(
|
||||||
|
props: VisuallyHiddenInputProps<T>,
|
||||||
|
) {
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
value,
|
||||||
|
checked,
|
||||||
|
bubbles = true,
|
||||||
|
type = "hidden",
|
||||||
|
style,
|
||||||
|
...inputProps
|
||||||
|
} = props;
|
||||||
|
|
||||||
|
const isCheckInput = React.useMemo(
|
||||||
|
() => type === "checkbox" || type === "radio" || type === "switch",
|
||||||
|
[type],
|
||||||
|
);
|
||||||
|
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const prevValueRef = React.useRef<T | boolean | undefined>(
|
||||||
|
isCheckInput ? checked : value,
|
||||||
|
);
|
||||||
|
|
||||||
|
const [measuredSize, setMeasuredSize] = React.useState<{
|
||||||
|
control: HTMLElement;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
|
const controlSize = React.useMemo<{
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
}>(
|
||||||
|
() =>
|
||||||
|
control && measuredSize?.control === control
|
||||||
|
? { width: measuredSize.width, height: measuredSize.height }
|
||||||
|
: {},
|
||||||
|
[control, measuredSize],
|
||||||
|
);
|
||||||
|
|
||||||
|
React.useLayoutEffect(() => {
|
||||||
|
if (!control) return;
|
||||||
|
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
|
||||||
|
const resizeObserver = new ResizeObserver((entries) => {
|
||||||
|
if (!Array.isArray(entries) || !entries.length) return;
|
||||||
|
|
||||||
|
const entry = entries[0];
|
||||||
|
if (!entry) return;
|
||||||
|
|
||||||
|
let width: number;
|
||||||
|
let height: number;
|
||||||
|
|
||||||
|
if ("borderBoxSize" in entry) {
|
||||||
|
const borderSizeEntry = entry.borderBoxSize;
|
||||||
|
const borderSize = Array.isArray(borderSizeEntry)
|
||||||
|
? borderSizeEntry[0]
|
||||||
|
: borderSizeEntry;
|
||||||
|
width = borderSize.inlineSize;
|
||||||
|
height = borderSize.blockSize;
|
||||||
|
} else {
|
||||||
|
width = control.offsetWidth;
|
||||||
|
height = control.offsetHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMeasuredSize({ control, width, height });
|
||||||
|
});
|
||||||
|
|
||||||
|
resizeObserver.observe(control, { box: "border-box" });
|
||||||
|
return () => {
|
||||||
|
resizeObserver.disconnect();
|
||||||
|
};
|
||||||
|
}, [control]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const currentValue = isCheckInput ? checked : value;
|
||||||
|
const prevValue = prevValueRef.current;
|
||||||
|
prevValueRef.current = currentValue;
|
||||||
|
|
||||||
|
const input = inputRef.current;
|
||||||
|
if (!input) return;
|
||||||
|
|
||||||
|
const inputProto = window.HTMLInputElement.prototype;
|
||||||
|
const propertyKey = isCheckInput ? "checked" : "value";
|
||||||
|
const eventType = isCheckInput ? "click" : "input";
|
||||||
|
|
||||||
|
let serializedCurrentValue: unknown = value;
|
||||||
|
if (isCheckInput) {
|
||||||
|
serializedCurrentValue = checked;
|
||||||
|
} else if (typeof value === "object" && value !== null) {
|
||||||
|
serializedCurrentValue = JSON.stringify(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const descriptor = Object.getOwnPropertyDescriptor(inputProto, propertyKey);
|
||||||
|
|
||||||
|
const setter = descriptor?.set;
|
||||||
|
|
||||||
|
if (prevValue !== currentValue && setter) {
|
||||||
|
const event = new Event(eventType, { bubbles });
|
||||||
|
setter.call(input, serializedCurrentValue);
|
||||||
|
input.dispatchEvent(event);
|
||||||
|
}
|
||||||
|
}, [value, checked, bubbles, isCheckInput]);
|
||||||
|
|
||||||
|
const composedStyle = React.useMemo<React.CSSProperties>(() => {
|
||||||
|
return {
|
||||||
|
...style,
|
||||||
|
...(controlSize.width !== undefined && controlSize.height !== undefined
|
||||||
|
? controlSize
|
||||||
|
: {}),
|
||||||
|
border: 0,
|
||||||
|
clip: "rect(0 0 0 0)",
|
||||||
|
clipPath: "inset(50%)",
|
||||||
|
height: "1px",
|
||||||
|
margin: "-1px",
|
||||||
|
overflow: "hidden",
|
||||||
|
padding: 0,
|
||||||
|
position: "absolute",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
width: "1px",
|
||||||
|
};
|
||||||
|
}, [style, controlSize]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
{...inputProps}
|
||||||
|
ref={inputRef}
|
||||||
|
aria-hidden={isCheckInput}
|
||||||
|
tabIndex={-1}
|
||||||
|
defaultChecked={isCheckInput ? checked : undefined}
|
||||||
|
style={composedStyle}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { VisuallyHiddenInput };
|
||||||
@@ -31,6 +31,7 @@ function MultiSelectInner<T>(
|
|||||||
hideSelectAll = false,
|
hideSelectAll = false,
|
||||||
searchable = true,
|
searchable = true,
|
||||||
searchMode = 'filter',
|
searchMode = 'filter',
|
||||||
|
searchMatch = 'fuzzy',
|
||||||
defaultSearchValue = '',
|
defaultSearchValue = '',
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
emptyIndicator = '검색 결과가 없습니다.',
|
emptyIndicator = '검색 결과가 없습니다.',
|
||||||
@@ -201,6 +202,7 @@ function MultiSelectInner<T>(
|
|||||||
selectedValues={selectedValues}
|
selectedValues={selectedValues}
|
||||||
searchable={searchable}
|
searchable={searchable}
|
||||||
searchMode={searchMode}
|
searchMode={searchMode}
|
||||||
|
searchMatch={searchMatch}
|
||||||
searchValue={searchValue}
|
searchValue={searchValue}
|
||||||
onSearchValueChange={handleSearchChange}
|
onSearchValueChange={handleSearchChange}
|
||||||
hideSelectAll={hideSelectAll}
|
hideSelectAll={hideSelectAll}
|
||||||
|
|||||||
@@ -11,14 +11,19 @@ import {
|
|||||||
CommandSeparator,
|
CommandSeparator,
|
||||||
} from '@/components/ui/command'
|
} from '@/components/ui/command'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types'
|
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions, MultiSelectSearchMatch } from './types'
|
||||||
import { isGroupedOptions } from './utils'
|
import { isGroupedOptions } from './utils'
|
||||||
|
|
||||||
|
function containsFilter(value: string, search: string) {
|
||||||
|
return value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0
|
||||||
|
}
|
||||||
|
|
||||||
interface MultiSelectContentProps<T> {
|
interface MultiSelectContentProps<T> {
|
||||||
options: MultiSelectOptions<T>
|
options: MultiSelectOptions<T>
|
||||||
selectedValues: string[]
|
selectedValues: string[]
|
||||||
searchable: boolean
|
searchable: boolean
|
||||||
searchMode: 'filter' | 'inputOnly'
|
searchMode: 'filter' | 'inputOnly'
|
||||||
|
searchMatch?: MultiSelectSearchMatch
|
||||||
searchValue: string
|
searchValue: string
|
||||||
onSearchValueChange: (value: string) => void
|
onSearchValueChange: (value: string) => void
|
||||||
hideSelectAll: boolean
|
hideSelectAll: boolean
|
||||||
@@ -96,6 +101,7 @@ export function MultiSelectContent<T>({
|
|||||||
selectedValues,
|
selectedValues,
|
||||||
searchable,
|
searchable,
|
||||||
searchMode,
|
searchMode,
|
||||||
|
searchMatch = 'fuzzy',
|
||||||
searchValue,
|
searchValue,
|
||||||
onSearchValueChange,
|
onSearchValueChange,
|
||||||
hideSelectAll,
|
hideSelectAll,
|
||||||
@@ -111,7 +117,7 @@ export function MultiSelectContent<T>({
|
|||||||
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Command shouldFilter={searchMode === 'filter'}>
|
<Command shouldFilter={searchMode === 'filter'} filter={searchMatch === 'contains' ? containsFilter : undefined}>
|
||||||
{searchable ? (
|
{searchable ? (
|
||||||
<CommandInput
|
<CommandInput
|
||||||
value={searchValue}
|
value={searchValue}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ export type {
|
|||||||
AnimationConfig,
|
AnimationConfig,
|
||||||
MultiSelectGroup,
|
MultiSelectGroup,
|
||||||
MultiSelectOption,
|
MultiSelectOption,
|
||||||
|
MultiSelectSearchMatch,
|
||||||
MultiSelectOptions,
|
MultiSelectOptions,
|
||||||
MultiSelectProps,
|
MultiSelectProps,
|
||||||
MultiSelectRef,
|
MultiSelectRef,
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export interface MultiSelectGroup<T = unknown> {
|
|||||||
|
|
||||||
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
|
||||||
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
export type MultiSelectSelectionMode = 'single' | 'multiple'
|
||||||
|
export type MultiSelectSearchMatch = 'fuzzy' | 'contains'
|
||||||
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
|
||||||
|
|
||||||
export interface MultiSelectResponsiveSettings {
|
export interface MultiSelectResponsiveSettings {
|
||||||
@@ -65,6 +66,7 @@ export interface MultiSelectProps<T = unknown>
|
|||||||
hideSelectAll?: boolean
|
hideSelectAll?: boolean
|
||||||
searchable?: boolean
|
searchable?: boolean
|
||||||
searchMode?: 'filter' | 'inputOnly'
|
searchMode?: 'filter' | 'inputOnly'
|
||||||
|
searchMatch?: MultiSelectSearchMatch
|
||||||
defaultSearchValue?: string
|
defaultSearchValue?: string
|
||||||
onSearchValueChange?: (value: string) => void
|
onSearchValueChange?: (value: string) => void
|
||||||
emptyIndicator?: React.ReactNode
|
emptyIndicator?: React.ReactNode
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export function DataTable<TData, TValue = unknown>({
|
|||||||
totalCount: serverTotalCount,
|
totalCount: serverTotalCount,
|
||||||
pagination: externalPagination,
|
pagination: externalPagination,
|
||||||
onPaginationChange: onServerPaginationChange,
|
onPaginationChange: onServerPaginationChange,
|
||||||
|
sorting: externalSorting,
|
||||||
onSortingChange: onServerSortingChange,
|
onSortingChange: onServerSortingChange,
|
||||||
selectMode = 'none',
|
selectMode = 'none',
|
||||||
onRowClick,
|
onRowClick,
|
||||||
@@ -41,7 +42,7 @@ export function DataTable<TData, TValue = unknown>({
|
|||||||
bottomPinnedRows = EMPTY_PINNED_ROWS,
|
bottomPinnedRows = EMPTY_PINNED_ROWS,
|
||||||
}: Readonly<DataTableProps<TData, TValue>>) {
|
}: Readonly<DataTableProps<TData, TValue>>) {
|
||||||
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
|
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
|
||||||
const [sorting, setSorting] = useState<SortingState>([])
|
const [internalSorting, setInternalSorting] = useState<SortingState>([])
|
||||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||||
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||||
const drag = usePreventClickOnDrag()
|
const drag = usePreventClickOnDrag()
|
||||||
@@ -78,6 +79,7 @@ export function DataTable<TData, TValue = unknown>({
|
|||||||
}, [columns, selectMode, selectionEnabled])
|
}, [columns, selectMode, selectionEnabled])
|
||||||
|
|
||||||
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
|
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
|
||||||
|
const sorting = !isClient && externalSorting ? externalSorting : internalSorting
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setRowSelection({})
|
setRowSelection({})
|
||||||
@@ -100,12 +102,26 @@ export function DataTable<TData, TValue = unknown>({
|
|||||||
[isClient, onServerPaginationChange],
|
[isClient, onServerPaginationChange],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const handleSortingChange = useCallback<OnChangeFn<SortingState>>(
|
||||||
|
(updater) => {
|
||||||
|
const nextSorting = typeof updater === 'function' ? updater(sorting) : updater
|
||||||
|
|
||||||
|
if (!isClient && onServerSortingChange) {
|
||||||
|
onServerSortingChange(nextSorting)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setInternalSorting(nextSorting)
|
||||||
|
},
|
||||||
|
[isClient, onServerSortingChange, sorting],
|
||||||
|
)
|
||||||
|
|
||||||
const combinedData = useMemo(
|
const combinedData = useMemo(
|
||||||
() => [...topPinnedRows, ...data, ...bottomPinnedRows],
|
() => [...topPinnedRows, ...data, ...bottomPinnedRows],
|
||||||
[topPinnedRows, data, bottomPinnedRows],
|
[topPinnedRows, data, bottomPinnedRows],
|
||||||
)
|
)
|
||||||
|
|
||||||
const internalGetRowId = useCallback((row: TData, index: number) => {
|
const internalGetRowId = useCallback((_row: TData, index: number) => {
|
||||||
if (index < topPinnedRows.length) return `__top-pinned-${index}`
|
if (index < topPinnedRows.length) return `__top-pinned-${index}`
|
||||||
if (index >= topPinnedRows.length + data.length) {
|
if (index >= topPinnedRows.length + data.length) {
|
||||||
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`
|
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`
|
||||||
@@ -128,7 +144,7 @@ export function DataTable<TData, TValue = unknown>({
|
|||||||
enableRowPinning: true,
|
enableRowPinning: true,
|
||||||
keepPinnedRows: true,
|
keepPinnedRows: true,
|
||||||
onRowSelectionChange: setRowSelection,
|
onRowSelectionChange: setRowSelection,
|
||||||
onSortingChange: setSorting,
|
onSortingChange: handleSortingChange,
|
||||||
onPaginationChange: handlePaginationChange,
|
onPaginationChange: handlePaginationChange,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
||||||
@@ -139,10 +155,6 @@ export function DataTable<TData, TValue = unknown>({
|
|||||||
getRowId: internalGetRowId,
|
getRowId: internalGetRowId,
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isClient) onServerSortingChange?.(sorting)
|
|
||||||
}, [isClient, onServerSortingChange, sorting])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectionEnabled) return
|
if (!selectionEnabled) return
|
||||||
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export interface DataTableProps<TData, TValue = unknown> {
|
|||||||
totalCount?: number
|
totalCount?: number
|
||||||
pagination?: PaginationState
|
pagination?: PaginationState
|
||||||
onPaginationChange?: (updater: Updater<PaginationState>) => void
|
onPaginationChange?: (updater: Updater<PaginationState>) => void
|
||||||
|
sorting?: SortingState
|
||||||
onSortingChange?: (sorting: SortingState) => void
|
onSortingChange?: (sorting: SortingState) => void
|
||||||
selectMode?: SelectMode
|
selectMode?: SelectMode
|
||||||
onRowClick?: (row: TData) => void
|
onRowClick?: (row: TData) => void
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
|
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import type { FilterValueOption, ListFilterTarget } from '@/types/list'
|
import type { FilterValueOption, ListFilterTarget } from '@/types/list'
|
||||||
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
||||||
@@ -47,6 +48,7 @@ export type BatchEditPayload = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type ListBatchEditDialogProps = {
|
export type ListBatchEditDialogProps = {
|
||||||
|
prjctIdx: number
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
open?: boolean
|
open?: boolean
|
||||||
onOpenChange?: (open: boolean) => void
|
onOpenChange?: (open: boolean) => void
|
||||||
@@ -75,6 +77,7 @@ const resultCodeGroups: { type: Exclude<ResultCodeType, ResultCodeType.SURVEY>;
|
|||||||
]
|
]
|
||||||
|
|
||||||
const ListBatchEditDialog = ({
|
const ListBatchEditDialog = ({
|
||||||
|
prjctIdx,
|
||||||
dialogId = 'listBatchEditDialog',
|
dialogId = 'listBatchEditDialog',
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
@@ -98,6 +101,7 @@ const ListBatchEditDialog = ({
|
|||||||
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map())
|
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map())
|
||||||
|
|
||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPDATE', active: resolvedOpen })
|
||||||
const defaultHeaderId = headerOptions[0]?.id ?? 0
|
const defaultHeaderId = headerOptions[0]?.id ?? 0
|
||||||
|
|
||||||
const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE
|
const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE
|
||||||
@@ -107,8 +111,6 @@ const ListBatchEditDialog = ({
|
|||||||
if (!resolvedOpen) return
|
if (!resolvedOpen) return
|
||||||
if (initialRows.length > 0) {
|
if (initialRows.length > 0) {
|
||||||
setRows(initialRows.map((row) => ({ ...row })))
|
setRows(initialRows.map((row) => ({ ...row })))
|
||||||
} else if (defaultHeaderId > 0) {
|
|
||||||
setRows([createRow(defaultHeaderId, isFileHeader(defaultHeaderId) ? LIST_BATCH_EDIT_FILE_DELETE_VALUE : '')])
|
|
||||||
} else {
|
} else {
|
||||||
setRows([])
|
setRows([])
|
||||||
}
|
}
|
||||||
@@ -116,7 +118,7 @@ const ListBatchEditDialog = ({
|
|||||||
setSurveyResultSelections({ ...initialSurveyResultCodes })
|
setSurveyResultSelections({ ...initialSurveyResultCodes })
|
||||||
setTarget('filtered')
|
setTarget('filtered')
|
||||||
setInvalidRowId(null)
|
setInvalidRowId(null)
|
||||||
}, [resolvedOpen, initialRows, initialResultCodes, initialSurveyResultCodes, defaultHeaderId])
|
}, [resolvedOpen, initialRows, initialResultCodes, initialSurveyResultCodes])
|
||||||
|
|
||||||
const handleOpenChange = (nextOpen: boolean) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
onOpenChange?.(nextOpen)
|
onOpenChange?.(nextOpen)
|
||||||
@@ -170,6 +172,7 @@ const ListBatchEditDialog = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
|
if (gate.submitBlocked || submitting) return
|
||||||
setInvalidRowId(null)
|
setInvalidRowId(null)
|
||||||
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
||||||
|
|
||||||
@@ -205,7 +208,6 @@ const ListBatchEditDialog = ({
|
|||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target })
|
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target })
|
||||||
handleOpenChange(false)
|
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
@@ -216,19 +218,23 @@ const ListBatchEditDialog = ({
|
|||||||
open={resolvedOpen}
|
open={resolvedOpen}
|
||||||
onOpenChange={handleOpenChange}
|
onOpenChange={handleOpenChange}
|
||||||
title={<span className="text-2xl font-bold">일괄 수정</span>}
|
title={<span className="text-2xl font-bold">일괄 수정</span>}
|
||||||
contentClassName="sm:max-w-[900px]"
|
contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
|
||||||
bodyClassName="space-y-4"
|
bodyClassName="space-y-4"
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||||
취소
|
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
{!gate.hasCurrentJob && (
|
||||||
|
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
|
||||||
적용
|
적용
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||||
|
{!gate.hasCurrentJob && <>
|
||||||
<div className="rounded-md border p-4 space-y-4">
|
<div className="rounded-md border p-4 space-y-4">
|
||||||
<p className="text-lg font-semibold">적용 대상</p>
|
<p className="text-lg font-semibold">적용 대상</p>
|
||||||
<ApplyFilterOption
|
<ApplyFilterOption
|
||||||
@@ -401,6 +407,7 @@ const ListBatchEditDialog = ({
|
|||||||
<Plus className="w-4 h-4" />
|
<Plus className="w-4 h-4" />
|
||||||
행 추가
|
행 추가
|
||||||
</Button>
|
</Button>
|
||||||
|
</>}
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,15 +4,25 @@ import { useState } from 'react'
|
|||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { KriDialog } from '@/components/common/KriDialog'
|
import { KriDialog } from '@/components/common/KriDialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
|
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
|
||||||
|
import { LIST_DOWNLOAD_JOB_TYPE } from '@/const/listJobConst'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||||
import KriDateRangePicker from '@/components/common/KriDateRangePicker'
|
import KriDateRangePicker from '@/components/common/KriDateRangePicker'
|
||||||
import type { ContactHistoryDownloadType, ListDownloadMode, ListDownloadPayload, ListFilterTarget } from '@/types/list'
|
import {
|
||||||
|
type ContactHistoryDownloadType,
|
||||||
|
ListEventHistoryOrder,
|
||||||
|
type ListDownloadMode,
|
||||||
|
type ListDownloadPayload,
|
||||||
|
type ListFilterTarget,
|
||||||
|
} from '@/types/list'
|
||||||
|
|
||||||
export type ListDownloadDialogProps = {
|
export type ListDownloadDialogProps = {
|
||||||
|
prjctIdx: number
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
open?: boolean
|
open?: boolean
|
||||||
onOpenChange?: (open: boolean) => void
|
onOpenChange?: (open: boolean) => void
|
||||||
@@ -30,6 +40,7 @@ const titleMap: Record<ListDownloadMode, string> = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ListDownloadDialog = ({
|
const ListDownloadDialog = ({
|
||||||
|
prjctIdx,
|
||||||
dialogId = 'listDownloadDialog',
|
dialogId = 'listDownloadDialog',
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
@@ -43,9 +54,12 @@ const ListDownloadDialog = ({
|
|||||||
const [contactHistoryDateFrom, setContactHistoryDateFrom] = useState('')
|
const [contactHistoryDateFrom, setContactHistoryDateFrom] = useState('')
|
||||||
const [contactHistoryDateTo, setContactHistoryDateTo] = useState('')
|
const [contactHistoryDateTo, setContactHistoryDateTo] = useState('')
|
||||||
const [contactHistoryType, setContactHistoryType] = useState<ContactHistoryDownloadType>('all')
|
const [contactHistoryType, setContactHistoryType] = useState<ContactHistoryDownloadType>('all')
|
||||||
|
const [historyOrder, setHistoryOrder] = useState<ListEventHistoryOrder>(ListEventHistoryOrder.DESC)
|
||||||
|
const [includeResult, setIncludeResult] = useState(true)
|
||||||
const [submitting, setSubmitting] = useState(false)
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
|
||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
const gate = useListJobGate({ prjctIdx, jobType: LIST_DOWNLOAD_JOB_TYPE[mode], active: resolvedOpen })
|
||||||
|
|
||||||
const handleOpenChange = (nextOpen: boolean) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
onOpenChange?.(nextOpen)
|
onOpenChange?.(nextOpen)
|
||||||
@@ -57,6 +71,7 @@ const ListDownloadDialog = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleDownload = async () => {
|
const handleDownload = async () => {
|
||||||
|
if (gate.submitBlocked || submitting) return
|
||||||
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
||||||
|
|
||||||
if (mode === 'contact-history') {
|
if (mode === 'contact-history') {
|
||||||
@@ -78,11 +93,12 @@ const ListDownloadDialog = ({
|
|||||||
mode,
|
mode,
|
||||||
target,
|
target,
|
||||||
onlyFiltered: target === 'filtered',
|
onlyFiltered: target === 'filtered',
|
||||||
|
includeResult,
|
||||||
contactHistoryDateFrom: mode === 'contact-history' ? contactHistoryDateFrom || undefined : undefined,
|
contactHistoryDateFrom: mode === 'contact-history' ? contactHistoryDateFrom || undefined : undefined,
|
||||||
contactHistoryDateTo: mode === 'contact-history' ? contactHistoryDateTo || undefined : undefined,
|
contactHistoryDateTo: mode === 'contact-history' ? contactHistoryDateTo || undefined : undefined,
|
||||||
contactHistoryType: mode === 'contact-history' ? contactHistoryType : undefined,
|
contactHistoryType: mode === 'contact-history' ? contactHistoryType : undefined,
|
||||||
|
historyOrder: mode === 'contact-history' ? historyOrder : undefined,
|
||||||
})
|
})
|
||||||
handleOpenChange(false)
|
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
@@ -93,20 +109,24 @@ const ListDownloadDialog = ({
|
|||||||
open={resolvedOpen}
|
open={resolvedOpen}
|
||||||
onOpenChange={handleOpenChange}
|
onOpenChange={handleOpenChange}
|
||||||
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||||
contentClassName="sm:max-w-[560px]"
|
contentClassName="sm:max-w-[560px] max-h-[90vh] overflow-y-auto"
|
||||||
bodyClassName="space-y-4"
|
bodyClassName="space-y-4"
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||||
취소
|
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" onClick={handleDownload} disabled={submitting} className="gap-2">
|
{!gate.hasCurrentJob && (
|
||||||
|
<Button type="button" onClick={handleDownload} disabled={submitting || gate.submitBlocked} className="gap-2">
|
||||||
<Download className="w-4 h-4" />
|
<Download className="w-4 h-4" />
|
||||||
다운로드
|
다운로드
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||||
|
{!gate.hasCurrentJob && <>
|
||||||
{mode === 'contact-history' ? (
|
{mode === 'contact-history' ? (
|
||||||
<div className="rounded-md border p-4 space-y-4">
|
<div className="rounded-md border p-4 space-y-4">
|
||||||
<p className="text-lg font-semibold">조회 기간</p>
|
<p className="text-lg font-semibold">조회 기간</p>
|
||||||
@@ -130,6 +150,16 @@ const ListDownloadDialog = ({
|
|||||||
filterSummary={filterSummary}
|
filterSummary={filterSummary}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{mode === 'list' || mode === 'contact-history' ? (
|
||||||
|
<div className="flex items-center gap-2 rounded-md border p-4">
|
||||||
|
<Checkbox
|
||||||
|
id="download-include-result"
|
||||||
|
checked={includeResult}
|
||||||
|
onCheckedChange={(checked) => setIncludeResult(checked === true)}
|
||||||
|
/>
|
||||||
|
<Label className="text-base" htmlFor="download-include-result">결과값 포함</Label>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
{mode === 'contact-history' ? (
|
{mode === 'contact-history' ? (
|
||||||
<div className="rounded-md border p-4 space-y-4">
|
<div className="rounded-md border p-4 space-y-4">
|
||||||
<p className="text-lg font-semibold">이력 기준</p>
|
<p className="text-lg font-semibold">이력 기준</p>
|
||||||
@@ -149,6 +179,26 @@ const ListDownloadDialog = ({
|
|||||||
</RadioGroup>
|
</RadioGroup>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
{mode === 'contact-history' && contactHistoryType === 'all' ? (
|
||||||
|
<div className="rounded-md border p-4 space-y-4">
|
||||||
|
<p className="text-lg font-semibold">이력 순서</p>
|
||||||
|
<RadioGroup
|
||||||
|
value={historyOrder}
|
||||||
|
onValueChange={(value) => setHistoryOrder(value as ListEventHistoryOrder)}
|
||||||
|
className="flex items-center gap-6 flex-wrap"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<RadioGroupItem value={ListEventHistoryOrder.DESC} id="download-history-order-desc" />
|
||||||
|
<Label className="text-base" htmlFor="download-history-order-desc">최근 이력이 왼쪽부터</Label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<RadioGroupItem value={ListEventHistoryOrder.ASC} id="download-history-order-asc" />
|
||||||
|
<Label className="text-base" htmlFor="download-history-order-asc">오래된 이력이 왼쪽부터</Label>
|
||||||
|
</div>
|
||||||
|
</RadioGroup>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</>}
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { RotateCcw } from 'lucide-react'
|
||||||
import { KriDialog } from '@/components/common/KriDialog'
|
import { KriDialog } from '@/components/common/KriDialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
@@ -107,6 +108,18 @@ const ListFilterDialog = ({
|
|||||||
[rows, headerOptions],
|
[rows, headerOptions],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 잠긴 헤더는 조회 조건에 쓰이지 않으므로 초기화 필요 여부 판단에서 제외한다.
|
||||||
|
const isResettable = rows.some((row) => {
|
||||||
|
if (isDisabledHeader(row.headerId)) return false
|
||||||
|
const defaultOperator = getHeaderOption(row.headerId)?.defaultOperator ?? 'eq'
|
||||||
|
return row.operator !== defaultOperator || row.textValue !== '' || row.multiValues.length > 0
|
||||||
|
})
|
||||||
|
|
||||||
|
// 다이얼로그 내 입력만 기본값으로 되돌린다. 실제 반영은 "적용"을 눌러야 이뤄진다.
|
||||||
|
const handleReset = () => {
|
||||||
|
setRows(headerOptions.map((option) => createFilterRow(option.id, headerOptions)))
|
||||||
|
}
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
@@ -138,7 +151,20 @@ const ListFilterDialog = ({
|
|||||||
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr] items-center border-b bg-muted px-4 text-sm font-semibold">
|
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr] items-center border-b bg-muted px-4 text-sm font-semibold">
|
||||||
<span>헤더</span>
|
<span>헤더</span>
|
||||||
<span>비교 연산자</span>
|
<span>비교 연산자</span>
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
<span>값</span>
|
<span>값</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-7 text-muted-foreground"
|
||||||
|
onClick={handleReset}
|
||||||
|
disabled={submitting || !isResettable}
|
||||||
|
>
|
||||||
|
<RotateCcw className="size-3.5" />
|
||||||
|
초기화
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="max-h-170 overflow-auto">
|
<div className="max-h-170 overflow-auto">
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
} from '@dnd-kit/sortable'
|
} from '@dnd-kit/sortable'
|
||||||
import { CSS } from '@dnd-kit/utilities'
|
import { CSS } from '@dnd-kit/utilities'
|
||||||
import { GripVertical, Plus, Trash2 } from 'lucide-react'
|
import { GripVertical, Plus, Trash2 } from 'lucide-react'
|
||||||
|
import { KriColorPalette } from '@/components/common/KriColorPalette'
|
||||||
import { KriDialog } from '@/components/common/KriDialog'
|
import { KriDialog } from '@/components/common/KriDialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
@@ -29,7 +30,7 @@ import { useDialog } from '@/hooks/useDialog'
|
|||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { listHeader, ListHeaderGrade, ListHeaderType } from '@/types/list'
|
import { listHeader, ListHeaderGrade, ListHeaderType } from '@/types/list'
|
||||||
import { LIST_HEADER_TYPE_LABEL, LIST_HEADER_TYPE_OPTIONS } from '@/const/listConst'
|
import { LIST_HEADER_TYPE_LABEL, LIST_HEADER_TYPE_OPTIONS, ListHeaderConst } from '@/const/listConst'
|
||||||
|
|
||||||
export type ListHeaderManageDialogProps = {
|
export type ListHeaderManageDialogProps = {
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
@@ -38,11 +39,13 @@ export type ListHeaderManageDialogProps = {
|
|||||||
prjctIdx: number
|
prjctIdx: number
|
||||||
rows: listHeader[]
|
rows: listHeader[]
|
||||||
onConfirm: (rows: listHeader[]) => void | Promise<void>
|
onConfirm: (rows: listHeader[]) => void | Promise<void>
|
||||||
|
saveDisabled?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
type ListHeaderRowProps = {
|
type ListHeaderRowProps = {
|
||||||
row: listHeader
|
row: listHeader
|
||||||
activeId: number | null
|
activeId: number | null
|
||||||
|
onHeaderColorChange: (id: number, color: string | null) => void
|
||||||
onHeaderNameChange: (id: number, listHderNm: string) => void
|
onHeaderNameChange: (id: number, listHderNm: string) => void
|
||||||
onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void
|
onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void
|
||||||
onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void
|
onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void
|
||||||
@@ -54,13 +57,30 @@ const COMMON_GRADE_ORDER_START = 101
|
|||||||
const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON
|
const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON
|
||||||
const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE
|
const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE
|
||||||
|
|
||||||
const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange, onFlagChange, onDelete }: ListHeaderRowProps) => {
|
const isInterviewerEditDisabled = (row: listHeader) =>
|
||||||
|
isImmutableGrade(row.listHderGrad) ||
|
||||||
|
row.listHderTy === ListHeaderConst.IS_USE ||
|
||||||
|
row.listHderTy === ListHeaderConst.OUTSOURCE ||
|
||||||
|
row.listHderTy === ListHeaderConst.CONTACT_INTERVIEWER ||
|
||||||
|
row.listHderTy === ListHeaderConst.FIELD_INTERVIEWER
|
||||||
|
|
||||||
|
const ListHeaderRow = ({
|
||||||
|
row,
|
||||||
|
activeId,
|
||||||
|
onHeaderColorChange,
|
||||||
|
onHeaderNameChange,
|
||||||
|
onHeaderTypeChange,
|
||||||
|
onFlagChange,
|
||||||
|
onDelete,
|
||||||
|
}: ListHeaderRowProps) => {
|
||||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId })
|
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId })
|
||||||
const canEditName = isCommonGrade(row.listHderGrad)
|
const canEditName = isCommonGrade(row.listHderGrad)
|
||||||
const canEditType = isCommonGrade(row.listHderGrad)
|
const canEditType = isCommonGrade(row.listHderGrad)
|
||||||
const canDelete = isCommonGrade(row.listHderGrad)
|
const canDelete = isCommonGrade(row.listHderGrad)
|
||||||
const canEditFlags = !isImmutableGrade(row.listHderGrad)
|
const canEditFlags = !isImmutableGrade(row.listHderGrad)
|
||||||
const canSort = isCommonGrade(row.listHderGrad)
|
const canSort = isCommonGrade(row.listHderGrad)
|
||||||
|
// IMMUTABLE 헤더의 색상은 서버가 저장하지 않으므로 선택을 막는다.
|
||||||
|
const canEditColor = !isImmutableGrade(row.listHderGrad)
|
||||||
|
|
||||||
const style: CSSProperties = {
|
const style: CSSProperties = {
|
||||||
transform: CSS.Transform.toString(transform),
|
transform: CSS.Transform.toString(transform),
|
||||||
@@ -78,7 +98,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
|
|||||||
ref={setNodeRef}
|
ref={setNodeRef}
|
||||||
style={style}
|
style={style}
|
||||||
className={cn(
|
className={cn(
|
||||||
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2',
|
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2',
|
||||||
(activeId === row.listHderId || isDragging) && 'bg-muted',
|
(activeId === row.listHderId || isDragging) && 'bg-muted',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -123,6 +143,12 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
|
|||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
<KriColorPalette
|
||||||
|
value={row.listHderColor ?? null}
|
||||||
|
onChange={(color) => onHeaderColorChange(row.listHderId, color)}
|
||||||
|
disabled={!canEditColor}
|
||||||
|
aria-label={`${row.listHderNm} 헤더 색상`}
|
||||||
|
/>
|
||||||
<div className="flex items-center gap-2 justify-center">
|
<div className="flex items-center gap-2 justify-center">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
id={`header-visible-${row.listHderId}`}
|
id={`header-visible-${row.listHderId}`}
|
||||||
@@ -152,7 +178,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
|
|||||||
id={`header-intrvwer-edit-${row.listHderId}`}
|
id={`header-intrvwer-edit-${row.listHderId}`}
|
||||||
checked={row.useIntrvwerEdit}
|
checked={row.useIntrvwerEdit}
|
||||||
onCheckedChange={(checked) => onFlagChange(row.listHderId, 'useIntrvwerEdit', checked === true)}
|
onCheckedChange={(checked) => onFlagChange(row.listHderId, 'useIntrvwerEdit', checked === true)}
|
||||||
disabled={!canEditFlags}
|
disabled={isInterviewerEditDisabled(row)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-center">
|
<div className="flex justify-center">
|
||||||
@@ -179,6 +205,7 @@ const ListHeaderManageDialog = ({
|
|||||||
prjctIdx,
|
prjctIdx,
|
||||||
rows,
|
rows,
|
||||||
onConfirm,
|
onConfirm,
|
||||||
|
saveDisabled = false,
|
||||||
}: ListHeaderManageDialogProps) => {
|
}: ListHeaderManageDialogProps) => {
|
||||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||||
const [localRows, setLocalRows] = useState<listHeader[]>([])
|
const [localRows, setLocalRows] = useState<listHeader[]>([])
|
||||||
@@ -247,6 +274,16 @@ const ListHeaderManageDialog = ({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleHeaderColorChange = (id: number, listHderColor: string | null) => {
|
||||||
|
setLocalRows((prev) =>
|
||||||
|
prev.map((row) => {
|
||||||
|
if (row.listHderId !== id) return row
|
||||||
|
if (isImmutableGrade(row.listHderGrad)) return row
|
||||||
|
return { ...row, listHderColor }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const handleHeaderNameChange = (id: number, listHderNm: string) => {
|
const handleHeaderNameChange = (id: number, listHderNm: string) => {
|
||||||
setLocalRows((prev) =>
|
setLocalRows((prev) =>
|
||||||
prev.map((row) => {
|
prev.map((row) => {
|
||||||
@@ -266,6 +303,7 @@ const ListHeaderManageDialog = ({
|
|||||||
prev.map((row) => {
|
prev.map((row) => {
|
||||||
if (row.listHderId !== id) return row
|
if (row.listHderId !== id) return row
|
||||||
if (isImmutableGrade(row.listHderGrad)) return row
|
if (isImmutableGrade(row.listHderGrad)) return row
|
||||||
|
if (field === 'useIntrvwerEdit' && isInterviewerEditDisabled(row)) return row
|
||||||
return { ...row, [field]: checked }
|
return { ...row, [field]: checked }
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -292,6 +330,7 @@ const ListHeaderManageDialog = ({
|
|||||||
useColView: true,
|
useColView: true,
|
||||||
useIntrvwerView: false,
|
useIntrvwerView: false,
|
||||||
useIntrvwerEdit: false,
|
useIntrvwerEdit: false,
|
||||||
|
listHderColor: null,
|
||||||
}
|
}
|
||||||
|
|
||||||
return [...prev, nextRow]
|
return [...prev, nextRow]
|
||||||
@@ -299,7 +338,12 @@ const ListHeaderManageDialog = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
|
if (saveDisabled || submitting) return
|
||||||
const names = localRows.map((row) => row.listHderNm.trim())
|
const names = localRows.map((row) => row.listHderNm.trim())
|
||||||
|
if (names.some((name) => name.length === 0)) {
|
||||||
|
alert('헤더명을 입력해 주세요.')
|
||||||
|
return
|
||||||
|
}
|
||||||
const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
|
const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
|
||||||
if (duplicateNames.length > 0) {
|
if (duplicateNames.length > 0) {
|
||||||
alert(`중복된 헤더명이 있습니다: ${duplicateNames.join(', ')}`)
|
alert(`중복된 헤더명이 있습니다: ${duplicateNames.join(', ')}`)
|
||||||
@@ -333,8 +377,10 @@ const ListHeaderManageDialog = ({
|
|||||||
let defaultOrder = 0
|
let defaultOrder = 0
|
||||||
let commonOrder = COMMON_GRADE_ORDER_START - 1
|
let commonOrder = COMMON_GRADE_ORDER_START - 1
|
||||||
const orderedRows = localRows.map((row) => {
|
const orderedRows = localRows.map((row) => {
|
||||||
const listHderOrder = isCommonGrade(row.listHderGrad) ? (commonOrder += 1) : (defaultOrder += 1)
|
const isCommon = isCommonGrade(row.listHderGrad)
|
||||||
return { ...row, prjctIdx: row.prjctIdx ?? prjctIdx, listHderOrder }
|
const listHderOrder = isCommon ? (commonOrder += 1) : (defaultOrder += 1)
|
||||||
|
const listHderNm = isCommon ? row.listHderNm.trim() : row.listHderNm
|
||||||
|
return { ...row, prjctIdx: row.prjctIdx ?? prjctIdx, listHderOrder, listHderNm }
|
||||||
})
|
})
|
||||||
await onConfirm(orderedRows)
|
await onConfirm(orderedRows)
|
||||||
handleOpenChange(false)
|
handleOpenChange(false)
|
||||||
@@ -354,12 +400,13 @@ const ListHeaderManageDialog = ({
|
|||||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||||
취소
|
취소
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
<Button type="button" onClick={handleConfirm} disabled={submitting || saveDisabled}>
|
||||||
저장
|
저장
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{saveDisabled && <p role="alert" className="mb-2 text-sm text-amber-800">리스트 작업이 진행 중이거나 작업 상태를 확인할 수 없어 헤더를 저장할 수 없습니다.</p>}
|
||||||
|
|
||||||
<div className="flex justify-between mb-2">
|
<div className="flex justify-between mb-2">
|
||||||
<span className="text-base text-red-600 font-semibold">⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다.</span>
|
<span className="text-base text-red-600 font-semibold">⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다.</span>
|
||||||
@@ -370,10 +417,11 @@ const ListHeaderManageDialog = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border overflow-hidden">
|
<div className="rounded-md border overflow-hidden">
|
||||||
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
|
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
|
||||||
<span>순서</span>
|
<span>순서</span>
|
||||||
<span>헤더명</span>
|
<span>헤더명</span>
|
||||||
<span>헤더 타입</span>
|
<span>헤더 타입</span>
|
||||||
|
<span>헤더 색상</span>
|
||||||
<span>헤더 노출</span>
|
<span>헤더 노출</span>
|
||||||
<span>필터 사용</span>
|
<span>필터 사용</span>
|
||||||
<span>면접원 노출</span>
|
<span>면접원 노출</span>
|
||||||
@@ -395,6 +443,7 @@ const ListHeaderManageDialog = ({
|
|||||||
key={row.listHderId}
|
key={row.listHderId}
|
||||||
row={row}
|
row={row}
|
||||||
activeId={activeId}
|
activeId={activeId}
|
||||||
|
onHeaderColorChange={handleHeaderColorChange}
|
||||||
onHeaderNameChange={handleHeaderNameChange}
|
onHeaderNameChange={handleHeaderNameChange}
|
||||||
onHeaderTypeChange={handleHeaderTypeChange}
|
onHeaderTypeChange={handleHeaderTypeChange}
|
||||||
onFlagChange={handleFlagChange}
|
onFlagChange={handleFlagChange}
|
||||||
|
|||||||
@@ -3,23 +3,44 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { KriDialog } from '@/components/common/KriDialog'
|
import { KriDialog } from '@/components/common/KriDialog'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
|
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||||
import type { ListFilterTarget, ListResetScope } from '@/types/list'
|
import type { ListFilterTarget, ListResetSelection } from '@/types/list'
|
||||||
|
import type { ProjectSurvey } from '@/types/project'
|
||||||
|
|
||||||
export type ListResetDialogProps = {
|
export type ListResetDialogProps = {
|
||||||
|
prjctIdx: number
|
||||||
|
/** 프로젝트에 연동된 설문 목록. undefined면 아직 불러오지 못한 상태로 보고 초기화를 막는다. */
|
||||||
|
surveys?: ProjectSurvey[]
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
open?: boolean
|
open?: boolean
|
||||||
onOpenChange?: (open: boolean) => void
|
onOpenChange?: (open: boolean) => void
|
||||||
selectedSids: string[]
|
selectedSids: string[]
|
||||||
filterSummary?: string[]
|
filterSummary?: string[]
|
||||||
onConfirm: (payload: { target: ListFilterTarget; scope: ListResetScope }) => void | Promise<void>
|
onConfirm: (payload: { target: ListFilterTarget; selection: ListResetSelection }) => void | Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResetSurveyOption = { prjctSurveyIdx: number; surveyName: string }
|
||||||
|
|
||||||
|
const toResetSurveyOptions = (surveys: ProjectSurvey[]): ResetSurveyOption[] => {
|
||||||
|
const seen = new Set<number>()
|
||||||
|
return [...surveys]
|
||||||
|
.sort((a, b) => a.surveyOrder - b.surveyOrder)
|
||||||
|
.flatMap((survey) => {
|
||||||
|
const id = survey.prjctSurveyIdx
|
||||||
|
if (id == null || seen.has(id)) return []
|
||||||
|
seen.add(id)
|
||||||
|
return [{ prjctSurveyIdx: id, surveyName: survey.surveyName }]
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const ListResetDialog = ({
|
const ListResetDialog = ({
|
||||||
|
prjctIdx,
|
||||||
|
surveys,
|
||||||
dialogId = 'listResetDialog',
|
dialogId = 'listResetDialog',
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
@@ -29,10 +50,38 @@ const ListResetDialog = ({
|
|||||||
}: ListResetDialogProps) => {
|
}: ListResetDialogProps) => {
|
||||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||||
const [target, setTarget] = useState<ListFilterTarget>('selected')
|
const [target, setTarget] = useState<ListFilterTarget>('selected')
|
||||||
const [scope, setScope] = useState<ListResetScope>('result-and-history')
|
const [resetList, setResetList] = useState(false)
|
||||||
|
const [resetContactHistory, setResetContactHistory] = useState(false)
|
||||||
|
const [resetInterviewHistory, setResetInterviewHistory] = useState(false)
|
||||||
|
const [selectedSurveyIds, setSelectedSurveyIds] = useState<number[]>([])
|
||||||
const [submitting, setSubmitting] = useState(false)
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
|
||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_RESET', active: resolvedOpen })
|
||||||
|
|
||||||
|
const surveysReady = surveys !== undefined
|
||||||
|
const surveyOptions = toResetSurveyOptions(surveys ?? [])
|
||||||
|
const allSurveyIds = surveyOptions.map((survey) => survey.prjctSurveyIdx)
|
||||||
|
// 설문 목록이 다시 조회되어 빠진 설문이 있으면 요청에서 제외한다.
|
||||||
|
const checkedSurveyIds = allSurveyIds.filter((id) => selectedSurveyIds.includes(id))
|
||||||
|
const hasSelection = resetList || resetContactHistory || resetInterviewHistory || checkedSurveyIds.length > 0
|
||||||
|
|
||||||
|
// 리스트 초기화는 모든 이력을 포함해야 하므로 이력을 전부 선택하고 잠근다.
|
||||||
|
// 해제 시에는 잠금 중 화면에 보이던 전체 선택 상태를 그대로 유지한다(잠금 중 로드된 설문 포함).
|
||||||
|
const handleResetListChange = (checked: boolean) => {
|
||||||
|
setResetList(checked)
|
||||||
|
setResetContactHistory(true)
|
||||||
|
setResetInterviewHistory(true)
|
||||||
|
setSelectedSurveyIds(allSurveyIds)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSurveyChange = (id: number, checked: boolean) => {
|
||||||
|
setSelectedSurveyIds((prev) => (checked ? [...prev.filter((v) => v !== id), id] : prev.filter((v) => v !== id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildSelection = (): ListResetSelection => resetList
|
||||||
|
? { resetList: true, resetContactHistory: true, resetInterviewHistory: true, resetSurveyIds: allSurveyIds }
|
||||||
|
: { resetList: false, resetContactHistory, resetInterviewHistory, resetSurveyIds: checkedSurveyIds }
|
||||||
|
|
||||||
const handleOpenChange = (nextOpen: boolean) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
onOpenChange?.(nextOpen)
|
onOpenChange?.(nextOpen)
|
||||||
@@ -43,14 +92,33 @@ const ListResetDialog = ({
|
|||||||
hideDialog(dialogId)
|
hideDialog(dialogId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// '새 작업'(완료 확인)을 누르면 이전 작업의 대상·범위를 이어 쓰지 않도록 초기값으로 되돌린다.
|
||||||
|
const gatePanel = {
|
||||||
|
...gate,
|
||||||
|
acknowledge: () => {
|
||||||
|
gate.acknowledge()
|
||||||
|
setTarget('selected')
|
||||||
|
setResetList(false)
|
||||||
|
setResetContactHistory(false)
|
||||||
|
setResetInterviewHistory(false)
|
||||||
|
setSelectedSurveyIds([])
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 전체 대상은 선택 시점에도 한 번 확인한다. 취소하면 기존 대상을 유지한다.
|
||||||
|
const handleTargetChange = (next: ListFilterTarget) => {
|
||||||
|
if (next === 'all' && target !== 'all' && !confirm('전체 대상을 선택하면 프로젝트의 모든 리스트가 초기화 대상이 됩니다. 선택하시겠습니까?')) return
|
||||||
|
setTarget(next)
|
||||||
|
}
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
|
if (gate.submitBlocked || submitting || !surveysReady || !hasSelection) return
|
||||||
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
||||||
if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return
|
if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return
|
||||||
|
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
await onConfirm({ target, scope })
|
await onConfirm({ target, selection: buildSelection() })
|
||||||
handleOpenChange(false)
|
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
@@ -61,24 +129,33 @@ const ListResetDialog = ({
|
|||||||
open={resolvedOpen}
|
open={resolvedOpen}
|
||||||
onOpenChange={handleOpenChange}
|
onOpenChange={handleOpenChange}
|
||||||
title={<span className="text-2xl font-bold">리스트 초기화</span>}
|
title={<span className="text-2xl font-bold">리스트 초기화</span>}
|
||||||
contentClassName="sm:max-w-[700px]"
|
contentClassName="sm:max-w-[700px] max-h-[90vh] overflow-y-auto"
|
||||||
bodyClassName="space-y-6 py-2"
|
bodyClassName="space-y-6 py-2"
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||||
취소
|
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting}>
|
{!gate.hasCurrentJob && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={handleConfirm}
|
||||||
|
disabled={submitting || gate.submitBlocked || !surveysReady || !hasSelection}
|
||||||
|
>
|
||||||
초기화
|
초기화
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
<ListJobGatePanel gate={gatePanel} acknowledgeLabel="새 작업" />
|
||||||
|
{!gate.hasCurrentJob && <>
|
||||||
<div className="rounded-md border p-4 space-y-4">
|
<div className="rounded-md border p-4 space-y-4">
|
||||||
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
<p className="text-lg font-semibold text-red-600">초기화 대상</p>
|
||||||
<ApplyFilterOption
|
<ApplyFilterOption
|
||||||
value={target}
|
value={target}
|
||||||
onValueChange={(v) => setTarget(v)}
|
onValueChange={handleTargetChange}
|
||||||
idPrefix="list-reset-target"
|
idPrefix="list-reset-target"
|
||||||
selectedSids={selectedSids}
|
selectedSids={selectedSids}
|
||||||
filterSummary={filterSummary}
|
filterSummary={filterSummary}
|
||||||
@@ -87,17 +164,65 @@ const ListResetDialog = ({
|
|||||||
|
|
||||||
<div className="rounded-md border p-4 space-y-4">
|
<div className="rounded-md border p-4 space-y-4">
|
||||||
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
|
<p className="text-lg font-semibold text-red-600">초기화 범위</p>
|
||||||
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2">
|
<div className="space-y-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-x-6 gap-y-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" />
|
<Checkbox
|
||||||
<Label className="text-base" htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label>
|
id="list-reset-scope-list"
|
||||||
|
checked={resetList}
|
||||||
|
onCheckedChange={(checked) => handleResetListChange(checked === true)}
|
||||||
|
/>
|
||||||
|
<Label className="text-base" htmlFor="list-reset-scope-list">리스트</Label>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" />
|
<Checkbox
|
||||||
<Label className="text-base" htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label>
|
id="list-reset-scope-contact"
|
||||||
|
checked={resetList || resetContactHistory}
|
||||||
|
disabled={resetList}
|
||||||
|
onCheckedChange={(checked) => setResetContactHistory(checked === true)}
|
||||||
|
/>
|
||||||
|
<Label className="text-base" htmlFor="list-reset-scope-contact">컨택이력</Label>
|
||||||
</div>
|
</div>
|
||||||
</RadioGroup>
|
<div className="flex items-center gap-2">
|
||||||
|
<Checkbox
|
||||||
|
id="list-reset-scope-interview"
|
||||||
|
checked={resetList || resetInterviewHistory}
|
||||||
|
disabled={resetList}
|
||||||
|
onCheckedChange={(checked) => setResetInterviewHistory(checked === true)}
|
||||||
|
/>
|
||||||
|
<Label className="text-base" htmlFor="list-reset-scope-interview">면접이력</Label>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
{(!surveysReady || surveyOptions.length > 0) && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm font-medium text-muted-foreground">설문 상태이력</p>
|
||||||
|
{!surveysReady && <p className="text-sm text-muted-foreground">설문 목록을 불러오는 중입니다.</p>}
|
||||||
|
<div className="flex flex-wrap items-center gap-x-6 gap-y-2">
|
||||||
|
{surveyOptions.map((survey) => {
|
||||||
|
const id = `list-reset-scope-survey-${survey.prjctSurveyIdx}`
|
||||||
|
return (
|
||||||
|
<div key={survey.prjctSurveyIdx} className="flex items-center gap-2">
|
||||||
|
<Checkbox
|
||||||
|
id={id}
|
||||||
|
checked={resetList || checkedSurveyIds.includes(survey.prjctSurveyIdx)}
|
||||||
|
disabled={resetList}
|
||||||
|
onCheckedChange={(checked) => handleSurveyChange(survey.prjctSurveyIdx, checked === true)}
|
||||||
|
/>
|
||||||
|
<Label className="text-base" htmlFor={id}>{survey.surveyName}</Label>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ul className="list-disc space-y-1 pl-5 text-sm text-muted-foreground">
|
||||||
|
<li>선택한 이력은 해당 유형의 이력과 최신 상태가 함께 초기화되며, 선택하지 않은 이력은 유지됩니다.</li>
|
||||||
|
<li>리스트를 선택하면 리스트와 모든 이력이 함께 초기화됩니다.</li>
|
||||||
|
<li>설문 상태이력 초기화는 외부 설문 시스템의 실제 응답 데이터를 삭제하지 않습니다.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</>}
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,9 @@ import { KriDialog } from '@/components/common/KriDialog'
|
|||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
|
||||||
import { KriSelect, KriSelectItem } from '@/components/common/KriSelect'
|
import { KriSelect, KriSelectItem } from '@/components/common/KriSelect'
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
|
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
|
||||||
import { useLoading } from '@/hooks/useLoading'
|
import { useLoading } from '@/hooks/useLoading'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import { formatKst } from '@kri/common'
|
import { formatKst } from '@kri/common'
|
||||||
@@ -22,6 +21,7 @@ export type ValidationOption = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type ListUploadDialogProps = {
|
export type ListUploadDialogProps = {
|
||||||
|
prjctIdx: number
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
open?: boolean
|
open?: boolean
|
||||||
onOpenChange?: (open: boolean) => void
|
onOpenChange?: (open: boolean) => void
|
||||||
@@ -32,10 +32,12 @@ export type ListUploadDialogProps = {
|
|||||||
headerRows?: listHeader[]
|
headerRows?: listHeader[]
|
||||||
}
|
}
|
||||||
|
|
||||||
const ACCEPT_EXTENSIONS = ['.xlsx', '.xls', '.csv']
|
const ACCEPT_EXTENSIONS = ['.xlsx']
|
||||||
|
// 전체 초기화 후 등록(RESET_AND_INSERT)은 위험성 때문에 사용하지 않는다.
|
||||||
const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE
|
const FIXED_UPLOAD_MODE = ListUploadMode.ADD_AND_CHANGE
|
||||||
|
|
||||||
const ListUploadDialog = ({
|
const ListUploadDialog = ({
|
||||||
|
prjctIdx,
|
||||||
dialogId = 'listUploadDialog',
|
dialogId = 'listUploadDialog',
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
@@ -52,8 +54,6 @@ const ListUploadDialog = ({
|
|||||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||||
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
|
const [excelHeaders, setExcelHeaders] = useState<string[]>([])
|
||||||
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
|
const [otherHeaderTypeMap, setOtherHeaderTypeMap] = useState<Record<number, ListHeaderType>>({})
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
const [uploadMode, setUploadMode] = useState<ListUploadMode>(ListUploadMode.ADD_AND_CHANGE)
|
|
||||||
const [submitting, setSubmitting] = useState(false)
|
const [submitting, setSubmitting] = useState(false)
|
||||||
const [historyExpanded, setHistoryExpanded] = useState(false)
|
const [historyExpanded, setHistoryExpanded] = useState(false)
|
||||||
const [validation, setValidation] = useState<ValidationOption>({
|
const [validation, setValidation] = useState<ValidationOption>({
|
||||||
@@ -62,6 +62,7 @@ const ListUploadDialog = ({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPLOAD', active: resolvedOpen })
|
||||||
|
|
||||||
const normalizedHistory = useMemo(
|
const normalizedHistory = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -94,7 +95,6 @@ const ListUploadDialog = ({
|
|||||||
setSelectedFile(null)
|
setSelectedFile(null)
|
||||||
setExcelHeaders([])
|
setExcelHeaders([])
|
||||||
setOtherHeaderTypeMap({})
|
setOtherHeaderTypeMap({})
|
||||||
setUploadMode(ListUploadMode.ADD_AND_CHANGE)
|
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
setHistoryExpanded(false)
|
setHistoryExpanded(false)
|
||||||
setValidation({
|
setValidation({
|
||||||
@@ -137,7 +137,7 @@ const ListUploadDialog = ({
|
|||||||
|
|
||||||
const { read, utils } = await import('xlsx')
|
const { read, utils } = await import('xlsx')
|
||||||
const buffer = await file.arrayBuffer()
|
const buffer = await file.arrayBuffer()
|
||||||
const workbook = read(buffer, { type: 'array' })
|
const workbook = read(buffer, { type: 'array', sheetRows: 1, sheets: 0 })
|
||||||
const firstSheet = workbook.SheetNames[0]
|
const firstSheet = workbook.SheetNames[0]
|
||||||
if (!firstSheet) return []
|
if (!firstSheet) return []
|
||||||
const rows = utils.sheet_to_json<(string | number | null)[]>(workbook.Sheets[firstSheet], { header: 1, raw: false })
|
const rows = utils.sheet_to_json<(string | number | null)[]>(workbook.Sheets[firstSheet], { header: 1, raw: false })
|
||||||
@@ -151,10 +151,11 @@ const ListUploadDialog = ({
|
|||||||
const lower = file.name.toLowerCase()
|
const lower = file.name.toLowerCase()
|
||||||
const valid = ACCEPT_EXTENSIONS.some((ext) => lower.endsWith(ext))
|
const valid = ACCEPT_EXTENSIONS.some((ext) => lower.endsWith(ext))
|
||||||
if (!valid) {
|
if (!valid) {
|
||||||
alert('엑셀 또는 CSV 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)')
|
alert('XLSX 파일만 업로드 가능합니다. (.xlsx)')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (file.size > 100 * 1024 * 1024) { alert('100MB 이하의 파일을 선택해 주세요.'); return }
|
||||||
setSelectedFile(file)
|
setSelectedFile(file)
|
||||||
void withLoadingAsync(async () => {
|
void withLoadingAsync(async () => {
|
||||||
try {
|
try {
|
||||||
@@ -168,6 +169,7 @@ const ListUploadDialog = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
|
if (gate.submitBlocked || submitting) return
|
||||||
if (!selectedFile) {
|
if (!selectedFile) {
|
||||||
alert('업로드할 파일을 선택해 주세요.')
|
alert('업로드할 파일을 선택해 주세요.')
|
||||||
return
|
return
|
||||||
@@ -177,7 +179,7 @@ const ListUploadDialog = ({
|
|||||||
try {
|
try {
|
||||||
const specificHeader = Object.fromEntries(
|
const specificHeader = Object.fromEntries(
|
||||||
Object.entries(otherHeaderTypeMap)
|
Object.entries(otherHeaderTypeMap)
|
||||||
.map(([index, value]) => [String(Number(index) + 1), value])
|
.map(([index, value]) => [String(Math.max(101, ...orderedHeaderRows.map(row => row.listHderId + 1)) + Number(index) - baseHeaderRows.length), value])
|
||||||
.filter(([, value]) => value !== ListHeaderConst.TEXT),
|
.filter(([, value]) => value !== ListHeaderConst.TEXT),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -187,8 +189,6 @@ const ListUploadDialog = ({
|
|||||||
checkDuplicatePhone: validation.checkPhoneDuplicate,
|
checkDuplicatePhone: validation.checkPhoneDuplicate,
|
||||||
...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}),
|
...(Object.keys(specificHeader).length > 0 ? { specificHeader } : {}),
|
||||||
})
|
})
|
||||||
resetState()
|
|
||||||
handleOpenChange(false)
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -201,7 +201,9 @@ const ListUploadDialog = ({
|
|||||||
() =>
|
() =>
|
||||||
excelHeaders.map((header, index) => {
|
excelHeaders.map((header, index) => {
|
||||||
const serverHeader = compareRows[index]
|
const serverHeader = compareRows[index]
|
||||||
const isMatched = !!serverHeader && serverHeader.listHderNm === header && serverHeader.listHderOrder === index + 1
|
// compareRows가 이미 listHderOrder 기준 정렬이라 위치로 순서를 보장한다. listHderOrder 값 자체는
|
||||||
|
// COMMON 헤더가 101부터 채번되어 index+1과 리터럴하게 같지 않을 수 있으므로(정상), 이름만 비교한다.
|
||||||
|
const isMatched = !!serverHeader && serverHeader.listHderNm.trim() === header
|
||||||
const isSettingRequired = !hasCommonHeader && index >= baseHeaderRows.length
|
const isSettingRequired = !hasCommonHeader && index >= baseHeaderRows.length
|
||||||
return {
|
return {
|
||||||
header,
|
header,
|
||||||
@@ -254,44 +256,23 @@ const ListUploadDialog = ({
|
|||||||
open={resolvedOpen}
|
open={resolvedOpen}
|
||||||
onOpenChange={handleDialogOpenChange}
|
onOpenChange={handleDialogOpenChange}
|
||||||
title={<span className="text-2xl font-bold">리스트 업로드</span>}
|
title={<span className="text-2xl font-bold">리스트 업로드</span>}
|
||||||
contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] overflow-hidden"
|
contentClassName="w-[min(960px,95vw)] max-w-[95vw] sm:max-w-[min(960px,95vw)] max-h-[90vh] grid-rows-[auto_minmax(0,1fr)_auto] overflow-hidden"
|
||||||
bodyClassName="min-w-0 space-y-6 py-2"
|
bodyClassName="min-w-0 space-y-6 overflow-y-auto py-2"
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
|
<Button type="button" variant="outline" onClick={() => handleDialogOpenChange(false)} disabled={submitting}>
|
||||||
취소
|
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch}>
|
{!gate.hasCurrentJob && (
|
||||||
|
<Button type="button" onClick={handleSubmit} disabled={!selectedFile || submitting || hasHeaderMismatch || gate.submitBlocked}>
|
||||||
{submitting ? '업로드 중...' : '업로드'}
|
{submitting ? '업로드 중...' : '업로드'}
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{
|
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
|
||||||
/*
|
{!gate.hasCurrentJob && <>
|
||||||
<div className="space-y-3">
|
|
||||||
<Label className="text-lg font-semibold">업로드 방식</Label>
|
|
||||||
<RadioGroup
|
|
||||||
value={String(uploadMode)}
|
|
||||||
onValueChange={(value) => setUploadMode(Number(value) as ListUploadMode)}
|
|
||||||
className="flex flex-wrap items-center gap-6"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<RadioGroupItem value={String(ListUploadMode.CHANGE)} id="list-upload-mode-change" />
|
|
||||||
<Label htmlFor="list-upload-mode-change" className="cursor-pointer">
|
|
||||||
전체 교체
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<RadioGroupItem value={String(ListUploadMode.ADD)} id="list-upload-mode-add" />
|
|
||||||
<Label htmlFor="list-upload-mode-add" className="cursor-pointer">
|
|
||||||
추가
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
</RadioGroup>
|
|
||||||
</div>
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<Label className="text-lg font-semibold">업로드 파일</Label>
|
<Label className="text-lg font-semibold">업로드 파일</Label>
|
||||||
<div className="min-w-0 flex items-center gap-2">
|
<div className="min-w-0 flex items-center gap-2">
|
||||||
@@ -423,6 +404,7 @@ const ListUploadDialog = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</>}
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,17 +8,19 @@ import type { DataTableColumn } from '@/components/data-table/DataTable.type'
|
|||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||||
import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message'
|
import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message'
|
||||||
import { MessageType } from '@kri/common/noti-hub'
|
import { isSendCancelable, MessageType } from '@kri/common/noti-hub'
|
||||||
|
import { MESSAGE_TYPE_LABEL } from '@/const/messageTemplateConst'
|
||||||
import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser'
|
import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser'
|
||||||
import { formatKst } from '@kri/common'
|
import { formatKst } from '@kri/common'
|
||||||
import type { PaginationState } from '@tanstack/react-table'
|
import type { PaginationState } from '@tanstack/react-table'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import type { BulkSendInfo } from '@kri/common/noti-hub'
|
import type { BulkSendInfo, SendResultInfo } from '@kri/common/noti-hub'
|
||||||
import type { SendResultInfo } from '@/types/message'
|
import type { SendCancelRequest } from '@/types/message'
|
||||||
|
import { useSendCancel } from '@/hooks/useSendCancel'
|
||||||
import {clientEnv} from "@/lib/env.client";
|
import {clientEnv} from "@/lib/env.client";
|
||||||
import { formatKoreanPhoneNumber } from "@/utils/phone";
|
import { formatKoreanPhoneNumber } from "@/utils/phone";
|
||||||
|
|
||||||
export type MessageHistoryType = 'sms' | 'email'
|
export type MessageHistoryType = 'sms' | 'email' | 'kko'
|
||||||
|
|
||||||
export type MessageHistoryDialogProps = {
|
export type MessageHistoryDialogProps = {
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
@@ -29,9 +31,43 @@ export type MessageHistoryDialogProps = {
|
|||||||
const tabLabelMap: Record<MessageHistoryType, string> = {
|
const tabLabelMap: Record<MessageHistoryType, string> = {
|
||||||
sms: '문자',
|
sms: '문자',
|
||||||
email: '이메일',
|
email: '이메일',
|
||||||
|
kko: '알림톡',
|
||||||
}
|
}
|
||||||
|
|
||||||
const historyColumns: DataTableColumn<BulkSendInfo>[] = [
|
// 취소 일시가 없으면 빈 칸으로 둔다.
|
||||||
|
const formatCancelDt = (cancelDt: string | undefined) => (cancelDt ? formatKst(cancelDt, 'dateTime') : null)
|
||||||
|
|
||||||
|
// 버튼만 셀 가운데에 둔다. 취소 일시는 다른 컬럼과 같은 기본 정렬을 따른다.
|
||||||
|
const CancelButton = ({ disabled, onClick }: { disabled: boolean; onClick: () => void }) => (
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={(e) => {
|
||||||
|
// 벌크 목록은 행 클릭으로 상세를 여므로 버튼 클릭이 행 선택으로 번지지 않게 한다.
|
||||||
|
e.stopPropagation()
|
||||||
|
onClick()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
예약 취소
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
|
||||||
|
type CancelColumnOptions = {
|
||||||
|
/** false(면접원)이면 취소 버튼 대신 취소 일시(없으면 빈 칸)를 표시한다. */
|
||||||
|
canCancel: boolean
|
||||||
|
onCancel: (request: SendCancelRequest) => void
|
||||||
|
cancelPending: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다.
|
||||||
|
const canCancelDetail = (row: SendResultInfo) => isSendCancelable(row) && !!row.sendIdx
|
||||||
|
|
||||||
|
// 취소 컬럼에는 취소 가능하면 버튼, 아니면 취소 일시(없으면 빈 칸) 중 하나만 표시한다.
|
||||||
|
const buildHistoryColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn<BulkSendInfo>[] => [
|
||||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||||
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||||
{ id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') },
|
{ id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') },
|
||||||
@@ -39,15 +75,44 @@ const historyColumns: DataTableColumn<BulkSendInfo>[] = [
|
|||||||
{ id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() },
|
{ id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() },
|
||||||
{ id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() },
|
{ id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() },
|
||||||
{ id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() },
|
{ id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() },
|
||||||
|
{
|
||||||
|
id: 'cancelDt',
|
||||||
|
header: '취소 일시',
|
||||||
|
accessorFn: (row) => row.cancelDt ?? '',
|
||||||
|
cell: ({ row }) =>
|
||||||
|
canCancel && isSendCancelable(row.original) ? (
|
||||||
|
<CancelButton
|
||||||
|
disabled={cancelPending}
|
||||||
|
onClick={() => onCancel({ type: 'bulk', bulkSendKey: row.original.bulkSendKey })}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
formatCancelDt(row.original.cancelDt)
|
||||||
|
),
|
||||||
|
},
|
||||||
{ id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') },
|
{ id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') },
|
||||||
{ id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' },
|
{ id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const detailColumns: DataTableColumn<SendResultInfo>[] = [
|
const buildDetailColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn<SendResultInfo>[] => [
|
||||||
|
{ id: 'sendTy', header: '유형', accessorFn: (row) => MESSAGE_TYPE_LABEL[row.sendTy] ?? String(row.sendTy) },
|
||||||
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' },
|
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' },
|
||||||
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
|
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
|
||||||
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || (row.sendTel ? formatKoreanPhoneNumber(row.sendTel) : '') || '-' },
|
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || (row.sendTel ? formatKoreanPhoneNumber(row.sendTel) : '') || '-' },
|
||||||
{ id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) },
|
{ id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) },
|
||||||
|
{
|
||||||
|
// 개별 건의 현재 취소 상태는 결과 컬럼(resultCode 라벨)으로 표시한다.
|
||||||
|
id: 'cancelDt',
|
||||||
|
header: '취소 일시',
|
||||||
|
accessorFn: (row) => row.cancelDt ?? '',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const { sendIdx, cancelDt } = row.original
|
||||||
|
return canCancel && canCancelDetail(row.original) && sendIdx ? (
|
||||||
|
<CancelButton disabled={cancelPending} onClick={() => onCancel({ type: 'single', sendIdx })} />
|
||||||
|
) : (
|
||||||
|
formatCancelDt(cancelDt)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||||
]
|
]
|
||||||
@@ -69,19 +134,15 @@ const MessageHistoryDialog = ({
|
|||||||
|
|
||||||
const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email')
|
const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email')
|
||||||
const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
||||||
const lmsListQuery = useBulkSendListQuery(MessageType.LMS_MMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
|
const kkoListQuery = useBulkSendListQuery(MessageType.KKO, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'kko')
|
||||||
|
|
||||||
const visibleRows = useMemo(() => {
|
const visibleRows = useMemo(() => {
|
||||||
if (tab === 'email') return emailListQuery.data ?? []
|
if (tab === 'email') return emailListQuery.data ?? []
|
||||||
|
if (tab === 'kko') return kkoListQuery.data ?? []
|
||||||
|
|
||||||
// 문자 길이에 따라 SMS로 발송된 건도 자동으로 LMS/MMS로 전환될 수 있는데, 이 경우 두 목록 API가
|
// 21/22/23 경로는 모두 문자 채널 전체를 반환하므로 한 번만 조회한다.
|
||||||
// 같은 bulkSendKey를 각각 반환해 합치면 행이 중복된다. bulkSendKey 기준으로 한 번만 남긴다.
|
return [...(smsListQuery.data ?? [])].sort((a, b) => (b.regDt ?? '').localeCompare(a.regDt ?? ''))
|
||||||
const merged = new Map<string, BulkSendInfo>()
|
}, [tab, emailListQuery.data, smsListQuery.data, kkoListQuery.data])
|
||||||
for (const row of [...(smsListQuery.data ?? []), ...(lmsListQuery.data ?? [])]) {
|
|
||||||
merged.set(row.bulkSendKey, row)
|
|
||||||
}
|
|
||||||
return Array.from(merged.values()).sort((a, b) => (b.regDt ?? '').localeCompare(a.regDt ?? ''))
|
|
||||||
}, [tab, emailListQuery.data, smsListQuery.data, lmsListQuery.data])
|
|
||||||
|
|
||||||
const detailQuery = useBulkSendDetailQuery(
|
const detailQuery = useBulkSendDetailQuery(
|
||||||
selectedKey ?? '',
|
selectedKey ?? '',
|
||||||
@@ -94,6 +155,9 @@ const MessageHistoryDialog = ({
|
|||||||
enabled && !!selectedKey,
|
enabled && !!selectedKey,
|
||||||
)
|
)
|
||||||
const detailExcelMutation = useBulkSendDetailExcelMutation()
|
const detailExcelMutation = useBulkSendDetailExcelMutation()
|
||||||
|
const { canCancel, cancel, isPending: cancelPending } = useSendCancel()
|
||||||
|
const historyColumns = buildHistoryColumns({ canCancel, onCancel: cancel, cancelPending })
|
||||||
|
const detailColumns = buildDetailColumns({ canCancel, onCancel: cancel, cancelPending })
|
||||||
|
|
||||||
const handleOpenChange = (nextOpen: boolean) => {
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
onOpenChange?.(nextOpen)
|
onOpenChange?.(nextOpen)
|
||||||
@@ -132,7 +196,7 @@ const MessageHistoryDialog = ({
|
|||||||
title={<span className="text-2xl font-bold">발송 이력</span>}
|
title={<span className="text-2xl font-bold">발송 이력</span>}
|
||||||
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
|
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
|
||||||
closeLabel="닫기"
|
closeLabel="닫기"
|
||||||
bodyClassName="space-y-4"
|
bodyClassName="min-w-0 space-y-4"
|
||||||
>
|
>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
|
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
|
||||||
@@ -141,6 +205,9 @@ const MessageHistoryDialog = ({
|
|||||||
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => handleSelectTab('email')}>
|
<Button type="button" variant={tab === 'email' ? 'default' : 'outline'} onClick={() => handleSelectTab('email')}>
|
||||||
{tabLabelMap.email}
|
{tabLabelMap.email}
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button type="button" variant={tab === 'kko' ? 'default' : 'outline'} onClick={() => handleSelectTab('kko')}>
|
||||||
|
{tabLabelMap.kko}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border overflow-hidden">
|
<div className="rounded-md border overflow-hidden">
|
||||||
@@ -169,7 +236,7 @@ const MessageHistoryDialog = ({
|
|||||||
<DataTable<SendResultInfo>
|
<DataTable<SendResultInfo>
|
||||||
columns={detailColumns}
|
columns={detailColumns}
|
||||||
data={detailQuery.data?.content ?? []}
|
data={detailQuery.data?.content ?? []}
|
||||||
getRowId={(row) => row.cmid}
|
getRowId={(row) => (row.sendIdx ? String(row.sendIdx) : row.cmid)}
|
||||||
isClient={false}
|
isClient={false}
|
||||||
pageCount={detailQuery.data?.totalPages ?? 0}
|
pageCount={detailQuery.data?.totalPages ?? 0}
|
||||||
totalCount={detailQuery.data?.totalElements ?? 0}
|
totalCount={detailQuery.data?.totalElements ?? 0}
|
||||||
|
|||||||
@@ -11,26 +11,23 @@ import { useDialog } from '@/hooks/useDialog'
|
|||||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||||
import {
|
import {
|
||||||
useMainTemplateIdxQuery,
|
useMainTemplateIdxQuery,
|
||||||
useSendBulkMessageMutation,
|
|
||||||
useTemplateListQuery,
|
useTemplateListQuery,
|
||||||
useTemplateQuery,
|
useTemplateQuery,
|
||||||
} from '@/query/message'
|
} from '@/query/message'
|
||||||
import { ChannelType, TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
|
import { getNearestFutureDateTime, isPastReserveDateTime, toReserveSendDt } from '@/lib/datetime'
|
||||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
|
||||||
import { cn } from '@/lib/utils'
|
|
||||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
|
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
|
||||||
import { ListHeaderConst } from '@/const/listConst'
|
import { ListHeaderConst } from '@/const/listConst'
|
||||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||||
import { KriEditor } from '@/components/kri-editor'
|
import MessageSendPreview from '@/components/message-template/MessageSendPreview'
|
||||||
import { normalizeQrCodeForEditor, QR_CODE_ALLOWED_HTML, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
|
import type { MessageSendChannel, TemplateSummaryWithPurpose } from '@/types/message'
|
||||||
import { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
|
import { useSubmitListJob } from '@/query/list-job'
|
||||||
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
|
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
|
||||||
import type { TemplateEmailWithAttachments } from '@/types/message'
|
import { MESSAGE_JOB_TYPE } from '@/const/listJobConst'
|
||||||
|
import { MESSAGE_CHANNEL_TYPE, TEMPLATE_PURPOSE } from '@/const/messageTemplateConst'
|
||||||
|
|
||||||
export type MessageSendMode = 'email' | 'sms'
|
export type MessageSendMode = MessageSendChannel
|
||||||
|
|
||||||
export type MessageSendDialogProps = {
|
export type MessageSendDialogProps = {
|
||||||
dialogId?: DialogId
|
dialogId?: DialogId
|
||||||
@@ -47,6 +44,7 @@ export type MessageSendDialogProps = {
|
|||||||
const titleMap: Record<MessageSendMode, string> = {
|
const titleMap: Record<MessageSendMode, string> = {
|
||||||
email: '메일 발송',
|
email: '메일 발송',
|
||||||
sms: '문자 발송',
|
sms: '문자 발송',
|
||||||
|
kko: '알림톡 발송',
|
||||||
}
|
}
|
||||||
|
|
||||||
const MessageSendDialog = ({
|
const MessageSendDialog = ({
|
||||||
@@ -63,7 +61,7 @@ const MessageSendDialog = ({
|
|||||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||||
const { selectedProject } = useSelectedProject()
|
const { selectedProject } = useSelectedProject()
|
||||||
|
|
||||||
const chnnlTy = mode === 'email' ? ChannelType.EMAIL : ChannelType.SMS
|
const chnnlTy = MESSAGE_CHANNEL_TYPE[mode]
|
||||||
|
|
||||||
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
||||||
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
||||||
@@ -75,11 +73,15 @@ const MessageSendDialog = ({
|
|||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
|
||||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||||
|
const gate = useListJobGate({ prjctIdx, jobType: MESSAGE_JOB_TYPE[mode], active: resolvedOpen })
|
||||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ''
|
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ''
|
||||||
const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0
|
const enabled = resolvedOpen && !!selectedProject && prjctIdx > 0
|
||||||
|
|
||||||
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
|
const templateListQuery = useTemplateListQuery(chnnlTy, itrntPrjctCd, enabled)
|
||||||
const templateList: TemplateSummary[] = templateListQuery.data ?? []
|
// 대량 발송 및 bulk key 생성 경로에서는 휴대전화번호 인증 템플릿(tmplatPurpose === 1)을 선택할 수 없다.
|
||||||
|
const templateList: TemplateSummaryWithPurpose[] = (templateListQuery.data ?? []).filter(
|
||||||
|
(t) => t.tmplatPurpose !== TEMPLATE_PURPOSE.PHONE_VERIFICATION,
|
||||||
|
)
|
||||||
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
|
const templateDetailQuery = useTemplateQuery(templateIdx ?? 0, enabled && !!templateIdx)
|
||||||
const selectedTemplate = templateDetailQuery.data ?? null
|
const selectedTemplate = templateDetailQuery.data ?? null
|
||||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||||
@@ -99,7 +101,7 @@ const MessageSendDialog = ({
|
|||||||
[listHeaders, headerType],
|
[listHeaders, headerType],
|
||||||
)
|
)
|
||||||
|
|
||||||
const sendBulkMessageMutation = useSendBulkMessageMutation(mode, prjctIdx)
|
const sendBulkMessageMutation = useSubmitListJob(prjctIdx)
|
||||||
|
|
||||||
const mainTemplateAppliedRef = useRef(false)
|
const mainTemplateAppliedRef = useRef(false)
|
||||||
|
|
||||||
@@ -159,6 +161,7 @@ const MessageSendDialog = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
|
if (gate.submitBlocked || submitting) return
|
||||||
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
|
||||||
if (!selectedTemplate || !templateIdx) {
|
if (!selectedTemplate || !templateIdx) {
|
||||||
alert('템플릿을 선택해 주세요.')
|
alert('템플릿을 선택해 주세요.')
|
||||||
@@ -172,7 +175,7 @@ const MessageSendDialog = ({
|
|||||||
alert('선택한 템플릿에 발송자 메일이 등록되어 있지 않습니다. 템플릿 설정을 확인해 주세요.')
|
alert('선택한 템플릿에 발송자 메일이 등록되어 있지 않습니다. 템플릿 설정을 확인해 주세요.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (mode === 'sms' && !templateSenderTel) {
|
if (mode !== 'email' && !templateSenderTel) {
|
||||||
alert('선택한 템플릿에 발송 번호가 등록되어 있지 않습니다. 템플릿 설정을 확인해 주세요.')
|
alert('선택한 템플릿에 발송 번호가 등록되어 있지 않습니다. 템플릿 설정을 확인해 주세요.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -180,6 +183,10 @@ const MessageSendDialog = ({
|
|||||||
alert('예약 발송 일시를 선택해 주세요.')
|
alert('예약 발송 일시를 선택해 주세요.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (scheduleType === 'reserve' && isPastReserveDateTime(reserveAt)) {
|
||||||
|
alert('예약 발송 일시는 현재 시각 이후로 선택해 주세요.')
|
||||||
|
return
|
||||||
|
}
|
||||||
const listFilter = buildListFilter()
|
const listFilter = buildListFilter()
|
||||||
if (target === 'selected' && listFilter.sidSet.length === 0) {
|
if (target === 'selected' && listFilter.sidSet.length === 0) {
|
||||||
alert('수신 대상이 없습니다.')
|
alert('수신 대상이 없습니다.')
|
||||||
@@ -188,21 +195,18 @@ const MessageSendDialog = ({
|
|||||||
|
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
const res = await sendBulkMessageMutation.mutateAsync({
|
await sendBulkMessageMutation.mutateAsync({
|
||||||
|
jobType: MESSAGE_JOB_TYPE[mode],
|
||||||
|
path: `messages/${mode}`,
|
||||||
|
body: {
|
||||||
tmplatIdx: templateIdx,
|
tmplatIdx: templateIdx,
|
||||||
resve: scheduleType === 'reserve',
|
resve: scheduleType === 'reserve',
|
||||||
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
|
sendDt: scheduleType === 'reserve' ? toReserveSendDt(reserveAt) : undefined,
|
||||||
listFilter,
|
listFilter,
|
||||||
destHeaderIds: [targetHeaderId],
|
destHeaderIds: [targetHeaderId],
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
if (res.failCount > 0) {
|
|
||||||
alert(`대상 ${res.targetCount}건 중 ${res.acceptCount}건 접수, ${res.failCount}건 실패했습니다.`)
|
|
||||||
} else {
|
|
||||||
alert(`대상 ${res.targetCount}건 발송 요청이 완료되었습니다.`)
|
|
||||||
}
|
|
||||||
onSent?.()
|
onSent?.()
|
||||||
handleOpenChange(false)
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -215,19 +219,23 @@ const MessageSendDialog = ({
|
|||||||
open={resolvedOpen}
|
open={resolvedOpen}
|
||||||
onOpenChange={handleOpenChange}
|
onOpenChange={handleOpenChange}
|
||||||
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
|
||||||
contentClassName="sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"
|
contentClassName={gate.hasCurrentJob ? "sm:max-w-[700px] max-h-[90vh] overflow-y-auto" : "sm:max-w-[1100px] max-h-[90vh] overflow-y-auto"}
|
||||||
bodyClassName="grid grid-cols-1 lg:grid-cols-2 gap-6"
|
bodyClassName={gate.hasCurrentJob ? "space-y-4" : "grid grid-cols-1 lg:grid-cols-2 gap-6"}
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
|
||||||
취소
|
{gate.hasCurrentJob ? '닫기' : '취소'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" onClick={handleConfirm} disabled={submitting}>
|
{!gate.hasCurrentJob && (
|
||||||
|
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
|
||||||
{submitting ? '발송 중...' : '발송'}
|
{submitting ? '발송 중...' : '발송'}
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" className="lg:col-span-2" />
|
||||||
|
{!gate.hasCurrentJob && <>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label className="text-base">템플릿을 선택해 주세요</Label>
|
<Label className="text-base">템플릿을 선택해 주세요</Label>
|
||||||
@@ -319,51 +327,8 @@ const MessageSendDialog = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border p-4 space-y-2">
|
<MessageSendPreview chnnlTy={chnnlTy} template={selectedTemplate} />
|
||||||
<p className="text-lg font-semibold">미리보기</p>
|
</>}
|
||||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
|
||||||
{selectedTemplate && (
|
|
||||||
<>
|
|
||||||
{chnnlTy !== ChannelType.SMS && (
|
|
||||||
<div className="rounded border p-2 text-lg font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
|
|
||||||
)}
|
|
||||||
{chnnlTy === ChannelType.SMS ? (
|
|
||||||
<div className="flex flex-col items-center">
|
|
||||||
<KriEditor
|
|
||||||
mode="sms"
|
|
||||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
|
|
||||||
onChange={() => {}}
|
|
||||||
isSmsReadOnly
|
|
||||||
placeholder="문자 내용을 입력해 주세요"
|
|
||||||
className="max-w-80 mx-0"
|
|
||||||
debounceMs={600}
|
|
||||||
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div
|
|
||||||
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: renderQrCodePreviewHtml(
|
|
||||||
applyLinkPreviewClass(
|
|
||||||
sanitizeHtmlForPreview(
|
|
||||||
normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || '(내용 없음)',
|
|
||||||
QR_CODE_ALLOWED_HTML,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<TemplateAttachmentList
|
|
||||||
tmplatIdx={selectedTemplate.tmplatIdx}
|
|
||||||
atchFl={(selectedTemplate as TemplateEmailWithAttachments).atchFl}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,18 +14,17 @@ import {
|
|||||||
useTemplateListQuery,
|
useTemplateListQuery,
|
||||||
useTemplateQuery,
|
useTemplateQuery,
|
||||||
} from '@/query/message'
|
} from '@/query/message'
|
||||||
import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
|
import type { TemplateSummary } from '@kri/common/noti-hub'
|
||||||
import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHtml'
|
import { getNearestFutureDateTime, isPastReserveDateTime, toReserveSendDt } from '@/lib/datetime'
|
||||||
import { KriEditor } from '@/components/kri-editor'
|
|
||||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
|
||||||
import { escapeHtml, substituteVariables } from '@/lib/variableSubstitution'
|
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import type { MessageSendChannel, TemplateEmailWithAttachments } from '@/types/message'
|
import type { MessageSendChannel, PhoneVerificationSendData } from '@/types/message'
|
||||||
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
|
import MessageSendPreview from '@/components/message-template/MessageSendPreview'
|
||||||
|
import { TEMPLATE_PURPOSE, MESSAGE_CHANNEL_TYPE } from '@/const/messageTemplateConst'
|
||||||
|
|
||||||
const titleMap: Record<MessageSendChannel, string> = {
|
const titleMap: Record<MessageSendChannel, string> = {
|
||||||
email: '메일 발송',
|
email: '메일 발송',
|
||||||
sms: '문자 발송',
|
sms: '문자 발송',
|
||||||
|
kko: '알림톡 발송',
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SingleMessageSendDialogProps = {
|
export type SingleMessageSendDialogProps = {
|
||||||
@@ -56,7 +55,7 @@ const SingleMessageSendDialog = ({
|
|||||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||||
|
|
||||||
const chnnlTy = channel === 'email' ? ChannelType.EMAIL : ChannelType.SMS
|
const chnnlTy = MESSAGE_CHANNEL_TYPE[channel]
|
||||||
|
|
||||||
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
const [templateIdx, setTemplateIdx] = useState<number | null>(null)
|
||||||
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
const [scheduleType, setScheduleType] = useState<'instant' | 'reserve'>('instant')
|
||||||
@@ -71,8 +70,8 @@ const SingleMessageSendDialog = ({
|
|||||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
|
||||||
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
const mainTemplateIdx = mainTemplateQuery.data ?? null
|
||||||
|
|
||||||
const previewValues = variableValues ?? {}
|
// tmplatPurpose === 1(휴대전화번호 인증) 템플릿은 SMS/LMS 단건 즉시 발송만 허용한다.
|
||||||
const resolvedTitle = selectedTemplate ? substituteVariables(selectedTemplate.tmplatTitle ?? '', previewValues) : ''
|
const isPhoneVerificationTemplate = selectedTemplate?.tmplatPurpose === TEMPLATE_PURPOSE.PHONE_VERIFICATION
|
||||||
|
|
||||||
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
|
const sendSingleMutation = useSendSingleMessageMutation(channel, prjctIdx)
|
||||||
|
|
||||||
@@ -86,6 +85,11 @@ const SingleMessageSendDialog = ({
|
|||||||
mainTemplateAppliedRef.current = false
|
mainTemplateAppliedRef.current = false
|
||||||
}, [resolvedOpen])
|
}, [resolvedOpen])
|
||||||
|
|
||||||
|
// 인증 템플릿 선택 시 예약 발송 옵션을 강제로 즉시 발송으로 되돌린다.
|
||||||
|
useEffect(() => {
|
||||||
|
if (isPhoneVerificationTemplate) setScheduleType('instant')
|
||||||
|
}, [isPhoneVerificationTemplate])
|
||||||
|
|
||||||
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
// 대표 템플릿이 있으면 최초 1회 자동 선택
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
|
if (!enabled || mainTemplateAppliedRef.current || !mainTemplateQuery.isSuccess) return
|
||||||
@@ -123,17 +127,33 @@ const SingleMessageSendDialog = ({
|
|||||||
alert('예약 발송 일시를 선택해 주세요.')
|
alert('예약 발송 일시를 선택해 주세요.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (scheduleType === 'reserve' && isPastReserveDateTime(reserveAt)) {
|
||||||
|
alert('예약 발송 일시는 현재 시각 이후로 선택해 주세요.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
setSubmitting(true)
|
setSubmitting(true)
|
||||||
try {
|
try {
|
||||||
await sendSingleMutation.mutateAsync({
|
const res = await sendSingleMutation.mutateAsync({
|
||||||
tmplatIdx: templateIdx,
|
tmplatIdx: templateIdx,
|
||||||
resve: scheduleType === 'reserve',
|
resve: scheduleType === 'reserve',
|
||||||
sendDt: scheduleType === 'reserve' ? new Date(reserveAt).toISOString() : undefined,
|
sendDt: scheduleType === 'reserve' ? toReserveSendDt(reserveAt) : undefined,
|
||||||
sid,
|
sid,
|
||||||
destHeaderIds: [destHeaderId],
|
destHeaderIds: [destHeaderId],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// cmid는 발송 CMID이며 verificationId와는 다른 식별자이므로 혼용하지 않는다.
|
||||||
|
// 서버 응답 바디가 비어 있는 경우(res가 null)를 대비해 안전하게 접근한다.
|
||||||
|
const cmid = res?.cmid
|
||||||
|
if (isPhoneVerificationTemplate && res?.data) {
|
||||||
|
// 휴대전화번호 인증 응답. verificationId/expireDt는 이후 인증 단계에서 사용할 값이나,
|
||||||
|
// 이 시스템에서는 인증번호 확인 절차를 사용하지 않으므로 현재는 별도로 활용하지 않는다.
|
||||||
|
const { verificationId, expireDt } = res.data as PhoneVerificationSendData
|
||||||
|
void verificationId
|
||||||
|
void expireDt
|
||||||
|
}
|
||||||
|
void cmid
|
||||||
|
|
||||||
alert('발송 요청이 완료되었습니다.')
|
alert('발송 요청이 완료되었습니다.')
|
||||||
onSent?.()
|
onSent?.()
|
||||||
handleOpenChange(false)
|
handleOpenChange(false)
|
||||||
@@ -177,6 +197,9 @@ const SingleMessageSendDialog = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{isPhoneVerificationTemplate ? (
|
||||||
|
<p className="text-sm text-muted-foreground">휴대전화번호 인증 템플릿은 즉시 발송만 가능합니다.</p>
|
||||||
|
) : (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label className="text-sm">발송 일시</Label>
|
<Label className="text-sm">발송 일시</Label>
|
||||||
<RadioGroup
|
<RadioGroup
|
||||||
@@ -197,51 +220,10 @@ const SingleMessageSendDialog = ({
|
|||||||
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
|
<KriDateTimePicker value={reserveAt} onChange={setReserveAt} placeholder="예약 일시 선택" />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2 rounded-md border p-4">
|
<MessageSendPreview chnnlTy={chnnlTy} template={selectedTemplate} variableValues={variableValues ?? {}} />
|
||||||
<p className="text-sm font-semibold">미리보기</p>
|
|
||||||
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
|
|
||||||
{selectedTemplate && (
|
|
||||||
<>
|
|
||||||
{chnnlTy !== ChannelType.SMS && (
|
|
||||||
<div className="rounded border p-2 text-sm font-semibold">{resolvedTitle ? `제목: ${resolvedTitle}` : '(제목 없음)'}</div>
|
|
||||||
)}
|
|
||||||
{chnnlTy === ChannelType.SMS ? (
|
|
||||||
<div className="flex flex-col items-center">
|
|
||||||
<KriEditor
|
|
||||||
mode="sms"
|
|
||||||
value={substituteVariables((selectedTemplate as TemplateSms).tmplatBody ?? '', previewValues)}
|
|
||||||
onChange={() => {}}
|
|
||||||
isSmsReadOnly
|
|
||||||
placeholder="문자 내용을 입력해 주세요"
|
|
||||||
className="max-w-80 mx-0"
|
|
||||||
debounceMs={600}
|
|
||||||
smsTitle={resolvedTitle}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div
|
|
||||||
className="rounded-md border bg-muted/30 p-3 text-sm"
|
|
||||||
dangerouslySetInnerHTML={{
|
|
||||||
__html: sanitizeHtmlForPreview(
|
|
||||||
substituteVariables(
|
|
||||||
selectedTemplate.tmplatBody || '(내용 없음)',
|
|
||||||
Object.fromEntries(Object.entries(previewValues).map(([key, val]) => [key, escapeHtml(val)])),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<TemplateAttachmentList
|
|
||||||
tmplatIdx={selectedTemplate.tmplatIdx}
|
|
||||||
atchFl={(selectedTemplate as TemplateEmailWithAttachments).atchFl}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</KriDialog>
|
</KriDialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { KriEditorProps, KriEditorMode } from "./types";
|
|||||||
import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
|
import { KriEditorHtmlOnly } from "./KriEditorHtmlOnly";
|
||||||
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
|
import { KriEditorWysiwyg } from "./KriEditorWysiwyg";
|
||||||
import {KriEditorSms} from "./KriEditorSms";
|
import {KriEditorSms} from "./KriEditorSms";
|
||||||
|
import { KriEditorKko } from "./KriEditorKko";
|
||||||
|
|
||||||
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
|
function resolveMode(mode?: KriEditorMode, editorMode?: KriEditorMode): KriEditorMode {
|
||||||
return mode ?? editorMode ?? "wysiwyg";
|
return mode ?? editorMode ?? "wysiwyg";
|
||||||
@@ -20,5 +21,9 @@ export function KriEditor(props: KriEditorProps) {
|
|||||||
return <KriEditorSms {...props} mode={mode} />
|
return <KriEditorSms {...props} mode={mode} />
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (mode === "kko") {
|
||||||
|
return <KriEditorKko {...props} mode={mode} />;
|
||||||
|
}
|
||||||
|
|
||||||
return <KriEditorWysiwyg {...props} mode={mode} />;
|
return <KriEditorWysiwyg {...props} mode={mode} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,7 +65,6 @@ export function KriEditorHtmlOnly({
|
|||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
applyExternalValue(value || '')
|
applyExternalValue(value || '')
|
||||||
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
|
// 최초 마운트 시 1회만 실행 — 이후 value 변경은 아래 effect가 처리한다.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
|
|||||||
59
src/components/kri-editor/KriEditorKko.tsx
Normal file
59
src/components/kri-editor/KriEditorKko.tsx
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { User } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import type { KriEditorProps } from './types'
|
||||||
|
|
||||||
|
type KkoEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'kko' }
|
||||||
|
|
||||||
|
export function KriEditorKko({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
placeholder = '미리볼 내용이 없습니다.',
|
||||||
|
className,
|
||||||
|
kkoTitle = '',
|
||||||
|
kkoSenderName = '',
|
||||||
|
kkoHeaderLabel = '알림톡 도착',
|
||||||
|
}: KkoEditorProps) {
|
||||||
|
const body = value ?? ''
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
|
||||||
|
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
|
||||||
|
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
|
||||||
|
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
|
||||||
|
<div className="flex h-full flex-col bg-[#d6e4f7] pt-8 pb-4">
|
||||||
|
{kkoSenderName ? (
|
||||||
|
<div className="border-b border-black/10 px-4 pb-3 text-center text-sm font-bold text-gray-900">{kkoSenderName}</div>
|
||||||
|
) : null}
|
||||||
|
<div className="flex-1 overflow-y-auto px-3 py-3">
|
||||||
|
{kkoSenderName ? (
|
||||||
|
<div className="mb-1 flex items-center gap-2">
|
||||||
|
<span aria-hidden="true" className="flex size-8 shrink-0 items-center justify-center rounded-full bg-gray-300 text-white">
|
||||||
|
<User className="size-5" />
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-gray-600">{kkoSenderName}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<div className="relative mr-3 ml-10 rounded-xl bg-white shadow-sm">
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="absolute -top-3 -right-3 flex size-8 items-center justify-center rounded-full bg-gray-800 text-[9px] font-bold text-white"
|
||||||
|
>
|
||||||
|
kakao
|
||||||
|
</span>
|
||||||
|
<div className="rounded-t-xl bg-[#FEE500] px-4 py-3 text-sm font-bold text-gray-900">{kkoHeaderLabel}</div>
|
||||||
|
{kkoTitle ? <div className="px-4 pt-3 text-sm font-bold break-words whitespace-pre-wrap text-gray-800">{kkoTitle}</div> : null}
|
||||||
|
{body.trim() ? (
|
||||||
|
<div className="px-4 py-3 text-sm leading-relaxed break-words whitespace-pre-wrap text-gray-700">{body}</div>
|
||||||
|
) : (
|
||||||
|
<div className="px-4 py-3 text-sm text-gray-400">{placeholder}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-2 left-1/2 h-1 w-32 -translate-x-1/2 rounded-full bg-gray-800" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -8,8 +8,23 @@ import { useTextareaInsert } from './hooks/useTextareaInsert'
|
|||||||
|
|
||||||
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
|
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
|
||||||
|
|
||||||
|
type SmsMessageType = 'SMS' | 'LMS' | 'MMS'
|
||||||
|
|
||||||
function calculateBytes(value: string): number {
|
function calculateBytes(value: string): number {
|
||||||
return Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 127 ? 2 : 1), 0)
|
return new TextEncoder().encode(value).byteLength
|
||||||
|
}
|
||||||
|
|
||||||
|
// 첨부파일이 있으면 MMS, 제목이 있거나 smsMaxBytes 이상이면 LMS, 나머지는 SMS로 미리보기 판정한다.
|
||||||
|
function getSmsMessageType(hasAttachment: boolean, byteSize: number, smsMaxBytes: number, title: string): SmsMessageType {
|
||||||
|
if (hasAttachment) return 'MMS'
|
||||||
|
if (byteSize >= smsMaxBytes || Boolean(title)) return 'LMS'
|
||||||
|
return 'SMS'
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTextareaMinHeight(hasImages: boolean, hasTitle: boolean): string {
|
||||||
|
if (hasImages) return '160px'
|
||||||
|
if (hasTitle) return '320px'
|
||||||
|
return '360px'
|
||||||
}
|
}
|
||||||
|
|
||||||
export function KriEditorSms({
|
export function KriEditorSms({
|
||||||
@@ -26,17 +41,33 @@ export function KriEditorSms({
|
|||||||
isSmsReadOnly = false,
|
isSmsReadOnly = false,
|
||||||
smsMaxBytes = 90,
|
smsMaxBytes = 90,
|
||||||
lmsMaxBytes = 2000,
|
lmsMaxBytes = 2000,
|
||||||
|
smsPreviewSuffix = '',
|
||||||
|
smsHasAttachment = false,
|
||||||
|
smsImages = [],
|
||||||
|
smsFrameClassName,
|
||||||
}: SmsEditorProps) {
|
}: SmsEditorProps) {
|
||||||
const [text, setText] = React.useState(value || '')
|
const [text, setText] = React.useState(value || '')
|
||||||
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
|
||||||
const latestTextRef = React.useRef(text)
|
const latestTextRef = React.useRef(text)
|
||||||
const lastTypeRef = React.useRef<'SMS' | 'LMS' | null>(null)
|
const lastTypeRef = React.useRef<SmsMessageType | null>(null)
|
||||||
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
|
||||||
const textareaInsert = useTextareaInsert(textareaRef)
|
const textareaInsert = useTextareaInsert(textareaRef)
|
||||||
const byteSize = React.useMemo(() => calculateBytes(text), [text])
|
const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text
|
||||||
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
|
const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText])
|
||||||
|
const messageType = getSmsMessageType(smsHasAttachment, byteSize, smsMaxBytes, smsTitle)
|
||||||
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
|
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
|
||||||
|
|
||||||
|
function getBadgeColor(): string {
|
||||||
|
switch (messageType) {
|
||||||
|
case 'SMS':
|
||||||
|
return 'bg-red-500'
|
||||||
|
case 'LMS':
|
||||||
|
return 'bg-blue-500'
|
||||||
|
case 'MMS':
|
||||||
|
return 'bg-green-500'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const commitText = React.useCallback((next: string, immediate = false) => {
|
const commitText = React.useCallback((next: string, immediate = false) => {
|
||||||
setText(next)
|
setText(next)
|
||||||
latestTextRef.current = next
|
latestTextRef.current = next
|
||||||
@@ -80,31 +111,45 @@ export function KriEditorSms({
|
|||||||
return (
|
return (
|
||||||
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
|
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
|
||||||
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
|
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
|
||||||
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
|
<div className={cn('relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl', smsFrameClassName)}>
|
||||||
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
|
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
|
||||||
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
|
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
|
||||||
<div className="mb-3 flex items-center justify-between px-2">
|
<div className="mb-3 flex items-center justify-between px-2">
|
||||||
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
|
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
|
||||||
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}>
|
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', getBadgeColor())}>
|
||||||
{messageType}
|
{messageType}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-1 flex-col overflow-hidden rounded-2xl bg-white shadow-sm">
|
<div className={cn('flex flex-1 flex-col rounded-2xl bg-white shadow-sm', smsImages.length > 0 ? 'overflow-y-auto' : 'overflow-hidden')}>
|
||||||
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
|
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
|
||||||
|
{smsImages.length > 0 ? (
|
||||||
|
<div className="flex shrink-0 flex-col gap-2 px-4 pt-3">
|
||||||
|
{smsImages.map((image) => (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element -- data/Object URL 미리보기라 next/image 최적화 대상이 아님
|
||||||
|
<img key={image.fileName} src={image.src} alt={image.fileName} title={image.fileName} className="w-full rounded-md object-contain" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
<textarea
|
<textarea
|
||||||
ref={textareaRef}
|
ref={textareaRef}
|
||||||
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
|
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
|
||||||
value={text}
|
value={text}
|
||||||
onChange={(event) => {
|
onChange={(event) => {
|
||||||
const next = event.target.value
|
const next = event.target.value
|
||||||
if (calculateBytes(next) <= lmsMaxBytes) commitText(next)
|
const nextPreview = smsPreviewSuffix ? `${next}\n${smsPreviewSuffix}` : next
|
||||||
|
if (calculateBytes(nextPreview) <= lmsMaxBytes) commitText(next)
|
||||||
}}
|
}}
|
||||||
onBlur={() => flushChange(latestTextRef.current)}
|
onBlur={() => flushChange(latestTextRef.current)}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
readOnly={isSmsReadOnly}
|
readOnly={isSmsReadOnly}
|
||||||
style={{ minHeight: smsTitle ? '320px' : '360px' }}
|
style={{ minHeight: getTextareaMinHeight(smsImages.length > 0, Boolean(smsTitle)) }}
|
||||||
{...textareaInsert.bindSelectionHandlers}
|
{...textareaInsert.bindSelectionHandlers}
|
||||||
/>
|
/>
|
||||||
|
{smsPreviewSuffix ? (
|
||||||
|
<div className="whitespace-pre-wrap px-4 pb-4 text-sm leading-relaxed text-gray-700">
|
||||||
|
{smsPreviewSuffix}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{byteSize > maxBytes ? (
|
{byteSize > maxBytes ? (
|
||||||
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
|
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import type { KriEditorCommand, KriEditorProps, ToolbarState } from "./types";
|
|||||||
import { resolveUploadUrl } from "./types";
|
import { resolveUploadUrl } from "./types";
|
||||||
import { FontSize } from "./extensions/font-size";
|
import { FontSize } from "./extensions/font-size";
|
||||||
import { Div } from "./extensions/div";
|
import { Div } from "./extensions/div";
|
||||||
|
import { ImageMap, ImageWithMap } from "./extensions/image-map";
|
||||||
import { compressImage } from "./utils/imageCompression";
|
import { compressImage } from "./utils/imageCompression";
|
||||||
import { sanitizeHtml } from "./utils/sanitizeHtml";
|
import { sanitizeHtml } from "./utils/sanitizeHtml";
|
||||||
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
|
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
|
||||||
@@ -34,9 +35,62 @@ import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPrevie
|
|||||||
import { Toolbar } from "./toolbar/Toolbar";
|
import { Toolbar } from "./toolbar/Toolbar";
|
||||||
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
import { useDebouncedChange } from "./hooks/useDebouncedChange";
|
||||||
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
import { useTextareaInsert } from "./hooks/useTextareaInsert";
|
||||||
|
import { useImageMapOverlay } from "./hooks/useImageMapOverlay";
|
||||||
|
|
||||||
type ViewMode = "wysiwyg" | "html";
|
type ViewMode = "wysiwyg" | "html";
|
||||||
|
|
||||||
|
type ToolbarEndSlotProps = Pick<KriEditorProps, "renderToolbarEnd"> & {
|
||||||
|
editor: Editor;
|
||||||
|
command: KriEditorCommand;
|
||||||
|
view: ViewMode;
|
||||||
|
};
|
||||||
|
|
||||||
|
// command는 ref를 사용하는 함수 묶음이라, 렌더 중 외부 함수에 직접 넘기면 React Compiler가
|
||||||
|
// ref 접근으로 판단한다. 별도 컴포넌트의 props로 전달해 렌더 범위를 분리한다(동작 동일).
|
||||||
|
function ToolbarEndSlot({ renderToolbarEnd, editor, command, view }: Readonly<ToolbarEndSlotProps>) {
|
||||||
|
return <>{renderToolbarEnd?.({ editor, command, view })}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 주입된 정제 함수가 우선이고, 없으면 sanitizeHtml 옵션에 따라 기본 정제기를 사용한다.
|
||||||
|
function sanitizeEditorHtml(
|
||||||
|
html: string,
|
||||||
|
htmlSanitizer: KriEditorProps["htmlSanitizer"],
|
||||||
|
sanitizeEnabled: boolean,
|
||||||
|
allowedCustomHtml: KriEditorProps["allowedCustomHtml"],
|
||||||
|
): string {
|
||||||
|
if (htmlSanitizer) return htmlSanitizer(html);
|
||||||
|
if (sanitizeEnabled) return sanitizeHtml(html, allowedCustomHtml);
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeHtmlDraft(
|
||||||
|
draftRef: { current: string },
|
||||||
|
textareaRef: { current: HTMLTextAreaElement | null },
|
||||||
|
html: string,
|
||||||
|
): void {
|
||||||
|
draftRef.current = html;
|
||||||
|
if (textareaRef.current) textareaRef.current.value = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
|
||||||
|
function syncEditorContent(editor: Editor, value: string, optimisticHtml: string): void {
|
||||||
|
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
|
||||||
|
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
|
||||||
|
const normalizedValue = value || "<p></p>";
|
||||||
|
if (normalizedValue === editor.getHTML() || normalizedValue === optimisticHtml) return;
|
||||||
|
|
||||||
|
editor.commands.setContent(normalizedValue, {
|
||||||
|
emitUpdate: false,
|
||||||
|
parseOptions: { preserveWhitespace: "full" },
|
||||||
|
});
|
||||||
|
|
||||||
|
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
|
||||||
|
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
|
||||||
|
if (normalizedValue.includes("<img")) {
|
||||||
|
editor.createNodeViews();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function getToolbarState(editor: Editor): ToolbarState {
|
function getToolbarState(editor: Editor): ToolbarState {
|
||||||
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
|
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
|
||||||
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
const hl = editor.getAttributes("highlight") as { color?: string | null };
|
||||||
@@ -68,7 +122,7 @@ function getToolbarState(editor: Editor): ToolbarState {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function KriEditorWysiwyg(props: KriEditorProps) {
|
export function KriEditorWysiwyg(props: Readonly<KriEditorProps>) {
|
||||||
const {
|
const {
|
||||||
|
|
||||||
label,
|
label,
|
||||||
@@ -97,6 +151,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
|
fontFamilyOptions = DEFAULT_FONT_FAMILY_OPTIONS,
|
||||||
editorExtensions = [],
|
editorExtensions = [],
|
||||||
allowedCustomHtml,
|
allowedCustomHtml,
|
||||||
|
enableImageMap = false,
|
||||||
|
htmlSanitizer,
|
||||||
|
getWysiwygCompatibility,
|
||||||
transformPreviewHtml,
|
transformPreviewHtml,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
@@ -110,19 +167,28 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs);
|
const { scheduleChange, flushChange, optimisticHtmlRef } = useDebouncedChange(onChange, debounceMs);
|
||||||
|
|
||||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
const previewContainerRef = useRef<HTMLDivElement | null>(null);
|
||||||
const htmlTextareaRef = useRef<HTMLTextAreaElement | null>(null);
|
const htmlTextareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||||
const htmlTi = useTextareaInsert(htmlTextareaRef);
|
const htmlTi = useTextareaInsert(htmlTextareaRef);
|
||||||
const { insertText: insertTextareaText } = htmlTi;
|
const { insertText: insertTextareaText } = htmlTi;
|
||||||
|
|
||||||
const [view, setView] = useState<ViewMode>("wysiwyg");
|
const getCompatibility = useCallback(
|
||||||
|
(html: string) => getWysiwygCompatibility?.(html) ?? { compatible: true },
|
||||||
|
[getWysiwygCompatibility],
|
||||||
|
);
|
||||||
|
const initialView: ViewMode = showHtmlToggle && !getCompatibility(value ?? "").compatible ? "html" : "wysiwyg";
|
||||||
|
const [view, setView] = useState<ViewMode>(initialView);
|
||||||
const [previewSource, setPreviewSource] = useState(value ?? "");
|
const [previewSource, setPreviewSource] = useState(value ?? "");
|
||||||
const viewRef = useRef<ViewMode>("wysiwyg");
|
const viewRef = useRef<ViewMode>(initialView);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
viewRef.current = view;
|
viewRef.current = view;
|
||||||
}, [view]);
|
}, [view]);
|
||||||
|
|
||||||
const htmlDraftRef = useRef<string>(value ?? "");
|
const htmlDraftRef = useRef<string>(value ?? "");
|
||||||
|
// HTML textarea는 비제어 컴포넌트다. 렌더 중 ref를 읽지 않도록, HTML 보기로 전환하는 시점의
|
||||||
|
// 초안을 state로 보관해 textarea가 마운트될 때의 초기값(defaultValue)으로만 사용한다.
|
||||||
|
const [htmlTextareaSeed, setHtmlTextareaSeed] = useState<string>(value ?? "");
|
||||||
const canImageUpload = Boolean(onImageUpload);
|
const canImageUpload = Boolean(onImageUpload);
|
||||||
|
|
||||||
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
const selectionRef = useRef<{ from: number; to: number } | null>(null);
|
||||||
@@ -179,7 +245,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
TableHeader,
|
TableHeader,
|
||||||
TableCell,
|
TableCell,
|
||||||
|
|
||||||
TiptapImage.configure({
|
(enableImageMap ? ImageWithMap : TiptapImage).configure({
|
||||||
inline: true,
|
inline: true,
|
||||||
allowBase64,
|
allowBase64,
|
||||||
HTMLAttributes: {
|
HTMLAttributes: {
|
||||||
@@ -191,6 +257,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
alwaysPreserveAspectRatio: true,
|
alwaysPreserveAspectRatio: true,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
...(enableImageMap ? [ImageMap] : []),
|
||||||
Placeholder.configure({ placeholder }),
|
Placeholder.configure({ placeholder }),
|
||||||
...editorExtensions,
|
...editorExtensions,
|
||||||
],
|
],
|
||||||
@@ -459,6 +526,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
if (viewRef.current === "wysiwyg") {
|
if (viewRef.current === "wysiwyg") {
|
||||||
const raw = editor.getHTML();
|
const raw = editor.getHTML();
|
||||||
htmlDraftRef.current = raw;
|
htmlDraftRef.current = raw;
|
||||||
|
setHtmlTextareaSeed(raw);
|
||||||
setView("html");
|
setView("html");
|
||||||
|
|
||||||
// WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로
|
// WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로
|
||||||
@@ -475,12 +543,17 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const raw = htmlDraftRef.current;
|
const raw = htmlDraftRef.current;
|
||||||
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
|
const compatibility = getCompatibility(raw);
|
||||||
|
if (!compatibility.compatible) {
|
||||||
|
toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const safe = sanitizeEditorHtml(raw, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
|
||||||
|
|
||||||
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
|
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
|
||||||
flushChange(preserveEmptyParagraphs(editor.getHTML()));
|
flushChange(preserveEmptyParagraphs(editor.getHTML()));
|
||||||
setView("wysiwyg");
|
setView("wysiwyg");
|
||||||
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
|
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt, setView, setPreviewSource, setHtmlTextareaSeed]);
|
||||||
|
|
||||||
const formatHtmlView = useCallback(async () => {
|
const formatHtmlView = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
@@ -493,7 +566,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
toast.error("HTML 정렬에 실패했습니다.");
|
toast.error("HTML 정렬에 실패했습니다.");
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
}, [scheduleChange]);
|
}, [scheduleChange, setPreviewSource]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
@@ -525,29 +598,29 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPreviewSource(value ?? "");
|
setPreviewSource(value ?? "");
|
||||||
if (!editor) return;
|
if (!editor || value == null) return;
|
||||||
if (viewRef.current === "html") return;
|
|
||||||
if (value == null) return;
|
|
||||||
|
|
||||||
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
|
// WYSIWYG로 손실 없이 편집할 수 없는 값은 HTML 보기로 전환해 원문을 유지한다.
|
||||||
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
|
if (showHtmlToggle && !getCompatibility(value).compatible) {
|
||||||
const normalizedValue = value || "<p></p>";
|
writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
|
||||||
const current = editor.getHTML();
|
if (viewRef.current !== "html") {
|
||||||
|
viewRef.current = "html";
|
||||||
if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) {
|
setHtmlTextareaSeed(value);
|
||||||
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
|
setView("html");
|
||||||
editor.commands.setContent(normalizedValue, {
|
|
||||||
emitUpdate: false,
|
|
||||||
parseOptions: {preserveWhitespace: "full"},
|
|
||||||
});
|
|
||||||
|
|
||||||
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
|
|
||||||
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
|
|
||||||
if (normalizedValue.includes("<img")) {
|
|
||||||
editor.createNodeViews();
|
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}, [value, editor, view]);
|
|
||||||
|
if (viewRef.current === "html") {
|
||||||
|
const isExternalChange = value !== optimisticHtmlRef.current && value !== htmlDraftRef.current;
|
||||||
|
if (getWysiwygCompatibility && isExternalChange) {
|
||||||
|
writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
syncEditorContent(editor, value, optimisticHtmlRef.current);
|
||||||
|
}, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
@@ -611,10 +684,18 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
|
|
||||||
const previewHtml = useMemo(() => {
|
const previewHtml = useMemo(() => {
|
||||||
const preserved = preserveEmptyParagraphs(previewSource);
|
const preserved = preserveEmptyParagraphs(previewSource);
|
||||||
const sanitized = sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
|
const sanitized = sanitizeEditorHtml(preserved, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
|
||||||
const withLinkStyle = applyLinkPreviewClass(sanitized);
|
const withLinkStyle = applyLinkPreviewClass(sanitized);
|
||||||
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
|
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
|
||||||
}, [allowedCustomHtml, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
|
}, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
|
||||||
|
|
||||||
|
// 이미지맵을 사용할 때만 미리보기에 <area> 영역을 표시한다.
|
||||||
|
const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml, enableImageMap && showPreview);
|
||||||
|
|
||||||
|
const wysiwygCompatibility = useMemo(
|
||||||
|
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
|
||||||
|
[editor, getCompatibility, previewSource, view],
|
||||||
|
);
|
||||||
|
|
||||||
if (!editor) {
|
if (!editor) {
|
||||||
return (
|
return (
|
||||||
@@ -640,6 +721,8 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
onPickImage={handlePickImage}
|
onPickImage={handlePickImage}
|
||||||
showHtmlToggle={showHtmlToggle}
|
showHtmlToggle={showHtmlToggle}
|
||||||
isHtmlView={view === "html"}
|
isHtmlView={view === "html"}
|
||||||
|
htmlToWysiwygDisabled={!wysiwygCompatibility.compatible}
|
||||||
|
htmlToWysiwygDisabledReason={wysiwygCompatibility.reason}
|
||||||
onToggleHtmlView={onToggleHtmlView}
|
onToggleHtmlView={onToggleHtmlView}
|
||||||
onFormatHtml={formatHtmlView}
|
onFormatHtml={formatHtmlView}
|
||||||
fontFamilyOptions={fontFamilyOptions}
|
fontFamilyOptions={fontFamilyOptions}
|
||||||
@@ -656,7 +739,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
onAddRow={addRow}
|
onAddRow={addRow}
|
||||||
onAddColumn={addColumn}
|
onAddColumn={addColumn}
|
||||||
onDeleteTable={deleteTable}
|
onDeleteTable={deleteTable}
|
||||||
customContent={props.renderToolbarEnd?.({ editor, command, view })}
|
customContent={
|
||||||
|
props.renderToolbarEnd ? (
|
||||||
|
<ToolbarEndSlot renderToolbarEnd={props.renderToolbarEnd} editor={editor} command={command} view={view} />
|
||||||
|
) : undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -670,7 +757,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
<textarea
|
<textarea
|
||||||
ref={htmlTextareaRef}
|
ref={htmlTextareaRef}
|
||||||
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
|
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
|
||||||
defaultValue={htmlDraftRef.current}
|
defaultValue={htmlTextareaSeed}
|
||||||
onMouseDown={(e) => e.stopPropagation()}
|
onMouseDown={(e) => e.stopPropagation()}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
htmlDraftRef.current = e.target.value;
|
htmlDraftRef.current = e.target.value;
|
||||||
@@ -681,14 +768,30 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
|||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
{...htmlTi.bindSelectionHandlers}
|
{...htmlTi.bindSelectionHandlers}
|
||||||
/>
|
/>
|
||||||
|
{!wysiwygCompatibility.compatible ? (
|
||||||
|
<output className="mt-2 block text-xs text-amber-700">
|
||||||
|
{wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."}
|
||||||
|
</output>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{showPreview && (
|
{showPreview && (
|
||||||
<div className={cn("border-t p-3", previewClassName)}>
|
<div className={cn("border-t p-3", previewClassName)}>
|
||||||
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
<div className="mb-2 text-sm font-semibold">미리보기</div>
|
||||||
<div className="rounded-md border bg-muted/30 p-3">
|
<div ref={previewContainerRef} className="relative rounded-md border bg-muted/30 p-3">
|
||||||
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
|
||||||
|
{imageMapOverlayBoxes.length > 0 && (
|
||||||
|
<div className="pointer-events-none absolute inset-0" aria-hidden="true">
|
||||||
|
{imageMapOverlayBoxes.map((box) => (
|
||||||
|
<div
|
||||||
|
key={box.key}
|
||||||
|
className="absolute border-2 border-sky-500 bg-sky-500/30"
|
||||||
|
style={box.style}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
93
src/components/kri-editor/extensions/image-map.ts
Normal file
93
src/components/kri-editor/extensions/image-map.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { Node, mergeAttributes } from '@tiptap/core'
|
||||||
|
import TiptapImage from '@tiptap/extension-image'
|
||||||
|
import type { DOMOutputSpec } from '@tiptap/pm/model'
|
||||||
|
|
||||||
|
export type ImageMapAreaAttributes = {
|
||||||
|
shape?: string
|
||||||
|
coords?: string
|
||||||
|
href?: string
|
||||||
|
alt?: string
|
||||||
|
title?: string
|
||||||
|
target?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const readAttribute = (element: Element, name: string): string | undefined =>
|
||||||
|
element.getAttribute(name) ?? undefined
|
||||||
|
|
||||||
|
export const ImageWithMap = TiptapImage.extend({
|
||||||
|
addAttributes() {
|
||||||
|
return {
|
||||||
|
...this.parent?.(),
|
||||||
|
usemap: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('usemap'),
|
||||||
|
renderHTML: (attributes) => attributes.usemap ? { usemap: attributes.usemap } : {},
|
||||||
|
},
|
||||||
|
align: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('align'),
|
||||||
|
renderHTML: (attributes) => attributes.align ? { align: attributes.align } : {},
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('style'),
|
||||||
|
renderHTML: (attributes) => attributes.style ? { style: attributes.style } : {},
|
||||||
|
},
|
||||||
|
loading: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('loading'),
|
||||||
|
renderHTML: (attributes) => attributes.loading ? { loading: attributes.loading } : {},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const ImageMap = Node.create({
|
||||||
|
name: 'imageMap',
|
||||||
|
group: 'block',
|
||||||
|
atom: true,
|
||||||
|
|
||||||
|
addAttributes() {
|
||||||
|
return {
|
||||||
|
name: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('name'),
|
||||||
|
renderHTML: (attributes) => attributes.name ? { name: attributes.name } : {},
|
||||||
|
},
|
||||||
|
id: {
|
||||||
|
default: null,
|
||||||
|
parseHTML: (element) => element.getAttribute('id'),
|
||||||
|
renderHTML: (attributes) => attributes.id ? { id: attributes.id } : {},
|
||||||
|
},
|
||||||
|
areas: {
|
||||||
|
default: [],
|
||||||
|
parseHTML: (element) => Array.from(element.children)
|
||||||
|
.filter((child) => child.tagName.toLowerCase() === 'area')
|
||||||
|
.map((area): ImageMapAreaAttributes => ({
|
||||||
|
shape: readAttribute(area, 'shape'),
|
||||||
|
coords: readAttribute(area, 'coords'),
|
||||||
|
href: readAttribute(area, 'href'),
|
||||||
|
alt: readAttribute(area, 'alt'),
|
||||||
|
title: readAttribute(area, 'title'),
|
||||||
|
target: readAttribute(area, 'target'),
|
||||||
|
})),
|
||||||
|
renderHTML: () => ({}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
parseHTML() {
|
||||||
|
return [{ tag: 'map' }]
|
||||||
|
},
|
||||||
|
|
||||||
|
renderHTML({ node, HTMLAttributes }) {
|
||||||
|
const mapAttributes = { ...HTMLAttributes }
|
||||||
|
delete mapAttributes.areas
|
||||||
|
const areas = (node.attrs.areas as ImageMapAreaAttributes[]).map((area): DOMOutputSpec => [
|
||||||
|
'area',
|
||||||
|
Object.fromEntries(Object.entries(area).filter(([, value]) => Boolean(value))),
|
||||||
|
])
|
||||||
|
|
||||||
|
return ['map', mergeAttributes(mapAttributes), ...areas] as DOMOutputSpec
|
||||||
|
},
|
||||||
|
})
|
||||||
48
src/components/kri-editor/hooks/useImageMapOverlay.ts
Normal file
48
src/components/kri-editor/hooks/useImageMapOverlay.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { useLayoutEffect, useRef, useState } from "react"
|
||||||
|
import { computeImageMapOverlayBoxes, type ImageMapOverlayBox } from "../utils/imageMapOverlay"
|
||||||
|
|
||||||
|
// previewHtml이 바뀔 때마다(이미지 로드/리사이즈 포함) <map>/<area> 오버레이 위치를 다시 계산한다.
|
||||||
|
// enabled가 false이면 계산·관찰하지 않는다.
|
||||||
|
export function useImageMapOverlay(
|
||||||
|
containerRef: React.RefObject<HTMLElement | null>,
|
||||||
|
previewHtml: string,
|
||||||
|
enabled = true,
|
||||||
|
): ImageMapOverlayBox[] {
|
||||||
|
const [boxes, setBoxes] = useState<ImageMapOverlayBox[]>([])
|
||||||
|
const frameRef = useRef<number | null>(null)
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const container = containerRef.current
|
||||||
|
if (!enabled || !container) {
|
||||||
|
setBoxes([])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const recompute = () => setBoxes(computeImageMapOverlayBoxes(container))
|
||||||
|
|
||||||
|
const scheduleRecompute = () => {
|
||||||
|
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current)
|
||||||
|
frameRef.current = requestAnimationFrame(recompute)
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleRecompute()
|
||||||
|
|
||||||
|
const images = Array.from(container.querySelectorAll<HTMLImageElement>("img[usemap]"))
|
||||||
|
images.forEach((img) => {
|
||||||
|
if (!img.complete) img.addEventListener("load", scheduleRecompute)
|
||||||
|
})
|
||||||
|
|
||||||
|
const resizeObserver = new ResizeObserver(scheduleRecompute)
|
||||||
|
resizeObserver.observe(container)
|
||||||
|
window.addEventListener("resize", scheduleRecompute)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current)
|
||||||
|
images.forEach((img) => img.removeEventListener("load", scheduleRecompute))
|
||||||
|
resizeObserver.disconnect()
|
||||||
|
window.removeEventListener("resize", scheduleRecompute)
|
||||||
|
}
|
||||||
|
}, [containerRef, previewHtml, enabled])
|
||||||
|
|
||||||
|
return boxes
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
export { KriEditor } from './KriEditor'
|
export { KriEditor } from './KriEditor'
|
||||||
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
|
export { KriEditorHtmlOnly } from './KriEditorHtmlOnly'
|
||||||
|
export { KriEditorKko } from './KriEditorKko'
|
||||||
export { KriEditorSms } from './KriEditorSms'
|
export { KriEditorSms } from './KriEditorSms'
|
||||||
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
|
export { KriEditorWysiwyg } from './KriEditorWysiwyg'
|
||||||
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
|
export { ToolbarButton as KriEditorToolbarButton } from './toolbar/ToolbarButton'
|
||||||
@@ -14,6 +15,7 @@ export type {
|
|||||||
KriEditorToolbarContext,
|
KriEditorToolbarContext,
|
||||||
KriEditorToolbarFeature,
|
KriEditorToolbarFeature,
|
||||||
KriEditorUploadResult,
|
KriEditorUploadResult,
|
||||||
|
KriEditorWysiwygCompatibility,
|
||||||
ToolbarState,
|
ToolbarState,
|
||||||
} from './types'
|
} from './types'
|
||||||
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'
|
export type { KriEditorToolbarButtonProps } from './toolbar/ToolbarButton'
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ interface ToolbarProps {
|
|||||||
onPickImage: () => void
|
onPickImage: () => void
|
||||||
showHtmlToggle: boolean
|
showHtmlToggle: boolean
|
||||||
isHtmlView: boolean
|
isHtmlView: boolean
|
||||||
|
htmlToWysiwygDisabled?: boolean
|
||||||
|
htmlToWysiwygDisabledReason?: string
|
||||||
onToggleHtmlView: () => void
|
onToggleHtmlView: () => void
|
||||||
onFormatHtml: () => void
|
onFormatHtml: () => void
|
||||||
fontFamilyOptions: KriEditorFontFamilyOption[]
|
fontFamilyOptions: KriEditorFontFamilyOption[]
|
||||||
@@ -77,6 +79,8 @@ export function Toolbar({
|
|||||||
onPickImage,
|
onPickImage,
|
||||||
showHtmlToggle,
|
showHtmlToggle,
|
||||||
isHtmlView,
|
isHtmlView,
|
||||||
|
htmlToWysiwygDisabled = false,
|
||||||
|
htmlToWysiwygDisabledReason,
|
||||||
onToggleHtmlView,
|
onToggleHtmlView,
|
||||||
onFormatHtml,
|
onFormatHtml,
|
||||||
fontFamilyOptions,
|
fontFamilyOptions,
|
||||||
@@ -298,7 +302,14 @@ export function Toolbar({
|
|||||||
{showHtmlToggle && enabled('html') ? (
|
{showHtmlToggle && enabled('html') ? (
|
||||||
<>
|
<>
|
||||||
<Separator orientation="vertical" className="mx-1 h-6" />
|
<Separator orientation="vertical" className="mx-1 h-6" />
|
||||||
<ToolbarButton active={isHtmlView} title={isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집'} onClick={onToggleHtmlView}><Code2 className="size-4" /></ToolbarButton>
|
<ToolbarButton
|
||||||
|
active={isHtmlView}
|
||||||
|
disabled={isHtmlView && htmlToWysiwygDisabled}
|
||||||
|
title={isHtmlView && htmlToWysiwygDisabled ? (htmlToWysiwygDisabledReason ?? 'WYSIWYG로 전환할 수 없습니다.') : (isHtmlView ? 'WYSIWYG로 전환' : 'HTML 편집')}
|
||||||
|
onClick={onToggleHtmlView}
|
||||||
|
>
|
||||||
|
<Code2 className="size-4" />
|
||||||
|
</ToolbarButton>
|
||||||
{isHtmlView ? (
|
{isHtmlView ? (
|
||||||
<ToolbarButton title="HTML 정렬" onClick={onFormatHtml}><IndentIncrease className="size-4" /></ToolbarButton>
|
<ToolbarButton title="HTML 정렬" onClick={onFormatHtml}><IndentIncrease className="size-4" /></ToolbarButton>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { Extensions } from '@tiptap/core'
|
|||||||
import type { Editor } from '@tiptap/react'
|
import type { Editor } from '@tiptap/react'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms'
|
export type KriEditorMode = 'wysiwyg' | 'both' | 'html' | 'sms' | 'kko'
|
||||||
export type KriEditorUploadResult = string | { url: string }
|
export type KriEditorUploadResult = string | { url: string }
|
||||||
|
|
||||||
export type KriEditorToolbarFeature =
|
export type KriEditorToolbarFeature =
|
||||||
@@ -40,11 +40,21 @@ export type KriEditorAllowedHtml = {
|
|||||||
attributes?: string[]
|
attributes?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type KriEditorWysiwygCompatibility = {
|
||||||
|
compatible: boolean
|
||||||
|
reason?: string
|
||||||
|
}
|
||||||
|
|
||||||
export type KriEditorFontFamilyOption = {
|
export type KriEditorFontFamilyOption = {
|
||||||
label: string
|
label: string
|
||||||
value: string
|
value: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type KriEditorSmsImage = {
|
||||||
|
fileName: string
|
||||||
|
src: string
|
||||||
|
}
|
||||||
|
|
||||||
export type KriEditorProps = {
|
export type KriEditorProps = {
|
||||||
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
|
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
|
||||||
onCommandReady?: (command: KriEditorCommand | null) => void
|
onCommandReady?: (command: KriEditorCommand | null) => void
|
||||||
@@ -70,15 +80,32 @@ export type KriEditorProps = {
|
|||||||
onImageUploadError?: (error: unknown) => void
|
onImageUploadError?: (error: unknown) => void
|
||||||
debounceMs?: number
|
debounceMs?: number
|
||||||
smsTitle?: string
|
smsTitle?: string
|
||||||
changeSmsType?: (type: 'SMS' | 'LMS') => void
|
/** Preview only; consumers must handle MMS. Actual delivery type is determined by the server. */
|
||||||
|
changeSmsType?: (type: 'SMS' | 'LMS' | 'MMS') => void
|
||||||
isSmsReadOnly?: boolean
|
isSmsReadOnly?: boolean
|
||||||
smsMaxBytes?: number
|
smsMaxBytes?: number
|
||||||
lmsMaxBytes?: number
|
lmsMaxBytes?: number
|
||||||
|
smsPreviewSuffix?: string
|
||||||
|
/** 첨부파일이 있으면 길이·제목과 무관하게 MMS로 판정한다. */
|
||||||
|
smsHasAttachment?: boolean
|
||||||
|
/** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */
|
||||||
|
smsImages?: KriEditorSmsImage[]
|
||||||
|
/** 휴대폰 프레임 class (기본 높이 h-[600px] 조정 등) */
|
||||||
|
smsFrameClassName?: string
|
||||||
|
/** 알림톡 미리보기의 강조 제목. 없으면 표시하지 않는다. */
|
||||||
|
kkoTitle?: string
|
||||||
|
/** 알림톡 미리보기의 채널명·발신 프로필 이름. 없으면 표시하지 않는다. */
|
||||||
|
kkoSenderName?: string
|
||||||
|
/** 알림톡 말풍선 상단 문구. 기본값 "알림톡 도착" */
|
||||||
|
kkoHeaderLabel?: string
|
||||||
toolbar?: KriEditorToolbarConfig | false
|
toolbar?: KriEditorToolbarConfig | false
|
||||||
fontFamilyOptions?: KriEditorFontFamilyOption[]
|
fontFamilyOptions?: KriEditorFontFamilyOption[]
|
||||||
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
|
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode
|
||||||
editorExtensions?: Extensions
|
editorExtensions?: Extensions
|
||||||
allowedCustomHtml?: KriEditorAllowedHtml
|
allowedCustomHtml?: KriEditorAllowedHtml
|
||||||
|
enableImageMap?: boolean
|
||||||
|
htmlSanitizer?: (html: string) => string
|
||||||
|
getWysiwygCompatibility?: (html: string) => KriEditorWysiwygCompatibility
|
||||||
transformPreviewHtml?: (html: string) => string
|
transformPreviewHtml?: (html: string) => string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
112
src/components/kri-editor/utils/imageMapOverlay.ts
Normal file
112
src/components/kri-editor/utils/imageMapOverlay.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
export type ImageMapOverlayBox = {
|
||||||
|
key: string
|
||||||
|
style: {
|
||||||
|
left: number
|
||||||
|
top: number
|
||||||
|
width: number
|
||||||
|
height: number
|
||||||
|
borderRadius?: string
|
||||||
|
clipPath?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parseCoords = (raw: string | null): number[] =>
|
||||||
|
(raw ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map((value) => Number(value.trim()))
|
||||||
|
.filter((value) => Number.isFinite(value))
|
||||||
|
|
||||||
|
// coords는 <img>의 원본(naturalWidth/Height) 기준이라, 미리보기에서 이미지가
|
||||||
|
// 리사이즈되어 렌더링된 크기에 맞춰 스케일 변환한 뒤 컨테이너 기준 좌표로 옮겨야 한다.
|
||||||
|
export function computeImageMapOverlayBoxes(container: HTMLElement): ImageMapOverlayBox[] {
|
||||||
|
const boxes: ImageMapOverlayBox[] = []
|
||||||
|
const containerRect = container.getBoundingClientRect()
|
||||||
|
const images = container.querySelectorAll<HTMLImageElement>("img[usemap]")
|
||||||
|
|
||||||
|
images.forEach((img, imageIndex) => {
|
||||||
|
if (!img.complete || img.naturalWidth === 0 || img.naturalHeight === 0) return
|
||||||
|
|
||||||
|
const mapName = img.getAttribute("usemap")?.replace(/^#/, "")
|
||||||
|
if (!mapName) return
|
||||||
|
|
||||||
|
const map = container.querySelector<HTMLMapElement>(`map[name="${CSS.escape(mapName)}"]`)
|
||||||
|
if (!map) return
|
||||||
|
|
||||||
|
const imgRect = img.getBoundingClientRect()
|
||||||
|
if (imgRect.width === 0 || imgRect.height === 0) return
|
||||||
|
|
||||||
|
const scaleX = imgRect.width / img.naturalWidth
|
||||||
|
const scaleY = imgRect.height / img.naturalHeight
|
||||||
|
const offsetX = imgRect.left - containerRect.left
|
||||||
|
const offsetY = imgRect.top - containerRect.top
|
||||||
|
|
||||||
|
map.querySelectorAll("area").forEach((area, areaIndex) => {
|
||||||
|
const shape = (area.getAttribute("shape") || "rect").toLowerCase()
|
||||||
|
const coords = parseCoords(area.getAttribute("coords"))
|
||||||
|
const key = `${imageIndex}-${areaIndex}`
|
||||||
|
|
||||||
|
if (shape === "rect" && coords.length >= 4) {
|
||||||
|
const [x1, y1, x2, y2] = coords
|
||||||
|
boxes.push({
|
||||||
|
key,
|
||||||
|
style: {
|
||||||
|
left: offsetX + Math.min(x1, x2) * scaleX,
|
||||||
|
top: offsetY + Math.min(y1, y2) * scaleY,
|
||||||
|
width: Math.abs(x2 - x1) * scaleX,
|
||||||
|
height: Math.abs(y2 - y1) * scaleY,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shape === "circle" && coords.length >= 3) {
|
||||||
|
const [cx, cy, r] = coords
|
||||||
|
boxes.push({
|
||||||
|
key,
|
||||||
|
style: {
|
||||||
|
left: offsetX + (cx - r) * scaleX,
|
||||||
|
top: offsetY + (cy - r) * scaleY,
|
||||||
|
width: r * 2 * scaleX,
|
||||||
|
height: r * 2 * scaleY,
|
||||||
|
borderRadius: "9999px",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shape === "poly" && coords.length >= 6 && coords.length % 2 === 0) {
|
||||||
|
const xs = coords.filter((_, i) => i % 2 === 0)
|
||||||
|
const ys = coords.filter((_, i) => i % 2 === 1)
|
||||||
|
const minX = Math.min(...xs)
|
||||||
|
const maxX = Math.max(...xs)
|
||||||
|
const minY = Math.min(...ys)
|
||||||
|
const maxY = Math.max(...ys)
|
||||||
|
const width = maxX - minX
|
||||||
|
const height = maxY - minY
|
||||||
|
if (width <= 0 || height <= 0) return
|
||||||
|
|
||||||
|
const points: string[] = []
|
||||||
|
for (let i = 0; i < coords.length; i += 2) {
|
||||||
|
const px = ((coords[i] - minX) / width) * 100
|
||||||
|
const py = ((coords[i + 1] - minY) / height) * 100
|
||||||
|
points.push(`${px}% ${py}%`)
|
||||||
|
}
|
||||||
|
|
||||||
|
boxes.push({
|
||||||
|
key,
|
||||||
|
style: {
|
||||||
|
left: offsetX + minX * scaleX,
|
||||||
|
top: offsetY + minY * scaleY,
|
||||||
|
width: width * scaleX,
|
||||||
|
height: height * scaleY,
|
||||||
|
clipPath: `polygon(${points.join(", ")})`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// shape="default"(이미지 전체)는 별도 오버레이 없이 그대로 둔다.
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return boxes
|
||||||
|
}
|
||||||
@@ -23,10 +23,11 @@ const CollapsibleHistorySection = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`space-y-2 ${showDivider ? 'border-t pt-3' : ''}`}>
|
<div className={`space-y-2 ${showDivider ? 'border-t pt-3' : ''}`}>
|
||||||
<div className="flex w-full items-center justify-between gap-2">
|
{/* 제목과 headerExtra가 한 줄에 들어가지 않으면 headerExtra를 다음 줄 오른쪽으로 내린다. */}
|
||||||
|
<div className="flex w-full flex-wrap items-center justify-between gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-semibold cursor-pointer"
|
className="flex min-w-0 flex-auto items-center gap-2 whitespace-nowrap text-left text-sm font-semibold cursor-pointer"
|
||||||
aria-expanded={open}
|
aria-expanded={open}
|
||||||
aria-controls={contentId}
|
aria-controls={contentId}
|
||||||
onClick={() => setOpen((prev) => !prev)}
|
onClick={() => setOpen((prev) => !prev)}
|
||||||
@@ -34,7 +35,7 @@ const CollapsibleHistorySection = ({
|
|||||||
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
|
||||||
{title}
|
{title}
|
||||||
</button>
|
</button>
|
||||||
{headerExtra}
|
{headerExtra ? <div className="ml-auto">{headerExtra}</div> : null}
|
||||||
</div>
|
</div>
|
||||||
{open ? <div id={contentId}>{children}</div> : null}
|
{open ? <div id={contentId}>{children}</div> : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -10,8 +10,10 @@ import { useAddListEventMutation, useDeleteListEventMutation, useListEventHistor
|
|||||||
import { useSendResultBySidQuery } from '@/query/message'
|
import { useSendResultBySidQuery } from '@/query/message'
|
||||||
import { useInternalInfoQuery } from '@/query/internal'
|
import { useInternalInfoQuery } from '@/query/internal'
|
||||||
import { clientEnv } from '@/lib/env.client'
|
import { clientEnv } from '@/lib/env.client'
|
||||||
import { ChannelType } from '@kri/common/noti-hub'
|
import { ChannelType, isSendCancelable } from '@kri/common/noti-hub'
|
||||||
import type { SendResultInfo } from '@/types/message'
|
import { MESSAGE_TYPE_LABEL } from '@/const/messageTemplateConst'
|
||||||
|
import type { SendResultInfo } from '@kri/common/noti-hub'
|
||||||
|
import { useSendCancel } from '@/hooks/useSendCancel'
|
||||||
import { formatKst } from '@kri/common'
|
import { formatKst } from '@kri/common'
|
||||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||||
@@ -239,6 +241,8 @@ const ContactEventSection = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => {
|
const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => {
|
||||||
|
const { canCancel: canCancelSend, cancel, isPending: cancelPending } = useSendCancel()
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
|
||||||
}
|
}
|
||||||
@@ -252,19 +256,42 @@ const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results:
|
|||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
<thead className="sticky top-0 bg-muted">
|
<thead className="sticky top-0 bg-muted">
|
||||||
<tr>
|
<tr>
|
||||||
|
<th className="p-2 text-left">유형</th>
|
||||||
<th className="p-2 text-left">수신처</th>
|
<th className="p-2 text-left">수신처</th>
|
||||||
<th className="p-2 text-left">결과</th>
|
<th className="p-2 text-left">결과</th>
|
||||||
<th className="p-2 text-left">발송일시</th>
|
<th className="p-2 text-left">발송일시</th>
|
||||||
|
{canCancelSend ? <th className="p-2 text-left"><span className="sr-only">예약 취소</span></th> : null}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{results.map((item) => (
|
{results.map((item) => {
|
||||||
<tr key={item.cmid} className="border-t">
|
const { sendIdx } = item
|
||||||
|
// 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다.
|
||||||
|
const canCancel = isSendCancelable(item) && !!sendIdx
|
||||||
|
return (
|
||||||
|
<tr key={sendIdx ?? item.cmid} className="border-t">
|
||||||
|
<td className="p-2">{MESSAGE_TYPE_LABEL[item.sendTy] ?? String(item.sendTy)}</td>
|
||||||
<td className="p-2">{item.destEml || item.destTel || '-'}</td>
|
<td className="p-2">{item.destEml || item.destTel || '-'}</td>
|
||||||
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td>
|
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td>
|
||||||
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td>
|
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td>
|
||||||
|
{canCancelSend ? (
|
||||||
|
<td className="p-2 text-right">
|
||||||
|
{canCancel && sendIdx ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={cancelPending}
|
||||||
|
onClick={() => cancel({ type: 'single', sendIdx })}
|
||||||
|
>
|
||||||
|
예약 취소
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</td>
|
||||||
|
) : null}
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
)
|
||||||
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
@@ -272,13 +299,14 @@ const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results:
|
|||||||
}
|
}
|
||||||
|
|
||||||
const SendResultHistory = ({ sid, prjctCd }: { sid: string; prjctCd: string }) => {
|
const SendResultHistory = ({ sid, prjctCd }: { sid: string; prjctCd: string }) => {
|
||||||
const [tab, setTab] = useState<'email' | 'sms'>('email')
|
const [tab, setTab] = useState<'email' | 'sms' | 'kko'>('email')
|
||||||
|
|
||||||
const emailQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.EMAIL, tab === 'email')
|
const emailQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.EMAIL, tab === 'email')
|
||||||
const smsQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.SMS, tab === 'sms')
|
const smsQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.SMS, tab === 'sms')
|
||||||
const activeQuery = tab === 'email' ? emailQuery : smsQuery
|
const kkoQuery = useSendResultBySidQuery(sid, prjctCd, clientEnv.REQUEST_SVC, ChannelType.KKO, tab === 'kko')
|
||||||
|
const activeQuery = tab === 'email' ? emailQuery : tab === 'sms' ? smsQuery : kkoQuery
|
||||||
|
|
||||||
const handleTabClick = (e: React.MouseEvent, next: 'email' | 'sms') => {
|
const handleTabClick = (e: React.MouseEvent, next: 'email' | 'sms' | 'kko') => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
setTab(next)
|
setTab(next)
|
||||||
}
|
}
|
||||||
@@ -307,6 +335,14 @@ const SendResultHistory = ({ sid, prjctCd }: { sid: string; prjctCd: string }) =
|
|||||||
>
|
>
|
||||||
문자
|
문자
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant={tab === 'kko' ? 'default' : 'outline'}
|
||||||
|
onClick={(e) => handleTabClick(e, 'kko')}
|
||||||
|
>
|
||||||
|
알림톡
|
||||||
|
</Button>
|
||||||
<RefreshIconButton onRefresh={() => activeQuery.refetch()} isFetching={activeQuery.isFetching} />
|
<RefreshIconButton onRefresh={() => activeQuery.refetch()} isFetching={activeQuery.isFetching} />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
import { useRef, useState, type ReactNode } from 'react'
|
||||||
import { Mail, MessageSquare, Paperclip, Phone, QrCode } from 'lucide-react'
|
import { Mail, MessageCircle, MessageSquare, Paperclip, Phone, QrCode } from 'lucide-react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||||
|
import { LIST_IS_USE_LABEL } from '@/components/table-column/ListTableColumn'
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
import { useDownloadListItemFileByHeaderMutation, useUploadListItemFileMutation } from '@/query/list'
|
import { useDownloadListItemFileByHeaderMutation, useUploadListItemFileMutation } from '@/query/list'
|
||||||
import { ListHeaderConst } from '@/const/listConst'
|
import { ListHeaderConst } from '@/const/listConst'
|
||||||
@@ -16,6 +17,7 @@ import { formatKst } from '@kri/common'
|
|||||||
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
||||||
import { substituteVariables } from '@/lib/variableSubstitution'
|
import { substituteVariables } from '@/lib/variableSubstitution'
|
||||||
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
||||||
|
import { isLightHexColor, normalizeHexColor } from '@/components/common/color-palette/color'
|
||||||
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
||||||
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
||||||
import { ctiClient } from '@/lib/cti/ctiClient'
|
import { ctiClient } from '@/lib/cti/ctiClient'
|
||||||
@@ -24,6 +26,7 @@ import { useCtiCallPhase } from '@/hooks/useCtiCallPhase'
|
|||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { downloadFile } from '@kri/common/browser'
|
import { downloadFile } from '@kri/common/browser'
|
||||||
import {
|
import {
|
||||||
|
buildKkoVariableValues,
|
||||||
buildListContactVariableValues,
|
buildListContactVariableValues,
|
||||||
resolveListHeaderValue,
|
resolveListHeaderValue,
|
||||||
} from '@/components/list-contact/listContactVariables'
|
} from '@/components/list-contact/listContactVariables'
|
||||||
@@ -50,39 +53,60 @@ export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearc
|
|||||||
for (const header of listHeaders) {
|
for (const header of listHeaders) {
|
||||||
if (header.listHderTy === ListHeaderConst.SID) continue
|
if (header.listHderTy === ListHeaderConst.SID) continue
|
||||||
if (!isListFieldVisibleForContact(header)) continue
|
if (!isListFieldVisibleForContact(header)) continue
|
||||||
|
// 사용 허용은 저장 시 코드("0"/"1"/"9")로 보내야 하므로 폼 값은 코드로 둔다.
|
||||||
|
// 문자·알림톡 변수 치환은 resolveListHeaderValue의 라벨을 그대로 사용한다.
|
||||||
|
if (header.listHderTy === ListHeaderConst.IS_USE) {
|
||||||
|
values[header.listHderId] = detail?.use != null ? String(detail.use) : ''
|
||||||
|
continue
|
||||||
|
}
|
||||||
values[header.listHderId] = resolveListHeaderValue(header, detail)
|
values[header.listHderId] = resolveListHeaderValue(header, detail)
|
||||||
}
|
}
|
||||||
|
|
||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
|
const IS_USE_OPTIONS = Object.entries(LIST_IS_USE_LABEL).map(([value, label]) => ({ value, label }))
|
||||||
|
|
||||||
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => {
|
const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
|
||||||
|
// Input/textarea는 수정 불가 상태에서도 드래그 선택/복사가 가능해야 해서 disabled 대신 readOnly를 쓴다.
|
||||||
|
// disabled는 공용 Input 컴포넌트의 disabled:pointer-events-none 때문에 마우스 이벤트 자체를 못 받는다.
|
||||||
|
const readOnlyContrastClass = 'bg-white read-only:text-foreground read-only:bg-muted/60'
|
||||||
|
|
||||||
|
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean, isEnding: boolean) => {
|
||||||
|
if (isEnding) return '종료 요청 중'
|
||||||
if (isDialing) return '거는 중'
|
if (isDialing) return '거는 중'
|
||||||
if (isOnCall) return '전화 끊기'
|
if (isOnCall) return '전화 끊기'
|
||||||
return '전화'
|
return '전화'
|
||||||
}
|
}
|
||||||
|
|
||||||
const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean) => {
|
const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean, isEnding: boolean) => {
|
||||||
if (!isCtiReady) return '전화 시스템에 연결되어 있지 않습니다.'
|
if (!isCtiReady) return '전화 시스템에 연결되어 있지 않습니다.'
|
||||||
if (isDialing) return '전화를 거는 중입니다.'
|
if (isDialing) return '전화를 거는 중입니다.'
|
||||||
|
if (isEnding) return '통화 종료를 확인하고 있습니다.'
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const FieldRow = ({ label, editable, children }: { label: string; editable?: boolean; children: ReactNode }) => (
|
const FieldRow = ({ label, color, children }: { label: string; color?: string | null; children: ReactNode }) => {
|
||||||
|
// 헤더에 지정한 색상(투명도 포함)이 기본색보다 우선한다. 형식이 잘못된 값은 기본색으로 표시한다.
|
||||||
|
const headerColor = normalizeHexColor(color)
|
||||||
|
const isDarkHeaderColor = headerColor !== null && !isLightHexColor(headerColor)
|
||||||
|
|
||||||
|
return (
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Label
|
<Label
|
||||||
className={cn(
|
className={cn(
|
||||||
'w-24 shrink-0 rounded-md px-2 py-2.5 text-sm font-bold text-foreground',
|
'w-24 shrink-0 wrap-anywhere rounded-md px-2 py-2.5 text-sm leading-snug font-bold',
|
||||||
editable && 'bg-blue-100 text-black',
|
headerColor === null && 'bg-blue-100',
|
||||||
|
isDarkHeaderColor ? 'text-white' : 'text-foreground',
|
||||||
)}
|
)}
|
||||||
|
style={headerColor ? { backgroundColor: headerColor } : undefined}
|
||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
</Label>
|
</Label>
|
||||||
<div className="min-w-0 flex-1">{children}</div>
|
<div className="min-w-0 flex-1">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const ListContactInfoPanel = ({
|
const ListContactInfoPanel = ({
|
||||||
prjctIdx,
|
prjctIdx,
|
||||||
@@ -110,7 +134,8 @@ const ListContactInfoPanel = ({
|
|||||||
const isCtiReady = ctiConnectionStatus === 'open'
|
const isCtiReady = ctiConnectionStatus === 'open'
|
||||||
const ctiCallPhase = useCtiCallPhase()
|
const ctiCallPhase = useCtiCallPhase()
|
||||||
const isDialing = ctiCallPhase === 'dialing'
|
const isDialing = ctiCallPhase === 'dialing'
|
||||||
const isOnCall = ctiCallPhase === 'active'
|
const isEnding = ctiCallPhase === 'ending'
|
||||||
|
const isOnCall = ctiCallPhase === 'active' || isEnding
|
||||||
|
|
||||||
const visibleHeaders = listHeaders
|
const visibleHeaders = listHeaders
|
||||||
.filter((header) => isListFieldVisibleForContact(header))
|
.filter((header) => isListFieldVisibleForContact(header))
|
||||||
@@ -123,6 +148,8 @@ const ListContactInfoPanel = ({
|
|||||||
const surveyResultByIdx = new Map((detail?.surveyResults ?? []).map((result) => [result.prjctSurveyIdx, result]))
|
const surveyResultByIdx = new Map((detail?.surveyResults ?? []).map((result) => [result.prjctSurveyIdx, result]))
|
||||||
|
|
||||||
const surveyUrlValues = buildListContactVariableValues(listHeaders, detail, sid)
|
const surveyUrlValues = buildListContactVariableValues(listHeaders, detail, sid)
|
||||||
|
// 알림톡은 #{설문명}도 설문 URL로 치환한다. 문자·메일은 기존처럼 헤더 값만 쓴다.
|
||||||
|
const kkoVariableValues = buildKkoVariableValues(surveyUrlValues, surveys)
|
||||||
|
|
||||||
const handleStartSurvey = (survey: ProjectSurvey) => {
|
const handleStartSurvey = (survey: ProjectSurvey) => {
|
||||||
if (!survey.surveyUrl) return
|
if (!survey.surveyUrl) return
|
||||||
@@ -141,14 +168,21 @@ const ListContactInfoPanel = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleCall = (telNum: string, listHderId: number) => {
|
const handleCall = (telNum: string, listHderId: number) => {
|
||||||
if (!isCtiReady || isDialing) return
|
if (!isCtiReady || isDialing || isEnding) return
|
||||||
// CTI_HANGUP_PENDING_VENDOR: 외주사 Hangup 명령 동작 확인 후 통화 중 버튼을 활성화하면 즉시 사용할 수 있다.
|
|
||||||
if (isOnCall) {
|
if (isOnCall) {
|
||||||
ctiClient.hangup()
|
ctiClient.hangup()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!telNum) return
|
if (!telNum.trim()) {
|
||||||
|
alert('전화번호가 없습니다.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// CTI는 ANINumber가 비어 있으면 Default 발신번호로 건다고 하지만, 의도치 않은 번호로 나가지 않도록 막는다.
|
||||||
|
if (!callerTelNum?.trim()) {
|
||||||
|
alert('프로젝트에 발신 번호가 등록되지 않았습니다.')
|
||||||
|
return
|
||||||
|
}
|
||||||
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid, listHderId, aniNumber: callerTelNum ?? '' })
|
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid, listHderId, aniNumber: callerTelNum ?? '' })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,13 +219,13 @@ const ListContactInfoPanel = ({
|
|||||||
const value = formValues[header.listHderId] ?? ''
|
const value = formValues[header.listHderId] ?? ''
|
||||||
const onChange = (next: string) => onFieldChange(header.listHderId, next)
|
const onChange = (next: string) => onFieldChange(header.listHderId, next)
|
||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.MEMO) {
|
if (header.listHderTy === ListHeaderConst.MEMO || header.listHderTy === ListHeaderConst.MULTILINE_TEXT) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
<textarea
|
<textarea
|
||||||
className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed ${disabledContrastClass}`}
|
className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${readOnlyContrastClass}`}
|
||||||
value={value}
|
value={value}
|
||||||
disabled={!editable}
|
readOnly={!editable}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</FieldRow>
|
</FieldRow>
|
||||||
@@ -200,24 +234,26 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
<div className="flex gap-2">
|
{/* 모바일(md 미만)은 버튼을 입력란 아래 줄로 내린다. */}
|
||||||
|
<div className="flex flex-col gap-2 md:flex-row">
|
||||||
<Input
|
<Input
|
||||||
value={formatKoreanPhoneNumber(value)}
|
value={formatKoreanPhoneNumber(value)}
|
||||||
disabled={!editable}
|
readOnly={!editable}
|
||||||
onChange={(e) => onChange(e.target.value.replace(/\D/g, ''))}
|
onChange={(e) => onChange(e.target.value.replace(/\D/g, ''))}
|
||||||
className={disabledContrastClass}
|
className={readOnlyContrastClass}
|
||||||
/>
|
/>
|
||||||
|
<div className="flex shrink-0 flex-wrap gap-2">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
|
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
|
||||||
disabled={isEditing || !isCtiReady || isDialing}
|
disabled={isEditing || !isCtiReady || isDialing || isEnding}
|
||||||
title={getCallButtonTitle(isCtiReady, isDialing)}
|
title={getCallButtonTitle(isCtiReady, isDialing, isEnding)}
|
||||||
onClick={() => handleCall(value, header.listHderId)}
|
onClick={() => handleCall(value, header.listHderId)}
|
||||||
>
|
>
|
||||||
<Phone className="h-4 w-4" />
|
<Phone className="h-4 w-4" />
|
||||||
{getCallButtonLabel(isDialing, isOnCall)}
|
{getCallButtonLabel(isDialing, isOnCall, isEnding)}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -229,6 +265,17 @@ const ListContactInfoPanel = ({
|
|||||||
<MessageSquare className="h-4 w-4" />
|
<MessageSquare className="h-4 w-4" />
|
||||||
발송
|
발송
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="shrink-0 gap-2"
|
||||||
|
disabled={isEditing}
|
||||||
|
onClick={() => handleSend('kko', header.listHderId)}
|
||||||
|
>
|
||||||
|
<MessageCircle className="h-4 w-4" />
|
||||||
|
알림톡
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{(isDialing || isOnCall) &&
|
{(isDialing || isOnCall) &&
|
||||||
<p className="text-sm text-red-600 font-medium mt-1">
|
<p className="text-sm text-red-600 font-medium mt-1">
|
||||||
@@ -241,14 +288,15 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.EMAIL) {
|
if (header.listHderTy === ListHeaderConst.EMAIL) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-col gap-2 md:flex-row">
|
||||||
<Input
|
<Input
|
||||||
value={value}
|
value={value}
|
||||||
disabled={!editable}
|
readOnly={!editable}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
className={disabledContrastClass}
|
className={readOnlyContrastClass}
|
||||||
/>
|
/>
|
||||||
|
<div className="flex shrink-0 gap-2">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -260,13 +308,14 @@ const ListContactInfoPanel = ({
|
|||||||
발송
|
발송
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</FieldRow>
|
</FieldRow>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.FILE) {
|
if (header.listHderTy === ListHeaderConst.FILE) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="min-w-0 flex-1 truncate text-sm">
|
<div className="min-w-0 flex-1 truncate text-sm">
|
||||||
{value ? (
|
{value ? (
|
||||||
@@ -305,9 +354,29 @@ const ListContactInfoPanel = ({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (header.listHderTy === ListHeaderConst.IS_USE) {
|
||||||
|
return (
|
||||||
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
|
<KriSingleSelect
|
||||||
|
items={IS_USE_OPTIONS}
|
||||||
|
value={value}
|
||||||
|
disabled={!editable}
|
||||||
|
onChange={onChange}
|
||||||
|
getValue={(item) => item.value}
|
||||||
|
getLabel={(item) => item.label}
|
||||||
|
searchable={false}
|
||||||
|
preventDeselect
|
||||||
|
widthClassName="w-full"
|
||||||
|
heightClassName="h-9"
|
||||||
|
className={disabledContrastClass}
|
||||||
|
/>
|
||||||
|
</FieldRow>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
|
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
<KriSingleSelect
|
<KriSingleSelect
|
||||||
items={header.filterContents ?? []}
|
items={header.filterContents ?? []}
|
||||||
value={value}
|
value={value}
|
||||||
@@ -324,12 +393,12 @@ const ListContactInfoPanel = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
|
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||||||
<Input
|
<Input
|
||||||
value={value}
|
value={value}
|
||||||
disabled={!editable}
|
readOnly={!editable}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
className={disabledContrastClass}
|
className={readOnlyContrastClass}
|
||||||
/>
|
/>
|
||||||
</FieldRow>
|
</FieldRow>
|
||||||
)
|
)
|
||||||
@@ -343,6 +412,8 @@ const ListContactInfoPanel = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<FieldRow key={survey.prjctSurveyIdx ?? survey.surveyOrder} label={survey.surveyName || 'Web'}>
|
<FieldRow key={survey.prjctSurveyIdx ?? survey.surveyOrder} label={survey.surveyName || 'Web'}>
|
||||||
|
{/* 모바일(md 미만)은 응답 상태를 버튼 아래 줄로 내린다. */}
|
||||||
|
<div className="flex flex-col items-start gap-2 md:flex-row md:items-center">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Button type="button" className="gap-2" disabled={isEditing} onClick={() => handleStartSurvey(survey)}>
|
<Button type="button" className="gap-2" disabled={isEditing} onClick={() => handleStartSurvey(survey)}>
|
||||||
조사 시작
|
조사 시작
|
||||||
@@ -351,6 +422,7 @@ const ListContactInfoPanel = ({
|
|||||||
<QrCode className="h-4 w-4" />
|
<QrCode className="h-4 w-4" />
|
||||||
QR
|
QR
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
{hasSurveyResponse ? (
|
{hasSurveyResponse ? (
|
||||||
<span className="text-sm">
|
<span className="text-sm">
|
||||||
[{resultCodes.find((rc) => rc.resultCdTy === ResultCodeType.SURVEY && rc.resultCd === result.lastResultCd)
|
[{resultCodes.find((rc) => rc.resultCdTy === ResultCodeType.SURVEY && rc.resultCd === result.lastResultCd)
|
||||||
@@ -372,7 +444,7 @@ const ListContactInfoPanel = ({
|
|||||||
itrntPrjctCd={itrntPrjctCd}
|
itrntPrjctCd={itrntPrjctCd}
|
||||||
sid={sid}
|
sid={sid}
|
||||||
destHeaderId={sendTarget?.headerId ?? 0}
|
destHeaderId={sendTarget?.headerId ?? 0}
|
||||||
variableValues={surveyUrlValues}
|
variableValues={sendTarget?.channel === 'kko' ? kkoVariableValues : surveyUrlValues}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { LIST_IS_USE_LABEL } from '@/components/table-column/ListTableColumn'
|
import { LIST_IS_USE_LABEL } from '@/components/table-column/ListTableColumn'
|
||||||
import { ListHeaderConst } from '@/const/listConst'
|
import { ListHeaderConst } from '@/const/listConst'
|
||||||
import type { listHeader, ListSearchWithFullResult } from '@/types/list'
|
import type { listHeader, ListSearchWithFullResult } from '@/types/list'
|
||||||
|
import type { ProjectSurvey } from '@/types/project'
|
||||||
import { isAssignHeaderType } from '@/utils/listAccess'
|
import { isAssignHeaderType } from '@/utils/listAccess'
|
||||||
|
import { substituteVariables } from '@/lib/variableSubstitution'
|
||||||
|
|
||||||
export const resolveListHeaderValue = (
|
export const resolveListHeaderValue = (
|
||||||
header: listHeader,
|
header: listHeader,
|
||||||
@@ -34,3 +36,21 @@ export const buildListContactVariableValues = (
|
|||||||
values.SID = sid
|
values.SID = sid
|
||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 알림톡 변수 값: 헤더 값에 더해 설문명(#{설문명})을 대상자 값으로 채운 설문 URL로 치환한다.
|
||||||
|
// 같은 이름의 헤더가 있으면 헤더 값을 우선한다.
|
||||||
|
export const buildKkoVariableValues = (
|
||||||
|
headerValues: Record<string, string>,
|
||||||
|
surveys: ProjectSurvey[],
|
||||||
|
): Record<string, string> => {
|
||||||
|
const values: Record<string, string> = { ...headerValues }
|
||||||
|
|
||||||
|
for (const survey of surveys) {
|
||||||
|
const surveyName = survey.surveyName?.trim()
|
||||||
|
const surveyUrl = survey.surveyUrl?.trim()
|
||||||
|
if (!surveyName || !surveyUrl || surveyName in values) continue
|
||||||
|
values[surveyName] = substituteVariables(surveyUrl, headerValues)
|
||||||
|
}
|
||||||
|
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|||||||
157
src/components/list/ListJobGate.tsx
Normal file
157
src/components/list/ListJobGate.tsx
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { useAtom } from 'jotai'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { ListJobProgress } from '@/components/list/ListJobProgress'
|
||||||
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
|
import { isAvailabilityUnsupported, isListJobGone, useListJob, useListJobAvailability, useUploadResetActive } from '@/query/list-job'
|
||||||
|
import { findTrackedListJob, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker'
|
||||||
|
import { listJobLabel } from '@/const/listJobConst'
|
||||||
|
import { blockerJobLabel, blockerPhaseLabel, blockerUserLabel, describeListJobAvailability } from '@/utils/listJobAvailability'
|
||||||
|
import { isActiveListJob, type ListJobType } from '@/types/list-job'
|
||||||
|
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
|
||||||
|
|
||||||
|
export type ListJobGateStatus = 'idle' | 'checking' | 'allowed' | 'blocked' | 'error' | 'unsupported'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 작업 다이얼로그(또는 배정 버튼 영역)에서 쓰는 접수 가능 여부와 내 현재 작업 상태.
|
||||||
|
* - availability: 다이얼로그는 차단 중 3초, 페이지는 평상시 10초·차단 중 3초 조회한다.
|
||||||
|
* - 내 현재 작업: localStorage 기록(사용자·프로젝트·jobType)의 작업 상세를 보여준다.
|
||||||
|
* requestLabel은 같은 jobType 안에서 이름이 갈리는 경우(배정/배정 초기화)에 넘긴다.
|
||||||
|
*/
|
||||||
|
export function useListJobGate({ prjctIdx, jobType, active, requestLabel, pollWhileIdle = false }: {
|
||||||
|
prjctIdx: number
|
||||||
|
jobType: ListJobType
|
||||||
|
active: boolean
|
||||||
|
requestLabel?: string
|
||||||
|
pollWhileIdle?: boolean
|
||||||
|
}) {
|
||||||
|
const { auth } = useAuth()
|
||||||
|
const userId = auth.user?.userId
|
||||||
|
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
|
||||||
|
const requestMatches = openRequest?.userId === userId && openRequest?.prjctIdx === prjctIdx && openRequest?.jobType === jobType
|
||||||
|
const availability = useListJobAvailability(prjctIdx, jobType, active, pollWhileIdle)
|
||||||
|
const uploadResetBlockers = availability.isSuccess && !availability.data.allowed
|
||||||
|
? availability.data.blockers.filter(blocker => blocker.blockingPhase === 'ACTIVE' && (blocker.jobType === 'LIST_UPLOAD' || blocker.jobType === 'LIST_RESET'))
|
||||||
|
: []
|
||||||
|
const uploadResetActive = useUploadResetActive(prjctIdx, active && uploadResetBlockers.length > 0)
|
||||||
|
const uploadResetJob = uploadResetActive.isSuccess && uploadResetActive.data.active
|
||||||
|
&& uploadResetBlockers.some(blocker => blocker.jobType === uploadResetActive.data.job?.jobType)
|
||||||
|
? uploadResetActive.data.job : null
|
||||||
|
const tracked = findTrackedListJob(useTrackedListJobs(), userId ?? '', prjctIdx, jobType)
|
||||||
|
const jobKey = requestMatches ? openRequest.jobKey : tracked?.jobKey ?? null
|
||||||
|
const detail = useListJob(prjctIdx, jobKey, active)
|
||||||
|
const job = detail.data?.jobKey === jobKey ? detail.data : undefined
|
||||||
|
const finishedJob = job && !isActiveListJob(job.jobStatus) ? job : undefined
|
||||||
|
const detailNotFound = isListJobGone(detail.error)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active && requestMatches && openRequest.opened) setOpenRequest(null)
|
||||||
|
}, [active, openRequest, requestMatches, setOpenRequest])
|
||||||
|
|
||||||
|
// 다른 탭·기기에서 접수한 내 작업이면 기록을 채워 진행 상태를 보여준다.
|
||||||
|
useEffect(() => {
|
||||||
|
const mine = availability.data?.blockers.find(blocker =>
|
||||||
|
blocker.mine && blocker.jobKey && blocker.jobType === jobType && blocker.blockingPhase === 'ACTIVE')
|
||||||
|
if (mine?.jobKey && userId) trackListJob({ userId, prjctIdx, jobType, jobKey: mine.jobKey })
|
||||||
|
}, [availability.data, jobType, prjctIdx, userId])
|
||||||
|
|
||||||
|
const status: ListJobGateStatus = !active ? 'idle'
|
||||||
|
: isAvailabilityUnsupported(availability.error) ? 'unsupported'
|
||||||
|
: availability.isError ? 'error'
|
||||||
|
// 재조회 중에는 직전 결과를 유지한다. 같은 쿼리를 페이지가 주기적으로 재조회하므로 isFetching을 '확인 중'으로
|
||||||
|
// 보면 그때마다 다이얼로그가 깜빡인다. 접수 직전에는 useSubmitListJob이 다시 확인한다.
|
||||||
|
: !availability.data ? 'checking'
|
||||||
|
: availability.data.allowed ? 'allowed' : 'blocked'
|
||||||
|
|
||||||
|
return {
|
||||||
|
prjctIdx,
|
||||||
|
jobType,
|
||||||
|
requestLabel: requestLabel ?? listJobLabel(jobType),
|
||||||
|
status,
|
||||||
|
availability: availability.data,
|
||||||
|
availabilityUpdatedAt: availability.dataUpdatedAt,
|
||||||
|
availabilitySucceeded: availability.isSuccess,
|
||||||
|
refetch: () => void availability.refetch(),
|
||||||
|
job,
|
||||||
|
hasCurrentJob: !!jobKey,
|
||||||
|
detailPending: active && !!jobKey && detail.isPending,
|
||||||
|
detailError: active && !!jobKey && detail.isError,
|
||||||
|
detailNotFound,
|
||||||
|
refetchDetail: () => void detail.refetch(),
|
||||||
|
uploadResetJob,
|
||||||
|
finishedJob,
|
||||||
|
// 확인 중·조회 실패·차단이면 실행 버튼을 막는다. 404(미배포)는 서버 판단에 맡긴다.
|
||||||
|
submitBlocked: status === 'checking' || status === 'error' || status === 'blocked' || (!!job && isActiveListJob(job.jobStatus)),
|
||||||
|
/** 완료 상태를 본 뒤 닫거나 확인을 누르면 기록을 지운다. 진행 중이면 유지한다. */
|
||||||
|
acknowledge: () => {
|
||||||
|
if (!finishedJob && !detailNotFound) return
|
||||||
|
if (jobKey) untrackListJob(jobKey)
|
||||||
|
if (requestMatches) setOpenRequest(null)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ListJobGate = ReturnType<typeof useListJobGate>
|
||||||
|
|
||||||
|
export function ListJobGatePanel({ gate, className = '', showCurrentJob = true, acknowledgeLabel = '확인' }: { gate: ListJobGate; className?: string; showCurrentJob?: boolean; acknowledgeLabel?: string }) {
|
||||||
|
const { status, availability, job, uploadResetJob } = gate
|
||||||
|
// 내 현재 작업으로 이미 보여주는 항목은 차단 목록에서 뺀다.
|
||||||
|
const listedBlockers = availability?.blockers.filter(blocker => !(showCurrentJob && blocker.mine && blocker.jobKey && blocker.jobKey === job?.jobKey)) ?? []
|
||||||
|
const remainingBlockerCount = availability ? Math.max(0, availability.blockerCount - (availability.blockers.length - listedBlockers.length)) : 0
|
||||||
|
const description = status === 'blocked' && availability && remainingBlockerCount > 0
|
||||||
|
? describeListJobAvailability({ ...availability, blockers: listedBlockers, blockerCount: remainingBlockerCount }, gate.jobType, gate.requestLabel)
|
||||||
|
: null
|
||||||
|
const uploadResetDetailShown = showCurrentJob && uploadResetJob?.mine && !!uploadResetJob.jobKey && job?.jobKey === uploadResetJob.jobKey
|
||||||
|
|
||||||
|
if (!(showCurrentJob && (job || gate.detailPending || gate.detailError)) && status !== 'checking' && status !== 'error' && !description) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`${className} space-y-3`}>
|
||||||
|
{showCurrentJob && gate.detailPending && <p role="status" className="text-sm text-muted-foreground">현재 작업 상태를 조회하는 중입니다.</p>}
|
||||||
|
{showCurrentJob && gate.detailError && <div role="alert" className="text-sm space-y-2">
|
||||||
|
<p>{gate.detailNotFound ? '작업을 찾을 수 없습니다. 보관 기간이 지났거나 접근할 수 없는 작업입니다.' : '현재 작업 상태를 불러오지 못했습니다.'}</p>
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={gate.detailNotFound ? gate.acknowledge : gate.refetchDetail}>{gate.detailNotFound ? '확인' : '다시 조회'}</Button>
|
||||||
|
</div>}
|
||||||
|
{showCurrentJob && job && (
|
||||||
|
<section className="rounded-md border p-3 space-y-2" aria-label="내 현재 작업">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<p className="font-semibold">내 현재 작업 · {listJobLabel(job.jobType, job.operation)}</p>
|
||||||
|
{gate.finishedJob && <Button type="button" size="sm" onClick={gate.acknowledge}>{acknowledgeLabel}</Button>}
|
||||||
|
</div>
|
||||||
|
<ListJobProgress prjctIdx={gate.prjctIdx} job={job} />
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
{status === 'checking' && <p role="status" className="text-sm text-muted-foreground">작업 가능 여부를 확인하는 중입니다.</p>}
|
||||||
|
{status === 'error' && (
|
||||||
|
<p role="alert" className="text-sm text-red-600">
|
||||||
|
작업 가능 여부를 확인하지 못했습니다.{' '}
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={gate.refetch}>다시 조회</Button>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{description && (
|
||||||
|
<div role="alert" className="rounded-md border border-amber-300 bg-amber-50 p-3 space-y-2 text-sm">
|
||||||
|
<p className="font-medium text-amber-800">{description.message}</p>
|
||||||
|
{listedBlockers.length > 0 && (
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{listedBlockers.map((blocker, index) => (
|
||||||
|
<li key={`${blocker.requestUserId}-${blocker.regDt}-${index}`}>
|
||||||
|
{blockerJobLabel(blocker)} · {blocker.mine ? '나' : blockerUserLabel(blocker)} · {blockerPhaseLabel(blocker)} · 접수 {blocker.regDt.replace('T', ' ').slice(0, 19)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{description.omittedCount > 0 && <p className="text-muted-foreground">외 {description.omittedCount.toLocaleString()}건은 표시하지 않았습니다.</p>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{status === 'blocked' && uploadResetJob && !uploadResetDetailShown && (
|
||||||
|
<div role="status" className="text-sm text-muted-foreground space-y-1">
|
||||||
|
<p>{listJobLabel(uploadResetJob.jobType)} 처리 {uploadResetJob.processedSidCnt.toLocaleString()}
|
||||||
|
{uploadResetJob.totalSidCnt === null ? '건 · 전체 집계 중' : ` / ${uploadResetJob.totalSidCnt.toLocaleString()}건`}</p>
|
||||||
|
{uploadResetJob.totalSidCnt !== null && uploadResetJob.totalSidCnt > 0 && <progress className="w-full" aria-label={`${listJobLabel(uploadResetJob.jobType)} 진행률`} max={uploadResetJob.totalSidCnt} value={Math.min(uploadResetJob.totalSidCnt, uploadResetJob.processedSidCnt)} />}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
200
src/components/list/ListJobProgress.tsx
Normal file
200
src/components/list/ListJobProgress.tsx
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { nextApi } from '@/lib/http-client'
|
||||||
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
|
import { clientEnv } from '@/lib/env.client'
|
||||||
|
import { LIST_JOB_STAGE_LABEL, LIST_JOB_STATUS_LABEL, listJobLabel } from '@/const/listJobConst'
|
||||||
|
import { isActiveListJob, type ListJob, type ListJobFailurePage } from '@/types/list-job'
|
||||||
|
import { formatMessageJobResult } from '@/utils/listJobResult'
|
||||||
|
|
||||||
|
type JobDetailPath = 'validation-errors' | 'sid-failures' | 'range-failures' | 'message-report/batches' | 'message-report/preparation-failures'
|
||||||
|
type JobDetailSection = { path: JobDetailPath; label: string }
|
||||||
|
|
||||||
|
function getDetailSections(job: ListJob): JobDetailSection[] {
|
||||||
|
const p = job.progress ?? {}
|
||||||
|
const positive = (value: unknown) => typeof value === 'number' && value > 0
|
||||||
|
if (job.jobType === 'LIST_UPLOAD') {
|
||||||
|
const sections: JobDetailSection[] = []
|
||||||
|
if (positive(p.validationErrorCnt) || job.jobStage === 'VALIDATION_FAILED' || job.errorCode === 'LIST_UPLOAD_VALIDATION_FAILED') {
|
||||||
|
sections.push({ path: 'validation-errors', label: '파일 검증 오류' })
|
||||||
|
}
|
||||||
|
if (positive(p.deleteFailedRangeCnt) || positive(p.insertFailedRangeCnt) || job.errorCode === 'PARTIAL_RANGE_FAILURE') {
|
||||||
|
sections.push({ path: 'range-failures', label: '구간 실패' })
|
||||||
|
}
|
||||||
|
return sections
|
||||||
|
}
|
||||||
|
if (['LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN'].includes(job.jobType)) {
|
||||||
|
return job.failedSidCnt > 0 ? [{ path: 'sid-failures', label: '실패한 리스트' }] : []
|
||||||
|
}
|
||||||
|
if (['EMAIL_BULK', 'SMS_BULK', 'KKO_BULK'].includes(job.jobType)) {
|
||||||
|
const sections: JobDetailSection[] = []
|
||||||
|
if (positive(p.recordedBatchCnt)) sections.push({ path: 'message-report/batches', label: '발송 접수 결과' })
|
||||||
|
if (positive(p.preparationFailedSidCnt)) sections.push({ path: 'message-report/preparation-failures', label: '발송 준비 실패' })
|
||||||
|
return sections
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
const DETAIL_FIELDS: Record<JobDetailPath, readonly (readonly [string, string])[]> = {
|
||||||
|
'validation-errors': [['rowNumber', '행'], ['sid', 'SID'], ['fieldName', '항목'], ['errorMessage', '사유']],
|
||||||
|
'sid-failures': [['sid', 'SID'], ['code', '사유'], ['chunkNo', '처리 구간']],
|
||||||
|
'range-failures': [['stage', '단계'], ['attempt', '처리 순번'], ['code', '사유']],
|
||||||
|
'message-report/batches': [
|
||||||
|
['batchNo', '접수 묶음'], ['status', '접수 상태'], ['targetRecipientCnt', '대상 수신처'],
|
||||||
|
['acceptedRecipientCnt', '접수'], ['failedRecipientCnt', '실패'], ['unknownRecipientCnt', '접수 여부 불명'],
|
||||||
|
],
|
||||||
|
'message-report/preparation-failures': [['code', '사유']],
|
||||||
|
}
|
||||||
|
const DETAIL_VALUE_LABEL: Record<string, string> = {
|
||||||
|
LIST_NOT_FOUND: '대상 리스트가 삭제되었거나 존재하지 않습니다.',
|
||||||
|
RANGE_EXECUTION_FAILED: '구간 처리 실패', TARGET_READ_FAILED: '대상 리스트 조회 실패',
|
||||||
|
ROW_PREPARATION_FAILED: '발송 내용 준비 실패', NO_DESTINATION: '수신처 없음', INVALID_DESTINATION: '수신처 형식 오류',
|
||||||
|
ACCEPTED: '접수 완료', PARTIAL: '일부 접수', REJECTED: '접수 거절', UNKNOWN: '접수 여부 불명',
|
||||||
|
INVALID_RESPONSE: '접수 응답 확인 불가', BULK_CREATION_FAILED: '발송 작업 생성 실패', CANCELLED_BEFORE_SEND: '발송 요청 전 중단',
|
||||||
|
}
|
||||||
|
const n = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString() : '-'
|
||||||
|
const text = (value: unknown) => typeof value === 'string' || typeof value === 'number' ? String(value).slice(0, 500) : ''
|
||||||
|
const stageLabel = (jobStage: string) => LIST_JOB_STAGE_LABEL[jobStage] ?? '처리 중'
|
||||||
|
|
||||||
|
function SidProgress({ total, processed }: { total: number | null; processed: number }) {
|
||||||
|
if (total === null || total <= 0) return null
|
||||||
|
return <progress aria-label="SID 처리 진행률" className="w-full" max={total} value={Math.min(total, processed)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function Progress({ job }: { job: ListJob }) {
|
||||||
|
const p = job.progress ?? {}
|
||||||
|
if (job.jobType.endsWith('_BULK')) return (
|
||||||
|
<div className="text-sm space-y-1">
|
||||||
|
<p>{formatMessageJobResult(job.progress)}</p>
|
||||||
|
<p>처리 수신자 {n(p.processedRecipientCnt)}건 / 준비된 수신자 {n(p.preparedRecipientCnt)}건</p>
|
||||||
|
<p className="text-muted-foreground">발송 요청의 접수 결과입니다. 실제 전달 결과는 발송 이력에서 확인하세요. 일부 접수 또는 접수 여부 불명이 있으면 중복 발송될 수 있으므로 전체 재발송 전에 내역을 확인해야 합니다.</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
if (job.jobType.endsWith('_DOWNLOAD')) return <p className="text-sm">파일 처리 대상 {n(p.processedSidCnt)} · 작성 행 {n(p.writtenRowCnt)} · 작성 파일 {n(p.writtenFileCnt)}</p>
|
||||||
|
return (
|
||||||
|
<div className="text-sm space-y-1">
|
||||||
|
<p>전체 {job.totalSidCnt === null ? '집계 중' : n(job.totalSidCnt)} · 반영 완료 {n(job.completedSidCnt)} · SID 실패 {n(job.failedSidCnt)} · 완료 구간 {n(job.completedChunkCnt)}</p>
|
||||||
|
{typeof p.deleteTotalSidCnt === 'number' && <p>기존 데이터 삭제 {n(p.deleteCompletedSidCnt)} / {n(p.deleteTotalSidCnt)} · 삭제 실패 구간 {n(p.deleteFailedRangeCnt)}</p>}
|
||||||
|
{typeof p.insertTotalSidCnt === 'number' && <p>신규 등록 {n(p.insertCompletedSidCnt)} / {n(p.insertTotalSidCnt)} · 등록 실패 구간 {n(p.insertFailedRangeCnt)}</p>}
|
||||||
|
<SidProgress total={job.totalSidCnt} processed={job.processedSidCnt} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function JobDetailItem({ path, item }: { path: JobDetailPath; item: Record<string, unknown> }) {
|
||||||
|
const sids = Array.isArray(item.sids) ? item.sids.filter((sid): sid is string => typeof sid === 'string') : []
|
||||||
|
const fields = DETAIL_FIELDS[path].flatMap(([field, label]) => {
|
||||||
|
const value = text(item[field])
|
||||||
|
if (!value) return []
|
||||||
|
const displayed = field === 'stage' ? stageLabel(value)
|
||||||
|
: field === 'code' || field === 'status' ? DETAIL_VALUE_LABEL[value] ?? value : value
|
||||||
|
return [`${label}: ${displayed}`]
|
||||||
|
})
|
||||||
|
return (
|
||||||
|
<div className="space-y-1 break-words">
|
||||||
|
<p>{fields.join(' · ') || '표시할 상세 정보가 없습니다.'}</p>
|
||||||
|
{sids.length > 0 && <details><summary className="cursor-pointer">대상 SID {sids.length.toLocaleString()}건</summary><p className="break-all">{sids.join(', ')}</p></details>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function JobFailures({ prjctIdx, job, sections }: { prjctIdx: number; job: ListJob; sections: JobDetailSection[] }) {
|
||||||
|
const { auth } = useAuth()
|
||||||
|
const [selectedPath, setSelectedPath] = useState(sections[0].path)
|
||||||
|
const section = sections.find(item => item.path === selectedPath) ?? sections[0]
|
||||||
|
const [offset, setOffset] = useState(0)
|
||||||
|
const failures = useQuery({
|
||||||
|
queryKey: ['listJobFailures', auth.user?.userId, prjctIdx, job.jobKey, section.path, offset, job.jobStatus],
|
||||||
|
queryFn: async (): Promise<ListJobFailurePage> => {
|
||||||
|
const value = await nextApi.get<unknown>(`/list-jobs/${prjctIdx}/${job.jobKey}/${section.path}?offset=${offset}&limit=100`, { skipResponseErrorHandler: true })
|
||||||
|
if (!value || typeof value !== 'object' || !('total' in value) || typeof value.total !== 'number'
|
||||||
|
|| !Number.isInteger(value.total) || value.total < 0
|
||||||
|
|| !('items' in value) || !Array.isArray(value.items) || !value.items.every(item => item && typeof item === 'object' && !Array.isArray(item))) throw new Error('상세 내역 응답이 올바르지 않습니다.')
|
||||||
|
return { total: value.total, offset, items: value.items }
|
||||||
|
},
|
||||||
|
refetchInterval: query => isActiveListJob(job.jobStatus) && query.state.status === 'success' ? 3000 : false,
|
||||||
|
retry: false,
|
||||||
|
meta: { ignoreGlobalLoading: true },
|
||||||
|
})
|
||||||
|
return (
|
||||||
|
<section className="rounded border p-3 space-y-3" aria-label="작업 상세 내역">
|
||||||
|
{sections.length > 1 ? <label className="flex gap-2 items-center text-sm">조회 항목
|
||||||
|
<select className="rounded border p-2" value={section.path} onChange={event => {
|
||||||
|
const next = sections.find(item => item.path === event.target.value)
|
||||||
|
if (next) { setSelectedPath(next.path); setOffset(0) }
|
||||||
|
}}>
|
||||||
|
{sections.map(item => <option key={item.path} value={item.path}>{item.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</label> : <p className="text-sm font-medium">{section.label}</p>}
|
||||||
|
{failures.isPending && <p role="status" className="text-sm">상세 내역을 조회하는 중입니다.</p>}
|
||||||
|
{failures.isError && <div role="alert" className="text-sm space-y-2">
|
||||||
|
<p>상세 내역을 불러오지 못했습니다.</p>
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => void failures.refetch()}>다시 조회</Button>
|
||||||
|
</div>}
|
||||||
|
{!failures.isError && failures.data && <>
|
||||||
|
<p className="text-sm">전체 {failures.data.total.toLocaleString()}건</p>
|
||||||
|
{failures.data.items.length === 0 ? <p className="text-sm text-muted-foreground">조회된 내역이 없습니다.</p> : <ul className="max-h-60 overflow-auto text-sm space-y-2">
|
||||||
|
{failures.data.items.map((item, index) => <li key={offset + index} className="border-b pb-1"><JobDetailItem path={section.path} item={item} /></li>)}
|
||||||
|
</ul>}
|
||||||
|
{failures.data.total > 100 && <div className="flex gap-2">
|
||||||
|
<Button type="button" variant="outline" disabled={offset === 0 || failures.isFetching} onClick={() => setOffset(Math.max(0, offset - 100))}>이전 100건</Button>
|
||||||
|
<Button type="button" variant="outline" disabled={offset + 100 >= failures.data.total || failures.isFetching} onClick={() => setOffset(offset + 100)}>다음 100건</Button>
|
||||||
|
</div>}
|
||||||
|
</>}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ListJobProgress({ prjctIdx, job }: { prjctIdx: number; job: ListJob }) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const [detailJobKey, setDetailJobKey] = useState<string | null>(null)
|
||||||
|
const detailOpen = detailJobKey === job.jobKey
|
||||||
|
const sections = getDetailSections(job)
|
||||||
|
const detailLabel = job.jobType === 'LIST_UPLOAD' ? '업로드 오류' : job.jobType.endsWith('_BULK') ? '발송 접수 내역' : '실패한 리스트'
|
||||||
|
const active = isActiveListJob(job.jobStatus)
|
||||||
|
const cancel = useMutation({
|
||||||
|
mutationFn: () => nextApi.post(`/list-jobs/${prjctIdx}/${job.jobKey}/cancel`),
|
||||||
|
retry: false,
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.info('중단을 요청했습니다. 이미 반영된 내용은 유지됩니다.')
|
||||||
|
for (const key of [['listJob'], ['listJobAvailability'], ['listJobMyActive'], ['listJobUploadResetActive']]) {
|
||||||
|
void qc.invalidateQueries({ queryKey: key })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
// 배정 작업은 진행 중일 때 operation에 따라 "배정 중"/"배정 초기화 중"으로 표시한다.
|
||||||
|
let statusText = LIST_JOB_STATUS_LABEL[job.jobStatus]
|
||||||
|
if (job.jobType === 'LIST_ASSIGN' && job.operation && job.jobStatus === 'RUNNING') {
|
||||||
|
statusText = `${listJobLabel(job.jobType, job.operation)} 중`
|
||||||
|
} else if (job.jobType.endsWith('_BULK') && job.jobStatus === 'SUCCEEDED') {
|
||||||
|
statusText = '접수 완료'
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{active && <p className="text-sm text-muted-foreground">창을 닫아도 작업은 계속되며, 완료 시 알림을 드립니다.</p>}
|
||||||
|
<p><strong>{statusText}</strong> · 단계: {stageLabel(job.jobStage)} · 접수 {job.regDt.replace('T', ' ').slice(0, 19)}</p>
|
||||||
|
<Progress job={job} />
|
||||||
|
{job.jobStatus === 'PARTIALLY_SUCCEEDED' && <p className="text-sm text-amber-700">일부 대상은 접수되지 않았거나 접수 여부를 확인하지 못했습니다. 아래 접수 내역과 준비 실패 내역을 확인해 주세요.</p>}
|
||||||
|
{job.jobStatus !== 'SUCCEEDED' && job.jobStatus !== 'PARTIALLY_SUCCEEDED' && !active && <p className="text-sm text-red-600">{job.errorMessage || (job.cancelReason === 'USER_REQUEST' ? '사용자 요청으로 중단됐습니다.' : '처리가 종료됐습니다.')} {job.jobStage === 'VALIDATION_FAILED' ? '파일 검증 단계에서 중단되어 리스트 데이터는 변경되지 않았습니다.' : '이미 반영된 내용이 있을 수 있으니 확인 후 다시 요청하세요.'}</p>}
|
||||||
|
{job.jobStatus === 'FAILED' && job.failedChunkNo != null && <p className="text-sm text-red-600">실패한 처리 구간: {n(job.failedChunkNo)}번째</p>}
|
||||||
|
{(job.resultFiles.length > 0 || job.jobType === 'LIST_UPLOAD') && <div className="flex flex-wrap gap-3 text-sm">
|
||||||
|
{job.resultFiles.map(file => file.ready
|
||||||
|
? <a className="underline" key={file.index} href={`${clientEnv.API_BASE}/list-jobs/${prjctIdx}/${job.jobKey}/files/${file.index}`} download={file.fileName} target="_blank" rel="noopener noreferrer">{file.fileName} 다운로드</a>
|
||||||
|
: <span key={file.index}>{file.fileName}: 다운로드 완료 또는 보관기간 종료</span>)}
|
||||||
|
{job.jobType === 'LIST_UPLOAD' && <a className="underline" href={`${clientEnv.API_BASE}/list-jobs/${prjctIdx}/${job.jobKey}/source-file`} download target="_blank" rel="noopener noreferrer">업로드 원본</a>}
|
||||||
|
</div>}
|
||||||
|
{job.resultFiles.length > 0 && <p className="text-sm text-muted-foreground">파일은 다운로드 후 또는 보관 기간 만료 시 삭제됩니다.</p>}
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{active && <Button variant="outline" disabled={cancel.isPending || job.jobStatus === 'CANCEL_REQUESTED'} onClick={() => {
|
||||||
|
if (confirm('작업을 중단할까요? 이미 반영된 구간은 유지됩니다.')) cancel.mutate()
|
||||||
|
}}>중단 요청</Button>}
|
||||||
|
{sections.length > 0 && <Button type="button" variant="outline" onClick={() => setDetailJobKey(detailOpen ? null : job.jobKey)}>{detailLabel} {detailOpen ? '닫기' : '보기'}</Button>}
|
||||||
|
</div>
|
||||||
|
{detailOpen && sections.length > 0 && <JobFailures key={`${job.jobKey}-${sections.map(section => section.path).join('|')}`} prjctIdx={prjctIdx} job={job} sections={sections} />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
22
src/components/list/ListJobRefreshNotice.tsx
Normal file
22
src/components/list/ListJobRefreshNotice.tsx
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import type { ListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
|
||||||
|
|
||||||
|
export function ListJobRefreshNotice({ monitor, clearsSelection = false }: {
|
||||||
|
monitor: ListJobPageMonitor
|
||||||
|
clearsSelection?: boolean
|
||||||
|
}) {
|
||||||
|
if (!monitor.pendingRefresh) return null
|
||||||
|
return (
|
||||||
|
<div role="status" className="flex items-center justify-between gap-3 rounded-md border bg-muted/30 p-3 text-sm">
|
||||||
|
<p>{monitor.refreshError ? '목록을 새로 불러오지 못했습니다. 다시 시도해 주세요.'
|
||||||
|
: clearsSelection ? '목록이 변경되었습니다. 새로고침하면 선택한 행이 해제됩니다.'
|
||||||
|
: '목록이 변경되었습니다. 작업을 마친 뒤 새로고침해 주세요.'}</p>
|
||||||
|
<Button type="button" variant="outline" size="sm" disabled={monitor.refreshBlocked || monitor.refreshing}
|
||||||
|
onClick={() => void monitor.refresh()}>
|
||||||
|
{monitor.refreshing ? '새로고침 중…' : '새로고침'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
113
src/components/list/ListJobWatcher.tsx
Normal file
113
src/components/list/ListJobWatcher.tsx
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { usePathname, useRouter } from 'next/navigation'
|
||||||
|
import { useAtom } from 'jotai'
|
||||||
|
import { useQueries, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
import { nextApi } from '@/lib/http-client'
|
||||||
|
import { isListJobGone, listJobKeys, useMyActiveListJobs } from '@/query/list-job'
|
||||||
|
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
|
||||||
|
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||||
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
|
import type { SelectedProject } from '@/store/jotai/project'
|
||||||
|
import { markListJobNotified, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker'
|
||||||
|
import { LIST_JOB_VIEW } from '@/const/listJobConst'
|
||||||
|
import { getListJobResultNotification } from '@/utils/listJobResult'
|
||||||
|
import { isActiveListJob, isListJobType, parseListJob, type ListJob } from '@/types/list-job'
|
||||||
|
|
||||||
|
function isProjectSelection(value: unknown, projectId: number): value is SelectedProject {
|
||||||
|
if (!value || typeof value !== 'object') return false
|
||||||
|
const project = value as Record<string, unknown>
|
||||||
|
return project.prjctIdx === projectId && typeof project.ff === 'boolean'
|
||||||
|
&& ['prjctCd', 'prjctName', 'itrntPrjctCd', 'ownerDept', 'ownerFw'].every(key => typeof project[key] === 'string')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 화면 없이 동작하는 전역 감시.
|
||||||
|
* - 현재 프로젝트의 진행 중인 내 작업을 서버에서 가져와 기록이 없으면 채운다(다른 탭·기기 보완).
|
||||||
|
* - 기록된 작업이 끝나면 완료 toast를 1회 띄우고 관련 데이터를 갱신한다.
|
||||||
|
*/
|
||||||
|
export function ListJobWatcher({ userId, prjctIdx }: { userId: string; prjctIdx: number }) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
|
||||||
|
const { selectedProject, setSelectedProject } = useSelectedProject()
|
||||||
|
const router = useRouter()
|
||||||
|
const pathname = usePathname()
|
||||||
|
const { hideAll } = useDialog()
|
||||||
|
const trackedJobs = useTrackedListJobs().filter(job => job.userId === userId)
|
||||||
|
const myActive = useMyActiveListJobs(prjctIdx, prjctIdx > 0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!openRequest) return
|
||||||
|
if (openRequest.userId !== userId) { setOpenRequest(null); return }
|
||||||
|
if (openRequest.opened) {
|
||||||
|
if (selectedProject?.prjctIdx !== openRequest.prjctIdx || pathname !== LIST_JOB_VIEW[openRequest.jobType].path) setOpenRequest(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (selectedProject?.prjctIdx === openRequest.prjctIdx) {
|
||||||
|
const path = LIST_JOB_VIEW[openRequest.jobType].path
|
||||||
|
if (pathname !== path) router.push(path)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let cancelled = false
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const value = await nextApi.get<unknown>(`/project/info/${openRequest.prjctIdx}`, { skipResponseErrorHandler: true })
|
||||||
|
if (cancelled) return
|
||||||
|
if (!isProjectSelection(value, openRequest.prjctIdx)) throw new Error('Invalid project selection')
|
||||||
|
setSelectedProject({
|
||||||
|
prjctIdx: value.prjctIdx, prjctCd: value.prjctCd, prjctName: value.prjctName,
|
||||||
|
itrntPrjctCd: value.itrntPrjctCd, ownerDept: value.ownerDept, ownerFw: value.ownerFw, ff: value.ff,
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
if (cancelled) return
|
||||||
|
toast.error('작업의 프로젝트를 열 수 없습니다. 접근 권한과 프로젝트 상태를 확인해 주세요.')
|
||||||
|
setOpenRequest(null)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [openRequest, pathname, router, selectedProject?.prjctIdx, setOpenRequest, setSelectedProject, userId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
for (const job of myActive.data ?? []) {
|
||||||
|
if (isListJobType(job.jobType)) trackListJob({ userId, prjctIdx, jobType: job.jobType, jobKey: job.jobKey })
|
||||||
|
}
|
||||||
|
}, [myActive.data, prjctIdx, userId])
|
||||||
|
|
||||||
|
const details = useQueries({
|
||||||
|
queries: trackedJobs.map(job => ({
|
||||||
|
queryKey: listJobKeys.detail(userId, job.prjctIdx, job.jobKey),
|
||||||
|
queryFn: async () => parseListJob(await nextApi.get(`/list-jobs/${job.prjctIdx}/${job.jobKey}`, { skipResponseErrorHandler: true })),
|
||||||
|
refetchInterval: (query: { state: { data?: ListJob } }) => query.state.data && !isActiveListJob(query.state.data.jobStatus) ? false : 3000,
|
||||||
|
retry: false,
|
||||||
|
meta: { ignoreGlobalLoading: true },
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
details.forEach((result, index) => {
|
||||||
|
const tracked = trackedJobs[index]
|
||||||
|
if (!tracked) return
|
||||||
|
if (isListJobGone(result.error)) {
|
||||||
|
untrackListJob(tracked.jobKey)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const job = result.data
|
||||||
|
if (!job || isActiveListJob(job.jobStatus) || !markListJobNotified(tracked.jobKey)) return
|
||||||
|
// 일부 실패·중단이어도 앞 구간은 반영됐을 수 있으므로 항상 갱신한다.
|
||||||
|
for (const key of [['list'], ['assign'], ['project'], ['message-report'], ['listJobMyActive'], ['listJobUploadResetActive'], ['listJobAvailability']]) {
|
||||||
|
void qc.invalidateQueries({ queryKey: key })
|
||||||
|
}
|
||||||
|
if (openRequest?.opened && openRequest.jobKey === tracked.jobKey) return
|
||||||
|
const open = { label: '보기', onClick: () => {
|
||||||
|
hideAll()
|
||||||
|
setOpenRequest({ userId, prjctIdx: tracked.prjctIdx, jobType: tracked.jobType, jobKey: tracked.jobKey, opened: false })
|
||||||
|
} }
|
||||||
|
const notification = getListJobResultNotification(job)
|
||||||
|
toast[notification.kind](notification.message, { action: open, description: notification.description })
|
||||||
|
})
|
||||||
|
}, [details, trackedJobs, openRequest, setOpenRequest, qc, userId, hideAll])
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
@@ -3,18 +3,27 @@
|
|||||||
import {
|
import {
|
||||||
Download,
|
Download,
|
||||||
FileClock,
|
FileClock,
|
||||||
|
Loader2,
|
||||||
Mail,
|
Mail,
|
||||||
|
MessageCircle,
|
||||||
MessageSquareMore,
|
MessageSquareMore,
|
||||||
RotateCcw,
|
RotateCcw,
|
||||||
Upload,
|
Upload,
|
||||||
|
type LucideIcon,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import type { ListDownloadMode } from '@/types/list'
|
import type { ListDownloadMode } from '@/types/list'
|
||||||
import type { MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
import type { MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
||||||
|
|
||||||
|
export type ListManageActionKey = 'reset' | 'upload' | ListDownloadMode | MessageSendMode
|
||||||
|
|
||||||
export type ListManageActionsProps = {
|
export type ListManageActionsProps = {
|
||||||
/** 리스트 초기화/헤더 관리/업로드처럼 내부 관리자 전용 버튼 노출 여부 (외주사 계정에는 숨겨야 함) */
|
/** 리스트 초기화/헤더 관리/업로드처럼 내부 관리자 전용 버튼 노출 여부 (외주사 계정에는 숨겨야 함) */
|
||||||
showAdminActions: boolean
|
showAdminActions: boolean
|
||||||
|
/** 비동기 작업이 진행 중인 버튼. 아이콘을 진행 표시로 바꾸고, 누르면 진행 다이얼로그가 열린다. */
|
||||||
|
runningActions?: ReadonlySet<ListManageActionKey>
|
||||||
|
disabledActions?: ReadonlySet<ListManageActionKey>
|
||||||
|
headerManageDisabled?: boolean
|
||||||
onReset: () => void
|
onReset: () => void
|
||||||
onHeaderManage: () => void
|
onHeaderManage: () => void
|
||||||
onUpload: () => void
|
onUpload: () => void
|
||||||
@@ -25,6 +34,9 @@ export type ListManageActionsProps = {
|
|||||||
|
|
||||||
export function ListManageActions({
|
export function ListManageActions({
|
||||||
showAdminActions,
|
showAdminActions,
|
||||||
|
runningActions,
|
||||||
|
disabledActions,
|
||||||
|
headerManageDisabled = false,
|
||||||
onReset,
|
onReset,
|
||||||
onHeaderManage,
|
onHeaderManage,
|
||||||
onUpload,
|
onUpload,
|
||||||
@@ -32,49 +44,58 @@ export function ListManageActions({
|
|||||||
onMessageSend,
|
onMessageSend,
|
||||||
onMessageHistory,
|
onMessageHistory,
|
||||||
}: ListManageActionsProps) {
|
}: ListManageActionsProps) {
|
||||||
|
const icon = (key: ListManageActionKey, Icon: LucideIcon) =>
|
||||||
|
runningActions?.has(key)
|
||||||
|
? <Loader2 className="w-4 h-4 animate-spin" aria-label="진행 중" />
|
||||||
|
: <Icon className="w-4 h-4" />
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex gap-2 items-center">
|
<div className="flex gap-2 items-center">
|
||||||
<div className="flex flex-1 items-center gap-2 flex-wrap">
|
<div className="flex flex-1 items-center gap-2 flex-wrap">
|
||||||
{showAdminActions && (
|
{showAdminActions && (
|
||||||
<>
|
<>
|
||||||
<Button variant="destructive" className="text-base gap-2" onClick={onReset}>
|
<Button variant="destructive" className="text-base gap-2" onClick={onReset} disabled={disabledActions?.has('reset')}>
|
||||||
<RotateCcw className="w-4 h-4" />
|
{icon('reset', RotateCcw)}
|
||||||
리스트 초기화
|
리스트 초기화
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="text-base" onClick={onHeaderManage}>
|
<Button className="text-base" onClick={onHeaderManage} disabled={headerManageDisabled}>
|
||||||
헤더 관리
|
헤더 관리
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="text-base gap-2" onClick={onUpload}>
|
<Button className="text-base gap-2" onClick={onUpload} disabled={disabledActions?.has('upload')}>
|
||||||
<Upload className="w-4 h-4" />
|
{icon('upload', Upload)}
|
||||||
리스트 업로드
|
리스트 업로드
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')}>
|
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list')} disabled={disabledActions?.has('list')}>
|
||||||
<Download className="w-4 h-4" />
|
{icon('list', Download)}
|
||||||
리스트
|
리스트
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')}>
|
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('contact-history')} disabled={disabledActions?.has('contact-history')}>
|
||||||
<Download className="w-4 h-4" />
|
{icon('contact-history', Download)}
|
||||||
컨택 이력
|
컨택 이력
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')}>
|
<Button className="text-base bg-excel gap-2" onClick={() => onDownload('list-change-history')} disabled={disabledActions?.has('list-change-history')}>
|
||||||
<Download className="w-4 h-4" />
|
{icon('list-change-history', Download)}
|
||||||
리스트 변경 이력
|
리스트 변경 이력
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')}>
|
<Button className="text-base gap-2" onClick={() => onDownload('upload-file')} disabled={disabledActions?.has('upload-file')}>
|
||||||
<Download className="w-4 h-4" />
|
{icon('upload-file', Download)}
|
||||||
업로드 파일(.zip)
|
업로드 파일(.zip)
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')}>
|
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('email')} disabled={disabledActions?.has('email')}>
|
||||||
<Mail className="w-4 h-4" />
|
{icon('email', Mail)}
|
||||||
이메일 발송
|
이메일 발송
|
||||||
</Button>
|
</Button>
|
||||||
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')}>
|
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('sms')} disabled={disabledActions?.has('sms')}>
|
||||||
<MessageSquareMore className="w-4 h-4" />
|
{icon('sms', MessageSquareMore)}
|
||||||
문자 발송
|
문자 발송
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button className="text-base bg-blue gap-2" onClick={() => onMessageSend('kko')} disabled={disabledActions?.has('kko')}>
|
||||||
|
{icon('kko', MessageCircle)}
|
||||||
|
알림톡 발송
|
||||||
|
</Button>
|
||||||
<Button className="text-base gap-2" onClick={onMessageHistory}>
|
<Button className="text-base gap-2" onClick={onMessageHistory}>
|
||||||
<FileClock className="w-4 h-4" />
|
<FileClock className="w-4 h-4" />
|
||||||
발송 이력
|
발송 이력
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState, type ClipboardEvent, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState, type ClipboardEvent, type ReactNode } from 'react'
|
||||||
import type { PaginationState, SortingState } from '@tanstack/react-table'
|
import type { PaginationState, SortingState } from '@tanstack/react-table'
|
||||||
import { Funnel, PencilLine } from 'lucide-react'
|
import { ChevronDown, Funnel, PencilLine } from 'lucide-react'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover'
|
||||||
import { DataTable } from '@/components/data-table/DataTable'
|
import { DataTable } from '@/components/data-table/DataTable'
|
||||||
import type { DataTableColumn, SelectMode } from '@/components/data-table/DataTable.type'
|
import type { DataTableColumn, SelectMode } from '@/components/data-table/DataTable.type'
|
||||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||||
@@ -12,7 +14,9 @@ import KriDateRangePicker, { type KriDateRange } from '@/components/common/KriDa
|
|||||||
import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes, type BatchEditRow, type BatchEditSurveyResultCodes } from '@/components/dialog/ListBatchEditDialog'
|
import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes, type BatchEditRow, type BatchEditSurveyResultCodes } from '@/components/dialog/ListBatchEditDialog'
|
||||||
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
|
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
|
||||||
import { useDialog } from '@/hooks/useDialog'
|
import { useDialog } from '@/hooks/useDialog'
|
||||||
import { useListSearchQuery, useUpdateListMutation } from '@/query/list'
|
import { cn } from '@/lib/utils'
|
||||||
|
import { useListSearchQuery } from '@/query/list'
|
||||||
|
import { useSubmitListJob } from '@/query/list-job'
|
||||||
import { getListColumns, LIST_IS_USE_LABEL, type ListTableRow } from '@/components/table-column/ListTableColumn'
|
import { getListColumns, LIST_IS_USE_LABEL, type ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||||
import { useAssignTargetRows } from '@/components/assign/AssignTargetList'
|
import { useAssignTargetRows } from '@/components/assign/AssignTargetList'
|
||||||
import { ListHeaderAssignConst, ListHeaderConst } from '@/const/listConst'
|
import { ListHeaderAssignConst, ListHeaderConst } from '@/const/listConst'
|
||||||
@@ -53,6 +57,8 @@ export type ListSearchTableProps = {
|
|||||||
listHeaders: listHeader[]
|
listHeaders: listHeader[]
|
||||||
fieldInterviewEnabled?: boolean
|
fieldInterviewEnabled?: boolean
|
||||||
enableBatchEdit?: boolean
|
enableBatchEdit?: boolean
|
||||||
|
batchEditDisabled?: boolean
|
||||||
|
dataRevision?: number
|
||||||
refreshKey?: number
|
refreshKey?: number
|
||||||
selectMode?: SelectMode
|
selectMode?: SelectMode
|
||||||
filterActions?: ReactNode
|
filterActions?: ReactNode
|
||||||
@@ -71,6 +77,8 @@ export type ListSearchTableProps = {
|
|||||||
initialSearchState?: ListSearchUiState
|
initialSearchState?: ListSearchUiState
|
||||||
onSearchStateChange?: (state: ListSearchUiState) => void
|
onSearchStateChange?: (state: ListSearchUiState) => void
|
||||||
focusRowId?: string
|
focusRowId?: string
|
||||||
|
/** 모바일(md 미만)에서 기본 검색 필터를 1열로 쌓고 접기/펼치기 토글을 노출한다. */
|
||||||
|
collapsibleFiltersOnMobile?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const toSidSet = (value: string) =>
|
const toSidSet = (value: string) =>
|
||||||
@@ -81,9 +89,13 @@ const toSidSet = (value: string) =>
|
|||||||
|
|
||||||
const deduplicateSidInput = (value: string) => [...new Set(toSidSet(value))].join(',')
|
const deduplicateSidInput = (value: string) => [...new Set(toSidSet(value))].join(',')
|
||||||
|
|
||||||
|
const HANGUL_PATTERN = /[ㄱ-ㆎ가-힣]/
|
||||||
|
const hasHangul = (value: string) => HANGUL_PATTERN.test(value)
|
||||||
|
const SID_HANGUL_HINT_DURATION_MS = 2000
|
||||||
|
|
||||||
const sanitizeSidInput = (value: string) => {
|
const sanitizeSidInput = (value: string) => {
|
||||||
let result = ''
|
let result = ''
|
||||||
let lastChar: 'digit' | 'comma' | 'tilde' | null = null
|
let lastChar: 'digit' | 'char' | 'comma' | 'tilde' | null = null
|
||||||
let segmentHasTilde = false
|
let segmentHasTilde = false
|
||||||
|
|
||||||
for (const ch of value) {
|
for (const ch of value) {
|
||||||
@@ -93,7 +105,15 @@ const sanitizeSidInput = (value: string) => {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ch === ',' && lastChar === 'digit') {
|
if (/[a-zA-Z_-]/.test(ch)) {
|
||||||
|
// 틸드 범위 검색은 숫자끼리만 허용되므로, 틸드 바로 뒤에는 문자를 붙이지 않는다.
|
||||||
|
if (lastChar === 'tilde') continue
|
||||||
|
result += ch
|
||||||
|
lastChar = 'char'
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ch === ',' && (lastChar === 'digit' || lastChar === 'char')) {
|
||||||
result += ch
|
result += ch
|
||||||
lastChar = 'comma'
|
lastChar = 'comma'
|
||||||
segmentHasTilde = false
|
segmentHasTilde = false
|
||||||
@@ -167,6 +187,8 @@ export function ListSearchTable({
|
|||||||
listHeaders,
|
listHeaders,
|
||||||
fieldInterviewEnabled = true,
|
fieldInterviewEnabled = true,
|
||||||
enableBatchEdit = false,
|
enableBatchEdit = false,
|
||||||
|
batchEditDisabled = false,
|
||||||
|
dataRevision = 0,
|
||||||
refreshKey = 0,
|
refreshKey = 0,
|
||||||
selectMode = 'multi',
|
selectMode = 'multi',
|
||||||
filterActions,
|
filterActions,
|
||||||
@@ -184,9 +206,12 @@ export function ListSearchTable({
|
|||||||
initialSearchState,
|
initialSearchState,
|
||||||
onSearchStateChange,
|
onSearchStateChange,
|
||||||
focusRowId,
|
focusRowId,
|
||||||
|
collapsibleFiltersOnMobile = false,
|
||||||
}: ListSearchTableProps) {
|
}: ListSearchTableProps) {
|
||||||
const { showDialog } = useDialog()
|
const { showDialog } = useDialog()
|
||||||
|
const [filtersOpen, setFiltersOpen] = useState(true)
|
||||||
const [searchText, setSearchText] = useState(initialSearchState?.searchText ?? '')
|
const [searchText, setSearchText] = useState(initialSearchState?.searchText ?? '')
|
||||||
|
const [showSidHangulHint, setShowSidHangulHint] = useState(false)
|
||||||
const [searchContactResult, setSearchContactResult] = useState<string[]>(initialSearchState?.searchContactResult ?? [])
|
const [searchContactResult, setSearchContactResult] = useState<string[]>(initialSearchState?.searchContactResult ?? [])
|
||||||
const [searchContactDateRange, setSearchContactDateRange] = useState<KriDateRange>(
|
const [searchContactDateRange, setSearchContactDateRange] = useState<KriDateRange>(
|
||||||
initialSearchState?.searchContactDateRange ?? { from: '', to: '' },
|
initialSearchState?.searchContactDateRange ?? { from: '', to: '' },
|
||||||
@@ -200,12 +225,15 @@ export function ListSearchTable({
|
|||||||
const [batchResultCodes, setBatchResultCodes] = useState<BatchEditResultCodes>({})
|
const [batchResultCodes, setBatchResultCodes] = useState<BatchEditResultCodes>({})
|
||||||
const [batchSurveyResultCodes, setBatchSurveyResultCodes] = useState<BatchEditSurveyResultCodes>({})
|
const [batchSurveyResultCodes, setBatchSurveyResultCodes] = useState<BatchEditSurveyResultCodes>({})
|
||||||
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
|
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
|
||||||
|
const handledRefreshKeyRef = useRef(refreshKey)
|
||||||
|
const previousExternalAssignFilterRef = useRef(externalAssignFilter)
|
||||||
|
const sidHangulHintTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
const selectedSids = useMemo(
|
const selectedSids = useMemo(
|
||||||
() => selectedRows.map((row) => String(row.sid ?? '')).filter((sid) => sid.length > 0),
|
() => selectedRows.map((row) => String(row.sid ?? '')).filter((sid) => sid.length > 0),
|
||||||
[selectedRows],
|
[selectedRows],
|
||||||
)
|
)
|
||||||
|
|
||||||
const updateListMutation = useUpdateListMutation(prjctIdx)
|
const updateListMutation = useSubmitListJob(prjctIdx)
|
||||||
|
|
||||||
const outsourceTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.OUTSOURCE })
|
const outsourceTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: ListHeaderAssignConst.OUTSOURCE })
|
||||||
const contactTargetRows = useAssignTargetRows({
|
const contactTargetRows = useAssignTargetRows({
|
||||||
@@ -507,6 +535,17 @@ export function ListSearchTable({
|
|||||||
const totalCount = listSearchQuery.data?.totalElements ?? 0
|
const totalCount = listSearchQuery.data?.totalElements ?? 0
|
||||||
const pageCount = listSearchQuery.data?.totalPages ?? 0
|
const pageCount = listSearchQuery.data?.totalPages ?? 0
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dataRevision) return
|
||||||
|
handleRowSelectionChange([])
|
||||||
|
}, [dataRevision, handleRowSelectionChange])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!listSearchQuery.isSuccess || listSearchQuery.isFetching || listSearchQuery.isPlaceholderData) return
|
||||||
|
const lastPage = Math.max(0, pageCount - 1)
|
||||||
|
if (pagination.pageIndex > lastPage) setPagination(previous => ({ ...previous, pageIndex: lastPage }))
|
||||||
|
}, [listSearchQuery.isSuccess, listSearchQuery.isFetching, listSearchQuery.isPlaceholderData, pageCount, pagination.pageIndex])
|
||||||
|
|
||||||
const headerOptions = useMemo(
|
const headerOptions = useMemo(
|
||||||
() =>
|
() =>
|
||||||
accessibleListHeaders
|
accessibleListHeaders
|
||||||
@@ -533,8 +572,42 @@ export function ListSearchTable({
|
|||||||
[accessibleFilterHeaders, getValueOptionsForHeader, lockedListFilterHeaderTypes],
|
[accessibleFilterHeaders, getValueOptionsForHeader, lockedListFilterHeaderTypes],
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleSearchClick = () => {
|
const resetToFirstPage = () => {
|
||||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
setPagination((prev) => (prev.pageIndex === 0 ? prev : { ...prev, pageIndex: 0 }))
|
||||||
|
}
|
||||||
|
|
||||||
|
const triggerSidHangulHint = (value: string) => {
|
||||||
|
if (!hasHangul(value)) {
|
||||||
|
setShowSidHangulHint(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setShowSidHangulHint(true)
|
||||||
|
if (sidHangulHintTimeoutRef.current) clearTimeout(sidHangulHintTimeoutRef.current)
|
||||||
|
sidHangulHintTimeoutRef.current = setTimeout(() => {
|
||||||
|
setShowSidHangulHint(false)
|
||||||
|
sidHangulHintTimeoutRef.current = null
|
||||||
|
}, SID_HANGUL_HINT_DURATION_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSearchTextChange = (value: string) => {
|
||||||
|
setSearchText(sanitizeSidInput(value))
|
||||||
|
triggerSidHangulHint(value)
|
||||||
|
resetToFirstPage()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleContactResultChange = (value: string[]) => {
|
||||||
|
setSearchContactResult(value)
|
||||||
|
resetToFirstPage()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleInterviewResultChange = (value: string[]) => {
|
||||||
|
setSearchInterviewResult(value)
|
||||||
|
resetToFirstPage()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSortingChange = (value: SortingState) => {
|
||||||
|
setSorting(value)
|
||||||
|
resetToFirstPage()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleSidPaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
const handleSidPaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
||||||
@@ -546,6 +619,8 @@ export function ListSearchTable({
|
|||||||
const selectionEnd = e.currentTarget.selectionEnd ?? selectionStart
|
const selectionEnd = e.currentTarget.selectionEnd ?? selectionStart
|
||||||
const nextValue = `${searchText.slice(0, selectionStart)}${normalizedText}${searchText.slice(selectionEnd)}`
|
const nextValue = `${searchText.slice(0, selectionStart)}${normalizedText}${searchText.slice(selectionEnd)}`
|
||||||
setSearchText(deduplicateSidInput(sanitizeSidInput(nextValue)))
|
setSearchText(deduplicateSidInput(sanitizeSidInput(nextValue)))
|
||||||
|
triggerSidHangulHint(nextValue)
|
||||||
|
resetToFirstPage()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleFilterConfirm = async (rows: FilterRow[]) => {
|
const handleFilterConfirm = async (rows: FilterRow[]) => {
|
||||||
@@ -555,6 +630,7 @@ export function ListSearchTable({
|
|||||||
|
|
||||||
const handleChangeSurveyResult = (prjctSurveyIdx: number, codes: string[]) => {
|
const handleChangeSurveyResult = (prjctSurveyIdx: number, codes: string[]) => {
|
||||||
setSurveyResultSelections((prev) => ({ ...prev, [prjctSurveyIdx]: codes }))
|
setSurveyResultSelections((prev) => ({ ...prev, [prjctSurveyIdx]: codes }))
|
||||||
|
resetToFirstPage()
|
||||||
}
|
}
|
||||||
|
|
||||||
const surveyResultCodeOptions = resultCodes.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)
|
const surveyResultCodeOptions = resultCodes.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)
|
||||||
@@ -565,14 +641,23 @@ export function ListSearchTable({
|
|||||||
setBatchSurveyResultCodes(Object.fromEntries(surveyResultCodes.map((item) => [item.prjctSurveyIdx, item.resultCd])))
|
setBatchSurveyResultCodes(Object.fromEntries(surveyResultCodes.map((item) => [item.prjctSurveyIdx, item.resultCd])))
|
||||||
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
|
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
|
||||||
await updateListMutation.mutateAsync({
|
await updateListMutation.mutateAsync({
|
||||||
|
jobType: 'LIST_UPDATE',
|
||||||
|
path: 'mutations/update',
|
||||||
|
body: {
|
||||||
updateContents,
|
updateContents,
|
||||||
updateResultCodes: resultCodeSelections,
|
updateResultCodes: resultCodeSelections,
|
||||||
updateSurveyResultCodes: surveyResultCodes,
|
updateSurveyResultCodes: surveyResultCodes,
|
||||||
listFilter: buildTargetFilter(target),
|
listFilter: buildTargetFilter(target),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
await listSearchQuery.refetch()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (sidHangulHintTimeoutRef.current) clearTimeout(sidHangulHintTimeoutRef.current)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onCurrentFilterChange?.(listSearchRequest.listFilter)
|
onCurrentFilterChange?.(listSearchRequest.listFilter)
|
||||||
}, [listSearchRequest.listFilter, onCurrentFilterChange])
|
}, [listSearchRequest.listFilter, onCurrentFilterChange])
|
||||||
@@ -607,6 +692,8 @@ export function ListSearchTable({
|
|||||||
}, [pagination, onPaginationChange])
|
}, [pagination, onPaginationChange])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (listHeaders.length === 0) return
|
||||||
|
|
||||||
setFilterRows((prev) => {
|
setFilterRows((prev) => {
|
||||||
const next = prev.filter((row) => {
|
const next = prev.filter((row) => {
|
||||||
const header = accessibleFilterHeaderById.get(row.headerId)
|
const header = accessibleFilterHeaderById.get(row.headerId)
|
||||||
@@ -614,29 +701,98 @@ export function ListSearchTable({
|
|||||||
})
|
})
|
||||||
return next.length === prev.length ? prev : next
|
return next.length === prev.length ? prev : next
|
||||||
})
|
})
|
||||||
}, [accessibleFilterHeaderById, lockedListFilterHeaderTypes])
|
}, [accessibleFilterHeaderById, listHeaders.length, lockedListFilterHeaderTypes])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!refreshKey) return
|
if (!refreshKey || handledRefreshKeyRef.current === refreshKey) return
|
||||||
|
handledRefreshKeyRef.current = refreshKey
|
||||||
|
|
||||||
|
if (pagination.pageIndex === 0) {
|
||||||
refetch()
|
refetch()
|
||||||
}, [refetch, refreshKey])
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resetToFirstPage()
|
||||||
|
}, [pagination.pageIndex, refetch, refreshKey])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (previousExternalAssignFilterRef.current === externalAssignFilter) return
|
||||||
|
previousExternalAssignFilterRef.current = externalAssignFilter
|
||||||
|
resetToFirstPage()
|
||||||
|
}, [externalAssignFilter])
|
||||||
|
|
||||||
|
// md 이상에서는 기존 클래스와 동일하게 렌더링되도록 모바일 전용 값만 분기한다.
|
||||||
|
const filterRowClassName = collapsibleFiltersOnMobile
|
||||||
|
? 'flex flex-col gap-2 md:flex-row md:flex-wrap md:items-center'
|
||||||
|
: 'flex items-center gap-2 flex-wrap'
|
||||||
|
const filterItemClassName = collapsibleFiltersOnMobile
|
||||||
|
? 'w-full md:w-auto md:flex-1 md:min-w-0 md:max-w-xs'
|
||||||
|
: 'flex-1 min-w-0 max-w-xs'
|
||||||
|
const dateFilterClassName = collapsibleFiltersOnMobile
|
||||||
|
? 'w-full md:w-auto md:flex-1 md:min-w-[240px] md:max-w-xs'
|
||||||
|
: 'flex-1 min-w-[240px] max-w-xs'
|
||||||
|
const surveyFilterClassName = collapsibleFiltersOnMobile
|
||||||
|
? 'w-full md:w-auto md:flex-1 md:min-w-[180px] md:max-w-xs'
|
||||||
|
: 'flex-1 min-w-[180px] max-w-xs'
|
||||||
|
|
||||||
|
// 접힌 상태에서도 기본 검색 조건 적용 여부를 알 수 있도록 토글 버튼에 표시한다.
|
||||||
|
const hasActiveFilters =
|
||||||
|
searchText.trim().length > 0 ||
|
||||||
|
searchContactResult.length > 0 ||
|
||||||
|
Boolean(searchContactDateRange.from || searchContactDateRange.to) ||
|
||||||
|
(fieldInterviewEnabled && searchInterviewResult.length > 0) ||
|
||||||
|
Object.values(surveyResultSelections).some((values) => values.length > 0)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
{collapsibleFiltersOnMobile ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-between md:hidden"
|
||||||
|
aria-expanded={filtersOpen}
|
||||||
|
aria-controls="list-search-filters"
|
||||||
|
onClick={() => setFiltersOpen((prev) => !prev)}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
검색 조건
|
||||||
|
{hasActiveFilters ? <Badge>적용 중</Badge> : null}
|
||||||
|
</span>
|
||||||
|
<ChevronDown className={cn('h-4 w-4 transition-transform', filtersOpen && 'rotate-180')} />
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div
|
||||||
|
id="list-search-filters"
|
||||||
|
className={cn('space-y-2', collapsibleFiltersOnMobile && !filtersOpen && 'hidden md:block')}
|
||||||
|
>
|
||||||
|
<div className={filterRowClassName}>
|
||||||
|
<div className={filterItemClassName}>
|
||||||
|
<Popover open={showSidHangulHint}>
|
||||||
|
<PopoverAnchor asChild>
|
||||||
<Input
|
<Input
|
||||||
placeholder="SID 검색"
|
placeholder="SID 검색"
|
||||||
className="h-9 bg-white flex-1 min-w-0 max-w-xs"
|
className="h-9 bg-white w-full"
|
||||||
value={searchText}
|
value={searchText}
|
||||||
onChange={(e) => setSearchText(sanitizeSidInput(e.target.value))}
|
onChange={(e) => handleSearchTextChange(e.target.value)}
|
||||||
onPaste={handleSidPaste}
|
onPaste={handleSidPaste}
|
||||||
/>
|
/>
|
||||||
<div className="flex-1 min-w-0 max-w-xs">
|
</PopoverAnchor>
|
||||||
|
<PopoverContent
|
||||||
|
align="start"
|
||||||
|
className="w-auto p-2 text-xs text-destructive"
|
||||||
|
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
|
한글은 입력할 수 없습니다. 한/영 전환 후 영문·숫자로 입력해 주세요.
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
<div className={filterItemClassName}>
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.CONTACT)}
|
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.CONTACT)}
|
||||||
value={searchContactResult}
|
value={searchContactResult}
|
||||||
onChange={setSearchContactResult}
|
onChange={handleContactResultChange}
|
||||||
getValue={(item) => String(item.resultCd)}
|
getValue={(item) => String(item.resultCd)}
|
||||||
getLabel={(item) => item.resultCdLbl}
|
getLabel={(item) => item.resultCdLbl}
|
||||||
placeholder="컨택 결과"
|
placeholder="컨택 결과"
|
||||||
@@ -651,14 +807,14 @@ export function ListSearchTable({
|
|||||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||||
}}
|
}}
|
||||||
placeholder="컨택 일자"
|
placeholder="컨택 일자"
|
||||||
className="flex-1 min-w-[240px] max-w-xs"
|
className={dateFilterClassName}
|
||||||
/>
|
/>
|
||||||
{fieldInterviewEnabled ? (
|
{fieldInterviewEnabled ? (
|
||||||
<div className="flex-1 min-w-0 max-w-xs">
|
<div className={filterItemClassName}>
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
||||||
value={searchInterviewResult}
|
value={searchInterviewResult}
|
||||||
onChange={setSearchInterviewResult}
|
onChange={handleInterviewResultChange}
|
||||||
getValue={(item) => String(item.resultCd)}
|
getValue={(item) => String(item.resultCd)}
|
||||||
getLabel={(item) => item.resultCdLbl}
|
getLabel={(item) => item.resultCdLbl}
|
||||||
placeholder="면접 결과"
|
placeholder="면접 결과"
|
||||||
@@ -670,11 +826,11 @@ export function ListSearchTable({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{surveys.length > 0 ? (
|
{surveys.length > 0 ? (
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className={filterRowClassName}>
|
||||||
{surveys
|
{surveys
|
||||||
.filter((survey) => survey.prjctSurveyIdx != null)
|
.filter((survey) => survey.prjctSurveyIdx != null)
|
||||||
.map((survey) => (
|
.map((survey) => (
|
||||||
<div key={survey.prjctSurveyIdx} className="flex-1 min-w-[180px] max-w-xs">
|
<div key={survey.prjctSurveyIdx} className={surveyFilterClassName}>
|
||||||
<KriMultiSelect
|
<KriMultiSelect
|
||||||
items={surveyResultCodeOptions}
|
items={surveyResultCodeOptions}
|
||||||
value={surveyResultSelections[survey.prjctSurveyIdx as number] ?? []}
|
value={surveyResultSelections[survey.prjctSurveyIdx as number] ?? []}
|
||||||
@@ -689,6 +845,7 @@ export function ListSearchTable({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2 flex-wrap justify-between">
|
<div className="flex items-center gap-2 flex-wrap justify-between">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
@@ -698,7 +855,7 @@ export function ListSearchTable({
|
|||||||
</Button>
|
</Button>
|
||||||
{filterActions}
|
{filterActions}
|
||||||
{enableBatchEdit ? (
|
{enableBatchEdit ? (
|
||||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')}>
|
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listBatchEditDialog')} disabled={batchEditDisabled}>
|
||||||
<PencilLine className="w-4 h-4" />
|
<PencilLine className="w-4 h-4" />
|
||||||
일괄 수정
|
일괄 수정
|
||||||
</Button>
|
</Button>
|
||||||
@@ -710,6 +867,7 @@ export function ListSearchTable({
|
|||||||
|
|
||||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||||
<DataTable<ListTableRow>
|
<DataTable<ListTableRow>
|
||||||
|
key={dataRevision}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
data={viewList}
|
data={viewList}
|
||||||
getRowId={(row) => String(row.sid)}
|
getRowId={(row) => String(row.sid)}
|
||||||
@@ -719,7 +877,8 @@ export function ListSearchTable({
|
|||||||
totalCount={totalCount}
|
totalCount={totalCount}
|
||||||
pagination={pagination}
|
pagination={pagination}
|
||||||
onPaginationChange={setPagination}
|
onPaginationChange={setPagination}
|
||||||
onSortingChange={setSorting}
|
sorting={sorting}
|
||||||
|
onSortingChange={handleSortingChange}
|
||||||
selectMode={selectMode}
|
selectMode={selectMode}
|
||||||
onRowSelectionChange={handleRowSelectionChange}
|
onRowSelectionChange={handleRowSelectionChange}
|
||||||
onRowClick={onRowClick}
|
onRowClick={onRowClick}
|
||||||
@@ -732,6 +891,7 @@ export function ListSearchTable({
|
|||||||
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
|
<ListFilterDialog headerOptions={filterHeaderOptions} initialRows={filterRows} onConfirm={handleFilterConfirm} />
|
||||||
{enableBatchEdit ? (
|
{enableBatchEdit ? (
|
||||||
<ListBatchEditDialog
|
<ListBatchEditDialog
|
||||||
|
prjctIdx={prjctIdx}
|
||||||
headerOptions={headerOptions}
|
headerOptions={headerOptions}
|
||||||
resultCodes={resultCodes}
|
resultCodes={resultCodes}
|
||||||
surveys={surveys}
|
surveys={surveys}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user