Compare commits
190 Commits
4b22120f45
...
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 | |||
| 39ab7996d9 | |||
| 081b53945a | |||
| e8f3308814 | |||
| 9b93d45ed0 | |||
| ef748142f8 | |||
| aad991b16b | |||
| 10ace4fe53 | |||
| d9398c5675 | |||
| f4a5a04922 | |||
| 3d0c24b2ee | |||
| 511493ab58 | |||
| 5eab2e4026 | |||
| 257ba6ca83 | |||
| e4604d9016 | |||
| 86b626b5ea | |||
| ad5aa5de73 | |||
| cf94ea21b7 | |||
| ff28925c6e | |||
| 6a2265e767 | |||
| 2d3761f694 | |||
| 618718585c | |||
| 0d17c21b8d | |||
| a28981099f | |||
| c9d0100913 | |||
| 605d2dba49 | |||
| e752a2067d | |||
| 65bbabe69b | |||
| 0285a3fe9d | |||
| 17289bf0e8 | |||
| d9f53c0c3d | |||
| 4388b7c048 | |||
| d97015741a | |||
| 9da39049cc | |||
| ce5a402253 | |||
| 72ee21ec65 | |||
| 157ba6155d | |||
| 4bfb9ae6ac | |||
| 58e9d0702e | |||
| 22509a892c | |||
| e5e7aed504 | |||
| fb37c237b6 | |||
| a7af497542 | |||
| 91920301ef | |||
| 2dd5b88c6f | |||
| d8b565276d | |||
| c7f261fb26 | |||
| b5b335bfe8 | |||
| bb2c0c1951 | |||
| 4ca93ab26a | |||
| 8352c8ca8d | |||
| 7275c77db0 | |||
| c12953ad9c | |||
| 36c7b41191 | |||
| c710a60beb | |||
| 22994c8434 | |||
| d14fa3720d | |||
| 192d47bdb1 | |||
| a8ce35f5bf | |||
| 6944064377 | |||
| 1953b6528b | |||
| f7ce249aa7 | |||
| bedcfbc9d1 | |||
| d8e894b136 |
@@ -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.
|
||||
18
.agent/profile.yml
Normal file
18
.agent/profile.yml
Normal file
@@ -0,0 +1,18 @@
|
||||
schema_version: 1
|
||||
|
||||
project:
|
||||
id: kri-contact-front
|
||||
name: KriContact Front
|
||||
type: internal-service
|
||||
layer: frontend
|
||||
legacy: false
|
||||
|
||||
stack:
|
||||
- typescript
|
||||
- react
|
||||
- nextjs
|
||||
|
||||
shared_contracts:
|
||||
consumes:
|
||||
- kri-front-common
|
||||
- kri-ui-registry
|
||||
18
.agent/project.md
Normal file
18
.agent/project.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# KriContact Front Project Instruction Router
|
||||
|
||||
## Required Project References
|
||||
|
||||
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
|
||||
|
||||
| Task scope | Required reference |
|
||||
|---|---|
|
||||
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
|
||||
|
||||
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
|
||||
|
||||
## Harness Workflow
|
||||
|
||||
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
|
||||
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
|
||||
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
|
||||
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.
|
||||
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.
|
||||
3
.env
3
.env
@@ -1 +1,4 @@
|
||||
NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d
|
||||
NEXT_PUBLIC_REQUEST_SVC = kri-contact
|
||||
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
|
||||
NEXT_PUBLIC_CTI_WS_URL=wss://teracall.kric.com:2302
|
||||
@@ -1,10 +1,9 @@
|
||||
NEXT_PUBLIC_ENV=dev
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api
|
||||
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
|
||||
|
||||
ENV=dev
|
||||
CONTACT_SERVER=http://localhost:4001
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
CONTACT_SERVER=http://127.0.0.1:4001
|
||||
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
AUTH_COOKIE_DOMAIN=kric.com
|
||||
|
||||
12
.env.local
12
.env.local
@@ -1,15 +1,9 @@
|
||||
NEXT_PUBLIC_ENV=local
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:4000/api
|
||||
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
|
||||
|
||||
ENV=local
|
||||
CONTACT_SERVER=http://localhost:4001
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
|
||||
#API_NOTIHUB_SERVER=https://localhost:4011/api/v1
|
||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
|
||||
#API_INTRANET_SERVER=http://localhost:3031/api/v1
|
||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
AUTH_COOKIE_DOMAIN=
|
||||
@@ -1,10 +1,9 @@
|
||||
NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
NEXT_PUBLIC_API_BASE=https://contact.kric.com/api
|
||||
NEXT_PUBLIC_KART_URL=https://kart.kric.com
|
||||
|
||||
ENV=prod
|
||||
CONTACT_SERVER=http://localhost:4001
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
CONTACT_SERVER=http://127.0.0.1:4001
|
||||
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
|
||||
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
AUTH_COOKIE_DOMAIN=kric.com
|
||||
|
||||
4
.gitattributes
vendored
Normal file
4
.gitattributes
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/.gitattributes text eol=lf
|
||||
/.agent/** text eol=lf
|
||||
/AGENTS.md text eol=lf
|
||||
/CLAUDE.md text eol=lf
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -23,6 +23,7 @@
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
/.idea/
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
|
||||
8
.idea/.gitignore
generated
vendored
8
.idea/.gitignore
generated
vendored
@@ -1,8 +0,0 @@
|
||||
# 디폴트 무시된 파일
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 에디터 기반 HTTP 클라이언트 요청
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
5
.idea/codeStyles/codeStyleConfig.xml
generated
5
.idea/codeStyles/codeStyleConfig.xml
generated
@@ -1,5 +0,0 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
|
||||
</state>
|
||||
</component>
|
||||
15
.idea/git_toolbox_prj.xml
generated
15
.idea/git_toolbox_prj.xml
generated
@@ -1,15 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GitToolBoxProjectSettings">
|
||||
<option name="commitMessageIssueKeyValidationOverride">
|
||||
<BoolValueOverride>
|
||||
<option name="enabled" value="true" />
|
||||
</BoolValueOverride>
|
||||
</option>
|
||||
<option name="commitMessageValidationEnabledOverride">
|
||||
<BoolValueOverride>
|
||||
<option name="enabled" value="true" />
|
||||
</BoolValueOverride>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
9
.idea/inspectionProfiles/Project_Default.xml
generated
9
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -1,9 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="CssUnresolvedCustomProperty" enabled="false" level="ERROR" enabled_by_default="false" />
|
||||
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="JavaCollectionWithNullableTypeArgument" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="UsePropertyAccessSyntax" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
12
.idea/material_theme_project_new.xml
generated
12
.idea/material_theme_project_new.xml
generated
@@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="MaterialThemeProjectNewConfig">
|
||||
<option name="metadata">
|
||||
<MTProjectMetadataState>
|
||||
<option name="migrated" value="true" />
|
||||
<option name="pristineConfig" value="false" />
|
||||
<option name="userId" value="4859b8f9:19a516124ff:-7ffa" />
|
||||
</MTProjectMetadataState>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/misc.xml
generated
6
.idea/misc.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/contact-front.iml" filepath="$PROJECT_DIR$/contact-front.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
2
.npmrc
Normal file
2
.npmrc
Normal file
@@ -0,0 +1,2 @@
|
||||
@kri:registry=https://gitea.kric.com/api/packages/KRi/npm/
|
||||
//gitea.kric.com/api/packages/KRi/npm/:_authToken=${GITEA_NPM_TOKEN}
|
||||
357
AGENTS.md
Normal file
357
AGENTS.md
Normal file
@@ -0,0 +1,357 @@
|
||||
<!--
|
||||
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
|
||||
Project: kri-contact-front
|
||||
Schema version: 1
|
||||
Edit the source fragments or repository .agent files, then recompose.
|
||||
-->
|
||||
|
||||
# KRI Development Base Instructions
|
||||
|
||||
This document defines the shared working rules for KRI development repositories.
|
||||
Keep project-specific facts and commands in the project profile and project rules.
|
||||
|
||||
## Instruction Resolution
|
||||
|
||||
Apply repository instructions in this order:
|
||||
|
||||
1. Base rules
|
||||
2. Project-type rules
|
||||
3. Technology-stack rules
|
||||
4. Shared consumer contracts
|
||||
5. Project-specific rules
|
||||
6. The explicitly approved task scope
|
||||
|
||||
Later and more specific instructions may override earlier general instructions only within their stated scope.
|
||||
|
||||
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
|
||||
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
|
||||
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
|
||||
|
||||
## Communication
|
||||
|
||||
- Respond to the user in Korean unless the user requests another language.
|
||||
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
|
||||
- Follow the repository's existing language conventions for code comments and user-facing messages.
|
||||
- Lead with the result or decision, then provide only the detail needed to verify it.
|
||||
- Do not create or retain a full session transcript.
|
||||
|
||||
### Attention-Aware Response Style
|
||||
|
||||
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
|
||||
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
|
||||
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
|
||||
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
|
||||
|
||||
## Work Authorization
|
||||
|
||||
- The default workflow is discussion first and explicit execution approval second.
|
||||
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
|
||||
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
|
||||
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
|
||||
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
|
||||
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
|
||||
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
|
||||
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
|
||||
|
||||
## Local Development Environment
|
||||
|
||||
- Primary OS: Windows 11.
|
||||
- Primary shell: PowerShell.
|
||||
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
|
||||
- Prefer repository-provided wrappers and scripts over globally installed commands.
|
||||
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
|
||||
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
|
||||
- Do not install or modify global toolchains as part of a project task.
|
||||
|
||||
Preferred human-facing tools:
|
||||
|
||||
- Classic ASP: Visual Studio Code
|
||||
- Java and Spring Boot: IntelliJ IDEA
|
||||
- C# and .NET: JetBrains Rider
|
||||
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
|
||||
- Python: JetBrains PyCharm
|
||||
- Microsoft SQL Server: SQL Server Management Studio
|
||||
- Other databases: JetBrains DataGrip
|
||||
|
||||
- These preferences do not authorize launching or controlling a GUI application.
|
||||
- Prefer IDE-independent commands that can also run in CI.
|
||||
- Do not modify global IDE settings.
|
||||
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
|
||||
- Preserve existing shared IDE configuration when it is already tracked.
|
||||
|
||||
## PowerShell and Path Safety
|
||||
|
||||
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
|
||||
- Prefer `-LiteralPath` when operating on an exact filesystem path.
|
||||
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
|
||||
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
|
||||
- Keep a filesystem operation within one shell from target resolution through execution.
|
||||
- Before a recursive delete or move, resolve and verify every absolute target.
|
||||
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
|
||||
- Prefer recoverable operations when practical.
|
||||
|
||||
## Change Discipline
|
||||
|
||||
- Preserve all existing user changes, including uncommitted and untracked work.
|
||||
- Keep changes minimal but complete for the approved objective.
|
||||
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
|
||||
- Do not overwrite or revert unrelated changes.
|
||||
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
|
||||
- Prefer changing an authoritative source over editing generated output.
|
||||
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
|
||||
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
|
||||
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
|
||||
|
||||
## Text Encoding and Korean Content Safety
|
||||
|
||||
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
|
||||
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
|
||||
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
|
||||
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
|
||||
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
|
||||
- Avoid whole-file rewrites for small changes.
|
||||
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
|
||||
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
|
||||
- Treat a console display problem and an on-disk encoding problem as separate issues.
|
||||
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
|
||||
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
|
||||
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
|
||||
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
|
||||
|
||||
## Git Safety
|
||||
|
||||
- Use `git status`, `git diff`, and `git log` for read-only investigation.
|
||||
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
|
||||
- Source-edit approval does not include commit or push approval.
|
||||
- Never amend an existing commit unless explicitly requested.
|
||||
- Before an approved commit, show the intended files, validation results, and proposed commit message.
|
||||
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
|
||||
|
||||
## Dependencies and External Actions
|
||||
|
||||
- Use the package manager, lockfile, and toolchain already selected by the repository.
|
||||
- Do not install global packages.
|
||||
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
|
||||
- Pause for approval if an unplanned dependency becomes necessary.
|
||||
- Keep lockfiles synchronized with approved dependency changes.
|
||||
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
|
||||
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
|
||||
- Remove secrets and unnecessary internal identifiers from external search queries.
|
||||
|
||||
## Database Safety
|
||||
|
||||
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
|
||||
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
|
||||
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
|
||||
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
|
||||
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
|
||||
- Source-change approval does not authorize migration execution.
|
||||
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
|
||||
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
|
||||
|
||||
## Secrets and Sensitive Data
|
||||
|
||||
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
|
||||
- Read sensitive files only when the approved task requires it and no safer source exists.
|
||||
- Prefer inspecting configuration keys and schemas without displaying secret values.
|
||||
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
|
||||
- Redact sensitive values when reporting errors or command output.
|
||||
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
|
||||
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
|
||||
|
||||
## Workflow Skills
|
||||
|
||||
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
|
||||
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
|
||||
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
|
||||
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
|
||||
|
||||
## Validation
|
||||
|
||||
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
|
||||
- Include intended validation in the discussion-phase plan.
|
||||
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
|
||||
- Limit formatting to files within the approved scope.
|
||||
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
|
||||
- Do not claim that a check passed unless it was executed successfully.
|
||||
- If a check cannot be run, state the exact reason.
|
||||
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
|
||||
- Do not fix unrelated failures without expanding the approved scope.
|
||||
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
|
||||
|
||||
## Artifacts and Session Records
|
||||
|
||||
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
|
||||
- Store durable information in the repository's existing documentation structure.
|
||||
- Do not place generated reports or temporary analysis files in the repository root.
|
||||
- Remove task-specific temporary files created by the current task after validation when removal is safe.
|
||||
|
||||
## Completion Report
|
||||
|
||||
When implementation is complete, report in Korean:
|
||||
|
||||
- what changed and why;
|
||||
- the main affected files or components;
|
||||
- validation commands actually executed and their results;
|
||||
- checks not executed and the reason;
|
||||
- remaining risks, assumptions, or follow-up work;
|
||||
- database, deployment, dependency, encoding, and compatibility impact when applicable.
|
||||
|
||||
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
|
||||
- Keep the report concise and do not include a full session transcript.
|
||||
|
||||
## Internal Service Project Rules
|
||||
|
||||
- Internal-only usage does not reduce security, privacy, compatibility, or validation requirements.
|
||||
- Preserve authentication, authorization, role boundaries, auditability, and personal-data protections.
|
||||
- Identify affected user workflows before changing visible behavior.
|
||||
- Treat Frontend and Backend repositories as separate deployable systems with an explicit API contract between them.
|
||||
- Coordinate request, response, authentication, error, and versioning changes across both sides when the approved scope includes both repositories.
|
||||
- Do not silently require a simultaneous Frontend and Backend deployment.
|
||||
- Prefer backward-compatible transitions when deployments may occur independently.
|
||||
- Include migration and rollback considerations for database, API, and configuration changes.
|
||||
- Do not modernize legacy code as an unrelated side effect.
|
||||
- Apply Classic ASP text-safety rules only when the project profile declares the `classic-asp` stack.
|
||||
- Do not access or modify production data merely because the service is internal.
|
||||
|
||||
## TypeScript
|
||||
|
||||
- Treat the repository's current TypeScript version, `tsconfig` files, module system, path aliases, and package manager as authoritative.
|
||||
- Preserve or strengthen existing strictness. Do not weaken compiler options or hide errors with broad `any`, `@ts-ignore`, or unsafe assertions.
|
||||
- Prefer narrow domain types, discriminated unions, and explicit boundary types over duplicated or overly generic shapes.
|
||||
- Validate untrusted runtime input even when a compile-time type exists.
|
||||
- Keep imports, exports, aliases, and generated-code boundaries consistent with the repository.
|
||||
- Do not introduce a JavaScript-to-TypeScript conversion outside the approved scope.
|
||||
- Run the repository's focused type-check, lint, test, and build commands as applicable.
|
||||
|
||||
## React
|
||||
|
||||
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
|
||||
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
|
||||
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
|
||||
- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable.
|
||||
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
|
||||
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
|
||||
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
|
||||
- Treat any planned Next.js migration as a separate policy and task; the current React application remains authoritative until that migration slice is approved.
|
||||
|
||||
## Next.js
|
||||
|
||||
- Treat the repository's current Next.js and React versions, routing model, rendering model, and package manager as authoritative.
|
||||
- Preserve server and client component boundaries. Add `use client` only when browser APIs, state, effects, or client-only libraries require it.
|
||||
- Keep secrets, privileged data access, and server-only modules out of client bundles.
|
||||
- Preserve established route, layout, middleware, authentication, authorization, caching, revalidation, and error-handling conventions.
|
||||
- Validate request parameters, payloads, headers, cookies, and external responses at runtime.
|
||||
- Do not create new frontend TypeScript type or interface names ending in `Dto` or `DTO`. Use domain- or purpose-specific names such as `User`, `UserInput`, `UserRequest`, or `UserResponse`; do not rename existing types solely to enforce this rule outside the approved scope.
|
||||
- Use the approved KRI frontend and UI contracts when the project profile includes them; do not copy shared implementations into an application.
|
||||
- Avoid incidental routing-model or rendering-strategy migrations.
|
||||
- Run the repository's focused lint, type-check, test, and production build commands as applicable.
|
||||
|
||||
## KriFrontCommon Consumer Contract
|
||||
|
||||
- Consume the published `@kri/common` package only through entry points declared by its `package.json` `exports` map.
|
||||
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
|
||||
- Prefer a public shared helper or an approved backward-compatible library addition over copying or forking shared behavior locally.
|
||||
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
|
||||
|
||||
### Required Shared References
|
||||
|
||||
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
||||
|
||||
| Task scope | Required reference |
|
||||
|---|---|
|
||||
| Package entry points, runtime boundaries, HTTP, authentication, state, storage, environment, or optional peer integrations | `.agent-harness/references/kri-front-common/package-and-runtime.md` |
|
||||
| React rendering performance, memoization, or React Compiler behavior | `.agent-harness/references/kri-front-common/react-compiler.md` |
|
||||
| Package upgrade, dependency changes, lockfile, or verification | `.agent-harness/references/kri-front-common/change-and-verification.md` |
|
||||
|
||||
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
|
||||
|
||||
## Noti-hub SMS Types
|
||||
|
||||
- `MessageType.SMS = 21`, `LMS = 22`, `MMS = 23`; `ChannelType.SMS = 2` is unchanged. `SMS_TYPE_ARRAY` and `SmsType` include all three.
|
||||
- `LMS_MMS = 22` remains a deprecated source-compatibility alias for LMS only. It does not represent MMS. Enum reverse lookup for 22 returns LMS. Use numeric bulk-list paths; the server no longer accepts LMS_MMS in paths. Numeric 21/22/23 bulk-list requests all return the entire SMS channel, not type-filtered lists.
|
||||
- Requests retain their existing URLs/body shapes. The server chooses the actual type per recipient after substitution: attachment -> MMS; otherwise title or UTF-8 body >= 90 bytes -> LMS; otherwise SMS.
|
||||
- Refresh templates from the save response (`tmplatTy`); display actual delivery types from `sendTy`, not the template or result code. A bulk can contain multiple SMS types. LMS/MMS share result codes; use existing server result labels.
|
||||
- SMS, LMS, MMS and KKO use cancellation code 9998. Verify with `npm run typecheck`, `npm run build`, and `node --test tests/noti-hub-sms.test.mjs`.
|
||||
|
||||
## Noti-hub Reservation Cancellation
|
||||
|
||||
- Import cancellation types, constants, and helpers from `@kri/common/noti-hub` only. They are runtime-neutral and require no optional peers.
|
||||
- Individual current cancellation state is determined by resultCode via isReserveCanceledResult; bulk current state is cancellationStatus (NONE/PARTIAL/ALL). These describe current cancellation state, not cancellation eligibility. cancelDt and cancelUser are request history, not current state.
|
||||
- SendResultInfo, SendInfo, and BulkSendInfo expose optional cancelable. Use isSendCancelable(item), which returns true only for cancelable === true, for cancellation eligibility; missing values from older responses are treated as false. Never infer eligibility from cancelDt, result labels, or result codes.
|
||||
- cancelable reflects query-time state and may change before cancellation. Determine the final outcome from SendCancelResponse counts.
|
||||
- sendIdx is the single-cancel identifier, not cmid. It is absent from the latest abbreviated report (/api/v1/report/last/send/...). Request sendIdx must be a positive integer; bulkSendKey is required and at most 32 characters.
|
||||
- EMAIL_RESERVE_CANCELED_RESULT_CODE is 108 for EMAIL. SMS_KKO_RESERVE_CANCELED_RESULT_CODE is 9998 for SMS, LMS, MMS, and KKO. Unknown message types are not recognized as canceled.
|
||||
- Display the server's resultViewLabel/resultLabel ("예약 취소"). There is no separate result-code list API.
|
||||
- HTTP 200 can contain notCancelableCount. parseSendCancelResponse validates nonnegative integer counts and targetCount = canceledCount + alreadyCanceledCount + notCancelableCount, throwing TypeError on invalid data. Bulk targetCount counts currently registered detail rows; response canceledCount counts only cancellations made by that request.
|
||||
- Existing response fields are unchanged; all added fields on existing types are optional. Verify with npm run typecheck and npm run build.
|
||||
|
||||
## HTTP Streaming
|
||||
|
||||
- `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body).
|
||||
- Streaming shares ordinary authentication, URL, body and HTTP-error policy. Read body incrementally; no automatic JSON/NDJSON/SSE parsing or reconnect is performed.
|
||||
- Streaming options accept an external AbortSignal. Caller cancellation raises AbortError without an HTTP error notification. Cancel the body when it will not be consumed.
|
||||
- timeoutMs covers connection/headers (and an HTTP error body); idleTimeoutMs covers inactivity after successful headers and resets on consumed chunks. Both default to the client's defaultTimeoutMs (60 seconds by default), and 0 disables that timer for streaming only.
|
||||
- Mid-stream transport/time-out errors reach the body reader. HTTP error statuses use existing HttpError handlers before a stream is returned. A 204 response has body=null.
|
||||
- See HTTP_STREAMING.md for examples and node --test tests/http-stream.test.mjs for focused validation after npm run build.
|
||||
|
||||
## KriUiRegistry Consumer Contract
|
||||
|
||||
When implementing or changing frontend UI, use this order:
|
||||
|
||||
1. Reuse an existing shared component in the project when it already meets the requirement.
|
||||
2. Prefer an approved component from KriUiRegistry.
|
||||
3. Otherwise, prefer a suitable shadcn/ui component.
|
||||
4. Create a custom component only when the preceding options cannot meet the requirement safely.
|
||||
|
||||
### KriAutoComplete Search Scroll
|
||||
|
||||
- `kri-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior.
|
||||
- When enabled, a search value change (including clearing it) resets the option list scroll to the top on the next animation frame in both `filter` and `inputOnly` modes. Async result updates alone do not trigger another reset.
|
||||
|
||||
### KriAutoComplete Option Tooltip
|
||||
|
||||
- `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior.
|
||||
- When enabled, hovering an option shows its full `label` in a right-side tooltip. `singleLine` stays on one line until the available viewport width; `wrap` wraps at 28rem. The item depends on the shadcn `tooltip` component and provides its own `TooltipProvider`.
|
||||
|
||||
### KriAutoComplete Search Match
|
||||
|
||||
- `kri-auto-complete` exposes `searchMatch?: 'fuzzy' | 'contains'` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `fuzzy` (cmdk's default subsequence scoring), preserving existing behavior.
|
||||
- `contains` keeps only options whose label or value contains the search text as a case-insensitive substring, in the original option order. It applies only when `searchMode` is `filter`.
|
||||
|
||||
### KriEditor SMS Preview
|
||||
|
||||
- `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract.
|
||||
- Attachment presence (`smsHasAttachment`) takes priority and reports MMS. Otherwise a title or UTF-8 preview size >= `smsMaxBytes` (default 90) reports LMS; the remainder reports SMS. LMS/MMS share `lmsMaxBytes` (default 2000).
|
||||
- UTF-8 byte counting includes `smsPreviewSuffix` and its separating newline, without storing the suffix in the body.
|
||||
- This is a preview. Use the template-save response for saved `tmplatTy` and delivery-result `sendTy` for actual per-recipient type after server substitution. Registry updates require updating installed consumer copies.
|
||||
|
||||
### Required Shared References
|
||||
|
||||
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
|
||||
|
||||
| Task scope | Required reference |
|
||||
|---|---|
|
||||
| Installing, upgrading, adapting, or verifying a registry component | `.agent-harness/references/kri-ui-registry/installation-and-adaptation.md` |
|
||||
| KriEditor HTML, image-map, sanitizer, or WYSIWYG compatibility | `.agent-harness/references/kri-ui-registry/editor-html-compatibility.md` |
|
||||
|
||||
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriUiRegistry's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
|
||||
|
||||
# KriContact Front Project Instruction Router
|
||||
|
||||
## Required Project References
|
||||
|
||||
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
|
||||
|
||||
| Task scope | Required reference |
|
||||
|---|---|
|
||||
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
|
||||
|
||||
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
|
||||
|
||||
## Harness Workflow
|
||||
|
||||
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
|
||||
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
|
||||
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
|
||||
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.
|
||||
@@ -1,18 +1,47 @@
|
||||
import type { NextConfig } from "next";
|
||||
import { createEnv, createKriNextConfig, env } from "@kri/common/config";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
output: "standalone",
|
||||
reactCompiler: true,
|
||||
const nextEnv = createEnv({
|
||||
CONTACT_SERVER: env.required("CONTACT_SERVER", process.env.CONTACT_SERVER),
|
||||
});
|
||||
|
||||
const nextConfig = createKriNextConfig({
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: "/contact-senario/:path*",
|
||||
destination: `${process.env.CONTACT_SERVER}/contact-senario/:path*`,
|
||||
destination: `${nextEnv.CONTACT_SERVER}/contact-senario/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/api/external/:path*",
|
||||
headers: [
|
||||
{ key: "Access-Control-Allow-Credentials", value: "true" },
|
||||
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PUT,PATCH,DELETE" },
|
||||
{
|
||||
key: "Access-Control-Allow-Headers",
|
||||
value: "Content-Type, Authorization, X-Requested-With",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
source: "/api/list-external/:path*",
|
||||
headers: [
|
||||
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PATCH" },
|
||||
{
|
||||
key: "Access-Control-Allow-Headers",
|
||||
value: "Content-Type, X-API-Key",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
}) satisfies NextConfig;
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
3525
package-lock.json
generated
3525
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
33
package.json
33
package.json
@@ -3,12 +3,16 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"dev": "next dev -p 4000",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"start": "next start -p 4000",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@kri/common": "^0.20.0",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
@@ -19,8 +23,10 @@
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tiptap/extension-color": "^3.13.0",
|
||||
"@tiptap/extension-font-family": "^3.13.0",
|
||||
"@tiptap/extension-highlight": "^3.13.0",
|
||||
"@tiptap/extension-image": "^3.13.0",
|
||||
"@tiptap/extension-link": "^3.13.0",
|
||||
@@ -34,30 +40,35 @@
|
||||
"@tiptap/extension-underline": "^3.13.0",
|
||||
"@tiptap/react": "^3.12.0",
|
||||
"@tiptap/starter-kit": "^3.12.0",
|
||||
"@types/lodash": "^4.17.21",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"cn": "0.5.2",
|
||||
"date-fns": "^4.4.0",
|
||||
"dompurify": "^3.4.10",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"jotai": "^2.15.1",
|
||||
"lodash": "^4.17.21",
|
||||
"lucide-react": "^0.553.0",
|
||||
"next": "^16.0.7",
|
||||
"next": "^16.4.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"prettier": "^3.9.6",
|
||||
"qrcode": "^1.5.4",
|
||||
"radix-ui": "^1.6.1",
|
||||
"react": "^19.2.1",
|
||||
"react-day-picker": "^10.0.1",
|
||||
"react-dom": "^19.2.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/node": "^20",
|
||||
"@types/node": "^24.19.2",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "^16.0.7",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
Before Width: | Height: | Size: 391 B |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
Before Width: | Height: | Size: 1.0 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
BIN
public/qr_example.png
Normal file
BIN
public/qr_example.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 851 KiB |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
Before Width: | Height: | Size: 128 B |
@@ -1 +0,0 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
Before Width: | Height: | Size: 385 B |
263
src/app/(pages)/(main)/assign/list/page.tsx
Normal file
263
src/app/(pages)/(main)/assign/list/page.tsx
Normal file
@@ -0,0 +1,263 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useAtom } from 'jotai'
|
||||
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
|
||||
import { useMounted } from '@kri/common/hooks'
|
||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import { AssignTargetList, useAssignTargetRows } from '@/components/assign/AssignTargetList'
|
||||
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
||||
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
||||
import { useListHeaderQuery } from '@/query/list'
|
||||
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 { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
|
||||
import type { ResultCode } from '@/types/project'
|
||||
import { isExternalManager } from '@/utils/userRole'
|
||||
|
||||
const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [
|
||||
ListHeaderAssignConst.CONTACT_INTERVIEWER,
|
||||
ListHeaderAssignConst.FIELD_INTERVIEWER,
|
||||
ListHeaderAssignConst.OUTSOURCE,
|
||||
]
|
||||
|
||||
const ASSIGNED_SENTINEL = '__ASSIGNED__'
|
||||
const UNASSIGNED_SENTINEL = '__UNASSIGNED__'
|
||||
const isAssignFilterSentinel = (value: string) => value === ASSIGNED_SENTINEL || value === UNASSIGNED_SENTINEL
|
||||
|
||||
const ListAssignPage = () => {
|
||||
const mounted = useMounted()
|
||||
const { auth } = useAuth()
|
||||
const { selectedProject } = useSelectedProject()
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||
const enabled = mounted && prjctIdx > 0
|
||||
const userRole = auth?.user?.userRole ?? 0
|
||||
const isExternalUser = isExternalManager(userRole)
|
||||
|
||||
const [assignType, setAssignType] = useState<ListHeaderAssignType>(ListHeaderAssignConst.CONTACT_INTERVIEWER)
|
||||
const effectiveAssignType =
|
||||
selectedProject?.ff === false && assignType === ListHeaderAssignConst.FIELD_INTERVIEWER
|
||||
? ListHeaderAssignConst.CONTACT_INTERVIEWER
|
||||
: isExternalUser && assignType === ListHeaderAssignConst.OUTSOURCE
|
||||
? ListHeaderAssignConst.CONTACT_INTERVIEWER
|
||||
: assignType
|
||||
const [selectedAssignId, setSelectedAssignId] = useState<string | undefined>(undefined)
|
||||
const [assignFilterIds, setAssignFilterIds] = useState<string[]>([])
|
||||
const [transferResve, setTransferResve] = useState(false)
|
||||
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
|
||||
const [filterSummary, setFilterSummary] = useState<string[]>([])
|
||||
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const assignMutation = useSubmitListJob(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 resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
|
||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
const assignTabTypes = useMemo(
|
||||
() =>
|
||||
ASSIGN_TAB_TYPES.filter((type) => {
|
||||
if (type === ListHeaderAssignConst.FIELD_INTERVIEWER && selectedProject?.ff === false) return false
|
||||
if (type === ListHeaderAssignConst.OUTSOURCE && isExternalUser) return false
|
||||
return true
|
||||
}),
|
||||
[selectedProject?.ff, isExternalUser],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProject?.ff === false && assignType === ListHeaderAssignConst.FIELD_INTERVIEWER) {
|
||||
setAssignType(ListHeaderAssignConst.CONTACT_INTERVIEWER)
|
||||
setSelectedAssignId(undefined)
|
||||
setAssignFilterIds([])
|
||||
return
|
||||
}
|
||||
if (isExternalUser && assignType === ListHeaderAssignConst.OUTSOURCE) {
|
||||
setAssignType(ListHeaderAssignConst.CONTACT_INTERVIEWER)
|
||||
setSelectedAssignId(undefined)
|
||||
setAssignFilterIds([])
|
||||
}
|
||||
}, [assignType, selectedProject?.ff, isExternalUser])
|
||||
|
||||
const handleTabChange = (value: string) => {
|
||||
setAssignType(Number(value) as ListHeaderAssignType)
|
||||
setSelectedAssignId(undefined)
|
||||
}
|
||||
|
||||
// "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다.
|
||||
const handleAssignFilterChange = (next: string[]) => {
|
||||
const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value))
|
||||
if (addedSentinel) {
|
||||
setAssignFilterIds([addedSentinel])
|
||||
return
|
||||
}
|
||||
setAssignFilterIds(next.filter((value) => !isAssignFilterSentinel(value)))
|
||||
}
|
||||
|
||||
const assignFilterItems = useMemo(
|
||||
() => [
|
||||
{ id: ASSIGNED_SENTINEL, name: '배정됨' },
|
||||
{ id: UNASSIGNED_SENTINEL, name: '배정되지 않음' },
|
||||
...assignTargetRows,
|
||||
],
|
||||
[assignTargetRows],
|
||||
)
|
||||
|
||||
const externalAssignFilter = useMemo(() => {
|
||||
if (assignFilterIds[0] === ASSIGNED_SENTINEL) {
|
||||
return { type: effectiveAssignType, values: [] as string[], condition: 'assigned' as const }
|
||||
}
|
||||
if (assignFilterIds[0] === UNASSIGNED_SENTINEL) {
|
||||
return { type: effectiveAssignType, values: [] as string[], condition: 'unassigned' as const }
|
||||
}
|
||||
return { type: effectiveAssignType, values: assignFilterIds }
|
||||
}, [effectiveAssignType, assignFilterIds])
|
||||
|
||||
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 () => {
|
||||
if (assignGate.submitBlocked || assignMutation.isPending) return
|
||||
if (!selectedAssignId) {
|
||||
alert('배정할 대상을 선택해주세요.')
|
||||
return
|
||||
}
|
||||
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
|
||||
return
|
||||
}
|
||||
|
||||
await assignMutation.mutateAsync({
|
||||
jobType: 'LIST_ASSIGN',
|
||||
path: `mutations/assign/${encodeURIComponent(selectedAssignId)}`,
|
||||
body: {
|
||||
assignType: effectiveAssignType,
|
||||
transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
|
||||
listFilter: currentListFilter,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const handleResetAssign = async () => {
|
||||
if (assignGate.submitBlocked || assignMutation.isPending) return
|
||||
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
|
||||
return
|
||||
}
|
||||
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
|
||||
|
||||
await assignMutation.mutateAsync({
|
||||
jobType: 'LIST_ASSIGN',
|
||||
path: 'mutations/assign-reset',
|
||||
body: {
|
||||
assignType: effectiveAssignType,
|
||||
listFilter: currentListFilter,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<ListJobPageQueryContext.Provider value="LIST_ASSIGN">
|
||||
<div className="flex gap-4 text-sm">
|
||||
<div className="w-72 shrink-0 space-y-2">
|
||||
<Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
|
||||
<TabsList className={`grid w-full ${assignTabTypes.length === 2 ? 'grid-cols-2' : assignTabTypes.length === 1 ? 'grid-cols-1' : 'grid-cols-3'}`}>
|
||||
{assignTabTypes.map((type) => (
|
||||
<TabsTrigger key={type} value={String(type)}>
|
||||
{LIST_HEADER_TYPE_LABEL[type]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
<AssignTargetList
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
assignType={effectiveAssignType}
|
||||
userRole={userRole}
|
||||
selectedId={selectedAssignId}
|
||||
onSelect={setSelectedAssignId}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<ListJobGatePanel gate={assignGate} />
|
||||
<ListJobRefreshNotice monitor={pageMonitor} />
|
||||
<ListSearchTable
|
||||
dataRevision={dataRevision}
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
userRole={userRole}
|
||||
userId={auth?.user?.userId ?? ''}
|
||||
userCmpn={auth?.user?.userCmpn ?? ''}
|
||||
resultCodes={resultCodeArray}
|
||||
surveys={surveyArray}
|
||||
listHeaders={listHeaders}
|
||||
fieldInterviewEnabled={selectedProject.ff !== false}
|
||||
selectMode="none"
|
||||
onCurrentFilterChange={setCurrentListFilter}
|
||||
onFilterSummaryChange={setFilterSummary}
|
||||
excludeFilterHeaderTypes={[effectiveAssignType]}
|
||||
externalAssignFilter={externalAssignFilter}
|
||||
filterActions={
|
||||
<KriMultiSelect
|
||||
items={assignFilterItems}
|
||||
value={assignFilterIds}
|
||||
onChange={handleAssignFilterChange}
|
||||
getValue={(item) => item.id}
|
||||
getLabel={(item) => item.name}
|
||||
placeholder={`${LIST_HEADER_TYPE_LABEL[effectiveAssignType]} 필터`}
|
||||
widthClassName="w-56"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
}
|
||||
rightActions={
|
||||
<>
|
||||
{effectiveAssignType === ListHeaderAssignConst.CONTACT_INTERVIEWER && (
|
||||
<label className="flex items-center gap-2 text-base cursor-pointer">
|
||||
<Checkbox
|
||||
checked={transferResve}
|
||||
onCheckedChange={(checked) => setTransferResve(checked === true)}
|
||||
/>
|
||||
예약 이관
|
||||
</label>
|
||||
)}
|
||||
<Button type="button" onClick={handleAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
|
||||
배정
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={handleResetAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
|
||||
배정 초기화
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ListJobPageQueryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListAssignPage
|
||||
473
src/app/(pages)/(main)/assign/project/page.tsx
Normal file
473
src/app/(pages)/(main)/assign/project/page.tsx
Normal file
@@ -0,0 +1,473 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { ProjectInfo } from "@/types/project";
|
||||
import { PROJECT_SEARCH_COUNT } from "@/const/projectConst";
|
||||
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
||||
import { UserInfo } from "@/types/user";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from "@/const/userConst";
|
||||
|
||||
import {
|
||||
useFieldworkUsersQuery,
|
||||
useRoleListQuery,
|
||||
} from "@/query/user";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
|
||||
import {
|
||||
useAssignedCmpnIdsQuery,
|
||||
useAssignedFieldworkIdsQuery,
|
||||
useSaveAssignedFieldworkMutation,
|
||||
useProjectTopQuery,
|
||||
} from "@/query/project";
|
||||
import { isExternalManager, isFieldWorkUser } from "@/utils/userRole";
|
||||
|
||||
const ProjectAssignPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
// 외주사 계정은 자기 회사 배정만 봐야 하므로 회사 select 자체를 조작하지 못하게 막는다.
|
||||
const isExternalUser = isExternalManager(auth.user?.userRole);
|
||||
|
||||
const companyQuery = useCmpnListQuery();
|
||||
const fwUsersQuery = useFieldworkUsersQuery(enabled);
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled);
|
||||
const assignedIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled);
|
||||
const saveAssignMutation = useSaveAssignedFieldworkMutation(prjctIdx);
|
||||
|
||||
const roleQuery = useRoleListQuery();
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const projectTopQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, mounted);
|
||||
const projectArray = projectTopQuery.data ?? [];
|
||||
const companyArray = useMemo(() => {
|
||||
const companies = companyQuery.data ?? [];
|
||||
const assignedCmpnIds = new Set(assignedCmpnIdsQuery.data ?? []);
|
||||
return companies.filter((company) => company.ownCmpn || assignedCmpnIds.has(company.cmpnId));
|
||||
}, [assignedCmpnIdsQuery.data, companyQuery.data]);
|
||||
|
||||
const roleArray: KriSelectItem[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles
|
||||
.filter(r => isFieldWorkUser(r.roleCd))
|
||||
.filter(r => selectedProject?.ff !== false || r.roleCd !== FIELD_INTERVIEWER_ROLE)
|
||||
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||
}, [roleQuery.data, selectedProject?.ff]);
|
||||
|
||||
const [companyFilter, setCompanyFilter] = useState<string>('');
|
||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
|
||||
const fwUserArray = fwUsersQuery.data ?? [];
|
||||
|
||||
const [originAssign, setOriginAssign] = useState<UserInfo[]>([]);
|
||||
const [assignUserArray, setAssignUserArray] = useState<UserInfo[]>([]);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
||||
// 선택/검색(좌/우)
|
||||
const [selectedAssignUser, setSelectedAssignUser] = useState<string[]>([]);
|
||||
const [searchAssign, setSearchAssign] = useState('');
|
||||
const debouncedAssign = useDebouncedValue(searchAssign, 500);
|
||||
|
||||
const [selectedAbleUser, setSelectedAbleUser] = useState<string[]>([]);
|
||||
const [searchAble, setSearchAble] = useState('');
|
||||
const debouncedAble = useDebouncedValue(searchAble, 500);
|
||||
|
||||
const resetSelect = useCallback(() => {
|
||||
setSelectedAssignUser([]);
|
||||
setSelectedAbleUser([]);
|
||||
setSearchAssign('');
|
||||
setSearchAble('');
|
||||
}, []);
|
||||
|
||||
const resetSelectAndAssign = useCallback(() => {
|
||||
resetSelect();
|
||||
setAssignUserArray(structuredClone(originAssign));
|
||||
setDirty(false);
|
||||
}, [originAssign, resetSelect]);
|
||||
|
||||
const [sourceProject, setSourceProject] = useState<ProjectInfo | undefined>(undefined);
|
||||
const handleSelectProject = (info: ProjectInfo | null) => {
|
||||
setSourceProject(info ?? undefined);
|
||||
resetSelect();
|
||||
};
|
||||
|
||||
const sourcePrjctIdx = sourceProject?.prjctIdx ?? 0;
|
||||
const sourceAssignedIdsQuery = useAssignedFieldworkIdsQuery(
|
||||
sourcePrjctIdx,
|
||||
mounted && sourcePrjctIdx > 0
|
||||
);
|
||||
|
||||
const ableUserArray: UserInfo[] = useMemo(() => {
|
||||
if (sourcePrjctIdx > 0) {
|
||||
const ids = sourceAssignedIdsQuery.data ?? [];
|
||||
return fwUserArray.filter(u => ids.includes(u.userId));
|
||||
}
|
||||
return structuredClone(fwUserArray);
|
||||
}, [fwUserArray, sourcePrjctIdx, sourceAssignedIdsQuery.data]);
|
||||
|
||||
const handleSelectAllLeft = (checked: boolean) => {
|
||||
setSelectedAssignUser(checked ? assignView.map(u => u.userId) : []);
|
||||
};
|
||||
|
||||
const handleSelectAllRight = (checked: boolean) => {
|
||||
setSelectedAbleUser(checked ? ableView.map(u => u.userId) : []);
|
||||
};
|
||||
|
||||
const handleToggleUnassign = (id: string) => {
|
||||
setSelectedAssignUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
|
||||
};
|
||||
|
||||
const handleToggleAssign = (id: string) => {
|
||||
setSelectedAbleUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
|
||||
};
|
||||
|
||||
const handleCompanyChange = (v: string) => {
|
||||
resetSelectAndAssign();
|
||||
setCompanyFilter(v);
|
||||
};
|
||||
|
||||
const handleRoleChange = (item: KriSelectItem) => {
|
||||
resetSelectAndAssign();
|
||||
setRoleFilter(item);
|
||||
};
|
||||
|
||||
const {
|
||||
assignView,
|
||||
ableView,
|
||||
} = useMemo(() => {
|
||||
const roleVal = roleFilter?.value;
|
||||
const cmpnVal = companyFilter;
|
||||
|
||||
const passBase = (u: UserInfo) =>
|
||||
(!roleVal || String(u.userRole) === roleVal) &&
|
||||
(!cmpnVal || u.userCmpn === cmpnVal);
|
||||
|
||||
const kwFilter = (u: UserInfo, k: string) =>
|
||||
u.userId.includes(k) || u.userName.includes(k);
|
||||
|
||||
// LEFT
|
||||
const _assignBase = assignUserArray.filter(passBase);
|
||||
const kAssign = debouncedAssign.trim();
|
||||
const _assignView = kAssign ? _assignBase.filter((u) => kwFilter(u, kAssign)) : _assignBase;
|
||||
|
||||
// RIGHT (exclude already assigned)
|
||||
const assignedSet = new Set(assignUserArray.map((u) => u.userId));
|
||||
const _ableBase0 = ableUserArray.filter(passBase).filter((u) => !assignedSet.has(u.userId));
|
||||
const kAble = debouncedAble.trim();
|
||||
const _ableView = kAble ? _ableBase0.filter((u) => kwFilter(u, kAble)) : _ableBase0;
|
||||
|
||||
return {
|
||||
assignView: _assignView,
|
||||
ableView: _ableView,
|
||||
};
|
||||
}, [
|
||||
assignUserArray,
|
||||
ableUserArray,
|
||||
roleFilter?.value,
|
||||
companyFilter,
|
||||
debouncedAssign,
|
||||
debouncedAble,
|
||||
]);
|
||||
|
||||
const assignInfoString = useMemo(() => {
|
||||
const cmpnAssign = companyFilter ? originAssign.filter(u => u.userCmpn === companyFilter) : originAssign;
|
||||
return roleArray.map(role => {
|
||||
const cnt = cmpnAssign.filter(u => String(u.userRole) === role.value).length;
|
||||
return `${role.label} : ${cnt}`;
|
||||
}).join(' / ');
|
||||
}, [roleArray, originAssign, companyFilter]);
|
||||
|
||||
const handleAssign = () => {
|
||||
const toAssign = ableView.filter(u => selectedAbleUser.includes(u.userId));
|
||||
if (toAssign.length === 0) return;
|
||||
|
||||
setAssignUserArray(prev => [...prev, ...toAssign]);
|
||||
setSelectedAbleUser([]);
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
if (selectedAssignUser.length === 0) return;
|
||||
|
||||
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
|
||||
setSelectedAssignUser([]);
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!selectedProject) {
|
||||
alert("옳지 않은 요청입니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
await saveAssignMutation.mutateAsync(assignUserArray.map(u => u.userId));
|
||||
setOriginAssign(structuredClone(assignUserArray));
|
||||
setDirty(false);
|
||||
alert("저장되었습니다.");
|
||||
};
|
||||
|
||||
// 로그인 계정의 소속 회사를 기본 선택하되, 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다.
|
||||
useEffect(() => {
|
||||
// 이미 유효한 값이 선택돼 있으면(사용자가 직접 고른 값 포함) 그대로 둔다.
|
||||
if (companyFilter && companyArray.some((company) => company.cmpnId === companyFilter)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cmpn = auth.user?.userCmpn ?? "";
|
||||
if (cmpn && companyArray.some((company) => company.cmpnId === cmpn)) {
|
||||
setCompanyFilter(cmpn);
|
||||
return;
|
||||
}
|
||||
|
||||
const ownCmpn = companyArray.find((company) => company.ownCmpn);
|
||||
setCompanyFilter(ownCmpn?.cmpnId ?? "");
|
||||
}, [auth.user?.userCmpn, companyArray, companyFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
if (roleArray.length === 0) return;
|
||||
if (roleFilter && roleArray.some(role => role.value === roleFilter.value)) return;
|
||||
|
||||
const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE));
|
||||
setRoleFilter(contactRole ?? roleArray[0]);
|
||||
}, [roleArray, roleFilter]);
|
||||
|
||||
// prjctIdx 바뀌면: 편집 상태 초기화(서버 데이터 다시 주입 받을 준비)
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
setDirty(false);
|
||||
resetSelect();
|
||||
setOriginAssign([]);
|
||||
setAssignUserArray([]);
|
||||
}, [enabled, prjctIdx, resetSelect]);
|
||||
|
||||
// 서버 배정 ids + fwUserArray 준비되면 "초기 1회" 주입
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
if (dirty) return;
|
||||
|
||||
const ids = assignedIdsQuery.data;
|
||||
if (!ids) return;
|
||||
|
||||
// fwUserArray가 아직 비어있을 수 있으니 둘 다 준비된 상태에서만
|
||||
if (!fwUserArray || fwUserArray.length === 0) return;
|
||||
|
||||
const assignUserInfoArray = fwUserArray.filter(u => ids.includes(u.userId));
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(structuredClone(assignUserInfoArray));
|
||||
resetSelect();
|
||||
}, [enabled, dirty, assignedIdsQuery.data, fwUserArray, resetSelect]);
|
||||
|
||||
if (!mounted || !selectedProject) return null;
|
||||
|
||||
return (
|
||||
<div className="bg-gray-50 p-1">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="mb-6 rounded-lg border border-gray-200 bg-white p-2 shadow-sm">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 text-lg font-medium text-gray-700 whitespace-nowrap text-right">회사</div>
|
||||
<KriSelect
|
||||
items={companyArray}
|
||||
value={companyFilter}
|
||||
onChange={handleCompanyChange}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
placeholder="회사 선택"
|
||||
className="w-56 h-9"
|
||||
useAll={false}
|
||||
disabled={isExternalUser}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 text-lg font-medium text-gray-700 whitespace-nowrap text-right">대상</div>
|
||||
<KriSelect
|
||||
items={roleArray}
|
||||
value={roleFilter?.value || ""}
|
||||
onChangeOption={handleRoleChange}
|
||||
placeholder="대상 선택"
|
||||
className="w-56 h-9"
|
||||
useAll={false}
|
||||
getValue={(x) => x.value}
|
||||
getLabel={(x) => x.label}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-6 mb-6">
|
||||
<div className="min-w-0">
|
||||
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13 flex items-center">
|
||||
<span className="truncate w-full">{assignInfoString}</span>
|
||||
</div>
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="bg-gray-50 p-2 border-b border-gray-200">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
value={searchAssign}
|
||||
onChange={(e) => setSearchAssign(e.target.value)}
|
||||
className="bg-white border-gray-300"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-[550px] overflow-y-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-2 text-left w-12">
|
||||
<Checkbox
|
||||
checked={selectedAssignUser.length === assignView.length && assignView.length > 0}
|
||||
onCheckedChange={handleSelectAllLeft}
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-2 text-left text-base font-medium">
|
||||
배정된 {roleFilter?.label} ( {assignView.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{assignView.map((userInfo) => (
|
||||
<tr
|
||||
key={userInfo.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedAssignUser.includes(userInfo.userId) ? 'bg-blue-50' : ''
|
||||
}`}
|
||||
onClick={() => handleToggleUnassign(userInfo.userId)}
|
||||
>
|
||||
<td className="p-2">
|
||||
<Checkbox
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
checked={selectedAssignUser.includes(userInfo.userId)}
|
||||
onCheckedChange={() => handleToggleUnassign(userInfo.userId)}
|
||||
/>
|
||||
</td>
|
||||
<td className="p-2 text-base">
|
||||
{userInfo.userName} ({userInfo.userId})
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col justify-center gap-4">
|
||||
<Button
|
||||
onClick={handleAssign}
|
||||
disabled={selectedAbleUser.length === 0}
|
||||
className="w-36 h-12 flex items-center justify-center text-base disabled:bg-gray-300"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
<span className="ml-2">배정 {selectedAbleUser.length}명</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleRemove}
|
||||
disabled={selectedAssignUser.length === 0}
|
||||
className="bg-red-600 hover:bg-red-700 w-36 h-12 flex items-center justify-center text-base disabled:bg-gray-300"
|
||||
>
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
<span className="ml-2">제외 {selectedAssignUser.length}명</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13">
|
||||
<KriSingleSelect<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(sourceProject?.prjctIdx ?? "")}
|
||||
onChange={() => {}}
|
||||
withInfo
|
||||
onItemChange={handleSelectProject}
|
||||
searchMode="inputOnly"
|
||||
onSearchValueChange={setSearchKeyword}
|
||||
placeholder="프로젝트 검색..."
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
preventDeselect
|
||||
hideOptionCheck
|
||||
useClear
|
||||
getLabel={(item) => `${item.prjctCd}_${item.prjctName}`}
|
||||
getValue={(item) => String(item.prjctIdx)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="bg-gray-50 p-2 border-b border-gray-200">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
value={searchAble}
|
||||
onChange={(e) => setSearchAble(e.target.value)}
|
||||
className="bg-white border-gray-300"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-[550px] overflow-y-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-2 text-left w-12">
|
||||
<Checkbox
|
||||
checked={selectedAbleUser.length === ableView.length && ableView.length > 0}
|
||||
onCheckedChange={handleSelectAllRight}
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-2 text-left text-base font-medium">
|
||||
배정 가능 {roleFilter?.label} ({ableView.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ableView.map((user) => (
|
||||
<tr
|
||||
key={user.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedAbleUser.includes(user.userId) ? 'bg-blue-50' : ''
|
||||
}`}
|
||||
onClick={() => handleToggleAssign(user.userId)}
|
||||
>
|
||||
<td className="p-2">
|
||||
<Checkbox
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
checked={selectedAbleUser.includes(user.userId)}
|
||||
onCheckedChange={() => handleToggleAssign(user.userId)}
|
||||
/>
|
||||
</td>
|
||||
<td className="p-2 text-base">
|
||||
{user.userName} ({user.userId})
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className=" px-12 h-9 text-base font-medium"
|
||||
>
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProjectAssignPage;
|
||||
@@ -1,14 +1,15 @@
|
||||
import MainLayout from "@/components/layout/MainLayout";
|
||||
import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
|
||||
import AppMainLayout from "@/components/app-shell/AppMainLayout";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
import {FONT_SIZE} from "@/const/commonConst";
|
||||
|
||||
function parseFontSize(raw: string | undefined | null) {
|
||||
if (!raw) return FONT_SIZE.MIN;
|
||||
if (!raw) return FONT_SIZE.DEFAULT;
|
||||
|
||||
const parsed = parseInt(raw, 10);
|
||||
if (Number.isNaN(parsed)) return FONT_SIZE.MIN;
|
||||
if (Number.isNaN(parsed)) return FONT_SIZE.DEFAULT;
|
||||
|
||||
return Math.min(
|
||||
FONT_SIZE.MAX,
|
||||
@@ -23,7 +24,7 @@ export default async function MainLayoutWrapper({
|
||||
}) {
|
||||
const cookieStore = await cookies();
|
||||
const fontSize = cookieStore.get(CookieKeys.FontSize);
|
||||
const accessToken = cookieStore.get("access_token")?.value;
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
||||
const initialFontSize = parseFontSize(fontSize?.value);
|
||||
|
||||
if (!accessToken) {
|
||||
@@ -31,8 +32,8 @@ export default async function MainLayoutWrapper({
|
||||
}
|
||||
|
||||
return (
|
||||
<MainLayout initialFontSize={initialFontSize}>
|
||||
<AuthSessionGate><AppMainLayout initialFontSize={initialFontSize}>
|
||||
{children}
|
||||
</MainLayout>
|
||||
</AppMainLayout></AuthSessionGate>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
const ListAssignPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
|
||||
return (<div>This is List Assign Page</div>)
|
||||
}
|
||||
|
||||
export default ListAssignPage;
|
||||
@@ -1,8 +1,257 @@
|
||||
const ListContactPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is List Contact Page</div>)
|
||||
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ArrowLeft, RefreshCw } from "lucide-react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useListDetailQuery, useListHeaderQuery, useUpdateListMutation } from "@/query/list";
|
||||
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
|
||||
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
|
||||
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
|
||||
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
|
||||
import { createEmptyListFilter, type listHeader } from "@/types/list";
|
||||
import type { ResultCode } from "@/types/project";
|
||||
import { isManager } from "@/utils/userRole";
|
||||
import {useCtiCallPhase} from "@/hooks/useCtiCallPhase";
|
||||
import {CTI_CALL_PHASE} from "@/const/ctiConst";
|
||||
|
||||
const CALL_NAVIGATION_GUARD_KEY = "__listContactCallNavigationGuard";
|
||||
|
||||
const ListContactPageContent = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const sid = searchParams.get("sid") ?? "";
|
||||
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const userId = auth?.user?.userId ?? "";
|
||||
const userRole = auth?.user?.userRole ?? 0;
|
||||
const ctiCallPhase = useCtiCallPhase();
|
||||
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
|
||||
const hasObservedCall = useRef(false);
|
||||
|
||||
const queriesEnabled = mounted && prjctIdx > 0;
|
||||
const enabled = queriesEnabled && !!sid;
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldBlockNavigation) return;
|
||||
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
//구형 브라우저를 커버하기 위함
|
||||
event.returnValue = true;
|
||||
};
|
||||
|
||||
const handleReloadShortcut = (event: KeyboardEvent) => {
|
||||
const isReloadShortcut =
|
||||
event.key === "F5" ||
|
||||
((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "r");
|
||||
|
||||
if (!isReloadShortcut) return;
|
||||
|
||||
event.preventDefault();
|
||||
if (!event.repeat) alert("통화 중에는 새로고침할 수 없습니다.");
|
||||
};
|
||||
|
||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||
window.addEventListener("keydown", handleReloadShortcut, true);
|
||||
return () => {
|
||||
window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
window.removeEventListener("keydown", handleReloadShortcut, true);
|
||||
};
|
||||
}, [shouldBlockNavigation]);
|
||||
|
||||
useEffect(() => {
|
||||
const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true;
|
||||
|
||||
if (!shouldBlockNavigation) {
|
||||
if (hasGuardEntry && hasObservedCall.current) window.history.back();
|
||||
hasObservedCall.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
hasObservedCall.current = true;
|
||||
let isRestoringHistory = false;
|
||||
|
||||
if (!hasGuardEntry) {
|
||||
window.history.pushState(
|
||||
{
|
||||
...window.history.state,
|
||||
[CALL_NAVIGATION_GUARD_KEY]: true,
|
||||
},
|
||||
"",
|
||||
window.location.href,
|
||||
);
|
||||
}
|
||||
|
||||
const handlePopState = () => {
|
||||
if (isRestoringHistory) {
|
||||
isRestoringHistory = false;
|
||||
return;
|
||||
}
|
||||
|
||||
alert("통화 중에는 페이지를 이동할 수 없습니다.");
|
||||
|
||||
isRestoringHistory = true;
|
||||
window.history.forward();
|
||||
};
|
||||
|
||||
window.addEventListener("popstate", handlePopState);
|
||||
return () => window.removeEventListener("popstate", handlePopState);
|
||||
}, [shouldBlockNavigation]);
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, queriesEnabled);
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, queriesEnabled);
|
||||
const listDetailQuery = useListDetailQuery(prjctIdx, sid, enabled);
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, queriesEnabled);
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx);
|
||||
|
||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
|
||||
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const initialFormValues = useMemo(
|
||||
() => buildInitialValues(listHeaders, listDetailQuery.data),
|
||||
[listHeaders, listDetailQuery.data],
|
||||
);
|
||||
const [formValues, setFormValues] = useState<Record<number, string>>(initialFormValues);
|
||||
|
||||
useEffect(() => {
|
||||
setFormValues(initialFormValues);
|
||||
}, [initialFormValues]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sid) return;
|
||||
alert("sid가 없으면 진행할 수 없습니다.");
|
||||
router.push("/list/manage");
|
||||
}, [sid, router]);
|
||||
|
||||
const handleGoToListManage = () => {
|
||||
if(shouldBlockNavigation){
|
||||
alert("통화 중에는 이동할 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
router.push("/list/manage");
|
||||
};
|
||||
|
||||
const handleFieldChange = (listHderId: number, value: string) => {
|
||||
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
|
||||
};
|
||||
|
||||
const handleCancelEdit = () => {
|
||||
setFormValues(initialFormValues);
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
const handleToggleEdit = async () => {
|
||||
if (!isEditing) {
|
||||
setIsEditing(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await updateListMutation.mutateAsync({
|
||||
updateContents: Object.fromEntries(Object.entries(formValues)),
|
||||
listFilter: { ...createEmptyListFilter(), sidSet: [sid] },
|
||||
});
|
||||
alert("저장되었습니다.");
|
||||
setIsEditing(false);
|
||||
listDetailQuery.refetch();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
if (!sid) return null;
|
||||
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
{/* 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="목록으로">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-xl font-bold tracking-tight max-lg:whitespace-nowrap lg:text-2xl">컨택 진행</h1>
|
||||
<span className="text-xl font-bold tracking-tight max-lg:min-w-0 max-lg:truncate lg:text-2xl">SID: {sid}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
disabled={listDetailQuery.isFetching}
|
||||
aria-label="리스트 정보 새로고침"
|
||||
title="리스트 정보 새로고침"
|
||||
onClick={() => listDetailQuery.refetch()}
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{isEditing ? (
|
||||
<Button type="button" variant="outline" disabled={updateListMutation.isPending} onClick={handleCancelEdit}>
|
||||
취소
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
|
||||
{isEditing ? '저장' : '수정'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||
<div className="h-[80vh] space-y-4 overflow-y-auto">
|
||||
<ListContactInfoPanel
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
itrntPrjctCd={itrntPrjctCd}
|
||||
userRole={userRole}
|
||||
isEditing={isEditing}
|
||||
listHeaders={listHeaders}
|
||||
detail={listDetailQuery.data}
|
||||
surveys={projectInfoQuery.data?.surveys ?? []}
|
||||
callerTelNum={projectInfoQuery.data?.callerTelNum}
|
||||
resultCodes={resultCodeArray}
|
||||
formValues={formValues}
|
||||
onFieldChange={handleFieldChange}
|
||||
onSaved={() => listDetailQuery.refetch()}
|
||||
/>
|
||||
|
||||
{isManager(userRole) ? (
|
||||
<ListUpdateHistoryPanel prjctIdx={prjctIdx} sid={sid} listHeaders={listHeaders} />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ListContactEventPanel
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
prjctCd={prjctCd}
|
||||
userId={userId}
|
||||
userRole={userRole}
|
||||
resultCodes={resultCodeArray}
|
||||
useFF={projectInfoQuery.data?.ff ?? false}
|
||||
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
|
||||
contactSenario={projectInfoQuery.data?.contactSenario}
|
||||
listHeaders={listHeaders}
|
||||
detail={listDetailQuery.data}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ListContactPage = () => (
|
||||
<Suspense fallback={null}>
|
||||
<ListContactPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
export default ListContactPage;
|
||||
@@ -1,25 +1,426 @@
|
||||
"use client";
|
||||
'use client'
|
||||
|
||||
import {useFontSizeValue} from "@/hooks/useFontSize";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import ProjectTitle from "@/components/layout/ProjectTitle";
|
||||
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 { useQueryClient } from '@tanstack/react-query'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useSelectedProject } from '@/hooks/useSelectedProject'
|
||||
import { useStorage } from '@/hooks/useStorage'
|
||||
import { StorageKeys } from '@/store/storage/storage-keys'
|
||||
import { ListManageActions, type ListManageActionKey } from '@/components/list/ListManageActions'
|
||||
import { ListSearchTable } from '@/components/list/ListSearchTable'
|
||||
import {
|
||||
useDownloadListExcelTemplateMutation,
|
||||
useDownloadUploadHistoryFileMutation,
|
||||
useListHeaderQuery,
|
||||
useListUploadHistoryQuery,
|
||||
useUpdateListHeaderMutation,
|
||||
} 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 type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import {
|
||||
createEmptyListFilter,
|
||||
ListEventHistoryBase,
|
||||
ListEventHistoryOrder,
|
||||
type LastListVisit,
|
||||
type ListDownloadMode,
|
||||
type ListDownloadPayload,
|
||||
type ListFilter,
|
||||
type ListFilterTarget,
|
||||
type listHeader,
|
||||
type ListSearchUiState,
|
||||
type ListResetRequest,
|
||||
type ListResetSelection,
|
||||
type ListUploadRequest,
|
||||
} from '@/types/list'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import ListResetDialog from '@/components/dialog/ListResetDialog'
|
||||
import ListUploadDialog from '@/components/dialog/ListUploadDialog'
|
||||
import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog'
|
||||
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
|
||||
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
|
||||
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
|
||||
import { downloadFile } from '@kri/common/browser'
|
||||
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
|
||||
import { isInternalManager, isManager } from "@/utils/userRole";
|
||||
import { applyListAccessFilter } from "@/utils/listAccess";
|
||||
|
||||
const toDateTimeRange = (from?: string, to?: string) => {
|
||||
if (!from || !to) return undefined
|
||||
return {
|
||||
startDate: `${from}T00:00:00`,
|
||||
endDate: `${to}T23:59:59`,
|
||||
}
|
||||
}
|
||||
|
||||
const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') => {
|
||||
downloadFile(new Blob([buffer], { type }), filename)
|
||||
}
|
||||
|
||||
const createEmptySearchUiState = (): ListSearchUiState => ({
|
||||
searchText: '',
|
||||
searchContactResult: [],
|
||||
searchContactDateRange: { from: '', to: '' },
|
||||
searchInterviewResult: [],
|
||||
surveyResultSelections: {},
|
||||
filterRows: [],
|
||||
sorting: [],
|
||||
})
|
||||
|
||||
const ListManagePage = () => {
|
||||
const fontSize = useFontSizeValue();
|
||||
const mounted = useMounted();
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const mounted = useMounted()
|
||||
const { auth } = useAuth()
|
||||
const { showDialog } = useDialog()
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
|
||||
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />;
|
||||
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
|
||||
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
|
||||
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
|
||||
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
|
||||
const [filterSummary, setFilterSummary] = useState<string[]>([])
|
||||
const [searchUiState, setSearchUiState] = useState<ListSearchUiState>(createEmptySearchUiState)
|
||||
const [listRefreshKey, setListRefreshKey] = useState(0)
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
|
||||
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null)
|
||||
const [restoreResolved, setRestoreResolved] = useState(false)
|
||||
const previousPrjctIdxRef = useRef(0)
|
||||
|
||||
const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage(
|
||||
StorageKeys.LastListVisit,
|
||||
)
|
||||
|
||||
const userRole = auth?.user?.userRole ?? CONTACT_INTERVIEWER_ROLE
|
||||
const userId = auth?.user?.userId ?? ''
|
||||
const userCmpn = auth?.user?.userCmpn ?? ''
|
||||
const prjctName = selectedProject?.prjctName ?? ''
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0
|
||||
const enabled = mounted && prjctIdx > 0
|
||||
const canManageList = isManager(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 projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
|
||||
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
|
||||
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 downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
|
||||
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
|
||||
const headerManageRows = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
// 컨택 진행 화면에서 돌아왔을 때 1회만 복원하고, 재방문 시 다시 나타나지 않도록 즉시 지운다.
|
||||
// ListSearchTable이 첫 마운트될 때 초기 페이지네이션 값이 확정돼 있어야 하므로(useState는 이후 prop
|
||||
// 변경을 반영하지 않음), selectedProject 하이드레이션이 끝나기 전에는 ListSearchTable을 아예 그리지 않는다.
|
||||
useEffect(() => {
|
||||
if (!mounted || !isSelectedProjectHydrated || restoreResolved) return
|
||||
const stored = getLastListVisit()
|
||||
if (stored) {
|
||||
setRestoredVisit(stored)
|
||||
removeLastListVisit()
|
||||
}
|
||||
setRestoreResolved(true)
|
||||
}, [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 selectedSidSet = useMemo(
|
||||
() =>
|
||||
selectedRows
|
||||
.map((row) => row.sid)
|
||||
.filter((sid): sid is string | number => typeof sid === 'string' || typeof sid === 'number')
|
||||
.map(String),
|
||||
[selectedRows],
|
||||
)
|
||||
|
||||
const refreshList = () => {
|
||||
setListRefreshKey((prev) => prev + 1)
|
||||
}
|
||||
|
||||
const buildTargetFilter = (target: ListFilterTarget) => {
|
||||
if (target === 'all') {
|
||||
return applyListAccessFilter(createEmptyListFilter(), { userRole, userId, userCmpn })
|
||||
}
|
||||
if (target === 'selected') {
|
||||
return applyListAccessFilter(
|
||||
{
|
||||
...createEmptyListFilter(),
|
||||
sidSet: selectedSidSet,
|
||||
},
|
||||
{ userRole, userId, userCmpn },
|
||||
)
|
||||
}
|
||||
return applyListAccessFilter(currentListFilter, { userRole, userId, userCmpn })
|
||||
}
|
||||
|
||||
const handleStartContact = (row: ListTableRow) => {
|
||||
const sid = String(row.sid ?? '')
|
||||
setLastListVisit({
|
||||
prjctIdx,
|
||||
sid,
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
...searchUiState,
|
||||
})
|
||||
router.push(`/list/contact?sid=${encodeURIComponent(sid)}`)
|
||||
}
|
||||
|
||||
const openDownloadDialog = (mode: ListDownloadMode) => {
|
||||
setDownloadMode(mode)
|
||||
showDialog('listDownloadDialog')
|
||||
}
|
||||
|
||||
const openMessageDialog = (mode: MessageSendMode) => {
|
||||
setMessageSendMode(mode)
|
||||
showDialog('messageSendDialog')
|
||||
}
|
||||
|
||||
const handleResetConfirm = async (payload: { target: ListFilterTarget; selection: ListResetSelection }) => {
|
||||
const body: ListResetRequest = {
|
||||
...payload.selection,
|
||||
listFilter: buildTargetFilter(payload.target),
|
||||
}
|
||||
await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body })
|
||||
}
|
||||
|
||||
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
|
||||
await submitJob.mutateAsync({ jobType: 'LIST_UPLOAD', path: 'upload', file, body: request })
|
||||
}
|
||||
|
||||
const handleDownloadTemplate = async () => {
|
||||
if (!prjctIdx) {
|
||||
alert("프로젝트를 선택해주세요.")
|
||||
return
|
||||
}
|
||||
|
||||
const buffer = await downloadListExcelTemplateMutation.mutateAsync(prjctIdx)
|
||||
downloadArrayBuffer(buffer, `${prjctName} list-upload-template.xlsx`)
|
||||
}
|
||||
|
||||
const handleHeaderManageConfirm = async (rows: listHeader[]) => {
|
||||
await updateListHeaderMutation.mutateAsync(rows)
|
||||
}
|
||||
|
||||
const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
|
||||
const listFilter = buildTargetFilter(payload.target)
|
||||
const jobType = LIST_DOWNLOAD_JOB_TYPE[payload.mode]
|
||||
|
||||
if (payload.mode === 'list') {
|
||||
await submitJob.mutateAsync({ jobType, path: `downloads/list?includeResult=${payload.includeResult}`, body: listFilter })
|
||||
return
|
||||
}
|
||||
|
||||
if (payload.mode === 'list-change-history') {
|
||||
await submitJob.mutateAsync({ jobType, path: 'downloads/update-history', body: listFilter })
|
||||
return
|
||||
}
|
||||
|
||||
if (payload.mode === 'upload-file') {
|
||||
await submitJob.mutateAsync({ jobType, path: 'downloads/item-files', body: listFilter })
|
||||
return
|
||||
}
|
||||
|
||||
await submitJob.mutateAsync({ jobType, path: `downloads/event-history?includeResult=${payload.includeResult}`, body: {
|
||||
listFilter,
|
||||
resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY],
|
||||
searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL,
|
||||
historyOrder: payload.historyOrder ?? ListEventHistoryOrder.DESC,
|
||||
dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo),
|
||||
} })
|
||||
}
|
||||
|
||||
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<div>
|
||||
This is Manage List Page <span>{fontSize}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
<ListJobPageQueryContext.Provider value="LIST_RESET">
|
||||
<div className="space-y-6 text-sm">
|
||||
<ListJobGatePanel gate={pageGate} showCurrentJob={false} />
|
||||
<ListJobRefreshNotice monitor={pageMonitor} clearsSelection={selectedRows.length > 0} />
|
||||
{canManageList && (
|
||||
<ListManageActions
|
||||
showAdminActions={isInternal}
|
||||
runningActions={runningActions}
|
||||
disabledActions={disabledActions}
|
||||
headerManageDisabled={pageGate.submitBlocked}
|
||||
onReset={() => showDialog('listResetDialog')}
|
||||
onHeaderManage={() => { if (!pageGate.submitBlocked) showDialog('listHeaderManageDialog') }}
|
||||
onUpload={() => showDialog('listUploadDialog')}
|
||||
onDownload={openDownloadDialog}
|
||||
onMessageSend={openMessageDialog}
|
||||
onMessageHistory={() => showDialog('messageHistoryDialog')}
|
||||
/>
|
||||
)}
|
||||
|
||||
export default ListManagePage;
|
||||
<ListSearchTable
|
||||
key={prjctIdx}
|
||||
prjctIdx={prjctIdx}
|
||||
enabled={enabled}
|
||||
userRole={userRole}
|
||||
userId={userId}
|
||||
userCmpn={userCmpn}
|
||||
resultCodes={resultCodeArray}
|
||||
surveys={surveyArray}
|
||||
listHeaders={headerManageRows}
|
||||
fieldInterviewEnabled={selectedProject?.ff !== false}
|
||||
enableBatchEdit={canManageList}
|
||||
batchEditDisabled={isActionDisabled('LIST_UPDATE')}
|
||||
dataRevision={dataRevision}
|
||||
selectMode={canManageList ? 'multi' : 'click-event'}
|
||||
refreshKey={listRefreshKey}
|
||||
onCurrentFilterChange={setCurrentListFilter}
|
||||
onFilterSummaryChange={setFilterSummary}
|
||||
onSelectedRowsChange={setSelectedRows}
|
||||
onRowClick={!canManageList ? handleStartContact : undefined}
|
||||
onRowDoubleClick={canManageList ? handleStartContact : undefined}
|
||||
initialPagination={
|
||||
restoredForThisProject
|
||||
? { pageIndex: restoredForThisProject.pageIndex, pageSize: restoredForThisProject.pageSize }
|
||||
: undefined
|
||||
}
|
||||
onPaginationChange={setPagination}
|
||||
initialSearchState={restoredForThisProject}
|
||||
onSearchStateChange={setSearchUiState}
|
||||
focusRowId={restoredForThisProject?.sid}
|
||||
collapsibleFiltersOnMobile
|
||||
/>
|
||||
|
||||
{isInternal && (
|
||||
<>
|
||||
<ListResetDialog
|
||||
key={prjctIdx}
|
||||
prjctIdx={prjctIdx}
|
||||
surveys={projectInfoQuery.data?.surveys}
|
||||
selectedSids={selectedSidSet}
|
||||
filterSummary={filterSummary}
|
||||
onConfirm={handleResetConfirm}
|
||||
/>
|
||||
<ListUploadDialog
|
||||
prjctIdx={prjctIdx}
|
||||
onUpload={handleUploadConfirm}
|
||||
onDownloadTemplate={handleDownloadTemplate}
|
||||
uploadHistory={uploadHistoryQuery.data ?? []}
|
||||
onDownloadHistory={async (item) => {
|
||||
const buffer = await downloadUploadHistoryFileMutation.mutateAsync(item.listUploadLogId)
|
||||
downloadArrayBuffer(buffer, item.fileName)
|
||||
}}
|
||||
headerRows={headerManageRows}
|
||||
/>
|
||||
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} saveDisabled={pageGate.submitBlocked} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{canManageList && (
|
||||
<>
|
||||
<ListDownloadDialog
|
||||
prjctIdx={prjctIdx}
|
||||
mode={downloadMode}
|
||||
selectedSids={selectedSidSet}
|
||||
filterSummary={filterSummary}
|
||||
onDownload={handleDownloadConfirm}
|
||||
/>
|
||||
<MessageSendDialog
|
||||
mode={messageSendMode}
|
||||
listHeaders={headerManageRows}
|
||||
currentFilter={currentListFilter}
|
||||
selectedRows={selectedRows}
|
||||
filterSummary={filterSummary}
|
||||
onSent={refreshList}
|
||||
/>
|
||||
<MessageHistoryDialog />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ListJobPageQueryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListManagePage
|
||||
|
||||
99
src/app/(pages)/(main)/manage/cmpn/page.tsx
Normal file
99
src/app/(pages)/(main)/manage/cmpn/page.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getCmpnColumns } from "@/components/table-column/CmpnTableColumn";
|
||||
import CmpnUpsertDialog from "@/components/dialog/CmpnUpsertDialog";
|
||||
import { useDialog } from "@/hooks/useDialog";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import type { CmpnInfoSaveRequest } from "@/types/cmpn";
|
||||
import {
|
||||
useCheckCmpnIdDuplicateMutation,
|
||||
useCmpnDetailQuery,
|
||||
useCmpnListQuery,
|
||||
useUpsertCmpnMutation,
|
||||
} from "@/query/cmpn";
|
||||
|
||||
const CmpnManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const mounted = useMounted();
|
||||
|
||||
const cmpnListQuery = useCmpnListQuery();
|
||||
const checkDupMutation = useCheckCmpnIdDuplicateMutation();
|
||||
const upsertMutation = useUpsertCmpnMutation();
|
||||
|
||||
const [editCmpnId, setEditCmpnId] = useState<string | null>(null);
|
||||
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create');
|
||||
const cmpnDetailQuery = useCmpnDetailQuery(editCmpnId ?? "", !!editCmpnId);
|
||||
|
||||
const cmpnList = cmpnListQuery.data ?? [];
|
||||
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode("create");
|
||||
setEditCmpnId(null);
|
||||
showDialog("cmpnUpsertDialog");
|
||||
};
|
||||
|
||||
const handleEdit = (cmpnId: string) => {
|
||||
setDialogMode("edit");
|
||||
setEditCmpnId(cmpnId);
|
||||
showDialog("cmpnUpsertDialog");
|
||||
};
|
||||
|
||||
const handleCheckDuplicate = (cmpnId: string) => {
|
||||
return checkDupMutation.mutateAsync(cmpnId);
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: CmpnInfoSaveRequest): Promise<void> => {
|
||||
await upsertMutation.mutateAsync({ mode: dialogMode, data });
|
||||
|
||||
if (dialogMode === "create") {
|
||||
alert("등록되었습니다.");
|
||||
} else {
|
||||
alert("수정되었습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getCmpnColumns({
|
||||
onEdit: handleEdit,
|
||||
});
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"회사 관리"} />
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleCreateClick}>
|
||||
회사 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={cmpnList}
|
||||
isClient={true}
|
||||
selectMode="single"
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.cmpnId}
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CmpnUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={dialogMode === "edit" ? (cmpnDetailQuery.data ?? undefined) : undefined}
|
||||
onSubmit={handleSubmit}
|
||||
onCheckDuplicate={handleCheckDuplicate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CmpnManagePage;
|
||||
@@ -1,199 +1,184 @@
|
||||
'use client'
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState} from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getUserColumns } from "../../../../../components/table-column/UserTableColumn";
|
||||
import _ from "lodash";
|
||||
import { getUserColumns } from "@/components/table-column/UserTableColumn";
|
||||
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
|
||||
import {UserInfo, UserInfoSaveRequest, UserUploadResponse} from "@/types/user";
|
||||
import {UserInfoSaveRequest} from "@/types/user";
|
||||
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {downloadBase64File, downloadFile} from "@/lib/utils";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {DataVerification} from "@/types/common";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from "@kri/common/browser";
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {DEFAULT_COMPANY_NAME, EXTERNAL_USER_ROLE} from "@/const/userConst";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import {Upload} from "lucide-react";
|
||||
import {
|
||||
useRoleListQuery,
|
||||
useUsersQuery,
|
||||
useUserDetailQuery,
|
||||
useCheckUserIdDuplicateMutation,
|
||||
useUpsertUserMutation,
|
||||
useDeleteUserMutation,
|
||||
useUploadUsersExcelMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
} from "@/query/user";
|
||||
import { useCmpnListQuery } from "@/query/cmpn";
|
||||
import { isInternalManager } from "@/utils/userRole";
|
||||
|
||||
const UserManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const mounted = useMounted();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
|
||||
const [userList, setUserList] = useState<UserInfo[]>([]);
|
||||
const [viewList, setViewList] = useState<UserInfo[]>([]);
|
||||
const [selectedUserArray, setSelectedUserArray] = useState<UserInfo[]>([]);
|
||||
const [userCmpnArray, setUserCmpnArray] = useState<string[]>([]);
|
||||
const [userRoleArray, setUserRoleArray] = useState<MultiSelectOption[]>([]);
|
||||
const { auth } = useAuth();
|
||||
const roleQuery = useRoleListQuery();
|
||||
const cmpnQuery = useCmpnListQuery();
|
||||
const usersQuery = useUsersQuery();
|
||||
|
||||
const checkDupMutation = useCheckUserIdDuplicateMutation();
|
||||
const upsertMutation = useUpsertUserMutation();
|
||||
const deleteMutation = useDeleteUserMutation();
|
||||
const uploadMutation = useUploadUsersExcelMutation();
|
||||
const downloadTemplateMutation = useDownloadUserExcelTemplateMutation();
|
||||
|
||||
const [editUserId, setEditUserId] = useState<string | null>(null);
|
||||
const userDetailQuery = useUserDetailQuery(editUserId ?? "", !!editUserId);
|
||||
|
||||
const userRoleArray: MultiSelectOption[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles.map((r) => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||
}, [roleQuery.data]);
|
||||
|
||||
const userCmpnArray = cmpnQuery.data ?? [];
|
||||
const userList = usersQuery.data ?? [];
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchCmpn, setSearchCmpn] = useState<string[]>([]);
|
||||
const [searchRole, setSearchRole] = useState<string[]>([]);
|
||||
|
||||
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create')
|
||||
const [editData, setEditData] = useState<Partial<UserInfoSaveRequest>>();
|
||||
|
||||
const setUserData = async () => {
|
||||
const roleList = await nextApi.get<RoleInfo[]>("/role");
|
||||
setUserRoleArray(
|
||||
roleList.map((role) => ({
|
||||
value: String(role.roleCd),
|
||||
label: role.roleNm,
|
||||
}))
|
||||
const viewList = useMemo(() => {
|
||||
let temp = userList;
|
||||
|
||||
const keyword = searchText.trim();
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
temp = temp.filter((row) =>
|
||||
[row.userId, row.userName].some((v) => (v ?? "").toLowerCase().includes(kw))
|
||||
);
|
||||
|
||||
const cmpnList = await nextApi.get<string[]>("/user/cmpn");
|
||||
setUserCmpnArray(cmpnList);
|
||||
|
||||
const userData = await nextApi.get<UserInfo[]>("/user");
|
||||
setUserList(userData);
|
||||
}
|
||||
|
||||
if (searchCmpn.length > 0) {
|
||||
temp = temp.filter((row) => searchCmpn.includes(row.userCmpn));
|
||||
}
|
||||
|
||||
if (searchRole.length > 0) {
|
||||
temp = temp.filter((row) => searchRole.includes(String(row.userRole)));
|
||||
}
|
||||
|
||||
return temp;
|
||||
}, [userList, searchText, searchCmpn, searchRole]);
|
||||
|
||||
// 등록 버튼 클릭
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode('create');
|
||||
setEditData(undefined);
|
||||
showDialog('userUpsertDialog');
|
||||
}
|
||||
setDialogMode("create");
|
||||
setEditUserId(null);
|
||||
showDialog("userUpsertDialog");
|
||||
};
|
||||
|
||||
// 중복 체크
|
||||
const handleCheckDuplicate = async (userId: string): Promise<DataVerification> => {
|
||||
return nextApi.get<DataVerification>("/user/check-user-id", {
|
||||
query: { userId },
|
||||
});
|
||||
}
|
||||
const handleCheckDuplicate = (userId: string) => {
|
||||
return checkDupMutation.mutateAsync(userId);
|
||||
};
|
||||
|
||||
|
||||
const handleSubmit = async (data: UserInfoSaveRequest): Promise<void> => {
|
||||
if (dialogMode === 'create') {
|
||||
await nextApi.put<void>("/user", data);
|
||||
await upsertMutation.mutateAsync({ mode: dialogMode, data });
|
||||
|
||||
if (dialogMode === "create") {
|
||||
alert("등록되었습니다.");
|
||||
} else {
|
||||
await nextApi.patch<void>("/user", data);
|
||||
}
|
||||
await setUserData();
|
||||
alert("수정되었습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (userId: string) => {
|
||||
setDialogMode('edit');
|
||||
nextApi.get<UserInfo>(`/user/${userId}`)
|
||||
.then((data) => {
|
||||
setEditData(data);
|
||||
showDialog('userUpsertDialog');
|
||||
})
|
||||
.catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
});
|
||||
// 수정 로직 또는 모달 열기
|
||||
}
|
||||
setDialogMode("edit");
|
||||
setEditUserId(userId);
|
||||
showDialog("userUpsertDialog");
|
||||
};
|
||||
|
||||
const handleDelete = (userId: string) => {
|
||||
// 삭제 확인 후 데이터 삭제
|
||||
if (confirm('정말 삭제하시겠습니까?')) {
|
||||
//삭제
|
||||
nextApi.del<void>(`/user/${encodeURIComponent(userId)}`)
|
||||
.then(async () => {
|
||||
alert("삭제 됐습니다.");
|
||||
await setUserData();
|
||||
})
|
||||
.catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
});
|
||||
}
|
||||
}
|
||||
const handleDelete = async (userId: string) => {
|
||||
if (!confirm("정말 삭제하시겠습니까?")) return;
|
||||
|
||||
await deleteMutation.mutateAsync(userId);
|
||||
alert("삭제되었습니다.");
|
||||
};
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file); // key 이름은 백엔드 @RequestPart("file") 와 동일해야 함
|
||||
|
||||
const res = await nextApi.postForm<UserUploadResponse>("/user/excel", formData);
|
||||
const res = await uploadMutation.mutateAsync(file);
|
||||
|
||||
if (res.hasErrorFile && res.errorFileBase64) {
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx");
|
||||
alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다.");
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE);
|
||||
}
|
||||
else{
|
||||
await setUserData();
|
||||
}
|
||||
alert(`${res.successCount}개의 계정이 생성되었습니다.`);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
const buffer = await nextApi.post<ArrayBuffer>(
|
||||
"/user/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
const buffer = await downloadTemplateMutation.mutateAsync();
|
||||
|
||||
if (buffer.byteLength > 0) {
|
||||
const blob = new Blob([buffer], {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
downloadFile(blob, "사용자 업로드 양식.xlsx");
|
||||
alert("다운로드 됐습니다.");
|
||||
downloadFile(blob, "사용자_업로드_양식.xlsx");
|
||||
alert("다운로드되었습니다.");
|
||||
} else {
|
||||
console.log("빈 파일입니다.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getUserColumns(
|
||||
{
|
||||
onEdit: handleEdit,
|
||||
onDelete: handleDelete
|
||||
},
|
||||
userRoleArray
|
||||
userRoleArray,
|
||||
userCmpnArray
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(setUserData);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let tempData = _.cloneDeep(userList);
|
||||
const keyword = searchText.trim();
|
||||
if (keyword){
|
||||
tempData = tempData.filter((row) =>
|
||||
[row.userId, row.userName].some((v) => v.toLowerCase().includes(keyword.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
if(searchCmpn.length > 0){
|
||||
tempData = tempData.filter((row) => searchCmpn.includes(row.userCmpn));
|
||||
}
|
||||
|
||||
if(searchRole.length > 0){
|
||||
tempData = tempData.filter((row) => searchRole.includes(String(row.userRole)));
|
||||
}
|
||||
|
||||
setViewList(tempData);
|
||||
}, [searchText, searchCmpn, searchRole, userList]);
|
||||
|
||||
const isInternal =
|
||||
mounted &&
|
||||
auth.user?.userRole != null &&
|
||||
auth.user.userRole < EXTERNAL_USER_ROLE
|
||||
isInternalManager(auth.user?.userRole)
|
||||
|
||||
const userCmpn = auth.user?.userCmpn ?? DEFAULT_COMPANY_NAME;
|
||||
// 로그인 계정의 소속 회사를 기본 선택하되, 회사 목록에 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다.
|
||||
const userCmpn = useMemo(() => {
|
||||
const currentCmpnId = auth.user?.userCmpn;
|
||||
const matched = userCmpnArray.find((c) => c.cmpnId === currentCmpnId);
|
||||
if (matched) return matched.cmpnId;
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />;
|
||||
const fallback = userCmpnArray.find((c) => c.ownCmpn);
|
||||
return fallback?.cmpnId ?? currentCmpnId ?? '';
|
||||
}, [auth.user?.userCmpn, userCmpnArray]);
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<BodyTitle titleText={"계정 관리"}/>
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"사용자 관리"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
placeholder="사용자 ID 또는 사용자 이름"
|
||||
className="w-70 h-9 bg-white"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
@@ -204,6 +189,8 @@ const UserManagePage = () => {
|
||||
items={userCmpnArray}
|
||||
value={searchCmpn}
|
||||
onChange={setSearchCmpn}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
placeholder="소속 회사"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
@@ -221,16 +208,16 @@ const UserManagePage = () => {
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
면접원 등록
|
||||
사용자 등록
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => showDialog('userUploadDialog')}
|
||||
className="gap-2 bg-green-600 hover:bg-green-700 content-text-lg"
|
||||
className="gap-2 bg-excel"
|
||||
>
|
||||
면접원 일괄 등록
|
||||
<Upload className="w-4 h-4" />
|
||||
사용자 일괄 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -239,17 +226,17 @@ const UserManagePage = () => {
|
||||
columns={columns}
|
||||
data={viewList}
|
||||
isClient={true}
|
||||
selectMode='single'
|
||||
onRowSelectionChange={setSelectedUserArray}
|
||||
selectMode='none'
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.userId} // row.id = userId
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UserUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={editData}
|
||||
initialData={dialogMode === "edit" ? (userDetailQuery.data ?? undefined) : undefined}
|
||||
isInternal={isInternal}
|
||||
userCmpn={userCmpn}
|
||||
userCmpnArray={userCmpnArray}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import {MessageType, TemplateEmail} from "@/types/messageTemplate";
|
||||
import { MessageType, TemplatePurpose, type TemplateEmail } from "@kri/common/noti-hub";
|
||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import type { TemplateWithPurpose } from "@/types/message";
|
||||
|
||||
const EmailTemplatePage = () => {
|
||||
|
||||
const defaultEmailTemplate : TemplateEmail = {
|
||||
const defaultEmailTemplate : TemplateWithPurpose & TemplateEmail = {
|
||||
tmplatIdx: undefined,
|
||||
itrntPrjctCd: '',
|
||||
tmplatTy: MessageType.EMAIL,
|
||||
tmplatPurpose: TemplatePurpose.NORMAL,
|
||||
tmplatNm: '',
|
||||
tmplatTitle: '',
|
||||
tmplatBody: '',
|
||||
@@ -16,7 +17,7 @@ const EmailTemplatePage = () => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<div className="space-y-6 text-sm">
|
||||
<MessageTemplate pageTitle={"이메일 템플릿 관리"} defaultTemplate={defaultEmailTemplate}/>
|
||||
</div>
|
||||
)
|
||||
|
||||
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,15 +1,16 @@
|
||||
'use client'
|
||||
|
||||
import {MessageType, TemplateSms} from "@/types/messageTemplate";
|
||||
import { MessageType, TemplatePurpose, type TemplateSms } from "@kri/common/noti-hub";
|
||||
import MessageTemplate from "@/components/message-template/MessageTemplate";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import type { TemplateWithPurpose } from "@/types/message";
|
||||
|
||||
const SmsTemplatePage = () => {
|
||||
|
||||
const defaultSmsTemplate : TemplateSms = {
|
||||
const defaultSmsTemplate : TemplateWithPurpose & TemplateSms = {
|
||||
tmplatIdx: undefined,
|
||||
itrntPrjctCd: '',
|
||||
tmplatTy: MessageType.SMS,
|
||||
tmplatPurpose: TemplatePurpose.NORMAL,
|
||||
tmplatNm: '',
|
||||
tmplatTitle: undefined,
|
||||
tmplatBody: '',
|
||||
@@ -18,7 +19,7 @@ const SmsTemplatePage = () => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<div className="space-y-6 text-sm">
|
||||
<MessageTemplate pageTitle="문자 템플릿 관리" defaultTemplate={defaultSmsTemplate}/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,61 +1,114 @@
|
||||
'use client'
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import {useMemo, useState} from "react";
|
||||
import {ChevronDown} from "lucide-react";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import {Badge} from "@/components/ui/badge";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {getProjectColumns} from "../../../components/table-column/ProjectTableColumn";
|
||||
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
|
||||
import {
|
||||
ProjectCreateRequest,
|
||||
ProjectInfo,
|
||||
ProjectListQuery,
|
||||
ProjectListRequest, ProjectOwnerResponse,
|
||||
ProjectStatus
|
||||
} from "@/types/project";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import {PaginationState, SortingState} from "@tanstack/react-table";
|
||||
import {PageRequest, PageResponse} from "@/types/common";
|
||||
import ProjectCreateDialog from "@/components/dialog/ProjectCreateDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {FW_USER_ROLE} from "@/const/userConst";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {useRouter} from "next/navigation";
|
||||
import type {Route} from "next";
|
||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||
import {useGroupCodeListQuery} from "@/query/intranet";
|
||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||
import {isInternalManager, isManager} from "@/utils/userRole";
|
||||
|
||||
const MainPage = () => {
|
||||
const router = useRouter();
|
||||
|
||||
const mounted = useMounted();
|
||||
const { users, isLoading } = useItrntUserList();
|
||||
const { showDialog } = useDialog();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { clearSelectedProject, setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [statusArray, setStatusArray] = useState<MultiSelectOption[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [fwArray, setFwArray] = useState<string[]>([]);
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||
const { setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [query, setQuery] = useState<ProjectListQuery>();
|
||||
|
||||
const [viewList, setViewList] = useState<ProjectInfo[]>([]);
|
||||
const [pageCount, setPageCount] = useState(0);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
const statusArray: MultiSelectOption[] = useMemo(() => {
|
||||
return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
|
||||
.sort((a, b) => a - b)
|
||||
.map((v) => ({
|
||||
value: String(v),
|
||||
label: PROJECT_STATUS_LABEL[v as ProjectStatus],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const enabled = mounted && !isLoading; // intranet user list 준비된 뒤에만 호출
|
||||
const ownerQuery = useProjectOwnerListQuery(enabled);
|
||||
const groupCodeListQuery = useGroupCodeListQuery(enabled);
|
||||
|
||||
const groupCodeLabelMap = useMemo(() => {
|
||||
return new Map((groupCodeListQuery.data ?? []).map((g) => [g.groupCode, g.groupCodeLabel]));
|
||||
}, [groupCodeListQuery.data]);
|
||||
|
||||
const deptArray = useMemo(() => {
|
||||
const ownerDeptList = ownerQuery.data?.ownerDeptList ?? [];
|
||||
|
||||
return ownerDeptList.map((code) => ({
|
||||
value: code,
|
||||
label: groupCodeLabelMap.get(code) ?? code,
|
||||
}));
|
||||
}, [ownerQuery.data?.ownerDeptList, groupCodeLabelMap]);
|
||||
|
||||
const fwArray = useMemo(() => {
|
||||
const ownerFwIDList = ownerQuery.data?.ownerFwList ?? [];
|
||||
|
||||
return ownerFwIDList.map((fwID) => ({
|
||||
value: fwID,
|
||||
label: users.find(u => u.userId === fwID)?.userNm ?? "",
|
||||
}));
|
||||
|
||||
}, [ownerQuery.data?.ownerFwList]);
|
||||
|
||||
const sort = sorting?.[0] ?? { id: "prjctIdx", desc: true as const };
|
||||
|
||||
const listQuery = useProjectListQuery({
|
||||
query,
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc",
|
||||
enabled,
|
||||
});
|
||||
|
||||
const viewList = listQuery.data?.content ?? [];
|
||||
const totalCount = listQuery.data?.totalElements ?? 0;
|
||||
const pageCount = listQuery.data?.totalPages ?? 0;
|
||||
|
||||
const createMutation = useCreateProjectMutation?.();
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||
const [searchDept, setSearchDept] = 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 columns = getProjectColumns(users);
|
||||
const userId = auth.user?.userId ?? "";
|
||||
const userRole = auth.user?.userRole ?? FW_USER_ROLE;
|
||||
const userRole = auth.user?.userRole;
|
||||
const isInternal = isInternalManager(userRole);
|
||||
|
||||
const handleSearchClick = () => {
|
||||
const searchStatusCode:ProjectStatus[] = searchStatus
|
||||
@@ -76,8 +129,7 @@ const MainPage = () => {
|
||||
showDialog('projectCreateDialog');
|
||||
}
|
||||
|
||||
const handleSubmit = async (data:ProjectCreateRequest): Promise<void> => {
|
||||
const projectInfo = await nextApi.put<ProjectInfo>("/project", data);
|
||||
const navigateWithProject = (projectInfo: ProjectInfo, path: Route) => {
|
||||
setSelectedProject({
|
||||
prjctIdx: projectInfo.prjctIdx,
|
||||
prjctCd: projectInfo.prjctCd,
|
||||
@@ -85,91 +137,35 @@ const MainPage = () => {
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
ownerDept: projectInfo.ownerDept,
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
ff: projectInfo.ff
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/project/info`;
|
||||
}
|
||||
|
||||
const handleClick = (projectInfo:ProjectInfo) => {
|
||||
setSelectedProject({
|
||||
prjctIdx: projectInfo.prjctIdx,
|
||||
prjctCd: projectInfo.prjctCd,
|
||||
prjctName: projectInfo.prjctName,
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
ownerDept: projectInfo.ownerDept,
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/list/manage`;
|
||||
}
|
||||
|
||||
// 중복 호출 방지(초기 mount에서 pagination/sorting 콜백이 각각 한번씩 날아오는 케이스 방어)
|
||||
const lastReqKeyRef = useRef<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
const reqKey = JSON.stringify({ query, pagination, sorting});
|
||||
if (lastReqKeyRef.current === reqKey) return;
|
||||
lastReqKeyRef.current = reqKey;
|
||||
|
||||
const sort = sorting?.[0] ?? {id: "prjctIdx", desc: true};
|
||||
const pageReq: PageRequest = {
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc"
|
||||
router.push(path);
|
||||
};
|
||||
|
||||
const searchBody: ProjectListRequest = {
|
||||
prjctText: query?.prjctText || "",
|
||||
prjctStatusList: query?.prjctStatusList || [],
|
||||
ownerDeptList: query?.ownerDeptList || [],
|
||||
ownerFwList: query?.ownerFwList || [],
|
||||
pageRequest: pageReq,
|
||||
}
|
||||
const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => {
|
||||
const projectInfo = await createMutation.mutateAsync(data);
|
||||
navigateWithProject(projectInfo, "/project/info");
|
||||
};
|
||||
|
||||
withLoadingAsync(() =>
|
||||
nextApi.post<PageResponse<ProjectInfo>>("/project/list", searchBody)
|
||||
.then((r) => {
|
||||
setViewList(r.content);
|
||||
setTotalCount(r.totalElements);
|
||||
setPageCount(r.totalPages);
|
||||
})
|
||||
.catch(() => {
|
||||
setViewList([]);
|
||||
setTotalCount(0);
|
||||
setPageCount(0);
|
||||
})
|
||||
);
|
||||
const handleClick = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/list/manage");
|
||||
|
||||
}, [query, pagination, sorting]);
|
||||
const handleNavigateToInfo = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/project/info");
|
||||
|
||||
useEffect(() => {
|
||||
clearSelectedProject();
|
||||
const columns = getProjectColumns(users, groupCodeLabelMap, isInternal ? handleNavigateToInfo : undefined);
|
||||
|
||||
const options: MultiSelectOption[] = Object.entries(ProjectStatus)
|
||||
.sort(([a], [b]) => Number(a) - Number(b))
|
||||
.map(([key, label]) => ({ value: key, label: String(label) }));
|
||||
|
||||
setStatusArray(options);
|
||||
|
||||
nextApi.get<ProjectOwnerResponse>("/project/owner-list")
|
||||
.then((res) => {
|
||||
setDeptArray(res.ownerDeptList);
|
||||
setFwArray(res.ownerFwList);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!mounted || isLoading) return <LoadingOverlay force />;
|
||||
if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<BodyTitle titleText={"프로젝트"}/>
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText={"프로젝트"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<div className="flex flex-col gap-2 md:flex-row md:flex-wrap md:items-center">
|
||||
<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
|
||||
placeholder="프로젝트 코드 Or 프로젝트 명"
|
||||
className="w-120 h-9 bg-white"
|
||||
className="h-9 flex-1 bg-white md:w-120 md:flex-none"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
@@ -178,8 +174,36 @@ 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",
|
||||
)}
|
||||
>
|
||||
{
|
||||
userRole < FW_USER_ROLE &&
|
||||
isManager(userRole) &&
|
||||
<KriMultiSelect
|
||||
items={statusArray}
|
||||
value={searchStatus}
|
||||
@@ -187,7 +211,7 @@ const MainPage = () => {
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="진행 상태"
|
||||
widthClassName="w-60"
|
||||
widthClassName="w-full md:w-60"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
}
|
||||
@@ -195,31 +219,38 @@ const MainPage = () => {
|
||||
items={deptArray}
|
||||
value={searchDept}
|
||||
onChange={setSearchDept}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 그룹"
|
||||
widthClassName="w-60"
|
||||
widthClassName="w-full md:w-60"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
<KriMultiSelect
|
||||
items={fwArray}
|
||||
value={searchFw}
|
||||
onChange={setSearchFw}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 실사"
|
||||
widthClassName="w-60"
|
||||
widthClassName="w-full md:w-60"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
className="hidden md:inline-flex"
|
||||
onClick={handleSearchClick}
|
||||
>
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
{isInternal && (
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
className="w-full md:w-auto"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
프로젝트 등록
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
@@ -229,12 +260,14 @@ const MainPage = () => {
|
||||
isClient={false}
|
||||
pageCount={pageCount}
|
||||
totalCount={totalCount}
|
||||
pagination={pagination}
|
||||
onPaginationChange={setPagination}
|
||||
onSortingChange={setSorting}
|
||||
selectMode='click-event'
|
||||
onRowClick={handleClick}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.prjctCd} // row.id = userId
|
||||
maxBodyHeight="71vh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
const ContactProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is Contact Progress Page</div>)
|
||||
}
|
||||
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
|
||||
import { ProgressEventType } from "@/types/progress";
|
||||
import { ResultCodeType } from "@/types/project";
|
||||
|
||||
const ContactProgressPage = () => (
|
||||
<ProgressPageContent
|
||||
eventTy={ProgressEventType.CONTACT}
|
||||
resultCdTy={ResultCodeType.CONTACT}
|
||||
pageTitle="컨택 현황"
|
||||
domainLabel="컨택"
|
||||
personLabel="컨택인력"
|
||||
/>
|
||||
);
|
||||
|
||||
export default ContactProgressPage;
|
||||
@@ -1,8 +0,0 @@
|
||||
const FieldworkProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
|
||||
return (<div>This is Fieldwork Progress Page</div>)
|
||||
}
|
||||
|
||||
export default FieldworkProgressPage;
|
||||
17
src/app/(pages)/(main)/progress/interview/page.tsx
Normal file
17
src/app/(pages)/(main)/progress/interview/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
|
||||
import { ProgressEventType } from "@/types/progress";
|
||||
import { ResultCodeType } from "@/types/project";
|
||||
|
||||
const InterviewProgressPage = () => (
|
||||
<ProgressPageContent
|
||||
eventTy={ProgressEventType.INTERVIEW}
|
||||
resultCdTy={ResultCodeType.INTERVIEW}
|
||||
pageTitle="면접 현황"
|
||||
domainLabel="면접"
|
||||
personLabel="면접원"
|
||||
/>
|
||||
);
|
||||
|
||||
export default InterviewProgressPage;
|
||||
@@ -1,8 +1,146 @@
|
||||
const MessageProgressPage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
|
||||
return (<div>This is Message Progress Page</div>)
|
||||
}
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import KriDateRangePicker from "@/components/common/KriDateRangePicker";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useSendResultSummaryQuery } from "@/query/message";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { MessageType } from "@kri/common/noti-hub";
|
||||
import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
|
||||
|
||||
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS, MessageType.MMS, MessageType.EMAIL, MessageType.KKO] as const;
|
||||
|
||||
const SEND_TYPE_LABEL: Record<number, string> = {
|
||||
[MessageType.SMS]: "단문",
|
||||
[MessageType.LMS]: "장문",
|
||||
[MessageType.MMS]: "첨부 문자",
|
||||
[MessageType.EMAIL]: "메일",
|
||||
[MessageType.KKO]: "알림톡",
|
||||
};
|
||||
|
||||
type SummaryRow = {
|
||||
sendTy: number;
|
||||
price: number;
|
||||
totalCount: number;
|
||||
cost: number;
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
standByCount: number;
|
||||
canceledCount: number;
|
||||
};
|
||||
|
||||
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
|
||||
list.reduce((acc, item) => acc + (item[field] as number | undefined ?? 0), 0);
|
||||
|
||||
const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
|
||||
SEND_TYPE_ORDER.map((sendTy) => {
|
||||
const matched = data.filter((item) => item.sendTy === sendTy);
|
||||
return {
|
||||
sendTy,
|
||||
price: matched[0]?.price ?? 0,
|
||||
totalCount: sum(matched, "totalCount"),
|
||||
cost: sum(matched, "cost"),
|
||||
successCount: sum(matched, "successCount"),
|
||||
failCount: sum(matched, "failCount"),
|
||||
standByCount: sum(matched, "standByCount"),
|
||||
canceledCount: sum(matched, "canceledCount"),
|
||||
};
|
||||
});
|
||||
|
||||
const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
|
||||
const caseUnit = (value: number) => `${value.toLocaleString()}건`;
|
||||
|
||||
const MessageProgressPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const [dateRange, setDateRange] = useState({ from: "", to: "" });
|
||||
|
||||
const prjctCd = selectedProject?.prjctCd ?? "";
|
||||
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
|
||||
const enabled = mounted && !!prjctCd;
|
||||
|
||||
const summaryQuery = useSendResultSummaryQuery(
|
||||
{
|
||||
reqstSvc: clientEnv.REQUEST_SVC,
|
||||
itrntPrjctCd,
|
||||
prjctCd,
|
||||
sendStartDt: dateRange.from ? `${dateRange.from}T00:00:00` : undefined,
|
||||
sendEndDt: dateRange.to ? `${dateRange.to}T23:59:59` : undefined,
|
||||
},
|
||||
enabled,
|
||||
);
|
||||
|
||||
const rows = useMemo(() => buildRows(summaryQuery.data ?? []), [summaryQuery.data]);
|
||||
|
||||
const total = useMemo(
|
||||
() => ({
|
||||
totalCount: rows.reduce((acc, row) => acc + row.totalCount, 0),
|
||||
cost: rows.reduce((acc, row) => acc + row.cost, 0),
|
||||
successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
|
||||
failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
|
||||
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
|
||||
canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0),
|
||||
}),
|
||||
[rows],
|
||||
);
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="발송 현황" />
|
||||
|
||||
<KriDateRangePicker value={dateRange} onChange={setDateRange} className="w-80" />
|
||||
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-primary text-primary-foreground">
|
||||
<tr>
|
||||
<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>
|
||||
<th className="h-10 px-3 text-center font-semibold border-b">취소</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.sendTy} className="border-b last:border-b-0">
|
||||
<td className="h-10 px-3 text-center">{SEND_TYPE_LABEL[row.sendTy]}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(row.price)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.totalCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(row.cost)}</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.standByCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(row.canceledCount)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr className="bg-gray-50 font-semibold">
|
||||
<td className="h-10 px-3 text-center" colSpan={2}>합계</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.totalCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{moneyUnit(total.cost)}</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.standByCount)}</td>
|
||||
<td className="h-10 px-3 text-center">{caseUnit(total.canceledCount)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
※ 보낸 내역을 토대로 계산된 값으로 실제 정산 금액과 차이가 발생할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MessageProgressPage;
|
||||
72
src/app/(pages)/(main)/progress/survey/page.tsx
Normal file
72
src/app/(pages)/(main)/progress/survey/page.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
'use client'
|
||||
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useProjectInfoQuery } from "@/query/project";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { SurveyType } from "@/types/project";
|
||||
import { SURVEY_TYPE_LABEL } from "@/const/projectConst";
|
||||
|
||||
const SurveyProgressPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||
const surveys = projectInfoQuery.data?.surveys ?? [];
|
||||
|
||||
const isLoading = !mounted || projectInfoQuery.isLoading;
|
||||
|
||||
if (isLoading) return <LoadingOverlayAdapter force />;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="설문 현황" />
|
||||
|
||||
{surveys.length === 0 ? (
|
||||
<p className="text-muted-foreground">연결된 설문이 없습니다.</p>
|
||||
) : (
|
||||
<div className="max-w-[600px] space-y-2">
|
||||
{surveys.map((survey) => {
|
||||
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 (
|
||||
<div
|
||||
key={survey.prjctSurveyIdx ?? survey.surveyOrder}
|
||||
className="flex items-center justify-between rounded-lg border bg-white p-4"
|
||||
>
|
||||
<div>
|
||||
<p className="font-semibold">{survey.surveyName}</p>
|
||||
<p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p>
|
||||
</div>
|
||||
{targetUrl ? (
|
||||
<Button asChild>
|
||||
<a href={targetUrl} target="_blank" rel="noopener noreferrer">
|
||||
바로가기
|
||||
</a>
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" disabled>바로가기</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SurveyProgressPage;
|
||||
@@ -1,498 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import {useCallback, useEffect, useMemo, useState} from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import {ProjectInfo} from "@/types/project";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {UserInfo} from "@/types/user";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {CONTACT_USER_ROLE, FW_USER_ROLE} from "@/const/userConst";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import _ from "lodash";
|
||||
|
||||
const ProjectAssignPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const [projectArray, setProjectArray] = useState<ProjectInfo[]>([]);
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const [sourceProject, setSourceProject] = useState<ProjectInfo>();
|
||||
|
||||
const [companyArray, setCompanyArray] = useState<string[]>([]);
|
||||
const [companyFilter, setCompanyFilter] = useState<string>('');
|
||||
const [roleArray, setRoleArray] = useState<KriSelectItem[]>([]);
|
||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem>();
|
||||
const [fwUserArray, setFwUserArray] = useState<UserInfo[]>([]);
|
||||
|
||||
const [originAssign, setOriginAssign] = useState<UserInfo[]>([]);
|
||||
const [assignUserArray, setAssignUserArray] = useState<UserInfo[]>([]);
|
||||
const [selectedAssignUser, setSelectedAssignUser] = useState<string[]>([]);
|
||||
const [searchAssign, setSearchAssign] = useState('');
|
||||
const debouncedAssign = useDebouncedValue(searchAssign, 500);
|
||||
|
||||
const [assignInfoString, setAssignInfoString] = useState<string>('');
|
||||
|
||||
const [ableUserArray, setAbleUserArray] = useState<UserInfo[]>([]);
|
||||
const [selectedAbleUser, setSelectedAbleUser] = useState<string[]>([]);
|
||||
const [searchAble, setSearchAble] = useState('');
|
||||
const debouncedAble = useDebouncedValue(searchAble, 500);
|
||||
|
||||
const searchTopProject = async (keyword: string) => {
|
||||
const res = await nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${PROJECT_SEARCH_COUNT}`,
|
||||
{ query: { keyword } }
|
||||
);
|
||||
|
||||
setProjectArray(res);
|
||||
};
|
||||
|
||||
const handleSelectProject = (info:ProjectInfo|null) => {
|
||||
if(info === null){
|
||||
setSourceProject(undefined)
|
||||
}
|
||||
else{
|
||||
setSourceProject(info);
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectAllLeft = (checked: boolean) => {
|
||||
if (checked) {
|
||||
setSelectedAssignUser(assignUserArray.map(u => u.userId))
|
||||
} else {
|
||||
setSelectedAssignUser([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectAllRight = (checked: boolean) => {
|
||||
if (checked) {
|
||||
setSelectedAbleUser(ableUserArray.map(u => u.userId))
|
||||
} else {
|
||||
setSelectedAbleUser([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleUnassign = (id: string) => {
|
||||
setSelectedAssignUser(prev =>
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id]
|
||||
)
|
||||
}
|
||||
|
||||
const handleToggleAssign = (id: string) => {
|
||||
setSelectedAbleUser(prev =>
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id]
|
||||
)
|
||||
}
|
||||
|
||||
const appendUserInfo = (
|
||||
userIdArray:string[],
|
||||
sourceArray:UserInfo[]
|
||||
) => {
|
||||
return sourceArray.filter(user => userIdArray.includes(user.userId));
|
||||
}
|
||||
|
||||
const resetSelect = () => {
|
||||
setSelectedAssignUser([]);
|
||||
setSelectedAbleUser([]);
|
||||
|
||||
//검색도 초기화
|
||||
setSearchAssign('');
|
||||
setSearchAble('');
|
||||
}
|
||||
|
||||
const resetSelectAndAssign = () => {
|
||||
resetSelect();
|
||||
setAssignUserArray(_.cloneDeep(originAssign));
|
||||
};
|
||||
|
||||
const handleCompanyChange = (v: string) => {
|
||||
resetSelectAndAssign();
|
||||
setCompanyFilter(v);
|
||||
// 필요하면 데이터도 같이 재조회/재계산 트리거
|
||||
};
|
||||
|
||||
const handleRoleChange = (item: KriSelectItem) => {
|
||||
resetSelectAndAssign();
|
||||
setRoleFilter(item);
|
||||
};
|
||||
|
||||
const handleAssign = () => {
|
||||
const toAssign = ableUserArray.filter(u => selectedAbleUser.includes(u.userId));
|
||||
setAssignUserArray(prev => [...prev, ...toAssign]);
|
||||
|
||||
setSelectedAbleUser([]);
|
||||
}
|
||||
|
||||
const handleRemove = () => {
|
||||
const toRemove = assignUserArray.filter(u => selectedAssignUser.includes(u.userId));
|
||||
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
|
||||
|
||||
setSelectedAssignUser([]);
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if(selectedProject){
|
||||
await nextApi.put(
|
||||
`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`,
|
||||
assignUserArray.map(u => u.userId)
|
||||
)
|
||||
|
||||
setOriginAssign(_.cloneDeep(assignUserArray));
|
||||
|
||||
alert("저장되었습니다.");
|
||||
}
|
||||
else{
|
||||
alert("옳지 않은 요청입니다.");
|
||||
}
|
||||
}
|
||||
|
||||
const baseFiltered = useCallback((users: UserInfo[]) => {
|
||||
return users.filter(
|
||||
(u) =>
|
||||
String(u.userRole) === roleFilter?.value &&
|
||||
u.userCmpn === companyFilter
|
||||
);
|
||||
}, [roleFilter, companyFilter]);
|
||||
|
||||
const withKeyword = useCallback((users: UserInfo[], keyword: string) => {
|
||||
const k = keyword.trim();
|
||||
if (!k) return users;
|
||||
|
||||
return users.filter(
|
||||
(u) => u.userId.includes(k) || u.userName.includes(k)
|
||||
);
|
||||
}, []);
|
||||
|
||||
const assignBase = useMemo(
|
||||
() => baseFiltered(assignUserArray),
|
||||
[assignUserArray, baseFiltered]
|
||||
);
|
||||
|
||||
const assignView = useMemo(
|
||||
() => withKeyword(assignBase, debouncedAssign),
|
||||
[assignBase, debouncedAssign, withKeyword]
|
||||
);
|
||||
|
||||
const assignedIdSet = useMemo(
|
||||
() => new Set(assignUserArray.map(u => u.userId)),
|
||||
[assignUserArray]
|
||||
);
|
||||
|
||||
const ableBase = useMemo(
|
||||
() => baseFiltered(ableUserArray)
|
||||
.filter((user) => !assignedIdSet.has(user.userId)),
|
||||
[ableUserArray, baseFiltered, assignedIdSet]
|
||||
);
|
||||
|
||||
const ableView = useMemo(
|
||||
() => withKeyword(ableBase, debouncedAble)
|
||||
.filter((user) => !assignedIdSet.has(user.userId)),
|
||||
[ableBase, debouncedAble, withKeyword, assignedIdSet]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchTopProject(keyword);
|
||||
}
|
||||
}, [debouncedKeyword]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
nextApi.get<UserInfo[]>("/user/fieldwork")
|
||||
.then(res => setFwUserArray(res));
|
||||
|
||||
nextApi.get<string[]>("/user/cmpn")
|
||||
.then((res) => setCompanyArray(res));
|
||||
|
||||
const roleList = await nextApi.get<RoleInfo[]>("/role")
|
||||
const roleOptionArray = roleList
|
||||
.filter(role => role.roleCd >= FW_USER_ROLE)
|
||||
.map((role) => ({
|
||||
value: String(role.roleCd),
|
||||
label: role.roleNm,
|
||||
}))
|
||||
setRoleArray(roleOptionArray);
|
||||
const contactRole = roleOptionArray.find((role) => role.value === CONTACT_USER_ROLE.toString());
|
||||
if(contactRole){
|
||||
setRoleFilter(contactRole);
|
||||
}
|
||||
})
|
||||
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
setCompanyFilter(auth.user.userCmpn || "")
|
||||
}
|
||||
}, [auth.user]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
if(selectedProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`);
|
||||
const assignUserInfoArray = appendUserInfo(res, fwUserArray);
|
||||
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(assignUserInfoArray);
|
||||
}else{
|
||||
setAssignUserArray([]);
|
||||
setOriginAssign([]);
|
||||
}
|
||||
resetSelect();
|
||||
});
|
||||
}, [fwUserArray, selectedProject, roleArray]);
|
||||
|
||||
useEffect(() => {
|
||||
const assignString = roleArray.map((role) => {
|
||||
const assignCount = originAssign.filter(user => user.userRole.toString() === role.value).length
|
||||
return `${role.label} : ${assignCount}`;
|
||||
}).join(' / ');
|
||||
|
||||
setAssignInfoString(assignString);
|
||||
}, [originAssign]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
let ableUserList :UserInfo[] = [];
|
||||
|
||||
if(sourceProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${sourceProject.prjctIdx}`);
|
||||
ableUserList = appendUserInfo(res, fwUserArray);
|
||||
}
|
||||
else{
|
||||
ableUserList = _.cloneDeep(fwUserArray);
|
||||
}
|
||||
|
||||
setAbleUserArray(ableUserList);
|
||||
});
|
||||
}, [fwUserArray, sourceProject]);
|
||||
|
||||
if (!mounted || !selectedProject) return null
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-1">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* 공용 필터 바 (회사 / 대상) */}
|
||||
<div className="mb-6 rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
|
||||
회사
|
||||
</div>
|
||||
<KriSelect
|
||||
items={companyArray}
|
||||
value={companyFilter}
|
||||
onChange={handleCompanyChange}
|
||||
placeholder="회사 선택"
|
||||
className="w-56 h-9"
|
||||
useAll={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
|
||||
대상
|
||||
</div>
|
||||
<KriSelect
|
||||
items={roleArray}
|
||||
value={roleFilter?.value || ""}
|
||||
onChangeOption={handleRoleChange}
|
||||
placeholder="대상 선택"
|
||||
className="w-56 h-9"
|
||||
useAll={false}
|
||||
getValue={(x) => x.value}
|
||||
getLabel={(x) => x.label}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 메인 배정 영역 */}
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-6 mb-6">
|
||||
{/* 왼쪽: 배정된 면접원 */}
|
||||
<div className="min-w-0">
|
||||
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15 flex items-center">
|
||||
<span className="truncate w-full">
|
||||
{assignInfoString}
|
||||
</span>
|
||||
</div>
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="bg-gray-50 p-3 border-b border-gray-200">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
value={searchAssign}
|
||||
onChange={(e) => setSearchAssign(e.target.value)}
|
||||
className="bg-white border-gray-300"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-[600px] overflow-y-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-black text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-3 text-left w-12">
|
||||
<Checkbox
|
||||
checked={selectedAssignUser.length === assignView.length && assignView.length > 0}
|
||||
onCheckedChange={handleSelectAllLeft}
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정된 {roleFilter?.label} ( {assignBase.length}명 )</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{assignView
|
||||
.map((userInfo) => (
|
||||
<tr
|
||||
key={userInfo.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedAssignUser.includes(userInfo.userId) ? 'bg-blue-50' : ''
|
||||
}`}
|
||||
onClick={() => handleToggleUnassign(userInfo.userId)}
|
||||
>
|
||||
<td className="p-3">
|
||||
<Checkbox
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
checked={selectedAssignUser.includes(userInfo.userId)}
|
||||
onCheckedChange={() => handleToggleUnassign(userInfo.userId)}
|
||||
/>
|
||||
</td>
|
||||
<td className="p-3 content-text-base">
|
||||
{userInfo.userName} ({userInfo.userId})
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 가운데: 배정/제외 버튼 */}
|
||||
<div className="flex flex-col justify-center gap-4">
|
||||
<Button
|
||||
onClick={handleAssign}
|
||||
disabled={selectedAbleUser.length === 0}
|
||||
className="bg-black hover:bg-gray-800 w-36 h-12 flex items-center justify-center content-text-base disabled:bg-gray-300"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
<span className="ml-2">배정 {selectedAbleUser.length}명</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleRemove}
|
||||
disabled={selectedAssignUser.length === 0}
|
||||
className="bg-red-600 hover:bg-red-700 w-36 h-12 flex items-center justify-center content-text-base disabled:bg-gray-300"
|
||||
>
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
<span className="ml-2">제외 {selectedAssignUser.length}명</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 오른쪽: 전체 면접원 풀 */}
|
||||
<div className="min-w-0">
|
||||
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15">
|
||||
<KriSingleSelect
|
||||
<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(sourceProject?.prjctIdx ?? "")}
|
||||
onChange={() => {}}
|
||||
withInfo
|
||||
onItemChange={handleSelectProject}
|
||||
searchMode="inputOnly"
|
||||
onSearchValueChange={setSearchKeyword}
|
||||
placeholder="프로젝트 검색..."
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
preventDeselect
|
||||
hideOptionCheck
|
||||
useClear
|
||||
getLabel={(item) => `${item.prjctCd}_${item.prjctName}`}
|
||||
getValue={(item) => String(item.prjctIdx)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="bg-gray-50 p-3 border-b border-gray-200">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
value={searchAble}
|
||||
onChange={(e) => setSearchAble(e.target.value)}
|
||||
className="bg-white border-gray-300"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-[600px] overflow-y-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-black text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-3 text-left w-12">
|
||||
<Checkbox
|
||||
checked={selectedAbleUser.length === ableView.length && ableView.length > 0}
|
||||
onCheckedChange={handleSelectAllRight}
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정 가능 {roleFilter?.label} ({ableBase.length}명 )</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ableView
|
||||
.map((user) => (
|
||||
<tr
|
||||
key={user.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedAbleUser.includes(user.userId) ? 'bg-blue-50' : ''
|
||||
}`}
|
||||
onClick={() => handleToggleAssign(user.userId)}
|
||||
>
|
||||
<td className="p-3">
|
||||
<Checkbox
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
checked={selectedAbleUser.includes(user.userId)}
|
||||
onCheckedChange={() => handleToggleAssign(user.userId)}
|
||||
/>
|
||||
</td>
|
||||
<td className="p-3 content-text-base">
|
||||
{user.userName} ({user.userId})
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 하단 저장 버튼 */}
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className="bg-black hover:bg-gray-800 px-12 h-11 content-text-base font-medium"
|
||||
>
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProjectAssignPage;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,103 +1,57 @@
|
||||
"use client";
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Card, CardContent, CardHeader} from "@/components/ui/card";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import {useSearchParams} from "next/navigation";
|
||||
import {LoginUser} from "@/types/auth";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useLoading } from "@/hooks/useLoading";
|
||||
import { useStorage } from "@/hooks/useStorage"
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {NONE_HTTP_ERROR} from "@/const/commonConst";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {apiError} from "@kri/common/http";
|
||||
import {NONE_HTTP_ERROR} from "@kri/common/http";
|
||||
import {useLoginMutation} from "@/query/auth";
|
||||
import {useInternalInfoQuery} from "@/query/internal";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
const LoginPage = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const { auth, setFromLoginResponse } = useAuth();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
const router = useRouter();
|
||||
|
||||
const loginMutation = useLoginMutation();
|
||||
const internalInfoQuery = useInternalInfoQuery(true);
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [userId, setUserId] = useState<string>("");
|
||||
const [userPw, setUserPw] = useState<string>("");
|
||||
const [seatNum, setSeatNum] = useState<string>(getSeatNumberStorage());
|
||||
const [loginType, setLoginType] = useState<string>(getLoginTypeStorage());
|
||||
|
||||
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 seatNumberInputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const tryLogin = () => {
|
||||
if(!userId){
|
||||
alert("아이디를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
if(!userPw){
|
||||
alert("PW를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
if(loginType === "call" && !seatNum){
|
||||
alert("자리번호를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
const tryLogin = async () => {
|
||||
if (!userId) return alert("아이디를 입력해주세요.");
|
||||
if (!userPw) return alert("비밀번호를 입력해주세요.");
|
||||
|
||||
setError(null);
|
||||
const loginRequestBody = {userId, userPw};
|
||||
const loginRequestOptions = {autoLogoutOnAuthError: false};
|
||||
|
||||
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
|
||||
return withLoadingAsync(() =>
|
||||
nextApi.post<LoginUser>(
|
||||
"/login", loginRequestBody, loginRequestOptions
|
||||
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
|
||||
try {
|
||||
setSeatNumberStorage(seatNum);
|
||||
setLoginTypeStorage(loginType);
|
||||
await loginMutation.mutateAsync({ userId, userPw });
|
||||
} catch (e) {
|
||||
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
|
||||
console.warn("Failed to persist SeatNumber to secure storage:", e);
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "로그인에 실패했습니다.",
|
||||
});
|
||||
if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
else setError(`로그인에 실패했습니다. (${err.message})`);
|
||||
}
|
||||
|
||||
setFromLoginResponse(data, seatNum);
|
||||
}).catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
}
|
||||
else if(err.code === NONE_HTTP_ERROR) {
|
||||
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
}
|
||||
else {
|
||||
setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
window.location.replace("/");
|
||||
if (loginMutation.isSuccess) {
|
||||
router.replace("/");
|
||||
}
|
||||
}, [auth.user]);
|
||||
|
||||
// URL 쿼리 파라미터에서 type 수신
|
||||
useEffect(() => {
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
let seatNumTemp = "";
|
||||
|
||||
if(typeParam === "call") {
|
||||
seatNumTemp = getSeatNumberStorage();
|
||||
}
|
||||
setSeatNum(seatNumTemp);
|
||||
setLoginType(typeParam);
|
||||
}, [searchParams]);
|
||||
}, [loginMutation.isSuccess, router]);
|
||||
|
||||
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
@@ -107,19 +61,6 @@ const LoginPage = () => {
|
||||
};
|
||||
|
||||
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
const seatNumberInput = seatNumberInputRef.current;
|
||||
if(loginType === "call" && seatNumberInput?.value === ""){
|
||||
seatNumberInput.focus();
|
||||
}
|
||||
else{
|
||||
tryLogin();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSeatNumberKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
tryLogin();
|
||||
@@ -135,7 +76,7 @@ const LoginPage = () => {
|
||||
<Image
|
||||
src="/kri_logo.png" // public/kri_logo.png
|
||||
alt="KRI 로고"
|
||||
width={500} // 원하는 크기로 줄이기
|
||||
width={500}
|
||||
height={500}
|
||||
className="object-contain ml-10"
|
||||
priority
|
||||
@@ -146,13 +87,13 @@ const LoginPage = () => {
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">ID</label>
|
||||
<label className="text-base font-medium">ID</label>
|
||||
<Input
|
||||
id="id"
|
||||
name="id"
|
||||
type="text"
|
||||
required
|
||||
placeholder="아이디를 입력하세요"
|
||||
placeholder="ID"
|
||||
value={userId}
|
||||
onChange={(e) => setUserId(e.currentTarget.value)}
|
||||
onKeyDown={handleIdKeyDown}
|
||||
@@ -160,39 +101,26 @@ const LoginPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Password</label>
|
||||
<label className="text-base font-medium">Password</label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
placeholder="PW를 입력하세요"
|
||||
placeholder="Password"
|
||||
value={userPw}
|
||||
onChange={(e) => setUserPw(e.currentTarget.value)}
|
||||
onKeyDown={handlePwKeyDown}
|
||||
ref={passwordInputRef}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{loginType === "call"?
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">자리번호 (면접원)</label>
|
||||
<Input
|
||||
id="seatNum"
|
||||
name="seatNum"
|
||||
type="text"
|
||||
placeholder="자리번호를 입력하세요"
|
||||
value={seatNum}
|
||||
onChange={(e) => setSeatNum(e.currentTarget.value)}
|
||||
onKeyDown={handleSeatNumberKeyDown}
|
||||
ref={seatNumberInputRef}
|
||||
/>
|
||||
</div>
|
||||
:
|
||||
null
|
||||
}
|
||||
|
||||
<p className="text-base">
|
||||
IP: {clientIp}
|
||||
</p>
|
||||
<p className={cn("text-base", isCallSeatAndUnable && "font-bold text-red-500")}>
|
||||
{isCallSeatAndUnable? "전화걸기 이용 불가(관리자에게 문의해 주세요)" : `자리번호: ${clientId}`}
|
||||
</p>
|
||||
{error && (
|
||||
<p className="text-sm text-red-500">
|
||||
{error}
|
||||
@@ -201,7 +129,8 @@ const LoginPage = () => {
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full mt-6 h-11"
|
||||
className="w-full mt-3 h-11"
|
||||
disabled={loginMutation.isPending}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
tryLogin();
|
||||
|
||||
@@ -1,49 +1,20 @@
|
||||
'use client'
|
||||
import { useLogoutMutation } from "@/query/auth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useStorage} from "@/hooks/useStorage";
|
||||
import {StorageKeys} from "@/store/storage/storage-keys";
|
||||
import { useEffect } from "react";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
|
||||
const LogoutPage = () => {
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
const { auth, logout } = useAuth();
|
||||
const { clearSelectedProject } = useSelectedProject();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const router = useRouter();
|
||||
const logoutMutation = useLogoutMutation();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
const runLogout = async () => {
|
||||
const userId = auth.user?.userId ?? "";
|
||||
clearSelectedProject();
|
||||
logout();
|
||||
|
||||
try {
|
||||
if(userId !== ""){
|
||||
const logoutRequestOptions = {autoLogoutOnAuthError: false};
|
||||
await nextApi.post(`/logout/${userId}`, null, logoutRequestOptions);
|
||||
}
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
}
|
||||
|
||||
const loginType = getLoginTypeStorage();
|
||||
const loginUrl = loginType === "call" ? "/login?type=call" : "/login";
|
||||
|
||||
router.replace(loginUrl);
|
||||
};
|
||||
|
||||
withLoadingAsync(runLogout);
|
||||
(async () => {
|
||||
await logoutMutation.mutateAsync();
|
||||
router.replace("/login");
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// Nothing to render while redirecting
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export default LogoutPage;
|
||||
28
src/app/(pages)/redirect/[slug]/page.tsx
Normal file
28
src/app/(pages)/redirect/[slug]/page.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import RedirectLanding from "@/components/external/RedirectLanding";
|
||||
import {notFound} from "next/navigation";
|
||||
import {ALLOW_REDIRECT} from "@/const/commonConst";
|
||||
import {RedirectSlug} from "@/types/common";
|
||||
|
||||
type redirectPageProps = {
|
||||
params: Promise<{ slug: string }>;
|
||||
searchParams?: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
const toRedirectSlug = (slug: string): RedirectSlug | null => {
|
||||
return ALLOW_REDIRECT.has(slug.toLowerCase()) ? (slug.toLowerCase() as RedirectSlug) : null;
|
||||
}
|
||||
|
||||
const redirectPage = async ({
|
||||
params,
|
||||
}: redirectPageProps) => {
|
||||
const { slug } = await params;
|
||||
const redirectSlug = toRedirectSlug(slug);
|
||||
|
||||
if (!redirectSlug) notFound();
|
||||
|
||||
return (
|
||||
<RedirectLanding redirectSlug={redirectSlug} />
|
||||
)
|
||||
}
|
||||
|
||||
export default redirectPage;
|
||||
35
src/app/(pages)/redirect/error/page.tsx
Normal file
35
src/app/(pages)/redirect/error/page.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import ErrorPage from "@/components/external/Error";
|
||||
import {ErrorCode} from "@/types/common";
|
||||
|
||||
function toErrorCode(raw: string | undefined): ErrorCode {
|
||||
if (raw === "500") return "500";
|
||||
// fetch_error, 기타 알 수 없는 코드 → 500으로 처리
|
||||
if (raw && raw !== "404") return "500";
|
||||
return "404";
|
||||
}
|
||||
|
||||
type RedirectErrorPageProps = {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
};
|
||||
|
||||
const RedirectErrorPage = async ({ searchParams }: RedirectErrorPageProps) => {
|
||||
const sp = await searchParams;
|
||||
|
||||
console.log(sp)
|
||||
|
||||
const code = toErrorCode(sp.code as string | undefined);
|
||||
const sid = (sp.sid as string | undefined) ?? "";
|
||||
|
||||
return (
|
||||
<ErrorPage
|
||||
code={code}
|
||||
errorDescription={
|
||||
sid
|
||||
? `오류가 발생했습니다. 관리자에게 문의할 경우 아래 코드를 전달해 주세요.\n리스트 ID : ${sid}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default RedirectErrorPage
|
||||
@@ -1,7 +1,8 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {ProjectCompanyAssignSummary, ProjectFieldworkAssignSummary} from "@/types/list";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -9,8 +10,8 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "prjct-outsource" && slug.length === 2) {
|
||||
const result = await contactApi.get<string[]>(`/assign/prjct-outsource/${slug[1]}`);
|
||||
if (action === "prjct-cmpn" && slug.length === 2) {
|
||||
const result = await contactApi.get<string[]>(`/assign/prjct-cmpn/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
@@ -19,6 +20,25 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "prjct-cmpn-summary" && slug.length === 2) {
|
||||
const result = await contactApi.get<ProjectCompanyAssignSummary>(`/assign/prjct-cmpn-summary/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "prjct-fieldwork-summary" && slug.length === 2) {
|
||||
const assignType = req.nextUrl.searchParams.get("assignType");
|
||||
const cmpnIds = req.nextUrl.searchParams.get("cmpnIds");
|
||||
if (!assignType) {
|
||||
return NextResponse.json({ message: "assignType이 필요합니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const query = `?assignType=${assignType}${cmpnIds ? `&cmpnIds=${encodeURIComponent(cmpnIds)}` : ""}`;
|
||||
const result = await contactApi.get<ProjectFieldworkAssignSummary>(
|
||||
`/assign/prjct-fieldwork-summary/${slug[1]}${query}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
@@ -31,7 +51,7 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "prjct-fieldwork" && slug.length === 2) {
|
||||
if ((action === "prjct-fieldwork" || action === "prjct-cmpn") && slug.length === 2) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
@@ -40,7 +60,7 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put(`/assign/prjct-fieldwork/${slug[1]}`, body);
|
||||
await contactApi.put(`/assign/${action}/${slug[1]}`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
93
src/app/api/cmpn/[[...slug]]/route.ts
Normal file
93
src/app/api/cmpn/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/http-server";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "check-cmpn-id") {
|
||||
const cmpnId = req.nextUrl.searchParams.get("cmpnId") ?? "";
|
||||
if (!cmpnId) {
|
||||
return NextResponse.json(
|
||||
{ message: "cmpnId 파라미터가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.get<DataVerification>("/cmpn/check-cmpn-id", {
|
||||
query: { cmpnId },
|
||||
});
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (slug.length === 1) {
|
||||
const result = await contactApi.get<CmpnInfo>(`/cmpn/${encodeURIComponent(action)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
const result = await contactApi.get<CmpnInfo[]>("/cmpn");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put("/cmpn", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.patch("/cmpn", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
100
src/app/api/external/[[...slug]]/route.ts
vendored
100
src/app/api/external/[[...slug]]/route.ts
vendored
@@ -1 +1,99 @@
|
||||
//외부 설문에 뎐동 되는 API
|
||||
// External survey event API.
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { RouteContext } from "@/types/common";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { getClientIp } from "@kri/common/server";
|
||||
import {
|
||||
EXTERNAL_ACTION_CODE_BY_SLUG,
|
||||
EXTERNAL_ENTRY_TYPE_CODE,
|
||||
ExternalAction,
|
||||
ExternalEntryTypeCode,
|
||||
ExternalEventBody,
|
||||
} from "@/types/external";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
|
||||
const getHeader = (headers: Headers, name: string): string | null => {
|
||||
const value = headers.get(name);
|
||||
return value && value.trim().length > 0 ? value : null;
|
||||
};
|
||||
|
||||
const getEntryTypeCode = (headers: Headers): ExternalEntryTypeCode => {
|
||||
return getHeader(headers, "x-entry-type") === "redirect"
|
||||
? EXTERNAL_ENTRY_TYPE_CODE.redirect
|
||||
: EXTERNAL_ENTRY_TYPE_CODE.api;
|
||||
};
|
||||
|
||||
const toExternalAction = (value: string): ExternalAction | null => {
|
||||
return value in EXTERNAL_ACTION_CODE_BY_SLUG ? (value as ExternalAction) : null;
|
||||
};
|
||||
|
||||
const toRequiredNumber = (value: string): number | null => {
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
};
|
||||
|
||||
const toRequiredSid = (value: string): string | null =>
|
||||
value.length > 0 ? value : null;
|
||||
|
||||
const buildExternalEventBody = (
|
||||
req: NextRequest,
|
||||
action: ExternalAction,
|
||||
prjctSurveyIdx: number,
|
||||
sid: string,
|
||||
): ExternalEventBody => {
|
||||
const pathname = req.nextUrl.pathname;
|
||||
const h = req.headers;
|
||||
const actionCode = EXTERNAL_ACTION_CODE_BY_SLUG[action];
|
||||
|
||||
return {
|
||||
action: actionCode,
|
||||
prjctSurveyIdx,
|
||||
sid,
|
||||
meta: {
|
||||
entryType: getEntryTypeCode(h),
|
||||
action: actionCode,
|
||||
psidx: String(prjctSurveyIdx),
|
||||
sid,
|
||||
remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req),
|
||||
uri: getHeader(h, "x-orig-uri") || pathname,
|
||||
url: getHeader(h, "x-orig-url") || req.url,
|
||||
userAgent: getHeader(h, "x-orig-user-agent") || getHeader(h, "user-agent"),
|
||||
referer: getHeader(h, "x-orig-referer") || getHeader(h, "referer"),
|
||||
origin: getHeader(h, "x-orig-origin") || getHeader(h, "origin"),
|
||||
xForwardedFor: getHeader(h, "x-orig-x-forwarded-for") || getHeader(h, "x-forwarded-for"),
|
||||
forwarded: getHeader(h, "x-orig-forwarded") || getHeader(h, "forwarded"),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const handleExternalEvent = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { searchParams } = req.nextUrl;
|
||||
const { slug = [] } = await context.params;
|
||||
const action = toExternalAction((slug[0] ?? "").toLowerCase());
|
||||
|
||||
if (slug.length !== 1 || !action) {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const prjctSurveyIdx = toRequiredNumber((searchParams.get("psidx") ?? "").trim());
|
||||
const sid = toRequiredSid((searchParams.get("sid") ?? "").trim());
|
||||
|
||||
if (!prjctSurveyIdx || !sid) {
|
||||
return NextResponse.json({ message: "psidx, sid는 필수입니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = buildExternalEventBody(req, action, prjctSurveyIdx, sid);
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
await contactApi.post(`/list-hist/survey`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const GET = handleExternalEvent;
|
||||
export const POST = handleExternalEvent;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi, createIntranetApi} from "@/lib/server-api";
|
||||
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse} from "@/types/project";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {createIntranetApi} from "@/lib/http-server";
|
||||
import {CallerTelNumInfo, IntranetProjectSearchResponse} from "@/types/project";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {GroupCodeInfo, ItrntUserInfo} from "@/types/user";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -28,6 +28,18 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "caller-tel-num"){
|
||||
const result = await itrntApi.get<CallerTelNumInfo[]>(`/telnum/caller`);
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "group-code-list"){
|
||||
const result = await itrntApi.get<GroupCodeInfo[]>(`/user/group-code-list`);
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createKartApi} from "@/lib/server-api";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {KonKiwiProjectInfo} from "@/types/project";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
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 result = await kartApi.get<KonKiwiProjectInfo[]>(
|
||||
`/project/list/${slug[1]}/${slug[2]}/${slug[3]}`,
|
||||
{ query: keyword ? { keyword } : {} }
|
||||
);
|
||||
const [, intranetCode, projectType] = slug;
|
||||
if (!intranetCode.trim() || intranetCode.length > 32 || !["0", "1"].includes(projectType)) {
|
||||
return NextResponse.json({ message: "프로젝트 정보를 확인해 주세요." }, { status: 400 });
|
||||
}
|
||||
const result = await contactApi.get<KonKiwiProjectInfo[]>(`/kart/project/list`, {
|
||||
query: { intranetCode, projectType, ...(keyword ? { keyword } : {}) },
|
||||
});
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
29
src/app/api/list-call-hist/[[...slug]]/route.ts
Normal file
29
src/app/api/list-call-hist/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
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 {ListCallHist} from "@/types/list";
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [prjctIdx, sid, action] = slug;
|
||||
if (!prjctIdx || !sid || (action !== "call-start" && action !== "call-close")) {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.put<ListCallHist>(
|
||||
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/${action}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
115
src/app/api/list-external/[[...slug]]/route.ts
Normal file
115
src/app/api/list-external/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { RouteContext } from "@/types/common";
|
||||
import { createContactApiWithApiKey } from "@/lib/http-server";
|
||||
import { errorToResponse } from "@kri/common/http";
|
||||
import { ListSearchExternal } from "@/types/list";
|
||||
|
||||
const getApiKey = (req: NextRequest) => req.headers.get("x-api-key");
|
||||
|
||||
// backend가 제공하는 메소드/경로 그대로 사용 (path variable)
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const apiKey = getApiKey(req);
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
|
||||
}
|
||||
|
||||
const { slug = [] } = await context.params;
|
||||
const [action, prjctCd, sid] = slug;
|
||||
const contactApi = await createContactApiWithApiKey(apiKey);
|
||||
|
||||
if (action === "header" && prjctCd) {
|
||||
const result = await contactApi.get<string[]>(`/list-external/header/${encodeURIComponent(prjctCd)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "search" && prjctCd && sid) {
|
||||
const result = await contactApi.get<ListSearchExternal>(
|
||||
`/list-external/search/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
// backend가 제공하는 메소드/경로 그대로 사용 (path variable)
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const apiKey = getApiKey(req);
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
|
||||
}
|
||||
|
||||
const { slug = [] } = await context.params;
|
||||
const [action, prjctCd, sid] = slug;
|
||||
|
||||
if (action === "update" && prjctCd && sid) {
|
||||
const body = await req.json().catch(() => null);
|
||||
const contactApi = await createContactApiWithApiKey(apiKey);
|
||||
const result = await contactApi.patch<number>(
|
||||
`/list-external/update/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
// 외부 연동 호환용: 항상 POST, path variable을 모두 url 쿼리 파람으로 받아 backend path variable로 전달
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const apiKey = getApiKey(req);
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
|
||||
}
|
||||
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const { searchParams } = req.nextUrl;
|
||||
const prjctCd = searchParams.get("prjctCd");
|
||||
const sid = searchParams.get("sid");
|
||||
const contactApi = await createContactApiWithApiKey(apiKey);
|
||||
|
||||
if (action === "header") {
|
||||
if (!prjctCd) {
|
||||
return NextResponse.json({ message: "prjctCd는 필수입니다." }, { status: 400 });
|
||||
}
|
||||
const result = await contactApi.get<string[]>(`/list-external/header/${encodeURIComponent(prjctCd)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "search") {
|
||||
if (!prjctCd || !sid) {
|
||||
return NextResponse.json({ message: "prjctCd, sid는 필수입니다." }, { status: 400 });
|
||||
}
|
||||
const result = await contactApi.get<ListSearchExternal>(
|
||||
`/list-external/search/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "update") {
|
||||
if (!prjctCd || !sid) {
|
||||
return NextResponse.json({ message: "prjctCd, sid는 필수입니다." }, { status: 400 });
|
||||
}
|
||||
const body = await req.json().catch(() => null);
|
||||
const result = await contactApi.patch<number>(
|
||||
`/list-external/update/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
73
src/app/api/list-hist/[[...slug]]/route.ts
Normal file
73
src/app/api/list-hist/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
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 {ListEventHistory, ListUpdateHistory} from "@/types/list";
|
||||
|
||||
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "event" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListEventHistory[]>(
|
||||
`/list-hist/event/${slug[1]}/${encodeURIComponent(slug[2])}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "update" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListUpdateHistory[]>(
|
||||
`/list-hist/update/${slug[1]}/${encodeURIComponent(slug[2])}`,
|
||||
);
|
||||
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 === "event" && slug.length === 2) {
|
||||
await contactApi.del(`/list-hist/event/${slug[1]}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "event") {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put(`/list-hist/event`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
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
|
||||
139
src/app/api/list/[[...slug]]/route.ts
Normal file
139
src/app/api/list/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import type {PageResponse} from "@kri/common";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {listHeader, ListSearchRequest, ListSearchWithFullResult} from "@/types/list";
|
||||
|
||||
const excelHeaders = {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
};
|
||||
|
||||
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "header") {
|
||||
const result = await contactApi.get<listHeader[]>(
|
||||
`/list-header/${slug[1]}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "upload-history") {
|
||||
const result = await contactApi.get(`/list/excel/upload-history/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "search-sid" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListSearchWithFullResult>(
|
||||
`/list/search-sid/${slug[1]}/${encodeURIComponent(slug[2])}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "item-file-download" && slug.length === 4) {
|
||||
const result = await contactApi.get<ArrayBuffer>(
|
||||
`/list/item-file/download/${slug[1]}/${encodeURIComponent(slug[2])}/${slug[3]}`,
|
||||
{ expectBinary: true },
|
||||
);
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "search-filter"){
|
||||
const body: ListSearchRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.post<PageResponse<ListSearchWithFullResult>>(
|
||||
`/list/search-filter/${slug[1]}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-template") {
|
||||
const prjctIdx = slug[1];
|
||||
if (!prjctIdx) {
|
||||
return NextResponse.json({ message: "prjctIdx 파라미터가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await contactApi.post<ArrayBuffer>(
|
||||
`/list/excel/template/${prjctIdx}`,
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
...excelHeaders,
|
||||
"Content-Disposition": 'attachment; filename="list_upload_template.xlsx"',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "item-file-upload" && slug.length === 3) {
|
||||
const form = await req.formData();
|
||||
await contactApi.postForm(`/list/item-file/upload/${slug[1]}/${encodeURIComponent(slug[2])}`, form);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "upload-history-file") {
|
||||
const result = await contactApi.post<ArrayBuffer>(
|
||||
`/list/excel/upload-history/file/${slug[1]}/${slug[2]}`,
|
||||
undefined,
|
||||
{ expectBinary: true },
|
||||
);
|
||||
return new NextResponse(result, { status: 200, headers: excelHeaders });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const body = await req.json().catch(() => null);
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "header") {
|
||||
await contactApi.patch(`/list-header/${slug[1]}`, body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "update") {
|
||||
const result = await contactApi.patch<number>(`/list/update/${slug[1]}`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {LoginRequest, LoginUser} from "@/types/auth";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { LoginRequest, LoginUser } from "@kri/common";
|
||||
import {setAuthCookie} from "@/lib/auth-cookie";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
//실제 Backend
|
||||
//?ㅼ젣 Backend
|
||||
type LoginResponse = {
|
||||
accessToken: string;
|
||||
user: LoginUser;
|
||||
@@ -18,13 +18,7 @@ export const POST = async (req: NextRequest) => {
|
||||
const result = await contactApi.post<LoginResponse>("/auth/login", body);
|
||||
|
||||
const res = NextResponse.json(result.user, { status: 200 });
|
||||
res.cookies.set("access_token", result.accessToken, {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 24 * 60 * 60, // 24시간
|
||||
});
|
||||
setAuthCookie(res, result.accessToken);
|
||||
|
||||
return res;
|
||||
} catch (error : unknown) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {setAuthCookie} from "@/lib/auth-cookie";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
_req: NextRequest,
|
||||
context: RouteContext
|
||||
) {
|
||||
try {
|
||||
@@ -21,13 +21,7 @@ export async function POST(
|
||||
await contactApi.post<boolean>(url);
|
||||
const res = NextResponse.json({ ok: true });
|
||||
|
||||
res.cookies.set("access_token", "", {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
});
|
||||
setAuthCookie(res, "");
|
||||
|
||||
return res;
|
||||
} catch (error: unknown) {
|
||||
|
||||
81
src/app/api/message-report/[[...slug]]/route.ts
Normal file
81
src/app/api/message-report/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
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 {FileResponse, PageRequest, PageResponse} from "@kri/common";
|
||||
import type {BulkSendInfo, SendResultInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, sendTy, reqstSvc, prjctCd] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
|
||||
const result = await contactApi.get<BulkSendInfo[]>(
|
||||
`/message-report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "send-result" && slug.length >= 4) {
|
||||
const [, sid, prjctCdParam, reqstSvcParam] = slug;
|
||||
const channelTy = req.nextUrl.searchParams.get("channelTy");
|
||||
const query = channelTy ? `?channelTy=${channelTy}` : "";
|
||||
const result = await contactApi.get<SendResultInfo[]>(
|
||||
`/message-report/send-result/${encodeURIComponent(sid)}/${prjctCdParam}/${reqstSvcParam}${query}`,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, bulkSendKey] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "bulk-detail" && bulkSendKey) {
|
||||
const body: PageRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
const result = await contactApi.post<PageResponse<SendResultInfo>>(
|
||||
`/message-report/bulk-detail/${bulkSendKey}`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "bulk-detail-excel" && bulkSendKey) {
|
||||
const result = await contactApi.post<FileResponse>(
|
||||
`/message-report/bulk-detail-excel/${bulkSendKey}`,
|
||||
undefined,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
if (action === "send-result-summary") {
|
||||
const body: SendResultSummaryRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
const result = await contactApi.post<SendResultSummaryResponse[]>(
|
||||
`/message-report/send-result-summary`,
|
||||
body,
|
||||
);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
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,26 +1,69 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createNotihubApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {Template, TemplateSummary} from "@/types/messageTemplate";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
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) => {
|
||||
try{
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
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"){
|
||||
const fileName = searchParams.get("fileName");
|
||||
if (!fileName) {
|
||||
return NextResponse.json({ message: "fileName은 필수입니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await contactApi.get<ArrayBuffer>(
|
||||
`/message-template/${slug[0]}/attachment?fileName=${encodeURIComponent(fileName)}`,
|
||||
{ expectBinary: true },
|
||||
);
|
||||
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/octet-stream" } });
|
||||
}
|
||||
|
||||
if(slug.length === 1){
|
||||
const result = await notihubApi.get<Template>(
|
||||
`/template/${slug[0]}`,
|
||||
const result = await contactApi.get<Template>(
|
||||
`/message-template/${slug[0]}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "list" && slug.length === 3){
|
||||
const result = await notihubApi.get<TemplateSummary[]>(
|
||||
`/template/list/${slug[1]}/${slug[2]}`,
|
||||
const result = await contactApi.get<TemplateSummary[]>(
|
||||
`/message-template/list/${slug[1]}/${slug[2]}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
@@ -33,10 +76,9 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try{
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "body-image" && slug.length === 2){
|
||||
const itrntPrjctCd = slug[1];
|
||||
@@ -51,8 +93,8 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
);
|
||||
}
|
||||
|
||||
const result = await notihubApi.putForm<string>(
|
||||
`/template/body-image/${itrntPrjctCd}`,
|
||||
const result = await contactApi.putForm<string>(
|
||||
`/message-template/body-image/${itrntPrjctCd}`,
|
||||
formData
|
||||
);
|
||||
|
||||
@@ -60,15 +102,15 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
}
|
||||
|
||||
if(!action){
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
const formData = await req.formData().catch(() => null);
|
||||
if (!formData) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await notihubApi.put<Template>(`/template`, body);
|
||||
const result = await contactApi.putForm<Template>(`/message-template`, formData);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
@@ -80,21 +122,20 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try{
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const notihubApi = await createNotihubApi();
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(!action){
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
const formData = await req.formData().catch(() => null);
|
||||
if (!formData) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await notihubApi.patch<Template>(`/template`, body);
|
||||
const result = await contactApi.request<Template>(`/message-template`, { method: "PATCH", form: formData });
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
@@ -103,3 +144,20 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
39
src/app/api/progress/[[...slug]]/route.ts
Normal file
39
src/app/api/progress/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
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 {ProgressDateResponse, ProgressSearchRequest, ProgressUserResponse} from "@/types/progress";
|
||||
|
||||
const ACTION_PATH: Record<string, string> = {
|
||||
"user": "/progress/user",
|
||||
"last-date": "/progress/last-date",
|
||||
"date": "/progress/date",
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, prjctIdx, eventTy] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
const basePath = ACTION_PATH[action];
|
||||
if (!basePath || !prjctIdx || !eventTy) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const body: ProgressSearchRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
|
||||
}
|
||||
|
||||
if (action === "user") {
|
||||
const result = await contactApi.post<ProgressUserResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
}
|
||||
|
||||
const result = await contactApi.post<ProgressDateResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
|
||||
return NextResponse.json(result, {status: 200});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,8 +1,9 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi, createIntranetApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {PageResponse, RouteContext} from "@/types/common";
|
||||
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import type {PageResponse} from "@kri/common";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {ProjectInfo, ProjectListRequest, ProjectOwnerResponse} from "@/types/project";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -51,7 +52,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(action === "list"){
|
||||
const body = await req.json().catch(() => null);
|
||||
const body: ProjectListRequest | null = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
@@ -171,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 {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(slug.length === 1){
|
||||
|
||||
64
src/app/api/reserve/[[...slug]]/route.ts
Normal file
64
src/app/api/reserve/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
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 {ListReserve} from "@/types/list";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "sid" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListReserve[]>(
|
||||
`/reserve/${slug[1]}/sid/${encodeURIComponent(slug[2])}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "user" && slug.length === 3 && slug[2] === "search") {
|
||||
const fromDt = req.nextUrl.searchParams.get("fromDt");
|
||||
const toDt = req.nextUrl.searchParams.get("toDt");
|
||||
if (!fromDt || !toDt) {
|
||||
return NextResponse.json({ message: "fromDt, toDt가 필요합니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await contactApi.get<ListReserve[]>(
|
||||
`/reserve/user/${encodeURIComponent(slug[1])}/search?fromDt=${fromDt}&toDt=${toDt}`,
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "user" && slug.length === 3) {
|
||||
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/user/${slug[2]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "user" && slug.length === 2) {
|
||||
const requestPast = req.nextUrl.searchParams.get("requestPast");
|
||||
const query = requestPast !== null ? `?requestPast=${requestPast}` : "";
|
||||
const result = await contactApi.get<ListReserve[]>(`/reserve/user/${encodeURIComponent(slug[1])}${query}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest) => {
|
||||
try {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
|
||||
}
|
||||
|
||||
const contactApi = await createContactApi();
|
||||
const result = await contactApi.put<ListReserve>(`/reserve`, body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,14 +1,12 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {ResultCode} from "@/types/project";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(slug.length === 1){
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi} from "@/lib/http-server";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/server-api";
|
||||
import {UserInfo, UserUploadResponse} from "@/types/user";
|
||||
import {DataVerification, RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/http-server";
|
||||
import type { UserInfo } from "@/types/user";
|
||||
import type { DataVerification, ExcelUploadResult } from "@kri/common";
|
||||
import type { RouteContext } from "@/types/common";
|
||||
import {errorToResponse} from "@kri/common/http";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
@@ -25,16 +26,6 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "cmpn"){
|
||||
const result = await contactApi.get<string[]>("/user/cmpn");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "outsource"){
|
||||
const result = await contactApi.get<UserInfo[]>("/user/outsource");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "fieldwork"){
|
||||
const result = await contactApi.get<UserInfo[]>("/user/fieldwork");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
@@ -63,7 +54,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "excel") {
|
||||
if (action === "excel-upload") {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
@@ -77,8 +68,8 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await contactApi.postForm<UserUploadResponse>(
|
||||
"/user/excel",
|
||||
const result = await contactApi.postForm<ExcelUploadResult>(
|
||||
"/user/excel/upload",
|
||||
backendForm
|
||||
);
|
||||
|
||||
@@ -158,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 {
|
||||
const { slug = [] } = await context.params;
|
||||
const [userId] = slug ?? [];
|
||||
|
||||
@@ -8,6 +8,20 @@
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
/* --content-font-size 배율 기반 font-size 스케일 (기본 text-* 유틸을 그대로 대체) */
|
||||
--text-xs: calc(var(--content-font-size) * 0.75);
|
||||
--text-sm: calc(var(--content-font-size) * 0.875);
|
||||
--text-base: var(--content-font-size);
|
||||
--text-lg: calc(var(--content-font-size) * 1.125);
|
||||
--text-xl: calc(var(--content-font-size) * 1.25);
|
||||
--text-2xl: calc(var(--content-font-size) * 1.5);
|
||||
--text-3xl: calc(var(--content-font-size) * 1.875);
|
||||
--text-4xl: calc(var(--content-font-size) * 2.25);
|
||||
--text-5xl: calc(var(--content-font-size) * 3);
|
||||
--text-6xl: calc(var(--content-font-size) * 3.75);
|
||||
--text-7xl: calc(var(--content-font-size) * 4.5);
|
||||
--text-8xl: calc(var(--content-font-size) * 6);
|
||||
--text-9xl: calc(var(--content-font-size) * 8);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
@@ -51,13 +65,13 @@
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary: oklch(0.33 0.07 255);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent: oklch(0.87 0.18 95);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
@@ -86,14 +100,14 @@
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--primary: oklch(0.55 0.09 255);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--accent: oklch(0.8 0.17 95);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
@@ -113,72 +127,27 @@
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
/* 배율별 유틸 클래스 */
|
||||
.content-text-xs {
|
||||
font-size: calc(var(--content-font-size) * 0.75);
|
||||
.bg-excel {
|
||||
background-color: #217346;
|
||||
}
|
||||
.bg-excel:hover {
|
||||
background-color: #185c37;
|
||||
}
|
||||
|
||||
.content-text-sm {
|
||||
font-size: calc(var(--content-font-size) * 0.875);
|
||||
.bg-blue {
|
||||
background-color: var(--color-blue-600);
|
||||
}
|
||||
.bg-blue:hover {
|
||||
background-color: var(--color-blue-700);
|
||||
}
|
||||
|
||||
.content-text-base {
|
||||
font-size: var(--content-font-size);
|
||||
}
|
||||
|
||||
.content-text-lg {
|
||||
font-size: calc(var(--content-font-size) * 1.125);
|
||||
}
|
||||
|
||||
.content-text-xl {
|
||||
font-size: calc(var(--content-font-size) * 1.25);
|
||||
}
|
||||
|
||||
.content-text-2xl {
|
||||
font-size: calc(var(--content-font-size) * 1.5);
|
||||
}
|
||||
|
||||
.content-text-3xl {
|
||||
font-size: calc(var(--content-font-size) * 1.875);
|
||||
}
|
||||
|
||||
.content-text-4xl {
|
||||
font-size: calc(var(--content-font-size) * 2.25);
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.placeholder-content-text-xs::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 0.75);
|
||||
}
|
||||
|
||||
.placeholder-content-text-sm::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 0.875);
|
||||
}
|
||||
|
||||
.placeholder-content-text-base::placeholder {
|
||||
font-size: var(--content-font-size);
|
||||
}
|
||||
|
||||
.placeholder-content-text-lg::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.125);
|
||||
}
|
||||
|
||||
.placeholder-content-text-xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.25);
|
||||
}
|
||||
|
||||
.placeholder-content-text-2xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.5);
|
||||
}
|
||||
|
||||
.placeholder-content-text-3xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.875);
|
||||
}
|
||||
|
||||
.placeholder-content-text-4xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 2.25);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* [제거됨] .content-text-* / .placeholder-content-text-*
|
||||
* --font-size-* 를 @theme inline 에 등록했기 때문에
|
||||
* 기본 text-xs ~ text-4xl 유틸이 이미 --content-font-size 배율을 반영합니다.
|
||||
* placeholder 스타일도 Tailwind 기본 placeholder: variant로 대체 가능합니다.
|
||||
* 예) placeholder-content-text-sm -> placeholder:text-sm
|
||||
*/
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@@ -194,14 +163,43 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 미리보기(.kri-editor-preview)는 실제 발송 HTML을 그대로 dangerouslySetInnerHTML로 그린다.
|
||||
Tailwind preflight가 img를 display:block + vertical-align:middle로 리셋하는데,
|
||||
실제 메일 클라이언트에는 이 리셋 CSS가 없어 img가 브라우저 기본값(inline, vertical-align:baseline)으로
|
||||
렌더링된다. 미리보기가 실제 발송 결과와 같아 보이도록 두 속성 다 기본값으로 되돌린다. */
|
||||
.kri-editor-preview img {
|
||||
display: inline;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
||||
/* 에디터 편집 화면은 [&_p]:my-2 유틸리티로 문단 사이 margin을 주지만,
|
||||
미리보기는 Tailwind preflight가 p의 기본 margin을 0으로 리셋해 내용 없는 빈 <p></p>가
|
||||
높이 0으로 사라진다. 편집 화면과 동일하게 margin을 줘서 빈 줄이 보이도록 한다. */
|
||||
.kri-editor-preview p {
|
||||
margin: 0.5em 0;
|
||||
}
|
||||
.kri-editor-preview p:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.kri-editor-preview p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
/* 내용이 전혀 없는 <p></p>는 높이가 0이라 위/아래 margin이 서로 collapse되어 사라진다.
|
||||
min-height로 실제 높이를 줘서 collapse를 막아야 빈 줄이 화면에 보인다. */
|
||||
.kri-editor-preview p:empty {
|
||||
min-height: 1em;
|
||||
}
|
||||
|
||||
.ProseMirror .ProseMirror-selectednode img {
|
||||
outline: 5px solid #0ea5e9;
|
||||
outline-offset: -5px;
|
||||
}
|
||||
/* 리사이즈 컨테이너 기본 배치 */
|
||||
/* Tiptap ResizableNodeView가 style.display = "flex"를 인라인으로 강제 지정하므로,
|
||||
inline 이미지 노드처럼 줄바꿈 없이 배치하려면 !important로 덮어써야 한다. */
|
||||
.ProseMirror [data-resize-container] {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
display: inline-block !important;
|
||||
}
|
||||
|
||||
/* 리사이즈 핸들 공통 스타일 */
|
||||
@@ -253,3 +251,4 @@
|
||||
.ProseMirror [data-resize-container][data-resize-state="resizing"] {
|
||||
outline: 1px dashed #0ea5e9;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
||||
import {Geist, Geist_Mono} from "next/font/google";
|
||||
import { AppProvider } from "@/components/providers/AppProvider";
|
||||
import "./globals.css";
|
||||
import {Toaster} from "sonner";
|
||||
import {Toaster} from "@/components/ui/sonner";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
|
||||
9
src/app/not-found.tsx
Normal file
9
src/app/not-found.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import ErrorPage from "@/components/external/Error";
|
||||
|
||||
const NotFound = () => {
|
||||
return (
|
||||
<ErrorPage code="404" />
|
||||
)
|
||||
}
|
||||
|
||||
export default NotFound
|
||||
155
src/components/app-shell/AppHeader.tsx
Normal file
155
src/components/app-shell/AppHeader.tsx
Normal file
@@ -0,0 +1,155 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { CalendarClock, LogOut, UserRound, ZoomIn, ZoomOut } from "lucide-react";
|
||||
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 type { TopMenuItem } from "@/config/menu.types";
|
||||
import type { LoginUser } from "@kri/common";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useInternalInfoQuery } from "@/query/internal";
|
||||
import { useCtiConnectionStatus } from "@/hooks/useCtiConnectionStatus";
|
||||
|
||||
interface AppHeaderProps {
|
||||
isMain: boolean;
|
||||
isContactPage: boolean;
|
||||
menuOpen: boolean;
|
||||
activeTopId: string;
|
||||
topMenus: TopMenuItem[];
|
||||
isViewProjectTitle: boolean;
|
||||
projectName?: string;
|
||||
userInfo?: LoginUser;
|
||||
fontSize: number;
|
||||
onToggleMenu: () => void;
|
||||
onNavigate: (path: string) => void;
|
||||
decreaseFontSize: () => void;
|
||||
increaseFontSize: () => void;
|
||||
onOpenReserveSearch: () => void;
|
||||
}
|
||||
|
||||
export function AppHeader({
|
||||
isMain,
|
||||
isContactPage,
|
||||
menuOpen,
|
||||
activeTopId,
|
||||
topMenus,
|
||||
isViewProjectTitle,
|
||||
projectName,
|
||||
userInfo,
|
||||
fontSize,
|
||||
onToggleMenu,
|
||||
onNavigate,
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
onOpenReserveSearch,
|
||||
}: AppHeaderProps) {
|
||||
const internalInfoQuery = useInternalInfoQuery(!!userInfo);
|
||||
const seatNo = internalInfoQuery.data?.clientId ?? "";
|
||||
const ctiConnectionStatus = useCtiConnectionStatus();
|
||||
const isCtiConnected = ctiConnectionStatus === "open";
|
||||
|
||||
const showProjectTitle = isViewProjectTitle && !!projectName;
|
||||
|
||||
return (
|
||||
<>
|
||||
<KriHeader
|
||||
logo={
|
||||
<div className="flex h-10 w-16 items-center justify-center sm:w-20">
|
||||
<Image
|
||||
src="/kri_logo.png"
|
||||
alt="KRI 로고"
|
||||
width={120}
|
||||
height={40}
|
||||
className="h-full w-full object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
homePath="/"
|
||||
menus={isContactPage? []:topMenus}
|
||||
activeMenuId={activeTopId}
|
||||
menuOpen={menuOpen}
|
||||
showMenuButton={!isMain && !isContactPage}
|
||||
onToggleMenu={onToggleMenu}
|
||||
onNavigate={(path) => {if(!isContactPage) onNavigate(path)}}
|
||||
className="border-gray-200 bg-white"
|
||||
// 모바일(sm 미만)은 헤더 폭이 좁아 로고와 우측 버튼이 겹치지 않도록 간격을 줄인다.
|
||||
innerClassName="h-16 gap-2 px-2 sm:gap-4 sm:px-4"
|
||||
center={
|
||||
showProjectTitle ? (
|
||||
<h1 className="ml-3 hidden truncate text-2xl font-bold lg:block" title={projectName}>{projectName}</h1>
|
||||
) : null
|
||||
}
|
||||
right={
|
||||
<>
|
||||
<div className="flex items-center gap-1 border-r pr-2 sm:pr-4">
|
||||
<Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={decreaseFontSize} title="폰트 작게">
|
||||
<ZoomOut className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="min-w-6 text-center text-xs text-gray-500" title={`글자 크기 ${fontSize}px`}>{fontSize}</span>
|
||||
<Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={increaseFontSize} title="폰트 크게">
|
||||
<ZoomIn className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon-lg" className="size-8 sm:size-10" onClick={onOpenReserveSearch} title="예약 내역 조회">
|
||||
<CalendarClock className="size-6" />
|
||||
</Button>
|
||||
<span className="hidden items-center gap-1.5 text-sm text-gray-600 sm:inline-flex">
|
||||
{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" />
|
||||
<span>로그아웃</span>
|
||||
</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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
243
src/components/app-shell/AppMainLayout.tsx
Normal file
243
src/components/app-shell/AppMainLayout.tsx
Normal file
@@ -0,0 +1,243 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode, useEffect, useMemo, useState } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import type { Route } from "next";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { getCurrentPositionMeta } from "@kri/common/browser";
|
||||
import { KriMainLayout } from "@/components/layout/KriMainLayout";
|
||||
import { AppHeader } from "@/components/app-shell/AppHeader";
|
||||
import { AppSidebar } from "@/components/app-shell/AppSidebar";
|
||||
import ReserveSearchDialog from "@/components/dialog/ReserveSearchDialog";
|
||||
import { useFontSize } from "@/hooks/useFontSize";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useDialog } from "@/hooks/useDialog";
|
||||
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
|
||||
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FONT_SIZE } from "@/const/commonConst";
|
||||
import { ListJobWatcher } from "@/components/list/ListJobWatcher";
|
||||
|
||||
type AppMainLayoutProps = {
|
||||
children: ReactNode;
|
||||
initialFontSize: number;
|
||||
};
|
||||
|
||||
type AccessControlledItem = {
|
||||
path?: string;
|
||||
accessRole: number[];
|
||||
children?: AccessControlledItem[];
|
||||
match?: (pathname: string) => boolean;
|
||||
};
|
||||
|
||||
function canAccess(accessRole: number[], userRole: number | undefined): boolean {
|
||||
return accessRole.length === 0 || (userRole !== undefined && accessRole.includes(userRole));
|
||||
}
|
||||
|
||||
function filterTopMenusByRole(menus: TopMenuItem[], userRole: number | undefined): TopMenuItem[] {
|
||||
return menus.filter((menu) => canAccess(menu.accessRole, userRole));
|
||||
}
|
||||
|
||||
function filterSubMenusByRole(children: SideSubMenuItem[] | undefined, userRole: number | undefined): SideSubMenuItem[] | undefined {
|
||||
const filtered = children?.filter((child) => canAccess(child.accessRole, userRole));
|
||||
return filtered?.length ? filtered : undefined;
|
||||
}
|
||||
|
||||
function filterSideMenusByRole(menus: SideMenuItem[], userRole: number | undefined): SideMenuItem[] {
|
||||
return menus.reduce<SideMenuItem[]>((acc, menu) => {
|
||||
if (!canAccess(menu.accessRole, userRole)) return acc;
|
||||
|
||||
const children = filterSubMenusByRole(menu.children, userRole);
|
||||
if (!menu.path && menu.children?.length && !children?.length) return acc;
|
||||
|
||||
acc.push({
|
||||
...menu,
|
||||
...(children ? { children } : { children: undefined }),
|
||||
});
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function pathMatches(item: AccessControlledItem, pathname: string): boolean {
|
||||
if (item.match?.(pathname)) return true;
|
||||
return Boolean(item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)));
|
||||
}
|
||||
|
||||
function findSideAccessChain(pathname: string, menus: SideMenuItem[]): AccessControlledItem[] | null {
|
||||
const matches: AccessControlledItem[][] = [];
|
||||
|
||||
menus.forEach((menu) => {
|
||||
if (menu.path && pathMatches(menu, pathname)) {
|
||||
matches.push([menu]);
|
||||
}
|
||||
|
||||
menu.children?.forEach((child) => {
|
||||
if (pathMatches(child, pathname)) {
|
||||
matches.push([menu, child]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (!matches.length) return null;
|
||||
|
||||
return matches.sort((a, b) => {
|
||||
const aPath = a.at(-1)?.path ?? "";
|
||||
const bPath = b.at(-1)?.path ?? "";
|
||||
return bPath.length - aPath.length;
|
||||
})[0];
|
||||
}
|
||||
|
||||
function findTopAccessChain(pathname: string, menus: TopMenuItem[]): AccessControlledItem[] | null {
|
||||
const match = menus.find((menu) => pathMatches(menu, pathname));
|
||||
return match ? [match] : null;
|
||||
}
|
||||
|
||||
function findAccessChain(pathname: string): AccessControlledItem[] | null {
|
||||
return (
|
||||
findSideAccessChain(pathname, [...projectSideMenus, ...manageSideMenus]) ??
|
||||
findTopAccessChain(pathname, topMenus)
|
||||
);
|
||||
}
|
||||
|
||||
export default function AppMainLayout({ children, initialFontSize }: AppMainLayoutProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const mounted = useMounted();
|
||||
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
|
||||
const { showDialog } = useDialog();
|
||||
const [menuOpen, setMenuOpen] = useState(true);
|
||||
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
|
||||
const userRole = auth.user?.userRole;
|
||||
|
||||
const isMain = pathname === "/";
|
||||
const isContactPage = pathname.startsWith("/list/contact");
|
||||
const isProjectMenu = !pathname.startsWith("/manage");
|
||||
const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info");
|
||||
const visibleTopMenus = useMemo(() => filterTopMenusByRole(topMenus, userRole), [userRole]);
|
||||
const visibleProjectSideMenus = useMemo(() => filterSideMenusByRole(projectSideMenus, userRole), [userRole]);
|
||||
const visibleManageSideMenus = useMemo(() => filterSideMenusByRole(manageSideMenus, userRole), [userRole]);
|
||||
const activeTop = visibleTopMenus.find((menu) => menu.match?.(pathname)) ?? visibleTopMenus[0] ?? topMenus[0];
|
||||
const sideMenus = isProjectMenu ? visibleProjectSideMenus : visibleManageSideMenus;
|
||||
const hasRouteAccess = useMemo(() => {
|
||||
if (!auth.user) return true;
|
||||
|
||||
const accessChain = findAccessChain(pathname);
|
||||
if (!accessChain) return true;
|
||||
|
||||
return accessChain.every((item) => canAccess(item.accessRole, userRole));
|
||||
}, [auth.user, pathname, userRole]);
|
||||
|
||||
const [openMenus, setOpenMenus] = useState<Record<string, boolean>>(() => {
|
||||
const initial: Record<string, boolean> = {};
|
||||
|
||||
sideMenus.forEach((item) => {
|
||||
if (item.children?.some((child) => pathname === child.path || pathname.startsWith(`${child.path}/`))) {
|
||||
initial[item.id] = true;
|
||||
}
|
||||
});
|
||||
|
||||
return initial;
|
||||
});
|
||||
|
||||
const movePage = (path: string) => {
|
||||
// 메뉴 설정(menu.data.ts)의 경로라 typedRoutes가 정적으로 검사할 수 없다.
|
||||
router.push(path as Route);
|
||||
};
|
||||
|
||||
const decreaseFontSize = () => {
|
||||
setFontSize(Math.max(FONT_SIZE.MIN, fontSize - 2));
|
||||
};
|
||||
|
||||
const increaseFontSize = () => {
|
||||
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
|
||||
};
|
||||
|
||||
// 모바일(lg 미만)에서는 사이드바가 본문을 덮는 오버레이라 메뉴를 접힌 상태로 시작한다.
|
||||
useEffect(() => {
|
||||
if (!window.matchMedia("(min-width: 64rem)").matches) setMenuOpen(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
if (!auth.user) {
|
||||
router.replace("/logout");
|
||||
}
|
||||
}, [auth.user, mounted, router]);
|
||||
|
||||
// 컨택결과 저장 시점에 GPS 권한 프롬프트가 뜨면 저장이 지연/누락될 수 있어,
|
||||
// 로그인 후 메인 진입 시점에 미리 권한을 받아 위치를 캐시해둔다(결과는 사용하지 않음).
|
||||
useEffect(() => {
|
||||
if (!mounted || !auth.user) return;
|
||||
void getCurrentPositionMeta();
|
||||
}, [mounted, auth.user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted || !auth.user || hasRouteAccess) return;
|
||||
|
||||
alert("접근 권한이 없습니다.");
|
||||
router.replace("/");
|
||||
}, [auth.user, hasRouteAccess, mounted, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSelectedProjectHydrated) return;
|
||||
if (!hasRouteAccess) return;
|
||||
|
||||
if (!isMain && isProjectMenu && !selectedProject) {
|
||||
alert("선택된 프로젝트가 없습니다.");
|
||||
router.replace("/");
|
||||
}
|
||||
}, [hasRouteAccess, isMain, isProjectMenu, isSelectedProjectHydrated, router, selectedProject]);
|
||||
|
||||
if (mounted && auth.user && !hasRouteAccess) return null;
|
||||
|
||||
return (
|
||||
<KriMainLayout
|
||||
fullHeight={false}
|
||||
className={cn("bg-gray-50", "h-screen overflow-hidden")}
|
||||
bodyClassName={cn(!isMain && isContactPage && "min-h-0")}
|
||||
mainClassName={cn("p-4", "min-h-0")}
|
||||
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
||||
sidebarOpen={!isMain && !isContactPage && menuOpen}
|
||||
onSidebarOpenChange={setMenuOpen}
|
||||
header={
|
||||
<AppHeader
|
||||
isMain={isMain}
|
||||
isContactPage={isContactPage}
|
||||
menuOpen={menuOpen}
|
||||
activeTopId={activeTop.id}
|
||||
topMenus={visibleTopMenus}
|
||||
isViewProjectTitle={isViewProjectTitle}
|
||||
projectName={selectedProject?.prjctName}
|
||||
userInfo={auth.user ?? undefined}
|
||||
fontSize={fontSize}
|
||||
onToggleMenu={() => setMenuOpen((prev) => !prev)}
|
||||
onNavigate={movePage}
|
||||
decreaseFontSize={decreaseFontSize}
|
||||
increaseFontSize={increaseFontSize}
|
||||
onOpenReserveSearch={() => showDialog("reserveSearchDialog")}
|
||||
/>
|
||||
}
|
||||
sidebar={
|
||||
!isMain && !isContactPage ? (
|
||||
<AppSidebar
|
||||
isProjectMenu={isProjectMenu}
|
||||
sideMenus={sideMenus}
|
||||
isOpen={menuOpen}
|
||||
pathname={pathname}
|
||||
openMenus={openMenus}
|
||||
onOpenMenusChange={setOpenMenus}
|
||||
onNavigate={movePage}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{children}
|
||||
{mounted && auth.user && <ListJobWatcher userId={auth.user.userId} prjctIdx={selectedProject?.prjctIdx ?? 0} />}
|
||||
<ReserveSearchDialog />
|
||||
</KriMainLayout>
|
||||
);
|
||||
}
|
||||
10
src/components/app-shell/AppPageTitle.tsx
Normal file
10
src/components/app-shell/AppPageTitle.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { KriPageTitle } from "@/components/layout/KriPageTitle";
|
||||
|
||||
interface AppPageTitleProps {
|
||||
titleText: string;
|
||||
}
|
||||
|
||||
export default function AppPageTitle({ titleText }: AppPageTitleProps) {
|
||||
return <KriPageTitle title={titleText} />;
|
||||
}
|
||||
|
||||
50
src/components/app-shell/AppSidebar.tsx
Normal file
50
src/components/app-shell/AppSidebar.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { KriSidebar } from "@/components/layout/KriSidebar";
|
||||
import { AppSidebarProjectSearch } from "@/components/app-shell/AppSidebarProjectSearch";
|
||||
import type { SideMenuItem } from "@/config/menu.types";
|
||||
|
||||
interface AppSidebarProps {
|
||||
isProjectMenu: boolean;
|
||||
sideMenus: SideMenuItem[];
|
||||
isOpen: boolean;
|
||||
pathname: string;
|
||||
openMenus: Record<string, boolean>;
|
||||
onOpenMenusChange: (openMenus: Record<string, boolean>) => void;
|
||||
onNavigate: (path: string) => void;
|
||||
}
|
||||
|
||||
export function AppSidebar({
|
||||
isProjectMenu,
|
||||
sideMenus,
|
||||
isOpen,
|
||||
pathname,
|
||||
openMenus,
|
||||
onOpenMenusChange,
|
||||
onNavigate,
|
||||
}: AppSidebarProps) {
|
||||
const openItemIds = Object.entries(openMenus)
|
||||
.filter(([, open]) => open)
|
||||
.map(([id]) => id);
|
||||
|
||||
return (
|
||||
<KriSidebar
|
||||
items={sideMenus}
|
||||
isOpen={isOpen}
|
||||
pathname={pathname}
|
||||
header={isProjectMenu ? <AppSidebarProjectSearch /> : null}
|
||||
openItemIds={openItemIds}
|
||||
onOpenItemIdsChange={(ids) => {
|
||||
onOpenMenusChange(
|
||||
sideMenus.reduce<Record<string, boolean>>((acc, item) => {
|
||||
acc[item.id] = ids.includes(item.id);
|
||||
return acc;
|
||||
}, {}),
|
||||
);
|
||||
}}
|
||||
onNavigate={(path) => onNavigate(path)}
|
||||
className="border-gray-200 bg-white"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,45 +1,32 @@
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {ProjectInfo} from "@/types/project";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useEffect, useState} from "react";
|
||||
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
|
||||
import {useMemo, useState} from "react";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {useProjectTopQuery} from "@/query/project";
|
||||
|
||||
export const SidebarProjectSearch = () =>{
|
||||
export const AppSidebarProjectSearch = () =>{
|
||||
const mounted = useMounted();
|
||||
|
||||
const { selectedProject, setSelectedProject } = useSelectedProject();
|
||||
const [searchKeyword, setSearchKeyword] = useState(selectedProject?.prjctCd || "");
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const [projectArray, setProjectArray] = useState<SelectedProject[]>([]);
|
||||
|
||||
const searchTopProject = async (keyword: string) => {
|
||||
const res = await nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${PROJECT_SEARCH_COUNT}`,
|
||||
{ query: { keyword } }
|
||||
);
|
||||
const enabled = mounted && !!selectedProject;
|
||||
const topQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, enabled);
|
||||
|
||||
setProjectArray(res);
|
||||
};
|
||||
const projectArray = useMemo(() => {
|
||||
const data = topQuery.data ?? [];
|
||||
return selectedProject ? [selectedProject, ...data] : data;
|
||||
}, [topQuery.data, selectedProject]);
|
||||
|
||||
const handleSelectProject = (info: SelectedProject | null) => {
|
||||
if(info === null) return;
|
||||
|
||||
if (!info) return;
|
||||
setSelectedProject(info);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchTopProject(keyword);
|
||||
}
|
||||
}, [debouncedKeyword]);
|
||||
|
||||
if (!mounted || !selectedProject) return null
|
||||
if (!mounted || !selectedProject) return null;
|
||||
|
||||
return (
|
||||
<KriSingleSelect
|
||||
@@ -52,7 +39,6 @@ export const SidebarProjectSearch = () =>{
|
||||
searchMode="inputOnly"
|
||||
onSearchValueChange={setSearchKeyword}
|
||||
placeholder="프로젝트 검색..."
|
||||
spanClassName="content-text-sm"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
preventDeselect
|
||||
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>}
|
||||
</>;
|
||||
}
|
||||
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
15
src/components/app-shell/LoadingOverlayAdapter.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
|
||||
const open = useAtomValue(loadingAtom);
|
||||
|
||||
return <KriLoadingOverlay open={force || open} {...props} />;
|
||||
}
|
||||
6
src/components/app-shell/index.ts
Normal file
6
src/components/app-shell/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { AppHeader } from "./AppHeader";
|
||||
export { AppSidebar } from "./AppSidebar";
|
||||
export { LoadingOverlayAdapter } from "./LoadingOverlayAdapter";
|
||||
export { default as AppMainLayout } from "./AppMainLayout";
|
||||
export { default as AppPageTitle } from "./AppPageTitle";
|
||||
|
||||
200
src/components/assign/AssignTargetList.tsx
Normal file
200
src/components/assign/AssignTargetList.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useCmpnListQuery } from '@/query/cmpn'
|
||||
import { useFieldworkUsersQuery } from '@/query/user'
|
||||
import {
|
||||
useAssignedCmpnIdsQuery,
|
||||
useAssignedCmpnSummaryQuery,
|
||||
useAssignedFieldworkIdsQuery,
|
||||
useAssignedFieldworkSummaryQuery,
|
||||
} from '@/query/project'
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import { ListHeaderAssignConst } from '@/const/listConst'
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
|
||||
import { isInternalManager } from '@/utils/userRole'
|
||||
import type { ListHeaderAssignType } from '@/types/list'
|
||||
|
||||
export type AssignTargetListProps = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
userRole: number
|
||||
selectedId?: string
|
||||
onSelect: (id: string) => void
|
||||
}
|
||||
|
||||
export type AssignTargetRow = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type UseAssignTargetRowsArgs = {
|
||||
prjctIdx: number
|
||||
enabled: boolean
|
||||
assignType: ListHeaderAssignType
|
||||
}
|
||||
|
||||
export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssignTargetRowsArgs): AssignTargetRow[] {
|
||||
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
|
||||
|
||||
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled && isOutsource)
|
||||
const cmpnListQuery = useCmpnListQuery()
|
||||
|
||||
const assignedFieldworkIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled && !isOutsource)
|
||||
const fieldworkUsersQuery = useFieldworkUsersQuery(enabled && !isOutsource)
|
||||
|
||||
return useMemo<AssignTargetRow[]>(() => {
|
||||
if (isOutsource) {
|
||||
const assignedIds = new Set(assignedCmpnIdsQuery.data ?? [])
|
||||
return (cmpnListQuery.data ?? [])
|
||||
.filter((cmpn) => assignedIds.has(cmpn.cmpnId))
|
||||
.map((cmpn) => ({ id: cmpn.cmpnId, name: cmpn.cmpnAlias || cmpn.cmpnId }))
|
||||
}
|
||||
|
||||
const targetRole =
|
||||
assignType === ListHeaderAssignConst.CONTACT_INTERVIEWER ? CONTACT_INTERVIEWER_ROLE : FIELD_INTERVIEWER_ROLE
|
||||
const assignedIds = new Set(assignedFieldworkIdsQuery.data ?? [])
|
||||
|
||||
return (fieldworkUsersQuery.data ?? [])
|
||||
.filter((user) => assignedIds.has(user.userId) && user.userRole === targetRole)
|
||||
.map((user) => ({ id: user.userId, name: user.userName }))
|
||||
}, [
|
||||
assignType,
|
||||
isOutsource,
|
||||
assignedCmpnIdsQuery.data,
|
||||
cmpnListQuery.data,
|
||||
assignedFieldworkIdsQuery.data,
|
||||
fieldworkUsersQuery.data,
|
||||
])
|
||||
}
|
||||
|
||||
type AssignSummaryRow = {
|
||||
id: string
|
||||
name: string
|
||||
assignedCount: number
|
||||
cmpn?: string
|
||||
}
|
||||
|
||||
export function AssignTargetList({
|
||||
prjctIdx,
|
||||
enabled,
|
||||
assignType,
|
||||
userRole,
|
||||
selectedId,
|
||||
onSelect
|
||||
}: AssignTargetListProps) {
|
||||
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
|
||||
const canFilterByCmpn = !isOutsource && isInternalManager(userRole)
|
||||
const showCmpnColumn = canFilterByCmpn
|
||||
const [cmpnIds, setCmpnIds] = useState<string[]>([])
|
||||
|
||||
const cmpnListQuery = useCmpnListQuery()
|
||||
const cmpnSummaryQuery = useAssignedCmpnSummaryQuery(prjctIdx, enabled && isOutsource)
|
||||
const fieldworkSummaryQuery = useAssignedFieldworkSummaryQuery(
|
||||
prjctIdx,
|
||||
assignType,
|
||||
cmpnIds,
|
||||
enabled && !isOutsource,
|
||||
)
|
||||
|
||||
const summary = isOutsource ? cmpnSummaryQuery.data : fieldworkSummaryQuery.data
|
||||
const isLoading = isOutsource ? cmpnSummaryQuery.isLoading : fieldworkSummaryQuery.isLoading
|
||||
|
||||
const cmpnAliasById = useMemo(
|
||||
() => new Map((cmpnListQuery.data ?? []).map((cmpn) => [cmpn.cmpnId, cmpn.cmpnAlias || cmpn.cmpnId])),
|
||||
[cmpnListQuery.data],
|
||||
)
|
||||
|
||||
const rows = useMemo<AssignSummaryRow[]>(() => {
|
||||
if (isOutsource) {
|
||||
return (cmpnSummaryQuery.data?.assignees ?? []).map((item) => ({
|
||||
id: item.cmpnId,
|
||||
name: item.cmpnAlias || item.cmpnId,
|
||||
assignedCount: item.assignedCount,
|
||||
}))
|
||||
}
|
||||
return (fieldworkSummaryQuery.data?.assignees ?? []).map((item) => ({
|
||||
id: item.userId,
|
||||
name: item.userName,
|
||||
assignedCount: item.assignedCount,
|
||||
cmpn: cmpnAliasById.get(item.userCmpn) ?? item.userCmpn,
|
||||
}))
|
||||
}, [isOutsource, cmpnSummaryQuery.data, fieldworkSummaryQuery.data, cmpnAliasById])
|
||||
|
||||
return (
|
||||
<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 ? (
|
||||
<div className="shrink-0 border-b border-gray-200 p-2">
|
||||
<KriMultiSelect
|
||||
items={cmpnListQuery.data ?? []}
|
||||
value={cmpnIds}
|
||||
onChange={setCmpnIds}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
placeholder="외주사 선택(전체)"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<table className="w-full table-fixed">
|
||||
<colgroup>
|
||||
<col className="w-20" />
|
||||
<col />
|
||||
{showCmpnColumn ? <col className="w-20" /> : null}
|
||||
<col className="w-14" />
|
||||
</colgroup>
|
||||
<thead className="bg-primary text-white sticky top-0">
|
||||
<tr>
|
||||
<th className="p-2 text-left text-base font-medium">ID</th>
|
||||
<th className="p-2 text-left text-base font-medium">이름</th>
|
||||
{showCmpnColumn ? <th className="p-2 text-left text-base font-medium">회사</th> : null}
|
||||
<th className="p-2 text-right text-base font-medium">배정</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={showCmpnColumn ? 4 : 3} className="p-4 text-center text-sm text-muted-foreground">
|
||||
불러오는 중...
|
||||
</td>
|
||||
</tr>
|
||||
) : rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={showCmpnColumn ? 4 : 3} className="p-4 text-center text-sm text-muted-foreground">
|
||||
대상이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
selectedId === row.id ? 'bg-accent' : ''
|
||||
}`}
|
||||
onClick={() => onSelect(row.id)}
|
||||
>
|
||||
<td className="p-2 text-base truncate">{row.id}</td>
|
||||
<td className="p-2 text-base truncate">{row.name}</td>
|
||||
{showCmpnColumn ? <td className="p-2 text-base truncate">{row.cmpn}</td> : null}
|
||||
<td className="p-2 text-base text-right">{row.assignedCount}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AssignTargetList
|
||||
147
src/components/chart/BaseEChart.tsx
Normal file
147
src/components/chart/BaseEChart.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { ComponentType, CSSProperties } from 'react'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import { CHART_HEIGHTS } from './chart.config'
|
||||
import { useResizeKey } from './useResizeKey'
|
||||
|
||||
type EChartsSeries = NonNullable<EChartsOption['series']>
|
||||
type ReactEChartsProps = {
|
||||
option: EChartsOption
|
||||
className?: string
|
||||
style?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
}
|
||||
|
||||
export type BaseEChartProps = {
|
||||
option: EChartsOption
|
||||
height?: number | string
|
||||
className?: string
|
||||
contentClassName?: string
|
||||
chartClassName?: string
|
||||
style?: CSSProperties
|
||||
contentStyle?: CSSProperties
|
||||
chartStyle?: CSSProperties
|
||||
notMerge?: boolean
|
||||
lazyUpdate?: boolean
|
||||
onEvents?: Record<string, (params: unknown) => void>
|
||||
resizeDebounceMs?: number
|
||||
normalizeValues?: boolean
|
||||
decimalPlaces?: number
|
||||
}
|
||||
|
||||
const roundNumber = (value: number, decimalPlaces: number) => {
|
||||
const factor = 10 ** decimalPlaces
|
||||
return Math.round((value + Number.EPSILON) * factor) / factor
|
||||
}
|
||||
|
||||
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
|
||||
if (typeof value === 'number') {
|
||||
return roundNumber(value, decimalPlaces)
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => normalizeDataValue(item, decimalPlaces))
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object' && 'value' in value) {
|
||||
const dataItem = value as Record<string, unknown>
|
||||
|
||||
return {
|
||||
...dataItem,
|
||||
value: normalizeDataValue(dataItem.value, decimalPlaces),
|
||||
}
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const normalizeSeries = (
|
||||
series: EChartsOption['series'] | undefined,
|
||||
decimalPlaces: number,
|
||||
): EChartsOption['series'] => {
|
||||
if (!series) return series
|
||||
|
||||
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
|
||||
const candidate = seriesOption as Record<string, unknown>
|
||||
const data = candidate.data
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
return seriesOption
|
||||
}
|
||||
|
||||
return {
|
||||
...candidate,
|
||||
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
|
||||
} as EChartsSeries
|
||||
}
|
||||
|
||||
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
|
||||
}
|
||||
|
||||
export function BaseEChart({
|
||||
option,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
className,
|
||||
contentClassName,
|
||||
chartClassName,
|
||||
style,
|
||||
contentStyle,
|
||||
chartStyle,
|
||||
notMerge = true,
|
||||
lazyUpdate = false,
|
||||
onEvents,
|
||||
resizeDebounceMs = 150,
|
||||
normalizeValues = true,
|
||||
decimalPlaces = 2,
|
||||
}: BaseEChartProps) {
|
||||
const resizeKey = useResizeKey(resizeDebounceMs)
|
||||
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
void import('echarts-for-react').then((module) => {
|
||||
if (!cancelled) {
|
||||
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const normalizedOption = useMemo<EChartsOption>(() => {
|
||||
if (!normalizeValues) return option
|
||||
|
||||
return {
|
||||
...option,
|
||||
series: normalizeSeries(option.series, decimalPlaces),
|
||||
}
|
||||
}, [decimalPlaces, normalizeValues, option])
|
||||
|
||||
return (
|
||||
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
|
||||
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
|
||||
{ReactECharts ? (
|
||||
<ReactECharts
|
||||
key={resizeKey}
|
||||
option={normalizedOption}
|
||||
className={chartClassName}
|
||||
style={{ width: '100%', height: '100%', ...chartStyle }}
|
||||
notMerge={notMerge}
|
||||
lazyUpdate={lazyUpdate}
|
||||
onEvents={onEvents}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default BaseEChart
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user